[go: up one dir, main page]

0% found this document useful (0 votes)
15 views67 pages

Java Lab Manual For Cse r20

The document contains a series of Java programming exercises covering various topics such as primitive data types, quadratic equations, race qualifications, searching algorithms, sorting algorithms, class mechanisms, constructors, method overloading, and inheritance. Each exercise includes an aim, program code, and sample output. The exercises are designed to help learners practice and understand key Java programming concepts.

Uploaded by

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

Java Lab Manual For Cse r20

The document contains a series of Java programming exercises covering various topics such as primitive data types, quadratic equations, race qualifications, searching algorithms, sorting algorithms, class mechanisms, constructors, method overloading, and inheritance. Each exercise includes an aim, program code, and sample output. The exercises are designed to help learners practice and understand key Java programming concepts.

Uploaded by

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

R20 JAVA PROGRAMMING Lab Programs

Exercise - 1 (Basics)

a). Write a JAVA program to display default value of all primitive data
type of JAVA
AIM:
JAVA program to display default value of all primitive data type of JAVA
PROGRAM:
class DefaultValues
{
static byte b;
static short s;
static int i;
static long l;
static float f;
static double d;
static char c;
static boolean bl;
public static void main(String[] args)
{
System.out.println("Byte :"+b);
System.out.println("Short :"+s);
System.out.println("Int :"+i);
System.out.println("Long :"+l);
System.out.println("Float :"+f);
System.out.println("Double :"+d);
System.out.println("Char :"+c);
System.out.println("Boolean :"+bl);
}
}

Output:
D:\GSK\JAVA>javac DefaultValues.java D:\GSK\
JAVA>java DefaultValues
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Double :0.0
Char:
Boolean: false
b). Write a java program that display the roots of a quadratic equation
ax2+bx+c=0. Calculate the discriminate D and basing on value of D, describe
the nature of root.

AIM: Java program that display the roots of a quadratic equation ax2+bx+c=0 and
Calculating the discriminate D basing on value of D and describing the nature of
root.

PROGRAM:

import java.util.Scanner;
class Solutions
{
public static void main(String[] args)
{
int a,b,c;
double x,y;
Scanner s=new Scanner(System.in);
System.out.println(“Enter the values of a,b, and c”);
a=s.nextInt();
b=s.nextInt();
c=s.nextInt();
int d=(b*b)-4*a*c;
if(d<0)
{
System.out.println(“No real roots”);
}
else
{
double l=Math.sqrt(d);
x=(-b-l)/2*a;
y=(-b+l)/2*a;
System.out.println(“Roots of given equation:”+x+” “+y);
}
}

}
Output:

D:\GSK\JAVA>javac Solutions.java

D:\GSK\JAVA>java Solutions

Enter the values of a,b,c


1
5
6
Roots of given equation:-3.0 -2.0

Output:

D:\GSK\JAVA>javac Solutions.java

D:\GSK\JAVA>java Solutions

Enter the values of a, b, c


1
2
2
No real solutions
c). Five Bikers Compete in a race such that they drive at a constant speed
which may or may not be the same as the other. To qualify the race, the speed
of a racer must be more than the average speed of all 5 racers. Take as input
the speed of each racer and print back the speed of qualifying racers.

AIM:
Java Program for Five Bikers Compete in a race such that they drive at a constant
speed which may or may not be the same as the other and to qualify the race, the
speed of a racer must be more than the average speed of all 5 racers. Take as input
the speed of each racer and print back the speed of qualifying racers.

PROGRAM:

import java.util.Scanner;
public class Racer
{
public static void main(String[] args)
{
float r1,r2,r3,r4,r5;
float average;
Scanner s = new Scanner(System.in);
System.out.print("Enter First Racer
Speed:"); r1 = s.nextFloat();
System.out.print("Enter Second Racer
Speed:"); r2 = s.nextFloat();
System.out.print("Enter Third Racer
Speed:"); r3 = s.nextFloat();
System.out.print("Enter Fourth Racer
Speed:"); r4 = s.nextFloat();
System.out.print("Enter Fifth Racer
Speed:"); r5 = s.nextFloat();
average = (r1+r2+r3+r4+r5) / 5;
System.out.println("Average:"+average);
if(r1 > average)
System.out.println("\n First Racer is qualify Racer Speed is:"+r1);
if(r2 > average)
System.out.println("\n Second Racer is qualify Racer Speed is:"+r2);
if(r3 > average)
System.out.println("\n Third Racer is qualify Racer Speed is:"+r3);
if(r4 > average)
System.out.println("\n Fourth Racer is qualify Racer Speed
is:"+r4); if(r5 > average)
System.out.println("\n Fifth Racer is qualify Racer Speed is:"+r5);
}
}

Output:

D:\GSK\JAVA>javac

Racer.java D:\GSK\JAVA>java

Racer Enter First Racer

Speed:45
Enter Second Racer Speed:55
Enter Third Racer Speed:60
Enter Fourth Racer Speed:65
Enter Fifth Racer Speed:70
Average:59.0

Third Racer is qualify Racer Speed is: 60.0


Fourth Racer is qualify Racer Speed is: 65.0
Fifth Racer is qualify Racer Speed is: 70.0
Exercise - 2 (Operations, Expressions, Control-flow, Strings)

a). Write a JAVA program to search for an element in a given list of


elements using binary search mechanism.

import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];

Scanner in = new Scanner(System.in);


System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search
) first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
Output:

D:\GSK\JAVA>javac BinarySearch.java

D:\GSK\JAVA>java BinarySearch
Enter number of elements
5
Enter 5 integers
2
5
8
10
15
Enter value to find
8
8 found at location 3.
b). Write a JAVA program to sort for an element in a given list of
elements using bubble sort

import java.util.Scanner;
class BubbleSort {
public static void main(String []args)
{ int n, i, j, swap;
Scanner in = new Scanner(System.in);

System.out.println("Input number of integers to sort");


n = in.nextInt();

int array[] = new int[n];

System.out.println("Enter " + n + " integers");

for (i = 0; i < n; i++)


array[i] = in.nextInt();

for (i = 0; i < ( n - 1 ); i++)


{
for (j = 0; j < n - i - 1; j++)
{
if (array[j] > array[j+1])
{
swap = array[j];
array[j] =
array[j+1]; array[j+1]
= swap;
}
}
}

System.out.println("Sorted list of numbers");

for (i = 0; i < n; i++)


System.out.println(array[i]);
}
}
Output:
D:\GSK\JAVA>javac BubbleSort.java

D:\GSK\JAVA>java BubbleSort
Input number of integers to sort
5
Enter 5 integers
5
4
3
2
1
Sorted list of numbers
1
2
3
4
5
(c). Write a JAVA program to sort for an element in a given list of elements
using merge sort.

import java.util.Scanner;
public class MergeSort
{
public static void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
sort(a, low, mid);
sort(a, mid, high);
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
}

public static void main(String[] args)


{
Scanner scan = new Scanner( System.in );
System.out.println("Merge Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
sort(arr, 0, n);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++) System.out.print(arr[i]
+" "); System.out.println();

}
}

Output:

D:\GSK\JAVA>javac MergeSort.java

D:\GSK\JAVA>java MergeSort
Merge Sort Test

Enter number of integer elements


7

Enter 7 integer elements


8
6
4
2
7
1
9

Elements after sorting


1246789
(d) Write a JAVA program using String Buffer to delete, remove character.

public class JavaStringBufferDeleteExample


{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello World");
sb1.delete(0,6);
System.out.println(sb1);

StringBuffer sb2 = new StringBuffer("Some Content");


System.out.println(sb2);
sb2.delete(0, sb2.length());
System.out.println(sb2);

StringBuffer sb3 = new StringBuffer("Hello World");


sb3.deleteCharAt(0);
System.out.println(sb3);
}
}

Output:

D:\GSK\JAVA>javac JavaStringBufferDeleteExample.java

D:\GSK\JAVA>java JavaStringBufferDeleteExample

World

Some Content

ello World
Exercise - 3 (Class, Objects)

a). Write a JAVA program to implement class mechanism. – Create a class,


methods and invoke them inside main method.

public class Helloworld {


static void call()
{
System.out.println(" World");
}
public static void main(String[] args)
{
System.out.println("Hello");
call();
}
}

Output:

D:\GSK\JAVA>javac Helloworld.java

D:\GSK\JAVA>java Helloworld
Hello
World
b). Write a JAVA program to implement constructor.

class Programming
{

Programming()
{
System.out.println("Constructor method called.");
}

public static void main(String[] args)


{
Programming object = new Programming();
}
}

Output:

D:\GSK\JAVA>javac Programming.java

D:\GSK\JAVA>java Programming

Constructor method called.


Exercise - 4 (Methods)

a). Write a JAVA program to implement constructor overloading.

class Square
{
int height;
int width;

Square()
{
height = 0;
width = 0;
}
Square(int side)
{
height = width = side;
}

Square(int sideh, int sidew)


{
height = sideh;
width = sidew;
}
}

