R23-Java Lab Exercise
R23-Java Lab Exercise
Compiled by:
Dr. B. Narayana Babu
Professor, Department of CAI
Department of CAI
SIDDARTHA EDUCATIONAL ACADEMY GROUP OF INSTITUTIONS
Approved by AICTE, New Delhi & Affiliated to JNTUA, Ananthapuramu, AP.
Near C. Gollapalli, Tirupati – 517 505, Andhra Pradesh
Mission
Imparting quality value based education of international standard and imbibing skill for solving real life
problems. Creating leadership qualities with perspective futuristic vision. Instilling habit of continual
learning.
Mission
To develop professionals who are skilled in the area of Artificial Intelligence and Data Science.
To impart quality and value based education and contribute towards the innovation of computing,
expert system, Data Science to raise satisfaction level of all stakeholders.
Our effort is to apply new advancements in high performance computing hardware and software.
PSO1 Ability to analyze and apply the knowledge of human cognition, Artificial Intelligence,
Machine Learning and data engineering in terms of real world problems to meet the
challenges of the future.
PSO2 Ability to develop computational knowledge and project development skills using
innovative tools and techniques to solve problems in the areas related to Deep Learning,
Machine learning, Artificial Intelligence.
PSO3 Ability to lead a product development company/team and use the acquired knowledge to
identify real-world research problems.
Course Objectives:
Do’s
1. Come with completed observation and record
2. Wear ID card before entering into the lab.
3. Read and understand how to carry out an activity thoroughly before coming to the
laboratory.
5. Report any broken plugs or exposed electrical wires to your lecturer/laboratory
technician immediately.
6. Write in time, out time and system details in the login register.
Don’ts
1. Do not eat or drink in the laboratory.
2. Do not operate mobile phones in the lab. Keep mobile phones either in silent or
switched off mode.
3. Do not change system settings.
4. Do not disturb your neighbouring students. They may be busy in completing tasks.
5. Do not remove anything from the computer laboratory without permission.
6. Do not use pen drives.
7. Do not misbehave.
INDEX
Exercise List of Experiments
a) Write a JAVA program to display default value of all primitive
data type of JAVA
1 b) Write a java program that display the roots of a quadratic
equation ax2+bx=0. Calculate the discriminate D and basing on
value of D, describe the nature of root.
a) Write a JAVA program to search for an element in a given list
of elements using binary search mechanism.
b) Write a JAVA program to sort for an element in a given list of
2
elements using bubble sort
c) Write a JAVA program using StringBuffer to delete, remove
character.
a) Write a JAVA program to implement class mechanism. Create
a class, methods and invoke them inside main method.
3 b) Write a JAVA program implement method overloading.
c) Write a JAVA program to implement constructor.
d) Write a JAVA program to implement constructor overloading.
a) Write a JAVA program to implement Single Inheritance
b) Write a JAVA program to implement multi level Inheritance
4
c) Write a JAVA program for abstract class to find areas of
different shapes
a) Write a JAVA program give example for “super” keyword.
b) Write a JAVA program to implement Interface. What kind of
5 Inheritance can be achieved?
c) Write a JAVA program that implements Runtime
polymorphism
a) Write a JAVA program that describes exception handling
mechanism
6 b) Write a JAVA program Illustrating Multiple catch clauses
c) Write a JAVA program for creation of Java Built-in Exceptions
d) Write a JAVA program for creation of User Defined Exception
a) Write a JAVA program that creates threads by extending
Thread class. First thread display “Good Morning “every 1 sec,
7
the second thread displays “Hello “every 2 seconds and the third
display “Welcome” every 3 seconds, (Repeat the same by
implementing Runnable)
b) Write a program illustrating is Alive and join ()
c) Write a Program illustrating Daemon Threads.
d) Write a JAVA program Producer Consumer Problem
a) Write a JAVA program that import and use the user
defined packages
b) Without writing any code, build a GUI that display text in
8 label and image in an ImageView (use JavaFX)
c) Build a Tip Calculator app using several JavaFX
components and learn how to respond to user
interactions with the GUI
Text and References:-
Text Books:
1. JAVA one step ahead, Anitha Seth, B.L.Juneja, Oxford.
2. Joy with JAVA, Fundamentals of Object Oriented Programming,
DebasisSamanta, MonalisaSarma, Cambridge, 2023.
3. JAVA 9 for Programmers, Paul Deitel, Harvey Deitel, 4th Edition, Pearson.
Reference Books
4. The complete Reference Java, 11th edition, Herbert Schildt,TMH
5. Introduction to Java programming, 7th Edition, Y Daniel Liang, Pearson
Online Learning Resources/Virtual Labs:
1.https://nptel.ac.in/courses/106/105/106105191/
2.https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_012880464547
618816 347_shared/overview
\
Lab Exercise
Lab – 1 (2 Hrs actual Time)
1. Write a program to display any message
2. Write a Java program to display default value of all primitive data types of java
3. Write a program check two strings are equal or not.
e) Do statements
3. Write a program to calculate the following
a) Find the length of array.
b) Demonstrate a one-dimensional array.
c) Demonstrate a two-dimensional array.
d) Demonstrate a multi-dimensional array.
4. Write a program to the find the following
a) Sum of digit
b) Prime number checking
5. Write a program to arrange the numbers in ascending order.
6. Write a program for calculating Matrix Operations.
a) Addition.
b) Multiplication.
Lab Manual
Installation of Java software:
Steps:
1. Download JDK7.0 from www.java.sun.com/downloads
Environment Variables
PATH:
1. This environment variable is to locate the compiler.
2. Right click MYCOMPUTER and find a properties tab, Click on Properties Tab and find
Advanced Tab, Click on it to see environment variables.
3. In this create a new environment variable called PATH and copy the location of java
compiler as value to it.
Default location:
$PATH= C:\Program Files\Java\Jdk1.6.0\bin;
CLASSPATH:
This environment variable will help the jvm to find the runtime environment of java i.e. all
predefined classes and interfaces can be located using this variable. The location for runtime
environment is JRE folder.
Installation of Java software, study of any Integrated development environment, Use Eclipse or
Netbeans platform and acquaint with the various menus. Create a test project, add a test class
and run it.
See how you can use auto suggestions, auto fill. Try code formatter and code refactoring like
renaming variables, methods and classes. Try debug step by step with java program to find prime
numbers between 1 to n.
1. Aim: To create and test java projects in Eclipse and Netbean platform
Step 4)
Click on
“Download” button
a) Displayingdefaultvalueofallprimitivedatatypes
AIM: To write a JAVA program to display default value of all primitive data type of
JAVA
SOURCE-CODE:
class defaultdemo
{
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("The default values of primitive data types are:");
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);
}}
Sample Input/output:
The default values of primitive data types are:
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Double :0.0
Char :
Boolean :false
NOTE:
To Compile:
javac defaultdemo.java
To Run:
java defaultdemo
SOURCE-CODE:
import java.util.*;
class quadraticdemo
{
public static void main(String[] args)
{
int a, b, c;
double r1, r2, D;
Scanner s = new Scanner(System.in);
System.out.println("Given quadratic equation:ax^2 + bx + c");
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 = b * b - 4 * a * c;
if(D > 0)
{
System.out.println("Roots are real and unequal");
r1 = ( - b + Math.sqrt(D))/(2*a);
r2 = (-b - Math.sqrt(D))/(2*a);
System.out.println("First root is:"+r1);
System.out.println("Second root is:"+r2);
}
else
if(D == 0)
{
System.out.println("Roots are real and equal");
r1 = (-b+Math.sqrt(D))/(2*a);
System.out.println("Root:"+r1);
}
else
SEGAI - Tirupati Page 19
NB
{
System.out.println("Roots are imaginary");
}}}
Sample OUTPUT:
Given quadratic equation:ax^2 + bx + c
Enter a:2
Enter b:3
Enter c:1
Roots are real and unequal
First root is:-0.5
Second root is:-1.0
NOTE:
To Compile:
javac quadraticdemo.java
To Run:
java quadraticdemo
Sample Output:-
Enter total number of elements: 5
SEGAI - Tirupati Page 21
NB
Enter elements: 2 4 6 8 9
Enter the search value: 8
number found
b) Bubble sort
AIM: To write a JAVA program to sort for an element in a given list of elements using
bubble sort
SOURCE-CODE:
import java.util.Scanner;
class bubbledemo
{
public static void main(String args[])
{
int n, i,j, temp;
int a[ ]=new int[20];
Scanner s = new Scanner(System.in);
System.out.println("Enter total number of elements:");
n = s.nextInt();
System.out.println("Enter elements:");
for (i = 0; i < n; i++)
a[i] = s.nextInt();
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}}}
System.out.println("The sorted elements are:");
for(i=0;i<n;i++)
SEGAI - Tirupati Page 22
NB
System.out.print("\t"+a[i]);
}}
Sample Output
Enter total number of elements:
10
Enter elements: 3 2 5 7 6 8 9 1 4 0
The sorted elements are: 0 1 2 3 4 5 6 7 8 9
C) Implementing StringBuffer
AIM: To write a JAVA program using StringBuffer to delete, remove character
SOURCE CODE:
class stringbufferdemo
{
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);
}}
Sample Output
World
Some Content
Hello World
SOURCE-CODE:
1. no return type and without parameter-list:
class A
{
int l=10,b=20;
void display()
{
System.out.println(l);
System.out.println(b);
}}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display();
}}
OUTPUT: 10 20
2. no return type and with parameter-list:
class A
{
void display(int l,int b)
{
System.out.println(l);
System.out.println(b);
}}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display(10,20);
}}
OUTPUT: 10 20
c) Method Overloading
AIM: To write a JAVA program implement method overloading
SOURCE-CODE:
class A
{
int l=10,b=20;
int area()
{
return l*b;
}
int area(int l,int b)
{
return l*b;
}}
SEGAI - Tirupati Page 25
NB
class overmethoddemo
{
public static void main(String args[])
{
A a1=new A();
int r1=a1.area();
System.out.println("The area is: "+r1);
int r2=a1.area(5,20);
System.out.println("The area is: "+r2);
}}
OUT-PUT:
The area is: 200
The area is: 100
d) Implementing Constructor
AIM: To write a JAVAto implement constructor
SOURCE-CODEs:
Sample OUTPUT:
The area is:200
l=u; b=v;
}
int area()
{
return l*b;
}}
class constructordemo
{
public static void main(String args[])
{
A a1=new A(10,20);
int r=a1.area();
System.out.println("The area is: "+r);
}}
OUT-PUT:
The area is:200
e) Constructor Overloading
AIM: To write a JAVA program to implement constructor overloading
SOURCE-CODE:
class A
{
int l,b;
A()
{
l=10;b=20;
}
A(int u,int v)
{
l=u;b=v;
}
int area()
{
return l*b;
}}
class overconstructdemo
{
public static void main(String args[])
{
A a1=new A();
int r1=a1.area();
System.out.println("The area is: "+r1);
A a2=new A(30,40);
int r2=a2.area();
System.out.println("The area is: "+r2);
}}
OUT-PUT:
The area is: 200
The area is: 1200
SEGAI - Tirupati Page 27
NB
SOURCE-CODE:
class A
{
A()
{
System.out.println("Inside A's Constructor");
}
}
class B extends A
{
B()
{
System.out.println("Inside B's Constructor");
}}
class singledemo
{
public static void main(String args[])
{
B b1=new B();
}}
OUTPUT:
Inside A's Constructor
Inside B's Constructor
B()
{
System.out.println("Inside B's Constructor");
}}
class C extends B
{
C()
{
System.out.println("Inside C's Constructor");
}}
class multidemo
{
public static void main(String args[])
{
C c1=new C();
}}
OUTPUT:
Inside A's Constructor
Inside B's Constructor
Inside C's Constructor
c) Abstract Class
AIM: To write a java program for abstract class to find areas of different shapes
SOURCE-CODE:
abstract class shape
{
abstract double area();
}
class rectangle extends shape
{
double l=12.5,b=2.5;
double area()
{
return l*b;
}}
class triangle extends shape
{
double b=4.2,h=6.5;
double area()
{
return 0.5*b*h;
}}
class square extends shape
{
double s=6.5;
double area()
{
return 4*s;
SEGAI - Tirupati Page 29
NB
}}
class shapedemo
{
public static void main(String[] args)
{
rectangle r1=new rectangle();
triangle t1=new triangle();
square s1=new square();
System.out.println("The area of rectangle is: "+r1.area());
System.out.println("The area of triangle is: "+t1.area());
System.out.println("The area of square is: "+s1.area());
}}
OUTPUT:
The area of rectangle is: 31.25
The area of triangle is: 13.65
The area of square is: 26.0
class A
{
int l,b;
A()
{
l=10; b=20;
}}
class B extends A
{
int h;
B()
{
super();
h=30;
}
int volume()
{
return l*b*h;
}}
class superdemo
{
public static void main(String args[])
{
B b1=new B();
int r=b1.volume();
System.out.println("The vol. is: "+r);
}}
OUTPUT: The vol. is:6000
A(int u,int v)
{
l=u; b=v;
}}
class B extends A
{
int h;
B(int u,int v,int w)
{
super(u,v);
h=w;
}
int volume()
{
return l*b*h;
}}
class superdemo
{
public static void main(String args[])
{
B b1=new B(30,20,30);
int r=b1.volume();
System.out.println("The vol. is: "+r);
}}
OUTPUT: The vol. is:18000
b) Implementing interface
AIM: To write a JAVA program to implement Interface.
SOURCE-CODEs:
(i) First form of interface implementation
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("B's method");
}}
class C extends B
{
public void callme()
{
System.out.println("C's method");
SEGAI - Tirupati Page 32
NB
}}
class interfacedemo
{
public static void main(String args[])
{
C c1=new C();
c1.display();
c1.callme();
}}
OUTPUT:
B's method
C's method
c1.show();
c1.callme();
c1.call();
}}
OUT-PUT:
This is in display method
This is in show method
This is in callme method
This is in call method
{
void call();
}
class D implements C
{
public void display()
{
System.out.println("interface A");
}
public void callme()
{
System.out.println("interface B");
}
public void call()
{
System.out.println("interface C");
}}
class interfacedemo
{
public static void main(String args[])
{
D d1=new D();
d1.display();
d1.callme();
d1.call(); } }
OUTPUT: interface A
interface B
interface C
SOURCE-CODE:
class A
{
void display()
{
System.out.println("Inside A class");
}
}
class B extends A
{
void display()
{
System.out.println("Inside B class");
}
}
class C extends A
{
void display()
{
System.out.println("Inside C class");
}
}
class runtimedemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
A ref;
ref=c1;
ref.display();
ref=b1;
ref.display();
ref=a1;
ref.display();
}
}
OUT-PUT:
Inside C class
Inside B class
Inside A class
a/b;
System.out.println (c);
}
catch(ArithmeticException e)
{
System.out.println (e);
}
}
}
OUT-PUT:
java.lang.ArithmeticException: / by zero
(ii)NullPointer Exception
class nullpointerdemo
{
public static void main(String args[])
{
try
{
String a = null; System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println(e);
}
}
}
OUT-PUT:
java.lang.NullPointerException
(iii)StringIndexOutOfBound Exception
class stringbounddemo
{
SEGAI - Tirupati Page 39
NB
(iv)FileNotFound Exception
import java.io.*;
class filenotfounddemo
{
public static void main(String args[])
{
try
{
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
SEGAI - Tirupati Page 40
NB
}
OUT-PUT:
java.io.FileNotFoundException: E:\file.txt (The system cannot find the file specified)
(v)NumberFormat Exception
class numberformatdemo
{
public static void main(String args[])
{
try
{
int num = Integer.parseInt ("babu") ;
System.out.println(num);
}
catch(NumberFormatException e)
{
System.out.println(e);
}
}
}
OUT-PUT:
java.lang.NumberFormatException: For input string: "babu"
(vi)ArrayIndexOutOfBounds Exception
class arraybounddemo
{
public static void main(String args[])
{
try
{
int a[] = new int[5];a[6] =
9;
}
catch(ArrayIndexOutOfBoundsException e)
SEGAI - Tirupati Page 41
NB
{
System.out.println (e);
}
}
}
OUT-PUT:
java.lang.ArrayIndexOutOfBoundsException: 6
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)
SOURCE-CODEs:
(i)Creating multiple threads using Thread class
System.out.println(e);
}
}
}
class C extends Thread
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class threaddemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
Cc1=newC();
a1.start();
b1.start();
c1.start();
}
}
OUT-PUT:
good morninghello
good morninggood
morningwelcome
hello
good morning
good morning
hello
good morning
welcome good
morninghello
good morninggood
morningwelcome
hello
good morninghello
SEGAI - Tirupati Page 44
NB
welcome hello
welcome
hello
hello
welcomehello
welcome
welcome
welcome
welcome
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
Thread.sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class runnabledemo
{
public static void main(String args[])
{
A a1=new A(); B
b1=new B(); C
c1=new C();
Thread t1=new Thread(a1);
Thread t2=new Thread(b1);
Thread t3=new Thread(c1);
t1.start();
t2.start();
t3.start();
}
}
OUT-PUT:
good morning
good morning
hello
good morning
welcome good
morninghello
good morninggood
morningwelcome
hello
goodmorning
goodmorning
hello
good morning
welcome
good morning
hello
SEGAI - Tirupati Page 46
NB
welcomehello
hello
welcomehello
welcomehello
hello
welcome
welcome
welcome
welcome
Thread t1;
producer(A a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int i=1;i<=10;i++)
{
a1.put(i);
}
}
}
class consumer implements Runnable
{
A a1;
Thread t1;
consumer(A a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int j=1;j<=10;j++)
{
a1.get();
}
}
}
class interdemo
{
public static void main(String args[])
{
A a1=new A();
producer p1=new producer(a1);
consumer c1=new consumer(a1);
}
}
OUT-PUT:
Put:1
Got:1
Put:2
Got:2
Put:3
SEGAI - Tirupati Page 51
NB
Got:3
Put:4
Got:4
Put:5
Got:5
Put:6
Got:6
Put:7
Got:7
Put:8
Got:8
Put:9
Got:9
Put:10
Got:10
Program to implement user defined packages in terms of creating a new package and
importing the same.
//Creating Package
package Pattern;
public class Pattern
{
public void pattern1()
{
int rows = 5;
for(int i = 1; i <= rows; ++i)
{
for(int j = 1; j <= i; ++j)
{
System.out.print("* ");
}
System.out.println();
}
}
public void pattern2()
{
int rows = 5;
for(int i = 1; i <= rows; ++i)
{
for(int j = 1; j <= i; ++j)
{
System.out.print(j + " ");
}
System.out.println();
}
}
public void pattern3()
{
int rows = 5;
for(int i = rows; i >= 1; --i)
{
for(int j = 1; j <= i; ++j)
{
System.out.print("* ");
}
System.out.println();
}
}
public void pattern4()
SEGAI - Tirupati Page 53
NB
{
int rows = 5;
for(int i = rows; i >= 1; --i)
{
for(int j = 1; j <= i; ++j)
{
System.out.print(j + " ");
}
System.out.println();
}
}
public void pattern5()
{
int alphabet = 65;
for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= i; j++)
{
System.out.print((char) alphabet + " ");
}
alphabet++;
System.out.println();
}
}
}
//Using Package
import Pattern.*;
class usePattern
{
public static void main(String args[])
{
Pattern p1=new Pattern();
p1.pattern1();
p1.pattern5();
}
}
Output:
E:>javac Pattern.java
E:>cd..
E:>javac usePattern.java
E:>java usePattern
**
***
****
*****
BB
C CC
D DDD
E EEEE
F FFFFF
SOURCE-CODE:
me.consume();
}
public void update( Graphics g )
{
g.drawImage( i, 0, 0, this );
}
public void paint( Graphics g )
{
update(g);
}
}
OUT-PUT: