Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 74

P-1 WAP to print some statements like “Hello World!”.

class demo{

public static void main(String args[])

System.out.println("Hello World"); }

}
P- 2 WAP to calculate room area using multiple classes.
import java.util.Scanner;
class demo
{
public static void main(String args[])
{

Scanner s= new Scanner(System.in);

System.out.println("Enter the length:");


double l= s.nextDouble();
System.out.println("Enter the breadth:");
double b= s.nextDouble();

double area=l*b;
System.out.println("Area of Rectangle is: " + area);
}
}
P-3 WAP to demonstrate the use of command line arguments.
class demo{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}
P-4. WAP to explain the basic data types used in java.

class demo {
public static void main(String args[])
{
char a = 'G';
int i = 89;
byte b = 4;
short s = 56;
double d = 4.355453532;
float f = 4.7333434f;

System.out.println("char: " + a);


System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
}
}
P-5. WAP to explain the type casting in java.

Implicit Typecasting :

class demo {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt;

System.out.println(myInt);
System.out.println(myDouble);
}
}

Explicit Typecasting:

class demo {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble;

System.out.println(myDouble);
System.out.println(myInt);
}
}
P-6 WAP to demonstrate java expressions using different operators
in java like relational, logical, bitwise operators etc.

Unary Operator:

class demo{

public static void main(String args[]){

int x=10;

System.out.println(x++);

System.out.println(++x);

System.out.println(x--);

System.out.println(--x);

Arithmetic Operator:

class demo{

public static void main(String args[]){

int a=10;

int b=5;

System.out.println(a+b);

System.out.println(a-b);

System.out.println(a*b);

System.out.println(a/b);

System.out.println(a%b);

}}
Java Left Shift Operator:

class demo{

public static void main(String args[]){

System.out.println(10<<2);

System.out.println(10<<3);

System.out.println(20<<2);

System.out.println(15<<4);

}}

Right Shift Operator:

class demo{

public static void main(String args[]){

System.out.println(10>>2);

System.out.println(20>>2);

System.out.println(20>>3);

}}

AND Operator Example: Logical && and Bitwise &:

class demo{

public static void main(String args[]){


int a=10;

int b=5;

int c=20;

System.out.println(a<b&&a<c);

System.out.println(a<b&a<c);

}}

OR Operator Example: Logical || and Bitwise | :

class demo{

public static void main(String args[]){

int a=10;

int b=5;

int c=20;

System.out.println(a>b||a<c);

System.out.println(a>b|a<c);

System.out.println(a>b||a++<c);

System.out.println(a);

System.out.println(a>b|a++<c);

System.out.println(a);

}}

Ternary Operator:

class demo{

public static void main(String args[]){


int a=2;

int b=5;

int min=(a<b)?a:b;

System.out.println(min);

}}

Assignment Operator:

class demo{

public static void main(String args[]){

int a=10;

int b=20;

a+=4;

b-=4;

System.out.println(a);

System.out.println(b);

}}
P-7. WAP to demonstrate if-else, nested if-else, if-else ladder.
publicclass Condition {
publicstaticvoidmain(String[] args)
{
ifElse(10);
nestedIfElse(12);
ifElseLadder(1000);

// If Else
publicstaticvoidifElse(int a)
{
if (a<5)
{
System.out.println("Value is below 5 i.e." + a);
}
else
{
System.out.println("Value is greater than 5 i.e." +a );
}
}

// nested if-else
publicstaticvoidnestedIfElse(int a)
{
if (a<10) {
if(a<5)
{
System.out.println("Value is less than 5 i.e. "+a);
}
else
{
System.out.println("Value is greater than 5 i.e."+a);
}
}
else
System.out.println("Value is greater than 10 i.e." +a);
}

//if else ladder


publicstaticvoidifElseLadder(int a)
{
if (a<5)
{
System.out.println("Value is less than 5 i.e." +a);
}
elseif (a<10)
{
System.out.println("Value is less than 10 i.e. "+a);
}
elseif (a<20)
{
System.out.println("Value is less than 20 i.e. "+a);
}
elseif (a<30)
{
System.out.println("Value is less than 30 i.e. "+a);
}
else
System.out.println("Value is too high.");

}
P-8. WAP to demonstrate switch statements.

publicclass Switch {

publicstaticvoidmain(String[] Args )
{
switchUse("Robin") ;
}

publicstaticvoidswitchUse(String name)
{
switch(name)
{
case "Robin":
{
System.out.println("Robin is being printed.");
break;
}
case "Tom":
{
System.out.println("Tom is being printed.");
break;
}
case "Zoobie":
{
System.out.println("Zoobie is being printed.");
break;
}
case "Alex":
{
System.out.println("Alex is being printed.");
break;
}

default:
System.out.println("Name is not in the switch statement.");

}
P-9. WAP to demonstrate “? :” operator.
publicclassTernaryOperator {

publicstaticvoidmain(String [] Args)
{

ternaryOperator("Tom");
}

publicstaticvoidternaryOperator(String name)
{
name = (name.equals("Robin"))? "Yes, the name is Robin": "Name is not Robin" ;
System.out.println(name);

}
P-10. WAP to explain the working of while, for and do while loops.
publicclass Loops {

publicstaticvoidmain(String[] args)
{

forLoop();
whileLoop();
do_WhileLoop();
}

publicstaticvoidforLoop()
{
{
System.out.println("Using For Loop");
for(int x=1;x<=5;x++)
{
System.out.println("value of x is = "+x );
}
System.out.println("__________________");
}
}
publicstaticvoidwhileLoop()
{
{
System.out.println("Using While Loop");
int y = 6;
while(y<=10)
{
System.out.println("value of y is = "+y);
y++;
}
System.out.println("__________________");
}

publicstaticvoiddo_WhileLoop()
{
{
System.out.println("Using Do_While Loop");
int z = 11;
do
{
System.out.println("value of z is = "+z);
z++;
}
while(z<=15);
}
}
}
P-11. WAP to demonstrate different types of constructors in java like default and
parameterize.

publicclassConstructorCaller {

publicstaticvoidmain(String[] args) {
Constructor c1 = newConstructor();
Constructor c2 = newConstructor("Rahul" , 12);
Constructor c3 = new Constructor("Rohit");

System.out.println(c1);
System.out.println(c2);
System.out.println(c3);

publicclass Constructor {

// user defined no arg constructor

String name;
int age;

publicConstructor()
{
System.out.println("This is the user defined no arg constructor.");
}
publicConstructor(String name , int age)
{
this.name = name;
this.age = age;
System.out.println("This is the constructor which initializes the value for the instance variabel name
and age");
}

publicConstructor(String name)
{
this(name, 23);
System.out.println("This is the constructor which is calling the other constructor");
}

public String getName()


{
return name;
}

publicintgetAge()
{
return age;
}

@Override
public String toString()
{
returngetName()+ " " + getAge();
}

}
P-12. WAP to explain method overloading and constructor overloading.

package college;
class Box
{
double width, height, depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = height = depth = 0;
}
// constructor used when cube is created
Box(doublelen)
{
width = height = depth = len;
}
// compute and return volume
doublevolume( )
{
return width * height * depth;
}
}

publicclass test
{
publicstaticvoidmain(String args[])
{
// create boxes using the various constructors
Box mybox1 = newBox(10, 20, 15);
Box mybox2 = newBox();
Box mycube = newBox(7);

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
}
}

OUTPUT
P-13. WAP to explain static methods and static members.
package college;
//Java program to demonstrate execution of static methods and static members
class test {
// static variable
staticinta = m1();

// static block
static
{
System.out.println("Inside static block");
}

// static method
staticint m1()
{
System.out.println("from m1");
return 20;
}

// static method(main !!)


publicstaticvoidmain(String[] args)
{
System.out.println("Value of a : " + a);
System.out.println("from main");
}
}

OUTPUT
P-14. WAP to demonstrate multilevel inheritance and super keyword.

package college;

class One
{
voidmessage()
{
System.out.println("This is One");
}
}

class Two extends One


{
voidmessage()
{
System.out.println("This is Two");
}
}
class Three extends Two
{
voidmessage()
{
System.out.println("This is Three");
}

// Note that display() is only in Three


voiddisplay()
{
// will invoke or call current class message() method
message();

// will invoke or call parent class message() method


super.message();
}
}

class test2
{
publicstaticvoidmain(String args[])
{
Three s = newThree();

// calling display() of Student


s.display();
}
}
OUTPUT
P-15. WAP to demonstrate method overriding in hierarchical inheritance.

package college;

class A
{
publicvoidmethod()
{
System.out.println("method of Class A");
}
}

class B extends A
{
publicvoidmethod()
{
System.out.println("method of Class B");
super.method();
}
}

class C extends A
{
publicvoidmethod()
{
System.out.println("method of Class C");
super.method();
}
}

class D extends A
{
publicvoidmethod()
{
System.out.println("method of Class D");
}
}
publicclass test15 {
publicstaticvoidmain(String args[])
{
B obj1 = newB( );
C obj2 = newC( );
D obj3 = newD( );
obj1.method( );
obj2.method( );
obj3.method( );
}

}
OUTPUT
P-16. WAP to explain the working of final classes and also use final methods and final
variables in your program.

package college;

finalpublicclass test16
{
finalvoidgetMethod()

{
System.out.println("method has been called");
}

publicstaticvoidmain(String[] args)

finalint hours=24;

System.out.println("Hours in 6 days = " + hours * 6);

}
}

OUTPUT
P-17. WAP to explain the concept of finalization.
package college;

class Bye {
publicstaticvoidmain(String[] args)
{
Bye m = newBye();

// Calling finalize method Explicitly.


m.finalize(); //call by programmer but object won't gets destroyed.
m = null;

// Requesting JVM to call Garbage Collector method


System.gc();
System.out.println("Main Completes");
}

// Here overriding finalize method


publicvoidfinalize()
{
System.out.println("finalize method overriden");
}
//call by Garbage Collector just before destroying the object.
}

Note : As finalize is a method and not a reserved keyword, so we can call finalize method Explicitly, then it will be
executed just like normal method call but object won’t be deleted/destroyed.

OUTPUT
P-18. WAP to demonstrate the use of abstract methods and abstract classes.

package college;
abstractclass Base {
Base(){System.out.println("Base Constructor Called");}
abstractvoidfun();
}
class Derived extends Base {
Derived(){System.out.println("Derived Constructor Called");}
voidfun() { System.out.println("Derived fun() called"); }
}
class Main {
publicstaticvoidmain(String args[]) {

// Uncommenting the following line will cause compiler error as the


// line tries to create an instance of abstract class.
// Base b = new Base();
// We can have references of Base type.
Base b = newDerived();
b.fun();
}
}
OUTPUT
P-19. WAP to demonstrate the use of access modifiers (Private, protected, public and
default).
As the name suggests access modifiers in Java helps to restrict the scope of a class, constructor , variable , method or
data member. There are four types of access modifiers available in java:
1. Default – No keyword required
2. Private
3. Protected
4. Public

package college;

//Class D_Access is having Default access modifier


classD_Access
{
voiddisplay()
{
System.out.println("Default:accessible only within the same package.");
}
}
classPri_Access
{ //method display is having private access modifier
privatevoiddisplay()
{
System.out.println("Private:only visible within the enclosing class.");
}
}
classPro_Access
{ //method display is having protected access modifier
protectedvoiddisplay()
{
System.out.println("Protected:accessible within same package or sub classes in different package.");
}
}

publicclass Access
{ //Class is having Public access modifier
publicvoiddisplay()
{
System.out.println("Public:Accessible from Everywhere");
}
publicstaticvoidmain(String[] args) {
D_Access d = newD_Access();
Pri_Accessp = newPri_Access();
Pro_Accesspr = newPro_Access();
Access pb = newAccess();
d.display();
//p.display(); This cannot be called as display is Private
pr.display();
pb.display();
}
}

OUTPUT
P-20. WA menu driven program to add, subtract and multiply two matrices.
package college;
importjava.util.Scanner;
publicclass matrix {
publicstaticvoidmain(String...args)
{
Scanner scanner = newScanner(System.in);
System.out.print("Enter number of rows in matrix : ");
int rows = scanner.nextInt();
System.out.print("Enter number of columns in matrix : ");
int columns = scanner.nextInt();
int[][] matrix1 = newint[rows][columns];
int[][] matrix2 = newint[rows][columns];

System.out.println("Enter the elements in first matrix :");


for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
matrix1[i][j] = scanner.nextInt();
}
}
System.out.println("Enter the elements in second matrix :");
for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

System.out.println("\nFirst matrix is : ");


for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.println();
}
System.out.println("\nSecond matrix is : ");
for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix2[i][j] + " ");
}
System.out.println();
}

System.out.println("\nEnter Choice for Action");


System.out.println("1: Addition of Matrix");
System.out.println("2: Subtraction of Matrix");
System.out.println("3: Multiplication of Matrix");
int a = scanner.nextInt();

if(a==1) {
//Addition of matrices.
int[][] resultMatix = newint[rows][columns];
for (inti = 0; i< rows; i++)
{
for (int j = 0; j < columns; j++)
{
resultMatix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

System.out.println("\nThe sum of the two matrices is : ");


for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(resultMatix[i][j] + " ");
}
System.out.println();
}
}

if(a==2) {
//Subtraction of matrices.
int[][] resultMatix2 = newint[rows][columns];
for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
resultMatix2[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
System.out.println("\nThe subtraction of the two matrices is : ");
for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(resultMatix2[i][j] + " ");
}
System.out.println();
}
}

if(a==3) {
//Multiply matrices
int[][] productMatrix = newint[rows][columns];
for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
for (int k = 0; k < columns; k++) {
productMatrix[i][j] = productMatrix[i][j] + matrix1[i][k] * matrix2[k][j];
}
}
}

System.out.println("\nProduct of matrix1 and matrix2 is");


for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(productMatrix[i][j] + " ");
}
System.out.println();
}
}
}
}
OUTPUT
21.WA menu driven program for selection sort, merge sort and quick sort.
package college;
import java.util.Scanner;
public class sort
{ static int arr[] = {64,25,12,22,11};
void selsort(int arr[])
{
int n = arr.length;// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++) { // Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}}
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j=low; j<high; j++) {
if (arr[j] < pivot) { // If current element is smaller than the pivot
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
/* The main function that implements QuickSort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quicksort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
quicksort(arr, low, pi-1);
quicksort(arr, pi+1, high);
}
}
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
} }
void mergesort(int arr[], int l, int r) // Main function that sorts arr[l..r] using merge()
{
if (l < r) {
int m = (l+r)/2;
mergesort(arr, l, m);
mergesort(arr , m+1, r);
merge(arr, l, m, r);
} }
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String[] args) {
System.out.println("The given array is");
int n = arr.length;
int choice;
sort s = new sort();
s.printArray(arr);
System.out.println("\nEnter 1 for selection sort");
System.out.println("Enter 2 for quick sort");
System.out.println("Enter 3 for merge sort");
Scanner sc = new Scanner(System.in);
choice = sc.nextInt();
if(choice ==1) {
s.selsort(arr);
System.out.println("Array After Selection Sort");
s.printArray(arr);}
choice = sc.nextInt();
if(choice==2) {
s.quicksort(arr, 0, n-1);
System.out.println("Array After Quick Sort");
s.printArray(arr);}
choice = sc.nextInt();
if(choice==3) {
s.mergesort(arr, 0, arr.length-1);
System.out.println("Array After Merge Sort");
s.printArray(arr);}
choice = sc.nextInt();
if(choice<=4)
System.out.println("Enter a valid choice");
}}
22. WAP in which you have to make a table to store name of students, age, course,
roll no and this table can be ordered in following ways:
 1: Alphabetical order (A to Z or Z to A) of name
 2: smallest to greatest or greatest to smallest order of age
 3: Ascending or descending order of roll no
 4: Bachelor to master or master to bachelor order of course
package college;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Table extends JFrame{
JFrame f;
JTable j;
// Constructor
Table()
{
f = new JFrame();
f.setBounds(100,100,500,400);
f.setTitle("Table Student Details");
// Data to be displayed in the JTable
String[][] data = {
{"Ahmad Faraz","21", "BTECH","012"}, {"Abid Ali","23", "MTECH","009"},
{"Adeeb","19", "BCA","010"}, {"Ilmaan","25", "MCA", "013"}};
String[] columnNames = { "Name","Age", "Course", "Roll Number"};
j = new JTable(data, columnNames);
JScrollPane sp = new JScrollPane(j);
j.setAutoCreateRowSorter(true);
f.add(sp);
f.setVisible(true);
}
public static void main(String[] args)
{
new Table();
}
}
OUTPUT
22(1) - ALPHABETICAL ORDER OF NAME (A-Z) or (Z-A)

22(2) - ORDER OF AGE (Ascending or Descending)

22(3) - ORDER OF COURSE


22(4) - ORDER OF ROLL NO.

P-23..WAP to demonstrate the commonly used “String” and “String Buffer” class
methods.
package college;
import java.io.*;
class Str {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("the end is near");
int p = s.length(); //Gives the Length of String
int q = s.capacity(); //Gives the Capacity Of String
System.out.println("Length of string the end is near=" + p);
System.out.println("Capacity of string the end is near=" + q);
s.append(": 2019"); //Adds : 2019 to the existing string
System.out.println(s);
s.insert(0,4 ); //Inserts 4 at position 0
System.out.println(s);
s.delete(0, 4); //Delete 4char from position 0
System.out.println(s);
s.deleteCharAt(6); //Performs char deletion at 6
System.out.println(s);
s.replace(5, 7, "ar "); //replaces the char from 5 to 7 by ar
System.out.println(s);
s.reverse(); //Reverses the String
System.out.println(s);
}
}
OUTPUT
P-24.WAP to demonstrate Wrapper class methods.
package college;

public class wrapper


{
public static void main(String args[])
{
//byte data type
byte a = 1;

// wrapping around Byte object


Byte byteobj = new Byte(a);

// int data type


int b = 10;

//wrapping around Integer object


Integer intobj = new Integer(b);

// float data type


float c = 18.6f;

// wrapping around Float object


Float floatobj = new Float(c);

// double data type


double d = 250.5;

// Wrapping around Double object


Double doubleobj = new Double(d);

// char data type


char e='a';

// wrapping around Character object


Character charobj=e;

// printing the values from objects


System.out.println("Values of Wrapper objects (printing as objects)");
System.out.println("Byte object byteobj: " + byteobj);
System.out.println("Integer object intobj: " + intobj);
System.out.println("Float object floatobj: " + floatobj);
System.out.println("Double object doubleobj: " + doubleobj);
System.out.println("Character object charobj: " + charobj);

// objects to data types (retrieving data types from objects)


// unwrapping objects to primitive data types
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;

// printing the values from data types


System.out.println("Unwrapped values (printing as data types)");
System.out.println("byte value, bv: " + bv);
System.out.println("int value, iv: " + iv);
System.out.println("float value, fv: " + fv);
System.out.println("double value, dv: " + dv);
System.out.println("char value, cv: " + cv);
}
}

OUTPUT
P-25.WAP to explain interfaces in java.

package college;
importjava.io.*;

//A simple interface


interface In1
{
// public, static and final
finalinta = 10;

// public and abstract


voiddisplay();
}

//A class that implements the interface.


class Test25 implements In1
{
// Implementing the capabilities of
// interface.
publicvoiddisplay()
{
System.out.println("The value of a is: ");
}

publicstaticvoid main (String[] args)


{
Test25 t = new Test25();
t.display();
System.out.println(a);
}
}
OUTPUT
P 26- WAP to demonstrate multiple inheritance in java
// First Parent class
class Parent1
{
voidfun()
{
System.out.println("Parent1");
}
}

// Second Parent Class


class Parent2
{
voidfun()
{
System.out.println("Parent2");
}
}

// Error : Test is inheriting from multiple


// classes
class Test extends Parent1, Parent2
{
publicstaticvoidmain(String args[])
{
Test t = newTest();
t.fun();
}
}

OUTPUT-
P 27- WAP to demonstrate package in java

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
OUTPUT-
P-28: WAP to explain static import in java with package.

import static java.lang.System.*;

class demo{

public static void main(String args[]){

out.println("Hello");//Now no need of System.out

out.println("Java");

}
P 29- WAP to demonstrate threading in java using thread class
class Multi extendsThread{
publicvoidrun(){
System.out.println("thread is running...");
}
publicstaticvoidmain(String args[]){
Multi t1=newMulti();
t1.start();
}
}
OUTPUT-
P-30: WAP to demonstrate threading in java using Runnable interface.

class RunnableDemo {

public static void main(String[] args)

System.out.println("Main thread is- "

+ Thread.currentThread().getName());

Thread t1 = new Thread(new RunnableDemo().new RunnableImpl());

t1.start();

private class RunnableImpl implements Runnable {

public void run()

System.out.println(Thread.currentThread().getName()

+ ", executing run() method!");

}
P31-WAP to explain try and catch statements in java
publicclass TryCatchExample2 {

publicstaticvoidmain(String[] args) {
try
{
intdata=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

OUTPUT-
P 32- WAP to demonstrate exception handling using multiple catch statements and finally
block
publicclass MultipleCatchBlock1 {

publicstaticvoidmain(String[] args) {

try{
inta[]=newint[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
finally {
System.out.println("rest of the code");
}
}
}

OUTPUT-
P 33- WAP to demonstrate the use of throw and throws keyword in java
classThrowExcep
{
staticvoidfun()
{
try
{
thrownewNullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}

publicstaticvoidmain(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}

OUTPUT-

classtst
{
publicstaticvoidmain(String[] args)throwsInterruptedException
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}

OUTPUT-
P 34- WAP to demonstrate Applet with all the states used in it.
package java_program;
import java.awt.*;
import java.applet.Applet;
import javax.swing.JOptionPane;

public class AppletLifecycle extends Applet {

TextArea messages = new TextArea(8, 30);

public AppletLifecycle() {
add(messages);
messages.append("Constructor executed\n");
}
public void init() {
messages.append("init method executed\n");
}
public void start() {
messages.append("start method executed\n");
}
public void paint(Graphics g) {
messages.append("Paint called\n");
}

public void stop() {


JOptionPane.showMessageDialog(null, "Stop method executed");
}

public void destroy() {


JOptionPane.showMessageDialog(null, "Destory method executed");
}

}
P-35: WAP to make graphic calculator.
package java_program;
import java.awt.*;
import java.awt.event.*;

public class MyCalculator extends Frame


{

public boolean setClear=true;


double number, memValue;
char op;

String digitButtonText[] = {"7", "8", "9", "4", "5", "6", "1", "2", "3", "0",
"+/-", "." };
String operatorButtonText[] = {"/", "sqrt", "*", "%", "-", "1/X", "+", "=" };
String memoryButtonText[] = {"MC", "MR", "MS", "M+" };
String specialButtonText[] = {"Backspc", "C", "CE" };

MyDigitButton digitButton[]=new MyDigitButton[digitButtonText.length];


MyOperatorButton operatorButton[]=new
MyOperatorButton[operatorButtonText.length];
MyMemoryButton memoryButton[]=new MyMemoryButton[memoryButtonText.length];
MySpecialButton specialButton[]=new MySpecialButton[specialButtonText.length];

Label displayLabel=new Label("0",Label.RIGHT);


Label memLabel=new Label(" ",Label.RIGHT);

final int FRAME_WIDTH=325,FRAME_HEIGHT=325;


final int HEIGHT=30, WIDTH=30, H_SPACE=10,V_SPACE=10;
final int TOPX=30, TOPY=50;

MyCalculator(String frameText)//constructor
{
super(frameText);

int tempX=TOPX, y=TOPY;


displayLabel.setBounds(tempX,y,240,HEIGHT);
displayLabel.setBackground(Color.RED);
displayLabel.setForeground(Color.WHITE);
add(displayLabel);

memLabel.setBounds(TOPX, TOPY+HEIGHT+ V_SPACE,WIDTH, HEIGHT);


add(memLabel);

// set Co-ordinates for Memory Buttons


tempX=TOPX;
y=TOPY+2*(HEIGHT+V_SPACE);
for(int i=0; i<memoryButton.length; i++)
{
memoryButton[i]=new MyMemoryButton(tempX,y,WIDTH,HEIGHT,memoryButtonText[i],
this);
memoryButton[i].setForeground(Color.RED);
y+=HEIGHT+V_SPACE;
}

//set Co-ordinates for Special Buttons


tempX=TOPX+1*(WIDTH+H_SPACE); y=TOPY+1*(HEIGHT+V_SPACE);
for(int i=0;i<specialButton.length;i++)
{
specialButton[i]=new
MySpecialButton(tempX,y,WIDTH*2,HEIGHT,specialButtonText[i], this);
specialButton[i].setForeground(Color.RED);
tempX=tempX+2*WIDTH+H_SPACE;
}

//set Co-ordinates for Digit Buttons


int digitX=TOPX+WIDTH+H_SPACE;
int digitY=TOPY+2*(HEIGHT+V_SPACE);
tempX=digitX; y=digitY;
for(int i=0;i<digitButton.length;i++)
{
digitButton[i]=new MyDigitButton(tempX,y,WIDTH,HEIGHT,digitButtonText[i],
this);
digitButton[i].setForeground(Color.BLUE);
tempX+=WIDTH+H_SPACE;
if((i+1)%3==0){tempX=digitX; y+=HEIGHT+V_SPACE;}
}

//set Co-ordinates for Operator Buttons


int opsX=digitX+2*(WIDTH+H_SPACE)+H_SPACE;
int opsY=digitY;
tempX=opsX; y=opsY;
for(int i=0;i<operatorButton.length;i++)
{
tempX+=WIDTH+H_SPACE;
operatorButton[i]=new
MyOperatorButton(tempX,y,WIDTH,HEIGHT,operatorButtonText[i], this);
operatorButton[i].setForeground(Color.RED);
if((i+1)%2==0){tempX=opsX; y+=HEIGHT+V_SPACE;}
}

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{System.exit(0);}
});

setLayout(null);
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setVisible(true);
}

static String getFormattedText(double temp)


{
String resText=""+temp;
if(resText.lastIndexOf(".0")>0)
resText=resText.substring(0,resText.length()-2);
return resText;
}

public static void main(String []args)


{
new MyCalculator("Calculator");
}
}

class MyDigitButton extends Button implements ActionListener


{
MyCalculator cl;
MyDigitButton(int x,int y, int width,int height,String cap, MyCalculator clc)
{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
static boolean isInString(String s, char ch)
{
for(int i=0; i<s.length();i++) if(s.charAt(i)==ch) return true;
return false;
}
public void actionPerformed(ActionEvent ev)
{
String tempText=((MyDigitButton)ev.getSource()).getLabel();

if(tempText.equals("."))
{
if(cl.setClear)
{cl.displayLabel.setText("0.");cl.setClear=false;}
else if(!isInString(cl.displayLabel.getText(),'.'))
cl.displayLabel.setText(cl.displayLabel.getText()+".");
return;
}

int index=0;
try{
index=Integer.parseInt(tempText);
}catch(NumberFormatException e){return;}

if (index==0 && cl.displayLabel.getText().equals("0")) return;

if(cl.setClear)
{cl.displayLabel.setText(""+index);cl.setClear=false;}
else
cl.displayLabel.setText(cl.displayLabel.getText()+index);
}//actionPerformed
}//class defination

class MyOperatorButton extends Button implements ActionListener


{
MyCalculator cl;

MyOperatorButton(int x,int y, int width,int height,String cap, MyCalculator


clc)
{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
public void actionPerformed(ActionEvent ev)
{
String opText=((MyOperatorButton)ev.getSource()).getLabel();

cl.setClear=true;
double temp=Double.parseDouble(cl.displayLabel.getText());

if(opText.equals("1/x"))
{
try
{double tempd=1/(double)temp;
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(opText.equals("sqrt"))
{
try
{double tempd=Math.sqrt(temp);
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(!opText.equals("="))
{
cl.number=temp;
cl.op=opText.charAt(0);
return;
}
// process = button pressed
switch(cl.op)
{
case '+':
temp+=cl.number;break;
case '-':
temp=cl.number-temp;break;
case '*':
temp*=cl.number;break;
case '%':
try{temp=cl.number%temp;}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
case '/':
try{temp=cl.number/temp;}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
}//switch

cl.displayLabel.setText(MyCalculator.getFormattedText(temp));
//cl.number=temp;
}//actionPerformed
}//class

class MyMemoryButton extends Button implements ActionListener


{
MyCalculator cl;

MyMemoryButton(int x,int y, int width,int height,String cap, MyCalculator clc)


{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
public void actionPerformed(ActionEvent ev)
{
char memop=((MyMemoryButton)ev.getSource()).getLabel().charAt(1);
cl.setClear=true;
double temp=Double.parseDouble(cl.displayLabel.getText());

switch(memop)
{
case 'C':
cl.memLabel.setText(" ");cl.memValue=0.0;break;
case 'R':
cl.displayLabel.setText(MyCalculator.getFormattedText(cl.memValue));break
;
case 'S':
cl.memValue=0.0;
case '+':
cl.memValue+=Double.parseDouble(cl.displayLabel.getText());
if(cl.displayLabel.getText().equals("0") ||
cl.displayLabel.getText().equals("0.0") )
cl.memLabel.setText(" ");
else
cl.memLabel.setText("M");
break;
}//switch
}//actionPerformed
}//class

class MySpecialButton extends Button implements ActionListener


{
MyCalculator cl;

MySpecialButton(int x,int y, int width,int height,String cap, MyCalculator clc)


{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
static String backSpace(String s)
{
String Res="";
for(int i=0; i<s.length()-1; i++) Res+=s.charAt(i);
return Res;
}
public void actionPerformed(ActionEvent ev)
{
String opText=((MySpecialButton)ev.getSource()).getLabel();
//check for backspace button
if(opText.equals("Backspc"))
{
String tempText=backSpace(cl.displayLabel.getText());
if(tempText.equals(""))
cl.displayLabel.setText("0");
else
cl.displayLabel.setText(tempText);
return;
}
//check for "C" button i.e. Reset
if(opText.equals("C"))
{
cl.number=0.0; cl.op=' '; cl.memValue=0.0;
cl.memLabel.setText(" ");
}

//it must be CE button pressed


cl.displayLabel.setText("0");cl.setClear=true;
}//actionPerformed
}//class
P 37- Write two different programs to copy a file in another file by character by character and byte
by byte methods.

import java.io.*;
class CopyDataFiletoFile
{
public static void main(String args[])throws IOException
{
FileInputStream Fread =new FileInputStream("Hello.txt");
FileOutputStream Fwrite=new FileOutputStream("Hello1.txt") ;
System.out.println("File is Copied");
int c;
while((c=Fread.read())!=-1)
Fwrite.write((char)c);
Fread.close();
Fwrite.close();
}
}

OUTPUT:-

// Copy a File in Another File by Byte by Byte method


import java.io.*;
public class BStream
{
public static void main(String[] args) throws IOException
{
FileInputStream Dread = null;
FileOutputStream Dwrite = null;

try
{
Dread = new FileInputStream("Anuj.txt");
Dwrite = new FileOutputStream ("Anuj1.txt");

// Reading source file and writing content to target


// file byte by byte
int temp;
while ((temp = Dread.read()) != -1)
Dwrite.write((byte)temp);
System.out.println("File Copied");
}
finally
{
if (Dread != null)
Dread.close();
if (Dwrite != null)
Dwrite.close();
}
}
}

OUTPUT::-
P 37- Write a Java application to print Pascal’s triangle

classPascalTriangle
{
publicstaticvoidmain(String args[])
{
inti,r=5,number,k,j;
// r is number of rows
for(i=0; i<r; i++)
{
for(k=r; k>i; k--)
{
System.out.print(" ");
}
number = 1;
for(j=0; j<=i; j++)
{
System.out.print(number+ " ");
number = number * (i-j) / (j+1);
}
System.out.println();
}
}
}

OUTPUT-
P 38- Write a Java program to compute the following series-
1 – x + x^2/2! – x^3/3! + x^4/4!....+(-/+1)nx^n/n! where x and n is accepted by user

importjava.util.Scanner;
classFactorialSeries
{
publicstaticintfact(int index)
{
int f=1,i;
for(i=1; i<=index; i++)
{
// to find factorial
f = f*i;
}
return f;
}
publicstaticvoidmain(String[] args)
{
intn,x,i,num=-1;
doublefrac,sum = 0;
Scanner sc = newScanner(System.in);
System.out.println("Enter n: ");
n =sc.nextInt();
System.out.println("Enter x: ");
x = sc.nextInt();
for(i=1; i<=n; i++)
{
frac = Math.pow(num,i)*((i*Math.pow(x,i))/fact(i));
sum = sum + frac;
}
System.out.println("Answer = " +sum);
}
}

OUTPUT-
P-39. Define a class BankAccount with appropriate member variables and methods
to deposit and withdraw amount. Refine BankAccount to SavingBankAccount and
CurrentBankAccount using inheritance. Use them in main class to demonstrate
dynamic method dispatch.

package college;
import java.util.Scanner;

class BankAccount
{
String Name;
int Amount;
int Balance=1000;
Scanner sc = new Scanner(System.in);

void showinfo()
{
System.out.println("Enter Name");
Name = sc.next();
System.out.println("Name = " +Name);
System.out.println("Balance = "+Balance);
}
void deposit()
{
System.out.println("Enter Amount to be Deposited");
Amount = sc.nextInt();
Balance = Balance + Amount ;
System.out.println("Updated Balance = "+Balance);

}
void withdraw()
{
System.out.println("Enter Amount to be Withdraw");
Amount = sc.nextInt();
if(Amount<Balance){
Balance = Balance - Amount ;}
else { System.out.println("Amount = Aukat se Bahar");}
System.out.println("Balance After withdrawing = "+Balance);
}
}
class SavingBankAccount extends BankAccount
{
void svaccount()
{
System.out.println("\nThis is savings Account ");
super.showinfo();
super.deposit();
super.withdraw();
}
}

class CurrentBankAccount extends SavingBankAccount


{
void curraccount()
{
System.out.println("\nThis is Current Account");
super.withdraw();
}
}

public class Account {


public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter Choice: Savings or Current Account?");
int Input = s.nextInt();
CurrentBankAccount c = new CurrentBankAccount();
if(Input==1)
{
c.svaccount();
}
if(Input==2)
{
c.curraccount();
}
else
{
System.out.println("Enter a Valid Choice");
}
}
}

OUTPUT:
P 40- Create an abstract class Shape and derived classes Rectangle and Circle from Shape class.
Implement abstract method of shape class in Rectangle and Circle class. Shape class contains:
origin (x,y) as data member, display() and area() as abstract methods. Circle class contains: radius
as data member. Rectangle class contains: length and width. (Use Inheritance, overloading and
overriding concept)

import java.util.Scanner;
abstract class Shape
{

public double x;
public float y;
abstract void display();
abstract void area();
}
class Circle extends Shape
{
private float radius;

public void area()


{

System.out.println("\n Enter the radius of Circle ::-");


Scanner sc= new Scanner(System.in);
radius=sc.nextFloat();

x=(3.14*radius*radius);
}

public void display()


{

System.out.println("\n Area of the Circle is :::- "+ x );


}

class Rectangle extends Shape


{

private float length;


private float width;

public void area()


{
System.out.println("\n Enter the two sides of the Rectangle :::- ");
Scanner sc= new Scanner(System.in);
width=sc.nextFloat();
length= sc.nextFloat();
y=(length*width);
}

public void display()


{
System.out.println("\n Area of the Rectangle is ::: - "+ y);
}

class TestShapeLen
{
public static void main(String an[])
{
Shape ob;
System.out.println(" \n 1 Circle \n 2 Rectangle");
System.out.println("\n Enter your Choice \n");
Scanner sc = new Scanner(System.in);
int ch=sc.nextInt();
if(ch==1)
{
ob= new Circle();

ob.area();
ob.display();
}

else if(ch==2)
{
ob = new Rectangle();

ob.area();
ob.display();
}
}
}

OUTPUT:-
41. Create a package named as MyPackage with a class named as Calculate. The class
should contain three methods with the following specifications:
 Volume(): Accepts three double type arguments i.e. width, height, depth; calculate
volume and return double type value.
 Add(): Accepts two integer type values, adds them and returns the value.
 Divide(): Accepts two integer type values, divides them and returns results.
Import this package into a file named as PackageDemo and call the above three
methods.

package MyPackage;
public class Calculate
{
public double Volume()
{
double width = 5.2;
double height = 4.2;
double depth = 3.0;
double v = width * height * depth ;
System.out.println("Volume is "+v);
return v;
}
public void Add()
{
int x = 2;
int y = 5;
int sum = x+y;
System.out.println("Add: sum is "+sum);
}
public void Divide()
{
int p = 10;
int q = 2;
int Div = p/q;
System.out.println("Division of p and q is "+Div);}
}

import MyPackage.Calculate;
public class packagedemo
{
public static void main(String[] args)
{
Calculate c = new Calculate();
c.Volume();
c.Add();
c.Divide();
}
}
OUTPUT
42. Write a program that will count number of characters, words and lines in a file.
The name should be passes as command line argument.

package college;

import java.io.*;
import java.util.Scanner;

public class File1 {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.print("Enter a path: ");
String path = sc.nextLine();
File file = new File(path);
FileInputStream fileStream = null;
try {
fileStream = new FileInputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);

String line;

// Initializing counters
int countWord = 0;
int sentenceCount = 0;
int characterCount = 0;
int paragraphCount = 1;
int whitespaceCount = 0;

// Reading line by line from the file until a null is returned


try {
while((line = reader.readLine()) != null)
{
if(line.equals(""))
{
paragraphCount++;
}
if(!(line.equals("")))
{

characterCount += line.length();

// \\s+ is the space delimiter in java


String[] wordList = line.split("\\s+");

countWord += wordList.length;
whitespaceCount += countWord -1;

// [!?.:]+ is the sentence delimiter in java


String[] sentenceList = line.split("[!?.:]+");

sentenceCount += sentenceList.length;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("Total word count = " + countWord);


System.out.println("Total number of sentences = " + sentenceCount);
System.out.println("Total number of characters = " + characterCount);
System.out.println("Number of paragraphs = " + paragraphCount);
System.out.println("Total number of whitespaces = " + whitespaceCount);
}
}
43.Write a multi-threaded Java program to print all numbers below 100,000 that
are both prime and Fibonacci number (some examples are 2, 3, 5, 13, etc.).
Design a thread that generates prime numbers below 100,000 and writes them
into a pipe. Design another thread that generates Fibonacci numbers and writes
them to another pipe. The main thread should read both the pipes to identify
numbers common to both.

package college;
import java.io.*;
import java.io.PipedWriter;
import java.io.PipedReader;

class fibonacci extends Thread


{
PipedWriter fw=new PipedWriter();

public PipedWriter getwrite()


{
return fw;
}
public void run()
{
super.run();
fibo();
}
int f(int n)
{
if(n<2)
return n;
else
return f(n-1)+f(n-2);
}
void fibo()
{
for(int i=2,fibv=0;(fibv=f(i))<100000;i++)
{
try{
fw.write(fibv);
}
catch(IOException e) {}
}
}
}
class prime extends Thread
{
PipedWriter pw=new PipedWriter();

public PipedWriter getwrite()


{
return pw;
}
public void run()
{
super.run();
prim();
}

public void prim()


{
for(int i=2;i<100000;i++)
{
if(isprime(i))
{
try{
pw.write(i);
}catch(IOException e){}
}
}
}
boolean isprime(int n)
{
boolean p=true;
int s=(int)Math.sqrt(n);
for(int i=2;i<=s;i++)
{
if(n%i==0)p=false;
}
return p;
}
}

class receiver extends Thread


{
PipedReader fibr,primer;
public receiver(fibonacci fib,prime pr)throws IOException
{
fibr=new PipedReader(fib.getwrite());
primer=new PipedReader(pr.getwrite());
}
public void run()
{
int p=0,f=0;
try{
p=primer.read();
f=fibr.read();
}
catch(IOException e){}
while(true)
{
try{
if(p==f)
{
System.out.println ("Match:"+p);
p=primer.read();
f=fibr.read();
}
else if(f<p)
f=fibr.read();
else
p=primer.read();
}catch(IOException e)
{System.exit(-1);}
}
}
}
class fibprimthr
{
public static void main (String[] args)throws IOException
{
fibonacci fi=new fibonacci();
prime pri=new prime();
receiver r=new receiver(fi,pri);
fi.start();
pri.start();
r.start();
}
}

You might also like