Java Manual
Java Manual
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");
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
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}};
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));
}
}
Constructor OverLoading:
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.");
}
}
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);
}
}
Output:
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...");
}
}
}
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:
10 20 30 40 50 60 70 80 90 100
10
20
30
40
50
60
70
80
90
100
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;
int a=5,b=0,c,d,f;
try
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;
int k;
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
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.
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;
int x;
Square(int n)
{
x = n;
}
public void run()
int sqr = x * x;
}
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 );
}
}
s.start();
c.start();
try
Thread.sleep(1000);
{
System.out.println(ex);
}
}
}
public class Thread1
{
Number n = new Number();
n.start();
}
Output:
Random Integer generated : 48
Cube of 48 = 110592
Square of 48 = 2304
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
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: