0% found this document useful (0 votes)
23 views59 pages

Employee Details Input Program

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views59 pages

Employee Details Input Program

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

P1: write a program to display Hello World message in console window.

class HelloWorld
{
public static void main(String[] args)
{
[Link]("Hello World…!");

}
}

Output:
Hello World…!
P2: Write a program to perform arithmetic and bitwise operations in a single
source program without object creation.

package LabPractical;
import [Link];
public class Question2
{
public static void main(String[] args)
{
Scanner scan = new Scanner([Link]);
double a, b; [Link]("Enter a
and b: ");a = [Link]();
b = [Link]();
[Link]("Arithmetic Operators:\n");

[Link](" %-15s: %f\n", "Sum", (a+b));


[Link](" %-15s: %f\n", "Difference", (a-b));

[Link](" %-15s: %f\n", "Product", (a*b));

[Link](" %-15s: %d\n", "Quotient", (int)(a/b));

[Link](" %-15s: %d\n", "Reminder", (int)(a%b));

[Link](" %-15s: %f\n", "PostIncrement", a++);

[Link](" %-15s: %f\n", "PreIncrement", ++a);


[Link]("\nBitwise Operators.\n");
int aa = (int)a;
int bb = (int)b;
[Link](" %-15s: %d\n", "NOT:", ~aa);
[Link](" %-15s: %d\n", "AND", aa&bb);
[Link](" %-15s: %d\n", "OR", aa|bb);
[Link](" %-15s: %d\n", "XOR", aa^bb);
[Link](" %-15s: %d\n", "RightShift", aa>>2);
[Link](" %-15s: %d\n", "LeftShift", aa<<2);
[Link]();
}
}
Output:

Enter a and b:
10
5
Arithmetic Operators:

Sum : 15.000000
Difference : 5.000000
Product : 50.000000
Quotient : 2
Reminder : 0
PostIncrement : 10.000000
PreIncrement: 12.000000

Bitwise Operators.

NOT: : -13
AND :4
OR : 13
P3: Write a program to perform arithmetic and bitwise operations by creating
individual methods and classes than create an object to execute the individual
methods of each operation.

import [Link];
public class Operators
{
public static void main(String[] args)
{
Scanner scan = new Scanner([Link]);
double a, b;
[Link]("Enter a and b: ");a =
[Link]();
b = [Link]();
Arithmetic arith = new Arithmetic(); [Link]("%-
15s: %f\n", "Sum", [Link](a, b));
[Link]("%-15s: %f\n", "Difference", [Link](a, b));
[Link]("%-15s: %f\n", "Product", [Link](a, b));
[Link]("%-15s: %f\n", "Quotient", [Link](a, b));
[Link]("%-15s: %f\n", "Reminder", [Link](a, b));
[Link]("%-15s: %f\n", "PostIncrement",
[Link](a));
[Link]("%-15s: %f\n", "PreIncrement",
[Link](a));
Bitwise bit = new Bitwise();
int aa = (int)a;
int bb = (int)b;
[Link]("%-15s: %d\n", "NOT:", [Link](~aa));
[Link]("%-15s: %d\n", "AND", [Link](aa, bb));
[Link]("%-15s: %d\n", "OR", [Link](aa, bb));
[Link]("%-15s: %d\n", "XOR", [Link](aa, bb));
[Link]("%-15s: %d\n", "RightShift", [Link](aa, 2));
[Link]("%-15s: %d\n", "LeftShift", [Link](aa, 2));
[Link]();
}
}
Package LabPracticals;
public class Arithmetic
{
Arithmetic()
{
[Link]("Arithmetic Operators\n");
}
double sum(double a, double b)
{
return a+b;
}
double diff(double a, double b)
{
return a-b;
}
double product(double a, double b)
{
return a*b;
}
double quotient(double a, double b)
{
return a/b;
}
double reminder(double a, double b)
{
return a%b;
}
double preIncrement(double a)
{
return ++a;
}
double postIncrement(double a)
{
return a++;
}
}
packageLabPractic;
public class
Bitwise{Bitwise()
{
[Link]("Bitwise Operators\n");
}
int and(int a, int b)
{
return a&b;
}
int or(int a, int b)
{
return a|b;
}
int xor(int a, int b)
{
return a^b;
}
int not(int a)
{
return ~a;
}
int rightShift(int a, int b)
{
return a>>b;
}
int leftShift(int a, int b)
{
return a<<b;
}
}
P4. Write a java program to display the employee details using
Scanner class.
import [Link];
class Employee
{
int id;
String name;
String desig;
float salary;
}
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("How many employees? ");
int n = [Link]();
Employee emp[] = new Employee[n];
for (int i = 0; i < n; i++)
{
emp[i] = new Employee();
[Link]("Enter " + (i + 1) + " Employee data :");
[Link]("Enter employee id :");
emp[i].id = [Link]();
[Link]("Enter employee name :");
emp[i].name = [Link]();
[Link]("Enter employee designation :");
emp[i].desig = [Link]();
[Link]("Enter employee salary :");
emp[i].salary = [Link]();
}
[Link](" \n\n********* All Employee Details are :*********\n");
for (int i = 0; i < n; i++)
{
[Link]("Employee id, Name, Designation and Salary :" + emp[0].id
+ " " + emp[i].name + " " + emp[i].desig + " " +emp[i].salary);
}
}
}

Output:
How many employees?
3
Enter 1 Employee data :
Enter employee id :111
Enter employee name :Naga
Enter employee designation :Developer
Enter employee salary :70000

Enter 2 Employee data :


Enter employee id :222
Enter employee name : Bhavani
Enter employee designation :Manager
Enter employee salary :80000
Enter 3 Employee data :
Enter employee id :333
Enter employee name :Bavvy
Enter employee designation :Programmer
Enter employee salary :90000

********* All Employee Details are :*********

Employee id, Name, Designation and Salary :


111 Naga Developer 70000.0

Employee id, Name, Designation and Salary :


222 Bhavani Manager 80000.0

Employee id, Name, Designation and Salary :


333 Bavvy Programmer 90000.0
P5: Write a Java program that prints all real solutions to the quadratic
equation ax2+bx+c = 0. Read in a, b, c and use the quadratic
formula. If the discriminate b2-4ac is negative, display a message
stating that there are no real solutions?

import [Link];
public class Question4
{
public static void main(String[] args)
{
Scanner scan = new Scanner([Link]); int a, b, c;
[Link]("Enter a, b and c:"); a = [Link]();
b = [Link](); c = [Link](); [Link]();
int dis = b*b - 4*a*c;
[Link]("Quadratic Equation: " + a + "x^2 + " + b + "x + "
+ c + " = 0\n");
if(dis<0)
[Link]("No real solution");
else
{
[Link]("Root_1: " + (-b+dis)/(2*a)); [Link]("Root_2: "
+ (-b-dis)/(2*a));
}
}
}
P6: The Fibonacci sequence is defined by the following rule.
The first 2 values in the sequence are 1, 1. Every subsequent value is
the sum of the 2 values preceding it. Write a Java program that
uses both recursive and non- recursive functions to print the nth value of
the Fibonacci sequence?

