Java Lab Manual-C21
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) {
this.id = 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 || name.length() <= 0) {
throw new IllegalArgumentException();
}
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(final String designation) {
this.designation = designation;
}
public String getCompany() {
return company;
}
public void setCompany(final String company) {
this.company = 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.
myemployee.setId(1001);
myemployee.setName("James");
myemployee.setDesignation("Software Developer");
myemployee.setCompany("ABC Corporation"
// Printing the employee details via the 'toString()' method that uses the getter methods.
System.out.println(myemployee.toString());
}
}
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 java.util.Scanner;
class test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter three numbers");
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
if(a>b)
{
if(a>c)
System.out.println(a+" is big");
else
System.out.println(c+" is big");
}
else
{
if(b>c)
System.out.println(b+" is big");
else
System.out.println(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
}
System.out.println("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[])
{
System.out.println("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);
System.out.println("area is : "+rect.GetData());
System.out.println("area is : "+rect1.GetData());
System.out.println("area is : "+rect2.GetData());
}
}
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){
System.out.println(s1.length());
System.out.println(s1.toLowerCase());
System.out.println(s1.toUpperCase());
System.out.println(s1.replace('l','a'));
System.out.println(s1.trim());
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s2.charAt(5));
System.out.println(s2.substring(3));
System.out.println(s2.substring(3,8));
System.out.println(s2.indexOf('i'));
}
Output:
9)write a java program using final members
System.out.println(p1);
Output:
10)write a java program to sort a list of names in lexicographical order.
import java.io.*;
import java.util.Arrays;
class GFG{
for(String string:strArr)
System.out.print(string+" ");
System.out.println();
String stringArray[]={"Harit","Girish","Gritav","Lovenish","Nikhil","Harman"};
Arrays.sort(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);
System.out.println("Area of Room is:"+room1.area());
System.out.println("Volume of Bedroom is:"+room1.volume());
}
}
Output:
12) Write a Java Program to implement multilevel inheritance by applying various access
controls to its data members and methods.
class A{
System.out.println("class A");
class B extends A{
System.out.println("class B");
class C extends B{
System.out.println("class C");
C c=new C();
c.disA();
c.disB();
c.disC();
}
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(){
System.out.println(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);
e1.display();
e2.display();
}
}
Output:
13.b) write a java program using ‘super’ keyword
class Base{
int num=30;
}
class Derived extends Base{
int num=20;
void calThis(){
System.out.println("Base 'num' :"+super.num);
System.out.println("Derived 'num' : "+num);
}
}
class SuperKeyword{
public static void main(String[] args){
Derived temp=new Derived();
temp.calThis();
}
}
Output:
14) Write a java program to illustrate method overriding
class Animal{
void eat(){
System.out.println("eating animal");
}
}
class Cow extends Animal{
void eat(){
System.out.println("drinking milk");
}
}
class calf extends Cow{
public static void main(String[] args){
Animal a1=new Animal();
Animal a2=new Cow();
Animal a3=new calf();
a1.eat();
a2.eat();
a3.eat();
}
}
Output:
15) Write java program to explain the use of final keyword in avoiding method overriding.
class P{
final void demo(){
System.out.println("class P method");
}
}
class C extends P{
void demo(){
System.out.println("class C method");
}
public static void main(String[] args){
C obj=new C();
obj.demo();
}
}
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();
System.out.println("Area of rectangle : "+r.getArea(3.4f,2.3f));
System.out.println("Area of triangle : "+t.getArea(3.4f,2.3f));
System.out.println("Area of circle : "+c.getArea(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;
System.out.println("total distance : "+totalDistance);
}
public void speed(){
int avgspeed=totalDistance/speed;
System.out.println("average speed : "+avgspeed);
}
public static void main(String[] args){
twoWheeler t1=new twoWheeler();
t1.totalDistance();
t1.speed();
}
}
Output:
18. Write a Java program on hybrid and hierarchical inheritance.
class C{
public void disp(){
System.out.println(" C ");
}
}
class A extends C{
public void disp(){
System.out.println(" A ");
}
}
class B extends C{
public void disp(){
System.out.println(" B ");
}
}
class D extends A{
public void disp(){
System.out.println(" D ");
}
public static void main(String[] args){
D obj=new D();
obj.disp();
}
}
Output:
18.b) Write a Java program on hierarchical inheritance
class A{
public void methodA(){
System.out.println("method of A");
}
}
class B extends A{
public void methodB(){
System.out.println("method of B");
}
}
class C extends A{
public void methodC(){
System.out.println("method of C");
}
}
class D extends A{
public void methodD(){
System.out.println("method of D");
}
}
class javaExample{
public static void main(String[] args){
B obj1=new B();
C obj2=new C();
D d1=new D();
obj1.methodA();
obj2.methodA();
d1.methodA();
}
}
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 : Protected.java
import ProtectPack.Protect;
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 java.util.*;
class myClass {
public static void main(String []args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter user name : ");
String username=sc.nextLine();
System.out.println("use name is : "+username);
}
}
Output :
22)write a java program using IO package
import java.io.FileReader;
public class ReadTest {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\simple.java");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Output :
23) write a java program using stream classes
import java.io.*;
class ReadData {
public static void main(String[] args) throws Exception{
System.out.println("enter byte,short,int,long,float,double values : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
byte bt = Byte.parseByte(br.readLine());
short sh = Short.parseShort(br.readLine());
int i=Integer.parseInt(br.readLine());
long ln=Long.parseLong(br.readLine());
float fl=Float.parseFloat(br.readLine());
double db=Double.parseDouble(br.readLine());
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
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) {
g.drawString(msg,x,y);
}
public void mouseClicked(MouseEvent e) {
x=10;y=20;
msg="mouse Clicked";
repaint();
}
public void mousePressed(MouseEvent e) {
x=e.getX();y=e.getY();
msg="mouse pressed";
repaint();
}
public void mouseReleased(MouseEvent e) {
x=e.getX();y=e.getY();
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=e.getX();
y=e.getY();
Graphics g=getGraphics();
g.setColor(Color.red);
g.fillOval(x,y,5,5);
showStatus("mouse dragged at : "+x+","+y);
}
public void mouseMoved(MouseEvent e) {
showStatus("mouse moved at : "+e.getX()+","+e.getY());
}
}
/*
<applet code="Mouseevents.class" height=600 width=600></applet>
*/
Output :
26.b) write a java program on Keyboard events
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
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+ke.getKeyChar();
repaint();
}
public void paint(Graphics g){
g.drawString(msg,100,50);
}
/*
<applet code="KeyEvents.class" 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) {
System.out.println(e);
}
System.out.println("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;
System.out.println(str.length());
}
catch (NullPointerException e) {
System.out.println(e);
}
System.out.println("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) {
System.out.println("arithmetic exception occured...");
}
catch (ArrayIndexOutOfBoundsException e2) {
System.out.println("arra insec out of bound exception occured..");
}
catch (Exception e3) {
System.out.println("unknown exception occured..");
}
System.out.println("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) {
System.out.println("divide by zero not possible");
}
arr[4]=3;
}
catch (ArrayIndexOutOfBoundsException e2) {
System.out.println("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)
{
System.out.println("normal priority = "+Thread.NORM_PRIORITY);
System.out.println("max priority = "+Thread.MAX_PRIORITY);
System.out.println("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++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class JavaSynch1
{
public static void main(String[] args)
{
Table obj=new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
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)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{
}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(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)
{
System.out.println("main thread starts execution of foo()");
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
}
System.out.println("main thread trying to call b.last()");
b.last();
}
public synchronized void last()
{
System.out.println("Inside A, this is last()");
}
}
class B
{
public synchronized void bar(A a)
{
System.out.println("child thread starts execution of bar()");
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
}
System.out.println("child thread trying to call a.last()");
a.last();
}
public synchronized void last()
{
System.out.println("Inside B, this is last()");
}
}
class Deadlock extends Thread
{
A a=new A();
B b=new B();
public void run()
{
b.bar(a);// get lock on b by child thread
}
public void m1()
{
this.start();
a.foo(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 com.mysql.jdbc.Driver.
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 java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/
sonoo","root","root”);
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
The above example will fetch all the records of emp table.
To connect java application with the mysql database mysqlconnector.jar 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
= con.prepareCall("{call peopleinfo(?,?)}");
cs.setString(1, "Bob");
cs.setInt(2, 64);
cs.execute();
ResultSet result
= s.executeQuery("select * from people");
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
System.out.println("Connection established......");
stmt.execute(query);
System.out.println("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(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
out.println(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 −