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

Java Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
57 views59 pages

Java Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 59

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

class HelloWorld
{
public static void main(String[] args)
{
System.out.println("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 java.util.Scanner;
public class Question2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double a, b; System.out.println("Enter a
and b: ");a = scan.nextDouble();
b = scan.nextDouble();
System.out.println("Arithmetic Operators:\n");

System.out.printf(" %-15s: %f\n", "Sum", (a+b));


System.out.printf(" %-15s: %f\n", "Difference", (a-b));

System.out.printf(" %-15s: %f\n", "Product", (a*b));

System.out.printf(" %-15s: %d\n", "Quotient", (int)(a/b));

System.out.printf(" %-15s: %d\n", "Reminder", (int)(a%b));

System.out.printf(" %-15s: %f\n", "PostIncrement", a++);

System.out.printf(" %-15s: %f\n", "PreIncrement", ++a);


System.out.println("\nBitwise Operators.\n");
int aa = (int)a;
int bb = (int)b;
System.out.printf(" %-15s: %d\n", "NOT:", ~aa);
System.out.printf(" %-15s: %d\n", "AND", aa&bb);
System.out.printf(" %-15s: %d\n", "OR", aa|bb);
System.out.printf(" %-15s: %d\n", "XOR", aa^bb);
System.out.printf(" %-15s: %d\n", "RightShift", aa>>2);
System.out.printf(" %-15s: %d\n", "LeftShift", aa<<2);
scan.close();
}
}
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 java.util.Scanner;
public class Operators
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double a, b;
System.out.println("Enter a and b: ");a =
scan.nextDouble();
b = scan.nextDouble();
Arithmetic arith = new Arithmetic(); System.out.printf("%-
15s: %f\n", "Sum", arith.sum(a, b));
System.out.printf("%-15s: %f\n", "Difference", arith.diff(a, b));
System.out.printf("%-15s: %f\n", "Product", arith.product(a, b));
System.out.printf("%-15s: %f\n", "Quotient", arith.quotient(a, b));
System.out.printf("%-15s: %f\n", "Reminder", arith.reminder(a, b));
System.out.printf("%-15s: %f\n", "PostIncrement",
arith.postIncrement(a));
System.out.printf("%-15s: %f\n", "PreIncrement",
arith.preIncrement(a));
Bitwise bit = new Bitwise();
int aa = (int)a;
int bb = (int)b;
System.out.printf("%-15s: %d\n", "NOT:", bit.not(~aa));
System.out.printf("%-15s: %d\n", "AND", bit.and(aa, bb));
System.out.printf("%-15s: %d\n", "OR", bit.or(aa, bb));
System.out.printf("%-15s: %d\n", "XOR", bit.xor(aa, bb));
System.out.printf("%-15s: %d\n", "RightShift", bit.rightShift(aa, 2));
System.out.printf("%-15s: %d\n", "LeftShift", bit.leftShift(aa, 2));
scan.close();
}
}
Package LabPracticals;
public class Arithmetic
{
Arithmetic()
{
System.out.println("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()
{
System.out.println("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 java.util.Scanner;
class Employee
{
int id;
String name;
String desig;
float salary;
}
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("How many employees? ");
int n = sc.nextInt();
Employee emp[] = new Employee[n];
for (int i = 0; i < n; i++)
{
emp[i] = new Employee();
System.out.println("Enter " + (i + 1) + " Employee data :");
System.out.print("Enter employee id :");
emp[i].id = sc.nextInt();
System.out.print("Enter employee name :");
emp[i].name = sc.next();
System.out.print("Enter employee designation :");
emp[i].desig = sc.next();
System.out.print("Enter employee salary :");
emp[i].salary = sc.nextFloat();
}
System.out.println(" \n\n********* All Employee Details are :*********\n");
for (int i = 0; i < n; i++)
{
System.out.println("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 java.util.Scanner;
public class Question4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in); int a, b, c;
System.out.println("Enter a, b and c:"); a = scan.nextInt();
b = scan.nextInt(); c = scan.nextInt(); scan.close();
int dis = b*b - 4*a*c;
System.out.println("Quadratic Equation: " + a + "x^2 + " + b + "x + "
+ c + " = 0\n");
if(dis<0)
System.out.println("No real solution");
else
{
System.out.println("Root_1: " + (-b+dis)/(2*a)); System.out.println("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 java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n, a=0, b=1, c;
System.out.println("Enter n:");
n = scan.nextInt(); scan.close();
System.out.println(" \nWithout Using Recursion: ");
System.out.print(a + " " + b + " ");
for(int i=1; i<=n-2; i++)
{
c = a+b;
System.out.print(c + " ");
a = b;
b = c;
}
System.out.println(" \n\nUsing Recursion: ");
for(int i=0; i<n; i++)
{
System.out.print(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 java.util.Scanner;
class PrimeNumbers
{
public static void main(String[] args)
{
int n;
int p;
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
n=s.nextInt();
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)
System.out.println(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 java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
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<result.length; 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;
}
}
System.out.println("Resultant Matrix:");
for(int i=0; i<result.length; i++)
{
for(int j=0; j<result[0].length; j++)
{
System.out.print(result[i][j]+ " ");
}
System.out.println();
}
}
}

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

import java.util.*;
class SortingAscendingOrderNames
{
void sortStrings()
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the value of n: ");
int n = s.nextInt();
String[] str = new String[n];
System.out.println("Enter strings: ");
for(int i = 0; i < n; i++)
{
str[i] = new String(s.next());
}
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;
}
}
}
System.out.println("Sorted list of strings is:");
for(int i = 0; i < n ; i++)
{
System.out.println(str[i]);
}
}
}
class Driver
{
public static void main(String[] args)
{
SortingAscendingOrderNames Names = new SortingAscendingOrderNames ();
Names.sortStrings();
}
}
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()
{
System.out.println("Constructor with No parameters");
}
Add(int a)
{
System.out.println("Single Parameter Constructor: "+a);
}
Add(int a, int b)
{
System.out.println("Two Parameter Constructor: "+(a+b));
}
Add(int a,int b,int c)
{
System.out.println("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)
{
System.out.println("Constructor OverLoading:\n");
MethodConstructorOverLoading obj=new MethodConstructorOverLoading
(10,20,30);
System.out.println("Calling Same Method with Different Parameters: \n");
System.out.println("Method with Single Parameter: "+obj.Sub(10));
System.out.println("Method with Two Parameter: "+obj.Sub(10,20));
System.out.println("Method with Three Parameter: "+obj.Sub(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 java.util.*;
abstract class Shape
{
int length, breadth, radius;
Scanner input = new Scanner(System.in);
abstract void printArea();
}
class Rectangle extends Shape
{
void printArea()
{
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}
class Triangle extends Shape
{
void printArea()
{
System.out.println("\n*** Finding the Area of Triangle ***");
System.out.print("Enter Base And Height: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Triangle is: " + (length * breadth) / 2);
}
}
class Cricle extends Shape
{
void printArea()
{
System.out.println("\n*** Finding the Area of Cricle ***");
System.out.print("Enter Radius: ");
radius = input.nextInt();
System.out.println("The area of Cricle is: " + 3.14f * radius * radius);
}
}
class AbstractClassExample
{
public static void main(String[] args)
{
Rectangle rec = new Rectangle();
rec.printArea();
Triangle tri = new Triangle();
tri.printArea();
Cricle cri = new Cricle();
cri.printArea();
}
}
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()
{
System.out.println("Start Event");
}
public void play()
{
System.out.println("Play Sports.");
}
public void show()
{
System.out.println("Show Hockey.");
}
};
hockey.start();
hockey.play();
hockey.show();
}
}

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

class Parentclass
{
void display()
{
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass
{
void display()
{
System.out.println("Child class method");
}
void printMsg()
{
display();
super.display();
}
public static void main(String args[])
{
Subclass obj= new Subclass();
obj.printMsg();
}
}
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();
v1.companyName("Honda");
v1.vehicleName("Shine");
v1.vehicleType(2);
v1.seatArrangement(2);
OtherFeatures v2 = new Car();

v2.companyName("Rolls Royce");
v2.vehicleName("Rolls-Royce Cullinan");
v2.vehicleType(4);
v2.seatArrangement(4);
v2.mileagePerLiter(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)
{
System.out.println(name + "'s product.");
}
public void vehicleName(String name)
{
System.out.println("Name of vehicle : " + name);
}
public void vehicleType(int i)
{
System.out.println(i + " wheeler.");
}
public void seatArrangement(int i)
{
System.out.println(i + " seater capacity.");
}
}

class Car extends Bike implements OtherFeatures


{
public void mileagePerLiter(int i)
{
System.out.println("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 java.util.*;
class Innerclass
{
Innerclass()
{
System.out.println("I am Outer Class");
}
class Main
{
Main()
{
System.out.println("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();
Innerclass.Main inner_obj=outer_obj.new Main();
System.out.println(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 )
{
System.out.println("Maximum value of two numbers is: " + num1);
}
else
{
System.out.println("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 java.io.*;
class Prg17
{
public static void main(String args[])
{
try
{
int lines=0,chars=0,words=0;
int code=0;
FileInputStream fis = new FileInputStream("test.txt");
while(fis.available()!=0)
{
code = fis.read();
if(code!=10)
chars++;
if(code==32)
words++;
if(code==13)
{
lines++;
words++;
}
}
System.out.println("No.of characters = "+chars);
System.out.println("No.of words = "+(words+1));
System.out.println("No.of lines = "+(lines+1));
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
{
System.out.println("Cannot read file...");
}
}
}

Test.txt ------> text file


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

Output:

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

import java.util.Scanner;
class palindrome
{
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
System.out.println("Enter a string as an input to check whether it is palindrome
or not");
String input= scanner.nextLine();
if(isPalindrome(input))
{
System.out.println(input+" is a palindrome string");
}
else
{
System.out.println(input+" is not a palindrome string");
}
}
public static boolean isPalindrome(String str)
{
int left = 0, right = str.length() - 1;
while(left < right)
{
if(str.charAt(left) != str.charAt(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 java.util.*;
class StringTokenizerDemo
{
public static void main(String args[])
{
int n;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter integers with one space gap:");
String s = sc.nextLine();
StringTokenizer st = new StringTokenizer(s, " ");
while (st.hasMoreTokens())
{
String temp = st.nextToken();
n = Integer.parseInt(temp);
System.out.println(n);
sum = sum + n;
}
System.out.println("sum of the integers is: " + sum);
sc.close();
}
}
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 java.util.Scanner;
class MultiCatchEx3
{
public static void main(String[] args)
{
int x, y;
Scanner sc = new Scanner(System.in);
try
{
System.out.println("Enter your first number");
x = Integer.parseInt(sc.nextLine());
System.out.println("Enter your second number");
y = Integer.parseInt(sc.nextLine());
int z = x / y;
System.out.println("z = " +z);
}
catch(ArithmeticException ae)
{
System.out.println("A number cannot be divided by 0, Illegal operation in
Java");
System.out.println("Exception thrown: " +ae);
}
catch(NumberFormatException nfe)
{
System.out.println("Invalid data types are entered, number must be an
integer.");
System.out.println("Exception thrown: " +nfe);
}
catch(RuntimeException re)
{
System.out.println("Exception thrown: " +re);
}
System.out.println("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:
java.lang.ArithmeticException: / 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: java.lang.NumberFormatException: 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 java.io.FileInputStream;

import java.util.Scanner;

public class Try_Catch

public static void main(String[] args)

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

try

Scanner s=new Scanner(System.in);

System.out.print("Enter a:");

a=s.nextInt();

System.out.print("Enter b:");

b=s.nextInt();

System.out.print("Enter c:");

c=s.nextInt();

d=a/b;

System.out.println(d);

f=a%c;

System.out.println(f);
FileInputStream fis = null;

fis = new FileInputStream("B:/myfile.txt");

int k;

while(( k = fis.read() ) != -1)

System.out.print((char)k);

fis.close();

catch(IndexOutOfBoundsException e)

System.out.println(e);

catch(NullPointerException e)

System.out.println(e);

catch(ArithmeticException e)

System.out.println(e);

catch(Exception e)
{

System.out.println(e);

Output:

Enter a:4

Enter b:5

Enter c:6

java.io.FileNotFoundException: B:/myfile.txt (No such file or directory)


P22: write a program to create user defined exception

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

Output:1
Enter your age
23
Valid age
Output:2
Enter your age
112
InvalidAgeException: Age is not valid
at CheckAge.validateAge(CheckAge.java:9)
at CheckAge.main(CheckAge.java:19)
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)
{
q.put(i++);
if(i== 10)
System.exit(0);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q= q;
new Thread(this, "consumer").start();
}
public void run()
{
while(true)
q.get();
}
}
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)
{
}
}
System.out.println("Producer " +n);
valueset= false;
notify();
return n;
}
synchronized void put(int n)
{
while(valueset)
{
try
{
wait();
}
catch(Exception e)
{
}
}
this.n= n;
valueset =true;
System.out.println("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 java.util.Random;

class Square extends Thread

int x;

Square(int n)

{
x = n;

}
public void run()

int sqr = x * x;

System.out.println("Square of " + x + " = " + sqr );

}
class Cube extends Thread

int x;

Cube(int n)
{

x = n;

}
public void run()

int cub = x * x * x;
System.out.println("Cube of " + x + " = " + cub );

}
}

class Number extends Thread

public void run()


{

Random random = new Random();


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

int randomInteger = random.nextInt(100);

System.out.println("Random Integer generated : " + randomInteger);


Square s = new Square(randomInteger);

s.start();

Cube c = new Cube(randomInteger);

c.start();
try

Thread.sleep(1000);

catch (InterruptedException ex)

{
System.out.println(ex);

}
}

}
public class Thread1

public static void main(String args[])

{
Number n = new Number();

n.start();
}

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 java.util.*;
class ArrayListObjects
{
public static void main(String[] args)
{
ArrayList<String> array_list=new ArrayList<String>();
System.out.println("Enter elements of the Array (Strings) : \n");
Scanner sc=new Scanner(System.in);
int size_of_array=sc.nextInt();
System.out.println("Enter "+size_of_array+" Array Names: \n");
for(int i=0;i<size_of_array;i++)
{
array_list.add(sc.next());
}
System.out.println("The List of Array are: ");
int count=0;
for(String i:array_list)
{
count++;
System.out.println(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 java.util.*;
class ArrayAddSearchRemove
{
public static void main(String [] args)
{
ArrayList<String> Fruits=new ArrayList<String>();
Scanner sc=new Scanner(System.in);
boolean flag=true;
while(flag)
{
System.out.println("Enter 1. Add Fruit \n 2. Search Fruit \n 3. Remove Fruit \n
4. Exit");
int option=sc.nextInt();
switch(option)
{
case 1:
System.out.println("Enter How many Fruits You want to add");
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
Fruits.add(sc.next());
}
System.out.println("The Final Fruit list is: \n");
System.out.println(Fruits);
break;
case 2: System.out.println("Enter Fruit name to Search");
String fruit_names=sc.next();
boolean search_result=Fruits.contains(fruit_names);
if(search_result)
{
System.out.println(fruit_names+" is in the Fruits list");
}
else
{
System.out.println(fruit_names+" is not there in the Fruit list");
}
break;
case 3: System.out.println("Enter Fruite Name to Remove from the list");
String fruit_name=sc.next();
Fruits.remove(fruit_name);
System.out.println("After Removed "+fruit_name+" the list of Friuts are: \n");
System.out.println(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

You might also like