import [Link];
public class Fibonacci
{
public static void main(String[] args)
{
Scanner scan = new Scanner([Link]);
int n, a=0, b=1, c;
[Link]("Enter n:");
n = [Link](); [Link]();
[Link](" \nWithout Using Recursion: ");
[Link](a + " " + b + " ");
for(int i=1; i<=n-2; i++)
{
c = a+b;
[Link](c + " ");
a = b;
b = c;
}
[Link](" \n\nUsing Recursion: ");
for(int i=0; i<n; i++)
{
[Link](fibonacci(i) + " ");
}
}
static int fibonacci(int n)
{
if(n==0)
return 0;
if(n==1)
return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
}

Output:
Enter n: 9
Without Using Recursion:
0 1 1 2 3 5 8 13 21

Using Recursion:
0 1 1 2 3 5 8 13 21
P7: Write a Java program that prompts the user for an integer and
then prints out all the prime numbers up to that Integer?
import [Link];
class PrimeNumbers
{
public static void main(String[] args)
{
int n;
int p;
Scanner s=new Scanner([Link]);
[Link]("Enter a number: ");
n=[Link]();
for(int i=2; i<n; i++)
{
p=0;
for(int j=2; j<i; j++)
{
if(i%j==0)
p=1;
}
if(p==0)
[Link](i);
}
}
}
Output:
Enter a number: 20
2 3 5 7 11 13 17 19
P8. Write a Java program to multiply two given matrices?
import [Link];
class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner([Link]);
int matrix1[][] = {{2, 4, 6},
{1, 3, 5}};
int matrix2[][] = {{1, 2},
{1, 3},
{1, 1}};

int result[][] = new int[2][2];


for(int i=0; i<[Link]; i++)
{
for(int j=0; j<result[0].length; j++)
{
int sum=0;
for(int k=0; k<matrix1[0].length; k++)
{
sum += matrix1[i][k]*matrix2[k][j];
}
result[i][j] = sum;
}
}
[Link]("Resultant Matrix:");
for(int i=0; i<[Link]; i++)
{
for(int j=0; j<result[0].length; j++)
{
[Link](result[i][j]+ " ");
}
[Link]();
}
}
}

Output:
Resultant Matrix:
12 22
9 16
P9: Write a Java program for sorting a given list of names in ascending order?

import [Link].*;
class SortingAscendingOrderNames
{
void sortStrings()
{
Scanner s = new Scanner([Link]);
[Link]("Enter the value of n: ");
int n = [Link]();
String[] str = new String[n];
[Link]("Enter strings: ");
for(int i = 0; i < n; i++)
{
str[i] = new String([Link]());
}
for(int i = 0; i < n; i++)
{
for(int j = i+1; j < n; j++)
{
if(str[i].compareTo(str[j])>0)
{
String temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
[Link]("Sorted list of strings is:");
for(int i = 0; i < n ; i++)
{
[Link](str[i]);
}
}
}
class Driver
{
public static void main(String[] args)
{
SortingAscendingOrderNames Names = new SortingAscendingOrderNames ();
[Link]();
}
}
Output:
Enter the value of n: 4
Enter strings:
NagaMalleswaraRao
VidhyaBhavani
Bavvy
Sunitha
Sorted list of strings is:
Bavvy
NagaMalleswaraRao
Sunitha
VidhyaBhavani
P10: Write a java program for Method overloading and Constructor
overloading.

class Add
{
Add()
{
[Link]("Constructor with No parameters");
}
Add(int a)
{
[Link]("Single Parameter Constructor: "+a);
}
Add(int a, int b)
{
[Link]("Two Parameter Constructor: "+(a+b));
}
Add(int a,int b,int c)
{
[Link]("Three Parameter Constructor: "+(a+b+c));
}
}

class MethodConstructorOverLoading extends MethodConstructorOverLoading


{
MethodConstructorOverLoading (int x,int y,int z)
{
super(x,y,z);
}
int Sub(int a)
{
return a;
}
int Sub(int a,int b)
{
return a-b;
}
int Sub(int a,int b,int c)
{
return a-b-c;
}
public static void main(String []args)
{
[Link]("Constructor OverLoading:\n");
MethodConstructorOverLoading obj=new MethodConstructorOverLoading
(10,20,30);
[Link]("Calling Same Method with Different Parameters: \n");
[Link]("Method with Single Parameter: "+[Link](10));
[Link]("Method with Two Parameter: "+[Link](10,20));
[Link]("Method with Three Parameter: "+[Link](10,20,30));
}
}
Output:

Constructor OverLoading:

Three Parameter Constructor: 60

Calling Same Method with Different Parameters:

Method with Single Parameter: 10

Method with Two Parameter: -10

Method with Three Parameter: -40


P11: Write a java program to represent Abstract class with example.

import [Link].*;
abstract class Shape
{
int length, breadth, radius;
Scanner input = new Scanner([Link]);
abstract void printArea();
}
class Rectangle extends Shape
{
void printArea()
{
[Link]("*** Finding the Area of Rectangle ***");
[Link]("Enter length and breadth: ");
length = [Link]();
breadth = [Link]();
[Link]("The area of Rectangle is: " + length * breadth);
}
}
class Triangle extends Shape
{
void printArea()
{
[Link]("\n*** Finding the Area of Triangle ***");
[Link]("Enter Base And Height: ");
length = [Link]();
breadth = [Link]();
[Link]("The area of Triangle is: " + (length * breadth) / 2);
}
}
class Cricle extends Shape
{
void printArea()
{
[Link]("\n*** Finding the Area of Cricle ***");
[Link]("Enter Radius: ");
radius = [Link]();
[Link]("The area of Cricle is: " + 3.14f * radius * radius);
}
}
class AbstractClassExample
{
public static void main(String[] args)
{
Rectangle rec = new Rectangle();
[Link]();
Triangle tri = new Triangle();
[Link]();
Cricle cri = new Cricle();
[Link]();
}
}
Output:
P12: Write a program to implement multiple Inheritances.

interface Event
{
public void start();
}
interface Sports
{
public void play();
}
interface Hockey extends Sports, Event
{
public void show();
}
public class Tester
{
public static void main(String[] args)
{
Hockey hockey = new Hockey()
{
public void start()
{
[Link]("Start Event");
}
public void play()
{
[Link]("Play Sports.");
}
public void show()
{
[Link]("Show Hockey.");
}
};
[Link]();
[Link]();
[Link]();
}
}

Output:
Start Event
Play Sports.
Show Hockey.
P13: write program to demonstrate method overriding and super keyword.

class Parentclass
{
void display()
{
[Link]("Parent class method");
}
}
class Subclass extends Parentclass
{
void display()
{
[Link]("Child class method");
}
void printMsg()
{
display();
[Link]();
}
public static void main(String args[])
{
Subclass obj= new Subclass();
[Link]();
}
}
Output:
Child class method
Parent class method
14. Write a java program to implement Interface using extends
keyword.

class ExtendsInterfaceDemo
{
public static void main(String arg[])
{
vehicle v1 = new Bike();
[Link]("Honda");
[Link]("Shine");
[Link](2);
[Link](2);
OtherFeatures v2 = new Car();

[Link]("Rolls Royce");
[Link]("Rolls-Royce Cullinan");
[Link](4);
[Link](4);
[Link](9);
}
}

interface vehicle
{
void companyName(String name);
void vehicleName(String name);
void vehicleType(int i);
void seatArrangement(int i);
}
interface OtherFeatures extends vehicle
{
void mileagePerLiter(int i);
}
class Bike implements vehicle
{
public void companyName(String name)
{
[Link](name + "'s product.");
}
public void vehicleName(String name)
{
[Link]("Name of vehicle : " + name);
}
public void vehicleType(int i)
{
[Link](i + " wheeler.");
}
public void seatArrangement(int i)
{
[Link](i + " seater capacity.");
}
}

class Car extends Bike implements OtherFeatures


{
public void mileagePerLiter(int i)
{
[Link]("Mileage : " + i + " Kmpl.");
}
}
Output:
Honda's product.
Name of vehicle: Shine
2 wheeler:
2 seater capacity.
Rolls Royce's product:
Name of vehicle: Rolls-Royce Cullinan
4 wheeler:
4 seater capacity:
Mileage: 9 Kmpl.
P15: Write a java program to create inner classes.
import [Link].*;
class Innerclass
{
Innerclass()
{
[Link]("I am Outer Class");
}
class Main
{
Main()
{
[Link]("I am Inner Class");
}
double areaTriangle(int height, int bredth)
{
return 0.5*height*bredth;
}
}
public static void main(String []args)
{
Innerclass outer_obj=new Innerclass();
[Link] inner_obj=outer_obj.new Main();
[Link](inner_obj.areaTriangle(10,20));
}
}
Output:

I am Outer Class
I am Inner Class
100.0
P16: Write a java program to create user defined package.

package MyPackage;
public class Compare
{
int num1, num2;
Compare(int n, int m)
{
num1 = n;
num2 = m;
}
public void getmax()
{
if ( num1 > num2 )
{
[Link]("Maximum value of two numbers is: " + num1);
}
else
{
[Link]("Maximum value of two numbers is: " + num2);
}
}

public static void main(String args[])


{
Compare current[] = new Compare[3];
current[1] = new Compare(5, 10);
current[2] = new Compare(123, 120);
for(int i=1; i < 3 ; i++)
{
current[i].getmax();
}
}
}

Output:

Maximum value of two numbers is: 10

Maximum value of two numbers is: 123


P17: Write a Java program that displays the number of characters, lines and
words in a text?

import [Link].*;
class Prg17
{
public static void main(String args[])
{
try
{
int lines=0,chars=0,words=0;
int code=0;
FileInputStream fis = new FileInputStream("[Link]");
while([Link]()!=0)
{
code = [Link]();
if(code!=10)
chars++;
if(code==32)
words++;
if(code==13)
{
lines++;
words++;
}
}
[Link]("[Link] characters = "+chars);
[Link]("[Link] words = "+(words+1));
[Link]("[Link] lines = "+(lines+1));
[Link]();
}
catch(FileNotFoundException e)
{
[Link]("Cannot find the specified file...");
}
catch(IOException i)
{
[Link]("Cannot read file...");
}
}
}

[Link] ------> text file


Hello
How are You Guys!
How do you do...!
How Old are You...!
He is Good Boy....!

Output:

[Link] characters = 81
[Link] words = 17
[Link] lines = 5
P18: Write a Java program that checks whether a given string is a palindrome or
not. Ex: MADAM is a palindrome?

import [Link];
class palindrome
{
public static void main(String[] args)
{
Scanner scanner=new Scanner([Link]);
[Link]("Enter a string as an input to check whether it is palindrome
or not");
String input= [Link]();
if(isPalindrome(input))
{
[Link](input+" is a palindrome string");
}
else
{
[Link](input+" is not a palindrome string");
}
}
public static boolean isPalindrome(String str)
{
int left = 0, right = [Link]() - 1;
while(left < right)
{
if([Link](left) != [Link](right))
{
return false;
}
left++;
right--;
}
return true;
}
}

Output:
Enter a string as an input to check whether it is palindrome or not
MADAM
MADAM is a palindrome string
P19: Write a Java program that reads a line of integers and then displays each
integer and the sum of all integers. (Use StringTokenizer class)?

import [Link].*;
class StringTokenizerDemo
{
public static void main(String args[])
{
int n;
int sum = 0;
Scanner sc = new Scanner([Link]);
[Link]("Enter integers with one space gap:");
String s = [Link]();
StringTokenizer st = new StringTokenizer(s, " ");
while ([Link]())
{
String temp = [Link]();
n = [Link](temp);
[Link](n);
sum = sum + n;
}
[Link]("sum of the integers is: " + sum);
[Link]();
}
}
Output:

Enter integers with one space gap:

10 20 30 40 50 60 70 80 90 100

10

20

30

40

50

60

70

80

90

100

sum of the integers is: 550


P20: Write a java program for creating single try block with multiple catch
blocks.
package exceptionHandling;
import [Link];
class MultiCatchEx3
{
public static void main(String[] args)
{
int x, y;
Scanner sc = new Scanner([Link]);
try
{
[Link]("Enter your first number");
x = [Link]([Link]());
[Link]("Enter your second number");
y = [Link]([Link]());
int z = x / y;
[Link]("z = " +z);
}
catch(ArithmeticException ae)
{
[Link]("A number cannot be divided by 0, Illegal operation in
Java");
[Link]("Exception thrown: " +ae);
}
catch(NumberFormatException nfe)
{
[Link]("Invalid data types are entered, number must be an
integer.");
[Link]("Exception thrown: " +nfe);
}
catch(RuntimeException re)
{
[Link]("Exception thrown: " +re);
}
[Link]("Out of try-catch block");
}
}

Output:
First Run:
Enter your first number
40
Enter your second number
20
z=2
Out of try-catch block
Second Run:
Enter your first number
40
Enter your second number
0
A number cannot be divided by 0, Illegal operation in Java Exception thrown:
[Link]: / by zero
Out of try-catch block

Third Run:
Enter your first number
40
Enter your second number
5.5
Invalid data types are entered, number must be an integer.
Exception thrown: [Link]: For input
string: "5.5"
Out of try-catch block
P21. write a program for multiple try blocks and multiple catch blocks including
finally.

import [Link];

import [Link];

public class Try_Catch

public static void main(String[] args)

int a=5,b=0,c,d,f;

try

Scanner s=new Scanner([Link]);

[Link]("Enter a:");

a=[Link]();

[Link]("Enter b:");

b=[Link]();

[Link]("Enter c:");

c=[Link]();

d=a/b;

[Link](d);

f=a%c;

[Link](f);
FileInputStream fis = null;

fis = new FileInputStream("B:/[Link]");

int k;

while(( k = [Link]() ) != -1)

[Link]((char)k);

[Link]();

catch(IndexOutOfBoundsException e)

[Link](e);

catch(NullPointerException e)

[Link](e);

catch(ArithmeticException e)

[Link](e);

catch(Exception e)
{

[Link](e);

Output:

Enter a:4

Enter b:5

Enter c:6

[Link]: B:/[Link] (No such file or directory)


P22: write a program to create user defined exception

import [Link];
class CheckAge
{
void validateAge(int age) throws InvalidAgeException
{
if (age <= 100 && age > 0)
{
[Link]("Valid age");
}
else
{
throw new InvalidAgeException("Age is not valid");
}
}
public static void main(String[] s)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter your age");
int age = [Link]();
CheckAge ck = new CheckAge();
try
{
[Link](age);
}
catch (InvalidAgeException e)
{
[Link]("Invalid Age " + [Link]());
}
}
}

Output:1
Enter your age
23
Valid age
Output:2
Enter your age
112
InvalidAgeException: Age is not valid
at [Link]([Link])
at [Link]([Link])
P23: Write a java program for producer and consumer problem
using Threads.

class Producer implements Runnable


{
Q q;
Producer(Q q)
{
this.q =q;
new Thread(this," producer").start();
}
public void run()
{
int i= 0;
while(true)
{
[Link](i++);
if(i== 10)
[Link](0);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q= q;
new Thread(this, "consumer").start();
}
public void run()
{
while(true)
[Link]();
}
}
class Program23
{
public static void main(String ar[])
{
Q q= new Q();
new Producer(q);
new Consumer(q);
}
}
class Q
{
int n;
boolean valueset= true;
synchronized int get()
{
while(!valueset)
{
try
{
wait();
}
catch(Exception e)
{
}
}
[Link]("Producer " +n);
valueset= false;
notify();
return n;
}
synchronized void put(int n)
{
while(valueset)
{
try
{
wait();
}
catch(Exception e)
{
}
}
this.n= n;
valueset =true;
[Link]("Consumer " +n);
notify();
}
}

Output:

Producer 0
Consumer 0
Producer 0
Consumer 1
Producer 1
Consumer 2
Producer 2
Consumer 3
Producer 3
Consumer 4
Producer 4
Consumer 5
Producer 5
Consumer 6
Producer 6
Consumer 7
Producer 7
Consumer 8
Producer 8
Consumer 9
Producer 9
P24: Write a java program that implements a multi-thread application that has
three threads. First thread generates random integer every 1 second and if
the value is even, second thread computes the square of the number and
prints. If the value is odd, the third thread will print the value of cube of
the number.

import [Link];

class Square extends Thread

int x;

Square(int n)

{
x = n;

}
public void run()

int sqr = x * x;

[Link]("Square of " + x + " = " + sqr );

}
class Cube extends Thread

int x;

Cube(int n)
{

x = n;

}
public void run()

int cub = x * x * x;
[Link]("Cube of " + x + " = " + cub );

}
}

class Number extends Thread

public void run()


{

Random random = new Random();


for(int i =0; i<5; i++)

int randomInteger = [Link](100);

[Link]("Random Integer generated : " + randomInteger);


Square s = new Square(randomInteger);

[Link]();

Cube c = new Cube(randomInteger);

[Link]();
try

[Link](1000);

catch (InterruptedException ex)

{
[Link](ex);

}
}

}
public class Thread1

public static void main(String args[])

{
Number n = new Number();

[Link]();
}

Output:
Random Integer generated : 48
Cube of 48 = 110592
Square of 48 = 2304

Random Integer generated : 11


Square of 11 = 121
Cube of 11 = 1331

Random Integer generated : 81


Square of 81 = 6561
Cube of 81 = 531441
Random Integer generated : 33
Square of 33 = 1089
Cube of 33 = 35937

Random Integer generated : 82


Square of 82 = 6724
Cube of 82 = 551368
P25: write a program to create dynamic array using ArrayList class and the print
the contents of the array object.

import [Link].*;
class ArrayListObjects
{
public static void main(String[] args)
{
ArrayList<String> array_list=new ArrayList<String>();
[Link]("Enter elements of the Array (Strings) : \n");
Scanner sc=new Scanner([Link]);
int size_of_array=[Link]();
[Link]("Enter "+size_of_array+" Array Names: \n");
for(int i=0;i<size_of_array;i++)
{
array_list.add([Link]());
}
[Link]("The List of Array are: ");
int count=0;
for(String i:array_list)
{
count++;
[Link](count+" : " +i);
}
}
}
Output:
Enter elements of the array (Strings):

4
Enter 4 Array Names:

NagaMalleswaraRao
VidhyaBhavani
Bavvy
Kanna

The List of Array are:


1: NagaMalleswaraRao
2: VidhyaBhavani
3: Bavvy
4: Kanna
P26: Write programs to implement add, search and remove operation on
ArrayList object.

import [Link].*;
class ArrayAddSearchRemove
{
public static void main(String [] args)
{
ArrayList<String> Fruits=new ArrayList<String>();
Scanner sc=new Scanner([Link]);
boolean flag=true;
while(flag)
{
[Link]("Enter 1. Add Fruit \n 2. Search Fruit \n 3. Remove Fruit \n
4. Exit");
int option=[Link]();
switch(option)
{
case 1:
[Link]("Enter How many Fruits You want to add");
int n=[Link]();
for(int i=0;i<n;i++)
{
[Link]([Link]());
}
[Link]("The Final Fruit list is: \n");
[Link](Fruits);
break;
case 2: [Link]("Enter Fruit name to Search");
String fruit_names=[Link]();
boolean search_result=[Link](fruit_names);
if(search_result)
{
[Link](fruit_names+" is in the Fruits list");
}
else
{
[Link](fruit_names+" is not there in the Fruit list");
}
break;
case 3: [Link]("Enter Fruite Name to Remove from the list");
String fruit_name=[Link]();
[Link](fruit_name);
[Link]("After Removed "+fruit_name+" the list of Friuts are: \n");
[Link](Fruits);
break;
case 4:
flag=false;
break;
}
}
}
}
Output:
Enter 1. Add Fruit
2. Search Fruit
3. Remove Fruit
4. Exit1
Enter How many Fruites You want to add
3
Apple
Banana
Mango
The Final Fruit list is:

[Apple, Banana, Mango]


Enter 1. Add Fruit
2. Search Fruit
3. Remove Fruit
4. Exit
2
Enter Fruit name to Search
Mango
Mango is in the Fruits list
Enter 1. Add Fruit
2. Search Fruit
3. Remove Fruit
4. Exit
3
Enter Fruite Name to Remove from the list
Apple
After Removed Apple the list of Friuts are:
[Banana, Mango]
Enter 1. Add Fruit
2. Search Fruit
3. Remove Fruit
4. Exit

Common questions

Powered by AI

StringTokenizer in Java simplifies the parsing of strings into tokens based on delimiters and is useful for simple token extraction. However, it is somewhat outdated and less flexible than newer alternatives like the String.split() method or the Scanner class, which provides more controlled handling of input, including regex support and easy conversion to different data types .

Recursion is preferred when the problem inherently fits a recursive structure or leads to a solution that is more readable and easier to implement, such as problems involving tree traversals or where the iterative solution may involve complex and cumbersome loops. It can also be suitable when short recursion does not incur significant overhead or when using functional programming languages that optimize tail recursion .

The recursive method of calculating the Fibonacci sequence is less efficient than the iterative method because it involves a lot of repetitive calculations and has higher time complexity O(2^n). In contrast, the iterative approach computes each Fibonacci number once and has a linear time complexity of O(n). The iterative method is generally more efficient and consumes less memory, making it more usable for larger values of n .

ArrayLists provide dynamic resizing, automatic handling of elements when adding/removing items, and offer more flexibility compared to traditional arrays, which have a fixed size. Unlike arrays, ArrayLists can store nulls and objects but require more overhead due to the dynamic nature and inherently higher complexity in certain operations, such as accessing elements, which can be slower compared to direct array indexing .

Multi-threading in Java introduces challenges such as race conditions, deadlocks, and inconsistent state due to improper access to shared resources. Synchronization, utilizing synchronized blocks or methods, is vital to ensure that only one thread accesses a critical section at a time. Additional techniques include using concurrent collections, locks, and atomic variables to simplify synchronization complexities. Designing clear access protocols and utilizing monitored conditions within code can mitigate these issues .

Using multiple catch blocks can lead to code duplication if exceptions share similar handling logic, creating a maintenance burden. Additionally, it can make the code harder to read, as understanding the flow requires keeping track of each specific exception type that might be caught. Simplifying multiple catch blocks into fewer ones can often achieve cleaner and more concise code .

The most critical elements include comprehensive input validation to ensure user inputs meet expected formats and ranges, robust exception handling mechanisms to manage runtime errors gracefully, and thorough testing of edge cases and error conditions. Moreover, using logging to track operations and errors, as well as applying design patterns like defensive programming, can significantly contribute to the robustness of a system .

Method overloading occurs when multiple methods with the same name are defined with different parameters, allowing for different implementations based on input parameters. Constructor overloading follows the same concept but applies to constructors, allowing multiple constructors in a class with different parameter lists. An example of method overloading could be a method called 'add' that takes either two integers or two doubles, and constructor overloading could involve constructors that initialize objects with varying types and numbers of input parameters .

Method overloading enhances polymorphism in Java by allowing multiple methods to coexist with the same name but different signatures (i.e., parameter lists). This enables one method call to be resolved to different method bodies based on the types and numbers of arguments passed at runtime. It provides flexibility and clarity in a program's structure by enabling the use of intuitive method names without conflict .

Exception handling in Java increases program reliability by enabling programs to recover from potential runtime errors, and ensures that resources such as file handlers and database connections are properly closed using finally blocks. Effective exception handling can improve maintenance by providing meaningful error alerts and improving the readability and traceability of errors within the codebase. However, improper use can lead to confusing logic and unhandled states if exceptions are not well mapped to potential errors .

You might also like