Java Lab Manual-C21
Java Lab Manual-C21
List of Experiments
1. Write a Java Program to define a class, define instance methods for setting and retrieving
values of instance variables and instantiate its object and operators.
2. Write a Java Program on control and iterative statements.
3. Write a java program to find the transpose, addition, subtraction and multiplication of a two-
dimensional matrix using loops.
4. Write a Java program on command line arguments.
5. Write a Java Program to define a class, describe its constructor, overload the Constructors
and instantiate its object.
6. Write a Java Program to illustrate method overloading.
7. Write a java program to demonstrate static variables and static methods.
8. Write a Java program to practice using String class and its methods.
9. Write a Java program using final members.
10. Write a Java Program to sort a list of names in lexicographical order.
11. Write a Java Program to implement single inheritance.
12. Write a Java Program to implement multilevel inheritance by applying various access
controls to its data members and methods.
13. Write a Java program using ‘this’and ‘super’keyword.
14. Write a java program to illustrate method overriding
15. Write java program to explain the use of final keyword in avoiding method overriding.
16. Write a program to demonstrate the use of interface.
17. Write a java program to implement multiple inheritance using the concept of interface.
18. Write a Java program on hybrid and hierarchical inheritance.
19. Write a Java program to implement the concept of importing classes from user defined
package and creating sub packages.
20. Write a Java program on access modifiers.
21. Write a Java program using util packages.
22. Write a Java program using io packages.
23. Write a Java program using stream classes.
24. Write a Java program on applet life cycle.
25. Write a Java program on all AWT controls along with Events and its Listeners.
26. Write a Java program on mouse and keyboard events.
27. Write a Java program on inbuilt Exceptions.
28. Write a Java program on Exception handling.
29. Write a program to implement multi-catch statements
30. Write a java program on nested try statements.
31. Write a java program to create user-defined exceptions.
32. Write a program to create thread (i)extending Thread class (ii) implementing Runnable
interface
33. Write a java program to create multiple threads and thread priorities.
34. Write a java program to implement thread synchronization.
35. Write a java program on Inter Thread Communication.
36. Write a java program on deadlock.
37. Write a Java program to establish connection with database.
38. Write a Java program on different types statements.
39. Write a Java program to perform DDL and DML statements using JDBC.
40. Write a Java program on Servlet life cycle.
41. Write a Java program to handle HTTP requests and responses using doGet() and doPost()
methods.
1. Write a Java Program to define a class, define instance methods for setting and
retrieving values of instance variables and instantiate its object and operators.
// Employee class.
class Employee {
// Member variables of the class.
private int id;
private String name;
private String designation;
private String company;
public int getId() {
return id;
}
public void setId(final int id) {
[Link] = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
// Validating the name and throwing an exception if name is null or length is <= 0.
if(name == null || [Link]() <= 0) {
throw new IllegalArgumentException();
}
[Link] = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(final String designation) {
[Link] = designation;
}
public String getCompany() {
return company;
}
public void setCompany(final String company) {
[Link] = company;
}
// 'toString()' method to print the values.
@Override
public String toString() {
return "Employee: [id= " + getId() + ", name= " + getName() + ", designation= " +
getDesignation() + ", company= " + getCompany() + "]";
}
}
// Main class.
public class AppMain {
public static void main(String[] args) {
// Creating the employee object.
final Employee myemployee = new Employee();
// Setting the employee details via the setter methods.
[Link](1001);
[Link]("James");
[Link]("Software Developer");
[Link]("ABC Corporation"
// Printing the employee details via the 'toString()' method that uses the getter methods.
[Link]([Link]());
}
}
Output:
2. Write a Java Program on control and iterative statements.
2a) Java program to find the biggest of three numbers using Nested if...else Statement
import [Link];
class test
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
[Link]("Enter three numbers");
int a=[Link]();
int b=[Link]();
int c=[Link]();
if(a>b)
{
if(a>c)
[Link](a+" is big");
else
[Link](c+" is big");
}
else
{
if(b>c)
[Link](b+" is big");
else
[Link](c+" is big");
}
}
}
Output:
2b) Program to find the sum of natural numbers from 1 to 100 using for loop
class test
{
public static void main(String[] args)
{
int sum = 0;
int n = 100;
// for loop
for (int i = 1; i <= n; ++i)
{
// body inside for loop
sum += i; // sum = sum + i
}
[Link]("Sum = " + sum);
}
}
Output:
3. Write a java program to find the transpose, addition, subtraction and multiplication of a
two-dimensional matrix using loops.
3a) Java Program to find the transpose of a matrix
Output:
3c) Java Program to find the subtraction of the two matrices
Output:
3d) Java Program to multiply two matrices
class test
{
public static void main(String args[])
{
[Link]("Your first argument is: "+args[0]);
}
}
Output:
5. Write a Java Program to define a class, describe its constructor, overload the
Constructors and instantiate its object.
class Rectangle{
int length,breath;
Rectangle(int x,int y){
length=x;
breath=y;
}
Rectangle(int x){
length=x;
breath=10;
}
Rectangle(){
length=31;
breath=11;
}
float GetData(){
return (length*breath);
}
}
class ConstructorOverloading{
public static void main(String[] args){
Rectangle rect=new Rectangle();
Rectangle rect1=new Rectangle(200);
Rectangle rect2=new Rectangle(200,700);
[Link]("area is : "+[Link]());
[Link]("area is : "+[Link]());
[Link]("area is : "+[Link]());
}
}
Output :
6)Write a Java Program to illustrate method overloading
Out put :
7)Write a java program to demonstrate static variables and static methods.
Output :
7.b)demonstrate static methods
Output:
8) Write a Java program to practice using String class and its methods
public class Stringtest{
public static void main(String[] args){
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]('l','a'));
[Link]([Link]());
[Link]([Link](s2));
[Link]([Link](s2));
[Link]([Link](5));
[Link]([Link](3));
[Link]([Link](3,8));
[Link]([Link]('i'));
}
Output:
9)write a java program using final members
[Link](p1);
Output:
10)write a java program to sort a list of names in lexicographical order.
import [Link].*;
import [Link];
class GFG{
for(String string:strArr)
[Link](string+" ");
[Link]();
String stringArray[]={"Harit","Girish","Gritav","Lovenish","Nikhil","Harman"};
[Link](stringArray,String.CASE_INSENSITIVE_ORDER);
printArray(stringArray);
Output:
11)write a java program to implement single inheritance.
class Room{
int length,breadth;
Room(int l,int b)
{
length=l;
breadth=b;
}
int area()
{
return(length*breadth);
}
}
class Bedroom extends Room{
int height;
Bedroom(int l,int b,int h)
{
super(l,b);
height=h;
}
int volume()
{
return(length*breadth*height);
}
}
public class InheritTest
{
public static void main(String[] args)
{
Bedroom room1=new Bedroom(10,12,5);
[Link]("Area of Room is:"+[Link]());
[Link]("Volume of Bedroom is:"+[Link]());
}
}
Output:
12) Write a Java Program to implement multilevel inheritance by applying various access
controls to its data members and methods.
class A{
[Link]("class A");
class B extends A{
[Link]("class B");
class C extends B{
[Link]("class C");
C c=new C();
[Link]();
[Link]();
[Link]();
}
Output :
13.a) Write a Java program using ‘this’ keyword.
class Employee{
int id;
String name;
float salary;
Employee(int id,String name,float salary){
id=id;
name=name;
salary=salary;
}
void display(){
[Link](id+" "+name+" "+salary);
}
}
class ThisKeyword{
public static void main(String[] args){
Employee e1=new Employee(12121,"suresh",50000f);
Employee e2=new Employee(112,"venkatesh",60000f);
[Link]();
[Link]();
}
}
Output:
13.b) write a java program using ‘super’ keyword
class Base{
int num=30;
}
class Derived extends Base{
int num=20;
void calThis(){
[Link]("Base 'num' :"+[Link]);
[Link]("Derived 'num' : "+num);
}
}
class SuperKeyword{
public static void main(String[] args){
Derived temp=new Derived();
[Link]();
}
}
Output:
14) Write a java program to illustrate method overriding
class Animal{
void eat(){
[Link]("eating animal");
}
}
class Cow extends Animal{
void eat(){
[Link]("drinking milk");
}
}
class calf extends Cow{
public static void main(String[] args){
Animal a1=new Animal();
Animal a2=new Cow();
Animal a3=new calf();
[Link]();
[Link]();
[Link]();
}
}
Output:
15) Write java program to explain the use of final keyword in avoiding method overriding.
class P{
final void demo(){
[Link]("class P method");
}
}
class C extends P{
void demo(){
[Link]("class C method");
}
public static void main(String[] args){
C obj=new C();
[Link]();
}
}
Output:
16) Write a program to demonstrate the use of interface.
interface Area{
static final float p=3.14f;
float getArea(float x,float y);
}
class Rectangle implements Area{
public float getArea(float x,float y){
return (x*y);
}
}
class Triangle implements Area{
public float getArea(float x,float y){
return (1/2*x*y);
}
}
class Circle implements Area{
public float getArea(float x,float y){
return (p*x*x);
}
}
class interfaceTest{
public static void main(String []args){
Area r,t,c;
r=new Rectangle();
t=new Triangle();
c=new Circle();
[Link]("Area of rectangle : "+[Link](3.4f,2.3f));
[Link]("Area of triangle : "+[Link](3.4f,2.3f));
[Link]("Area of circle : "+[Link](3.4f,2.3f));
}
}
Output:
17) Write a java program to implement multiple inheritance using the concept of interface.
interface MotorBike{
int speed=50;
public void totalDistance();
}
interface cycle{
int distance=150;
public void speed();
}
public class twoWheeler implements MotorBike,cycle{
int totalDistance;
int avgspeed;
public void totalDistance(){
totalDistance=speed*distance;
[Link]("total distance : "+totalDistance);
}
public void speed(){
int avgspeed=totalDistance/speed;
[Link]("average speed : "+avgspeed);
}
public static void main(String[] args){
twoWheeler t1=new twoWheeler();
[Link]();
[Link]();
}
}
Output:
18. Write a Java program on hybrid and hierarchical inheritance.
class C{
public void disp(){
[Link](" C ");
}
}
class A extends C{
public void disp(){
[Link](" A ");
}
}
class B extends C{
public void disp(){
[Link](" B ");
}
}
class D extends A{
public void disp(){
[Link](" D ");
}
public static void main(String[] args){
D obj=new D();
[Link]();
}
}
Output:
18.b) Write a Java program on hierarchical inheritance
class A{
public void methodA(){
[Link]("method of A");
}
}
class B extends A{
public void methodB(){
[Link]("method of B");
}
}
class C extends A{
public void methodC(){
[Link]("method of C");
}
}
class D extends A{
public void methodD(){
[Link]("method of D");
}
}
class javaExample{
public static void main(String[] args){
B obj1=new B();
C obj2=new C();
D d1=new D();
[Link]();
[Link]();
[Link]();
}
}
Output:
19. Write a Java program to implement the concept of importing classes from user defined
package and creating sub packages.
Output :
20. Write a Java program on access modifiers.
//file : [Link]
import [Link];
class Protected extends Protect{
public static void main(String[] args){
Protect p=new Protect();
p.method1();
}
}
Output :
21)write a java program using util package
import [Link].*;
class myClass {
public static void main(String []args) {
Scanner sc=new Scanner([Link]);
[Link]("enter user name : ");
String username=[Link]();
[Link]("use name is : "+username);
}
}
Output :
22)write a java program using IO package
import [Link];
public class ReadTest {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\[Link]");
int i;
while((i=[Link]())!=-1)
[Link]((char)i);
[Link]();
}
}
Output :
23) write a java program using stream classes
import [Link].*;
class ReadData {
public static void main(String[] args) throws Exception{
[Link]("enter byte,short,int,long,float,double values : ");
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
byte bt = [Link]([Link]());
short sh = [Link]([Link]());
int i=[Link]([Link]());
long ln=[Link]([Link]());
float fl=[Link]([Link]());
double db=[Link]([Link]());
import [Link].*;
import [Link].*;
import [Link].*;
public class Mouseevents extends Applet implements MouseListener,MouseMotionListener {
String msg="";
int x=0,y=0;
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g) {
[Link](msg,x,y);
}
public void mouseClicked(MouseEvent e) {
x=10;y=20;
msg="mouse Clicked";
repaint();
}
public void mousePressed(MouseEvent e) {
x=[Link]();y=[Link]();
msg="mouse pressed";
repaint();
}
public void mouseReleased(MouseEvent e) {
x=[Link]();y=[Link]();
msg="mouse released";
repaint();
}
public void mouseEntered(MouseEvent e) {
x=10;y=20;
msg="mouse entered";
repaint();
}
public void mouseExited(MouseEvent e) {
x=10;y=20;
msg="mouse exited";
repaint();
}
public void mouseDragged(MouseEvent e) {
x=[Link]();
y=[Link]();
Graphics g=getGraphics();
[Link]([Link]);
[Link](x,y,5,5);
showStatus("mouse dragged at : "+x+","+y);
}
public void mouseMoved(MouseEvent e) {
showStatus("mouse moved at : "+[Link]()+","+[Link]());
}
}
/*
<applet code="[Link]" height=600 width=600></applet>
*/
Output :
26.b) write a java program on Keyboard events
import [Link].*;
import [Link];
import [Link].*;
public class KeyEvents extends Applet implements KeyListener{
String msg="";
}
public void keyPressed ( KeyEvent ke){
showStatus("Key Pressed");
}
public void keyReleased ( KeyEvent ke){
showStatus("key released");
}
public void keyTyped ( KeyEvent ke){
msg=msg+[Link]();
repaint();
}
public void paint(Graphics g){
[Link](msg,100,50);
}
/*
<applet code="[Link]" height=200 width=300>
</applet>
*/
Output :
27) write a java program on inbuilt exceptions
public class trycatch {
public static void main(String[] args) {
try {
int data=10/0;
}
catch(ArithmeticException e) {
[Link](e);
}
[Link]("result of the code...");
}
}
Output :
28) write a java program on exception handling
public class pointer {
public static void main(String[] args) {
try {
String str=null;
[Link]([Link]());
}
catch (NullPointerException e) {
[Link](e);
}
[Link]("result of the code...");
}
}
Output :
29) Write a java program to implement multicatch statements
public class multicatchblock {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch (ArithmeticException e1) {
[Link]("arithmetic exception occured...");
}
catch (ArrayIndexOutOfBoundsException e2) {
[Link]("arra insec out of bound exception occured..");
}
catch (Exception e3) {
[Link]("unknown exception occured..");
}
[Link]("result of the code..");
}
}
Output :
30) write a java program on nested try statements
public class tryintry {
public static void main(String[] args) {
try {
int arr[]={1,0,4,2};
try {
int x=arr[3]/arr[1];
}
catch (ArithmeticException e) {
[Link]("divide by zero not possible");
}
arr[4]=3;
}
catch (ArrayIndexOutOfBoundsException e2) {
[Link]("array index out of bounds exception..");
}
}
}
Output :
31) write a java program to create user defined exception
class CMEException extends RuntimeException {
CMEException(String s) {
super(s);
}
}
class exceptiontest {
public static void main(String[] args) {
throw new CMEException("diploma CME students");
}
}
Output :
32. Write a program to create thread (i)extending Thread class (ii) implementing Runnable
interface
(i) Create thread using extending Thread class
In the above two programs, as a programmer we can’t expect the exact output. The Thread
Scheduler will decide the exact output.
33. Write a java program to create multiple threads and thread priorities.
a) Java program to create multiple threads.
class test
{
public static void main(String[] args)
{
[Link]("normal priority = "+Thread.NORM_PRIORITY);
[Link]("max priority = "+Thread.MAX_PRIORITY);
[Link]("min priority = "+Thread.MIN_PRIORITY);
}
}
Output:
normal priority = 5
max priority = 10
min priority = 1
34. Write a java program to implement thread synchronization
// thread synchronization
class Table
{
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
[Link](n*i);
try
{
[Link](400);
}
catch (Exception e)
{
[Link](e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
[Link](100);
}
}
class JavaSynch1
{
public static void main(String[] args)
{
Table obj=new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
[Link]();
[Link]();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
35. Write a java program on Inter Thread Communication.
class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
[Link]("going to withdraw...");
if([Link]<amount)
{
[Link]("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{
}
}
[Link]-=amount;
[Link]("withdraw completed...");
}
synchronized void deposit(int amount)
{
[Link]("going to deposit...");
[Link]+=amount;
[Link]("deposit completed... ");
notify();
}
}
class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{
[Link](15000);
}
}.start();
new Thread()
{
public void run()
{
[Link](10000);
}
}
start();
}
}
Output:
going to withdraw...
Less balance; waiting for deposit... going to deposit...
deposit completed... withdraw completed
36. Write a java program on deadlock.
// deadlock example
class A
{
public synchronized void foo(B b)
{
[Link]("main thread starts execution of foo()");
try
{
[Link](5000);
}
catch (InterruptedException e)
{
}
[Link]("main thread trying to call [Link]()");
[Link]();
}
public synchronized void last()
{
[Link]("Inside A, this is last()");
}
}
class B
{
public synchronized void bar(A a)
{
[Link]("child thread starts execution of bar()");
try
{
[Link](5000);
}
catch (InterruptedException e)
{
}
[Link]("child thread trying to call [Link]()");
[Link]();
}
public synchronized void last()
{
[Link]("Inside B, this is last()");
}
}
class Deadlock extends Thread
{
A a=new A();
B b=new B();
public void run()
{
[Link](a);// get lock on b by child thread
}
public void m1()
{
[Link]();
[Link](b);// get lock on a by main thread
}
public static void main(String[] args)
{
Deadlock d=new Deadlock();
d.m1();
}
}
Output:
For connecting java application with the mysql database, you need to follow 5 steps to perform
database connectivity.
In this example we are using MySql as the database. So we need to know following informations
for the mysql database:
1. Driver class: The driver class for the mysql database is [Link].
4. Password: Password is given by the user at the time of installing the mysql database. In this
example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
In this example, sonoo is the database name, root is the username and password.
import [Link].*;
class MysqlCon
{
public static void main(String args[])
{
try
{
[Link]("[Link]");
Connectioncon=[Link]("jdbc:mysql://localhost:3306/
sonoo","root","root”);
//here sonoo is database name, root is username and password
Statement stmt=[Link]();
ResultSet rs=[Link]("select * from emp");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}
The above example will fetch all the records of emp table.
To connect java application with the mysql database [Link] file is required to be
loaded.
2. set classpath
Output:
// Class
class GFG {
Output:
38 b) Using Callable Statement
// Main class
class GFG {
CallableStatement cs
= [Link]("{call peopleinfo(?,?)}");
[Link](1, "Bob");
[Link](2, 64);
[Link]();
ResultSet result
= [Link]("select * from people");
import [Link];
import [Link];
import [Link];
import [Link];
[Link](new [Link]());
[Link]("Connection established......");
[Link](query);
[Link]("Table Created......");
Output :
Table created.
40. Write a Java program on Servlet life cycle.
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Output:
41. Write a Java program to handle HTTP requests and responses using doGet() and
doPost() methods.
if([Link](Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
[Link](docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n"
);
}
doGet(request, response);
}
}
Output :
Now calling the above servlet would display current system time after every 5 seconds as
follows. Just run the servlet and wait to see the result −