class ImplSquare
{
public static void main(String args[])
{
Square sObj1 = new Square();
Square sObj2 = new Square(5);
Square sObj3 = new Square(2,3);

System.out.println("Variable values of object1 : ");


System.out.println("Object1 height = " + sObj1.height);
System.out.println("Object1 width = " + sObj1.width);
System.out.println("");

System.out.println("Variable values of object2 : ");


System.out.println("Object2 height = " + sObj2.height);
System.out.println("Object2 width = " + sObj2.width);
System.out.println("");

System.out.println("Variable values of object3 : ");


System.out.println("Object3 height = " + sObj3.height);
System.out.println("Object3 width = " + sObj3.width);
}
}

Output:

D:\GSK\JAVA>javac ImplSquare.java

D:\GSK\JAVA>java ImplSquare
Variable values of object1 :
Object1 height = 0
Object1 width = 0

Variable values of object2 :


Object2 height = 5
Object2 width = 5

Variable values of object3 :


Object3 height = 2
Object3 width = 3
b). Write a JAVA program implement method overloading.

class Sum
{
void add(int a, int b)
{
System.out.println("Sum of two="+(a+b));
}

void add(int a, int b,int c)


{
System.out.println("Sum of three="+(a+b+c));
}
}
class Polymorphism
{
public static void main(String args[])
{
Sum s=new Sum();

s.add(10,15);
s.add(10,20,30);
}
}

Output:

D:\GSK\JAVA>javac Polymorphism.java D:\GSK\

JAVA>java Polymorphism
Sum of two=25
Sum of three=60
Exercise - 5 (Inheritance)

a). Write a JAVA program to implement Single Inheritance

class Dimensions
{
int length;
int breadth;
}

class Rectangle extends Dimensions


{
int a;
void area()
{
a = length * breadth;
}

class Area
{
public static void main(String args[])
{
Rectangle Rect = new Rectangle();
Rect.length = 7;
Rect.breadth = 16;
Rect.area();
System.out.println("The Area of rectangle of length "
+Rect.length+" and breadth "+Rect.breadth+" is "+Rect.a);
}
}

Output:

D:\GSK\JAVA>javac Area.java D:\GSK\

JAVA>java Area

The Area of rectangle of length 7 and breadth 16 is 112


b). Write a JAVA program to implement multi level Inheritance

class students
{
private int sno;
private String sname;
public void setstud(int no,String name)
{
sno = no;
sname = name;
}
public void putstud()
{
System.out.println("Student No : " + sno);
System.out.println("Student Name : " + sname);
}
}
class marks extends students
{
protected int mark1,mark2;
public void setmarks(int m1,int m2)
{
mark1 = m1;
mark2 = m2;
}
public void putmarks()
{
System.out.println("Mark1 : " + mark1);
System.out.println("Mark2 : " + mark2);
}
}
class finaltot extends marks
{
private int total;
public void calc()
{
total = mark1 + mark2;
}
public void puttotal()
{
System.out.println("Total : " + total);
}
public static void main(String args[])
{
finaltot f = new finaltot();
f.setstud(100,"Nithya");
f.setmarks(78,89);
f.calc();
f.putstud();
f.putmarks();
f.puttotal();
}
}

Output:

D:\GSK\JAVA>javac finaltot.java

D:\GSK\JAVA>java finaltot

Student No : 100

Student Name : Nithya

Mark1 : 78

Mark2 : 89

Total : 167
c). Write a java program for abstract class to find areas of different shapes

abstract class Shape


{
void display()
{
}
}

class Circle extends Shape


{
void display()
{
System.out.println("You are using circle class");
}
}

class Rectangle extends Shape


{
void display()
{
System.out.println("You are using rectangle class");
}
}

class Triangle extends Shape


{
void display()
{
System.out.println("You are using triangle class");
}
}
class AbstractClassDemo
{
public static void main(String args[])
{
Shape sObj = new
Circle(); sobj.display();

sObj = new Rectangle();


sobj.display();

sObj = new Triangle();


sobj.display();
}
}

Output:

D:\GSK\JAVA>javac AbstractClassDemo.java

D:\GSK\JAVA>java AbstractClassDemo

You are using circle class


You are using rectangle class
You are using triangle class
Exercise - 6 (Inheritance - Continued)

a). Write a JAVA program give example for “super” keyword.

class SuperExample {

int a = 10;
}

class SubClass extends SuperExample

{ void display() {

int a = super.a;
System.out.println("The value is : " + a);
}
}

class MainClass {

public static void main(String args[]) {

SubClass obj = new SubClass();


obj.display();
}
}

Output:

D:\GSK\JAVA>javac MainClass.java D:\

GSK\JAVA>java MainClass
The value is : 10
b). Write a JAVA program to implement Interface. What kind of
Inheritance can be achieved?

import java.lang.*;
import java.io.*;
interface Exam
{
void percent_cal();
}
class Student
{
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2)
{
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
}
void display()
{
System.out.println ("Name of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("Marks of Subject 2: "+mark2);
}
}
class Result extends Student implements Exam
{
Result(String n, int r, int m1, int m2)
{
super(n,r,m1,m2);
}
public void percent_cal()
{
int total=(mark1+mark2);
float percent=total*100/200;
System.out.println ("Percentage: "+percent+"%");
}
void display()
{
super.display();
}
}
class Multiple
{
public static void main(String args[])
{
Result R = new Result("Ra.one",12,93,84);
R.display();
R.percent_cal();
}
}

Output:

D:\GSK\JAVA>javac Multiple.java

D:\GSK\JAVA>java Multiple

Name of Student: Ra.one

Roll No. of Student: 12

Marks of Subject 1: 93

Marks of Subject 2: 84

Percentage: 88.0%

Multiple Inheritance : – Java does not support multiple inheritances. So that


reason java provides an alternate approach is called as interfaces, it supports the
concept of multiple inheritances. Although a Java class does not be a subclass of
more than one superclass, it can implement more than one interface without
creating any problem.
Exercise - 7 (Exception)

a).Write a JAVA program that describes exception handling


mechanism

import java.util.Scanner;
class Division {
public static void main(String[] args) {
int a, b, result;
Scanner input = new
Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt();
b = input.nextInt();
try {
result = a / b;
System.out.println("Result = " +
result);
}
catch (ArithmeticException e)
{ System.out.println("Exception caught: Division by
zero.");
}
finally {
System.out.println("finally block will execute always.");
}
}
}

Output:

D:\GSK\JAVA>javac Division.java D:\GSK\

JAVA>java Division
Input two integers
4
5
Result = 0
finally block will execute always.

D:\GSK\JAVA>java Division
Input two integers
5
0
Exception caught: Division by zero.
finally block will execute always.
b).Write a JAVA program Illustrating Multiple catch clauses

public class ExceptionExample


{
public static void main(String argv[])
{
int num1 = 10;
int num2 = 0;
int result = 0;
int arr[] = new int[5];
try {
arr[0] = 0;
arr[1] = 1;
arr[2] = 2;
arr[3] = 3;
arr[4] = 4;
arr[5] = 5;

result = num1 / num2;


System.out.println("Result of Division : " + result);

}catch (ArithmeticException e) {
System.out.println("Err: Divided by Zero");

}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Err: Array Out of Bound");
}

}
}

Output:

D:\GSK\JAVA>javac ExceptionExample.java D:\

GSK\JAVA>java ExceptionExample

Err: Array Out of Bound


Exercise – 8 (Runtime Polymorphism)

a). Write a JAVA program that implements Runtime polymorphism

class Shape
{
void draw()
{
System.out.println("drawing...");
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle...");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("drawing circle...");
}
}
class Triangle extends Shape
{
void draw()
{
System.out.println("drawing triangle...");
}
}
class TestPolymorphism
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}

Output:

D:\GSK\JAVA>javac TestPolymorphism.java

D:\GSK\JAVA>java TestPolymorphism
drawing rectangle...
drawing circle...
drawing triangle...
b). Write a Case study on run time polymorphism, inheritance
that implements in above problem

Polymorphism in Java

Polymorphism in java is a concept by which we can perform a single action by


different ways. Polymorphism is derived from 2 greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.

There are two types of polymorphism in java: compile time polymorphism and
runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.

If you overload static method in java, it is the example of compile time


polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a


call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a


superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

When reference variable of Parent class refers to the object of Child class, it is
known as upcasting. For example:
class A

class B extends A

A a=new B();//upcasting

In the above example, we are creating three classes Rectangle, Circle and Triangle.
Rectangle class extends Shape class and overrides its draw() method, Circle class
extends Shape class and overrides its draw() method and Triangle class extends
Shape class and overrides its draw() method . We are calling the draw() method by
the reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, subclass method is invoked at
runtime.

Since method invocation is determined by the JVM not compiler, it is known as


runtime polymorphism. In this way one class inherits the properties of another
class is the concept of inheritance. Thus inheritance is used in runtime
polymorphism.
Exercise – 9 (User defined Exception)
a). Write a JAVA program for creation of Illustrating throw

class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
}

public static void main(String args[])


{
avg();
}
}

Output:

D:\GSK\JAVA>javac Test.java

D:\GSK\JAVA>java Test

Exception caught
b). Write a JAVA program for creation of Illustrating finally

class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}

Output:

D:\GSK\JAVA>javac ExceptionTest.java D:\GSK\

JAVA>java ExceptionTest
out of try
finally is always executed.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3
out of bounds for length 2 at ExceptionTest.main(ExceptionTest.java:9)
c). Write a JAVA program for creation of Java Built-in Exceptions

class Exception_Demo {

public static void main(String args[])

try

int a = 30, b = 0;

int c = a / b; // cannot divide by zero

System.out.println("Result = " + c);

catch (ArithmeticException e)

System.out.println(" ArithmeticException Demo ");

System.out.println("\t Can't divide a number by 0");

try

int a[] = new int[5];

a[6] = 9; // accessing 7th element in an array of

// size 5

catch (ArrayIndexOutOfBoundsException e)

System.out.println(" ArrayIndexOutOfBoundsException Demo ");

System.out.println("\t Array Index is Out Of Bounds");


}

try

String a = null; // null value

System.out.println(a.charAt(0));

catch (NullPointerException e)

System.out.println(" NullPointerException Demo ");

System.out.println("\t NullPointerException..");

try

// "akki" is not a number

int num = Integer.parseInt("akki");

System.out.println(num);

catch (NumberFormatException e)

System.out.println(" NumberFormatException Demo ");

System.out.println("\t Number format exception");

}
Output:

D:\GSK\JAVA>javac Exception_Demo.java D:\

GSK\JAVA>java Exception_Demo

ArithmeticException Demo

Can't divide a number by 0

ArrayIndexOutOfBoundsException Demo

Array Index is Out Of Bounds

NullPointerException Demo

NullPointerException..

NumberFormatException Demo

Number format exception

d).Write a JAVA program for creation of User Defined Exception

class MyException extends

Exception{ String str1;

MyException(String str2)

{ str1=str2;

public String toString(){

return ("MyException Occurred: "+str1) ;

class UserException{

public static void main(String args[]){


try{

System.out.println("Starting of try block");

// I'm throwing the custom exception using throw

throw new MyException("This is My error Message");


}

catch(MyException exp)

{ System.out.println("Catch Block") ;

System.out.println(exp) ;

Output:

D:\GSK\JAVA>javac UserException.java

D:\GSK\JAVA>java UserException

Starting of try block

Catch Block

MyException Occurred: This is My error Message


Exercise – 10 (Threads)
a). Write a JAVA program that creates threads by extending Thread class
.First thread display “Good Morning “every 1 sec, the second thread displays
“Hello “every 2 seconds and the third display “Welcome” every 3 seconds
,(Repeat the same by implementing Runnable)

class FirstThread extends Thread


{
public void run()
{

System.out.println( "\t GOOD MORNING ");

try
{
Thread.sleep(1);
}
catch (InterruptedException ie)
{

System.out.println( "First Thread " +ie);


}
}
}
class SecondThread extends Thread
{

public void run()


{

System.out.println( "\t HELLO " );

try
{
Thread.sleep (2);
}
catch (InterruptedException ie)
{

System.out.println( "Second Thread " +ie);


}
}
}
class ThirdThread extends Thread
{

public void run()


{

System.out.println( "\t WELCOME" );

try
{
Thread.sleep (3);
}
catch (InterruptedException ie)
{

System.out.println( "Third Thread " +ie);


}
}
}
class ThreadDemo
{

public static void main(String args[])


{

FirstThread firstThread = new FirstThread();

SecondThread secondThread = new

SecondThread(); ThirdThread thirdThread =

new ThirdThread();

firstThread.start();

secondThread.start();

thirdThread.start();
}
}
Output:

D:\GSK\JAVA>javac ThreadDemo.java D:\GSK\

JAVA>java ThreadDemo
HELLO
WELCOME
GOOD MORNING

Write a JAVA program that creates threads by implementing Runnable


class FirstThread implements Runnable
{

public void run()


{

System.out.println( "\t GOOD MORNING ");

try
{
Thread.sleep(1);
}
catch (InterruptedException ie)
{

System.out.println( "First Thread " +ie);


}
}
}
class SecondThread implements Runnable
{

public void run()


{

System.out.println( "\t HELLO " );


try
{
Thread.sleep (2);
}
catch (InterruptedException ie)
{

System.out.println( "Second Thread " +ie);


}
}
}
class ThirdThread implements Runnable
{

public void run()


{

System.out.println( "\t WELCOME" );

try
{
Thread.sleep (3);
}
catch (InterruptedException ie)
{

System.out.println( "Third Thread " +ie);


}
}
}
class ThreadDemo1
{

public static void main(String args[])


{

FirstThread firstThread = new FirstThread();

SecondThread secondThread = new SecondThread();


ThirdThread thirdThread = new ThirdThread();

Thread thread1 = new Thread(firstThread);


thread1.start();

Thread thread2 = new Thread(secondThread);


thread2.start();

Thread thread3 = new


Thread(thirdThread); thread3.start();
}
}

Output:

D:\GSK\JAVA>javac ThreadDemo1.java D:\GSK\

JAVA>java ThreadDemo1
HELLO
GOOD MORNING
WELCOME
b). Write a program illustrating isAlive and join ()

class ThreadExample extends Thread


{
public void run()
{
System.out.println("Thread");
try
{
Thread.sleep(300);
}
catch (InterruptedException ie)
{
}
System.out.println("Example using isAlive() and join()");
}
public static void main(String[] args)
{
ThreadExample c1 = new ThreadExample();
c1.start();
System.out.println(c1.isAlive());
try
{
c1.join(); // Waiting for c1 to finish
}
catch (InterruptedException ie)
{
}
System.out.println(c1.isAlive());

}
}

Output:
D:\GSK\JAVA>javac ThreadExample.java

D:\GSK\JAVA>java ThreadExample
true
Thread
Example using isAlive() and join()
false
c). Write a Program illustrating Daemon Threads.

public class DaemonThread extends Thread


{
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println("Daemon Thread Works");
}
else
{
System.out.println("user Thread Works");
}
}
public static void main(String a[])
{
DaemonThread dt1 = new DaemonThread();
DaemonThread dt2 = new DaemonThread();
DaemonThread dt3 = new DaemonThread();

dt1.setDaemon(true);

dt1.start();
dt2.start();
dt3.start();
}
}

Output:

D:\GSK\JAVA>javac DaemonThread.java

D:\GSK\JAVA>java DaemonThread
Daemon Thread Works
user Thread Works
user Thread Works
Exercise - 11 (Threads continuity)

a).Write a JAVA program Producer Consumer Problem

class ProducerConsumerTest {

public static void main(String[] args) {

CubbyHole c = new CubbyHole();

Producer p1 = new Producer(c, 1);

Consumer c1 = new Consumer(c, 1);

p1.start();

c1.start();

class CubbyHole

{ private int

contents;

private boolean available = false;

public synchronized int get()

{ while (available == false) {

try {

wait();

} catch (InterruptedException e) {}

available = false;

notifyAll();

return contents;
}

public synchronized void put(int value)

{ while (available == true) {

try {

wait();

} catch (InterruptedException e) { }

contents = value;

available = true;

notifyAll();

class Consumer extends Thread

{ private CubbyHole cubbyhole;

private int number;

public Consumer(CubbyHole c, int number)

{ cubbyhole = c;

this.number = number;

public void run()

{ int value = 0;

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

{ value =

cubbyhole.get();

System.out.println("Consumer #" + this.number + " got: " + value);

}
}

class Producer extends Thread {

private CubbyHole

cubbyhole; private int

number;

public Producer(CubbyHole c, int number)

{ cubbyhole = c;

this.number = number;

public void run() {

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

{ cubbyhole.put(i);

System.out.println("Producer #" + this.number + " put: " + i);

try {

sleep((int)(Math.random() * 100));

} catch (InterruptedException e) { }

Output:

D:\GSK\JAVA>javac ProducerConsumerTest.java

D:\GSK\JAVA>java ProducerConsumerTest

Producer #1 put: 0

Consumer #1 got: 0

Producer #1 put: 1
Consumer #1 got: 1

Producer #1 put: 2

Consumer #1 got: 2

Producer #1 put: 3

Consumer #1 got: 3

Producer #1 put: 4

Consumer #1 got: 4

b).Write a case study on thread Synchronization after solving the above


producer consumer problem

Producer-Consumer solution using threads in Java

In computing, the producer–consumer problem (also known as the bounded-buffer


problem) is a classic example of a multi-process synchronization problem. The
problem describes two processes, the producer and the consumer, which share a
common, fixed-size buffer used as a queue.

 The producer’s job is to generate data, put it into the buffer, and start again.
 At the same time, the consumer is consuming the data (i.e. removing it from
the buffer), one piece at a time.

Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and
that the consumer won’t try to remove data from an empty buffer.

Solution
The producer is to either go to sleep or discard data if the buffer is full. The next
time the consumer removes an item from the buffer, it notifies the producer, who
starts to fill the buffer again. In the same way, the consumer can go to sleep if it
finds the buffer to be empty. The next time the producer puts data into the buffer, it
wakes up the sleeping consumer.
An inadequate solution could result in a deadlock where both processes are waiting
to be awakened.
Exercise – 12 (Packages)
a). Write a JAVA program illustrate class path

The package keyword is used to create a package in java.

//save as Simple.java

package mypack;

public class Simple{

public static void main(String args[])

{ System.out.println("Welcome to package");

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

For example

javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You
can use any directory name like /home (in case of Linux), d:/abc (in case of
windows) etc. If you want to keep the package within the same directory, you can
use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination. The . represents the current folder.
Output:

Welcome to package

b). Write a case study on including in class path in your os environment


of your package.

What is Classpath?

Classpath is system environment variable used by the Java compiler and JVM.
Java compiler and JVM is used Classpath to determine the location of
required class files.

C:\Program Files\Java\jdk1.6.0\bin

Setting Java Classpath in Windows

In order to set Classpath for Java in Windows (any version either Windows
XP, Windows 2000 or Windows 7) you need to specify the value of environment
variable CLASSPATH, the name of this variable is not case sensitive and it
doesn’t matter if the name of your environment variable is Classpath,
CLASSPATH or classpath in Java.

Here is Step by Step guide for setting Java Classpath in Windows:

1. Go to Environment variable window in Windows by pressing "Windows +


Pause “--> Advanced --> Environment variable " or you can go from right
click on my computer than choosing properties and then Advanced and
then
Environment variable this will open Environment variable window
in windows.
2. Now specify your environment variable CLASSPATH and put the value of
your JAVA_HOME\lib and also include current directory by including
(dot or period sign).
3. Now to check the value of Java classpath in windows type "echo
%CLASSPATH" in your DOS command prompt and it will show you
the value of directory which is included in CLASSPATH.

You can also set classpath in windows by using DOS command

like: set CLASSPATH=%CLASSPATH%;JAVA_HOME\lib;


This way you can set the classpath in Windows XP, windows 2000 or
Windows 7 and 8, as they all come with command prompt.

c). Write a JAVA program that import and use the defined your package
in the previous Problem

//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.A;

class B{

public static void main(String args[])

{ A obj = new A();

obj.msg();

}
}

To Compile: javac -d . A.java

To Compile: javac -d . B.java

To Run: java mypack.B

Output:

Hello
Exercise - 13 (Applet)
a) Write a JAVA program to paint like paint brush in applet.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=”Paint.class” width=500, height=500>
</applet>
*/
public class Paint extends Applet implements MouseMotionListener {

int width, height;


Image backbuffer;
Graphics backg;

public void init()


{ width =
getSize().width;
height = getSize().height;

backbuffer = createImage( width, height );


backg = backbuffer.getGraphics();
backg.setColor( Color.white );
backg.fillRect( 0, 0, width, height );
backg.setColor( Color.red );

backbuffer = createImage( width, height );


backg = backbuffer.getGraphics();
backg.setColor( Color.white );
backg.fillRect( 0, 0, width, height );
backg.setColor( Color.blue );

addMouseMotionListener( this );
}
public void mouseMoved( MouseEvent e ) {
} public void mouseDragged( MouseEvent e )
{ int x = e.getX();
int y = e.getY();
backg.fillOval(x-10,y-10,20,20);
repaint();
e.consume();
}
public void update( Graphics g )
{ g.drawImage( backbuffer, 0, 0, this );
}
public void paint( Graphics g )
{ update( g );
}
}

0utput:
b) Write a JAVA program to display analog clock using Applet.

import java.applet.*;

import java.awt.*;

import java.util.*;

import java.text.*;

/*

<applet code="MyClock.class" width="300" height="300">


</applet>

*/

public class MyClock extends Applet implements Runnable

{ int width, height;

Thread t = null;

boolean threadSuspended;

int hours=0, minutes=0, seconds=0;

String timeString = "";

public void init()

{ width =

getSize().width;

height = getSize().height;

setBackground( Color.black );

public void start()

{ if ( t == null ) {

t = new Thread( this );


t.setPriority( Thread.MIN_PRIORITY );

threadSuspended = false;

t.start();

else {

if ( threadSuspended )

{ threadSuspended = false;

synchronized( this ) {

notify();

public void stop()

{ threadSuspended = true;

public void run()

{ try {

while (true) {

Calendar cal = Calendar.getInstance();

hours = cal.get( Calendar.HOUR_OF_DAY );

if ( hours > 12 ) hours -= 12;

minutes = cal.get( Calendar.MINUTE );

seconds = cal.get( Calendar.SECOND );


SimpleDateFormat formatter

= new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );

Date date = cal.getTime();

timeString = formatter.format( date );

// Now the thread checks to see if it should suspend itself

if ( threadSuspended ) {

synchronized( this ) {

while ( threadSuspended )

{ wait();

repaint();

t.sleep( 1000 ); // interval specified in milliseconds

catch (Exception e) { }

void drawHand( double angle, int radius, Graphics g )

{ angle -= 0.5 * Math.PI;

int x = (int)( radius*Math.cos(angle) );

int y = (int)( radius*Math.sin(angle) );

g.drawLine( width/2, height/2, width/2 + x, height/2 + y );

}
void drawWedge( double angle, int radius, Graphics g )

{ angle -= 0.5 * Math.PI;

int x = (int)( radius*Math.cos(angle)

); int y = (int)( radius*Math.sin(angle)

); angle += 2*Math.PI/3;

int x2 = (int)( 5*Math.cos(angle) );

int y2 = (int)( 5*Math.sin(angle) );

angle += 2*Math.PI/3;

int x3 = (int)( 5*Math.cos(angle) );

int y3 = (int)( 5*Math.sin(angle) );

g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );

g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );

g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );

public void paint( Graphics g )

{ g.setColor( Color.gray );

drawWedge( 2*Math.PI * hours / 12, width/5, g );

drawWedge( 2*Math.PI * minutes / 60, width/3, g );

drawHand( 2*Math.PI * seconds / 60, width/2, g );

g.setColor( Color.white );

g.drawString( timeString, 10, height-10 );

}
Output:

c) Write a JAVA program to create different shapes and fill colors


using Applet.

import java.awt.*;

import java.applet.*;

/*

<applet code= ”graphicsdemo” width=500 height=500>

</applet>

*/

public class graphicsdemo extends Applet

public void paint(Graphics g)

int x[]={10,220,220};

int y[]={400,400,520};
int n=3;

g.drawLine(10,30,200,30);

g.setColor(Color.blue);

g.drawRect(10,40,200,30);

g.setColor(Color.red);

g.fillRect(10,80,200,30);

g.setColor(Color.orange);

g.drawRoundRect(10,120,200,30,20,20);

g.setColor(Color.green);

g.fillRoundRect(10,160,200,30,20,20);

g.setColor(Color.blue);

g.drawOval(10,200,200,30);

g.setColor(Color.black);

g.fillOval(10,240,40,40);

g.setColor(Color.yellow);

g.drawArc(10,290,200,30,0,180);

g.setColor(Color.yellow);

g.fillArc(10,330,200,30,0,180);

g.setColor(Color.pink);

g.fillPolygon(x,y,n);

}
Exercise - 14 (Event Handling)

a).Write a JAVA program that display the x and y position of the cursor
movement using Mouse.

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

/*
<applet code="AppletMouseXY" width=300 height=300>
</applet>
*/

public class AppletMouseXY extends Applet implements MouseListener,


MouseMotionListener
{
int x, y;
String str="";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this); } // override ML 5 abstract methods
public void mousePressed(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Released";
repaint();
}
public void mouseClicked(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Clicked";
repaint();
}
public void mouseEntered(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Exited";
repaint(); } // override two abstract methods of MouseMotionListener
public void mouseMoved(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse Moved";
repaint();
}
public void mouseDragged(MouseEvent e)
{
x = e.getX();
y = e.getY();
str = "Mouse dragged";
repaint(); } // called by repaint() method
public void paint(Graphics g)
{
g.setFont(new Font("Monospaced", Font.BOLD, 20));
g.fillOval(x, y, 10, 10);
g.drawString(x + "," + y, x+10, y -10);
g.drawString(str, x+10, y+20);
showStatus(str + " at " + x + "," + y);
}
}
Output:
b).Write a JAVA program that identifies key-up key-down event user
entering text in a Applet.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="SimpleKey" width=300 height=100>
</applet> */
public class SimpleKey extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output
coordinates public void init() {
addKeyListener(this);
requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke)
{ showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{ showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{ msg += ke.getKeyChar();
repaint();
} // Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
} }
Output:

You might also like