Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Lab Manual-C21

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 76

JAVA PROGRAMMING LAB PRACTICE – C21

II DIPLOMA IV SEMESTER CODE: CS-407

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

public class test


{
public static void main(String args[])
{
//creating a matrix
int original[][]={{1,3,4},{2,4,3},{3,4,5}};
//creating another matrix to store transpose of a matrix
int transpose[][]=new int[3][3]; //3 rows and 3 columns
//Code to transpose a matrix
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
transpose[i][j]=original[j][i];
}
}
System.out.println("Printing Matrix without transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(original[i][j]+" ");
}
System.out.println();//new line
}
System.out.println("Printing Matrix After Transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(transpose[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output:
3b) Java Program to find the addition of two matrices

public class test


{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,3,4},{2,4,3},{3,4,5}};
int b[][]={{1,3,4},{2,4,3},{1,2,4}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//adding and printing addition of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
} Test it Now

Output:
3c) Java Program to find the subtraction of the two matrices

public class test


{
public static void main(String args[])
{
//creating two matrices
int a[][]={{5,4},{6,4}};
int b[][]={{1,3},{2,1}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
c[i][j]=a[i][j]-b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}

Output:
3d) Java Program to multiply two matrices

public class test


{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//multiplying and printing multiplication of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}
}
Output:
4. Write a Java program on command line arguments.

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

public class Sum{


public int sum(int x,int y){
return (x+y);
}
public int sum(int x,int y,int z){
return (x+y+z);
}
public double sum(double x,double y){
return (x+y);
}
public static void main(String[] args){
Sum s=new Sum();
System.out.println(s.sum(10,20));
System.out.println(s.sum(10,20,30));
System.out.println(s.sum(10.5,20.5));
}
}

Out put :
7)Write a java program to demonstrate static variables and static methods.

7a)demonstrate static variables


public class Student{
int id;
String name;
static String collageName="GPT Masabtank";
Student(int i,String n){
id=i;
name=n;
}
void display(){
System.out.println(id+"\t"+name+"\t"+collageName);
}
public static void main(String[] args){
Student s1=new Student(101,"suresh");
Student s2=new Student(112,"venkat");
s1.display();
s2.display();
}
}

Output :
7.b)demonstrate static methods

public class Mathoperation{


static float mul(float a,float b){
return (a*b);
}

static float div(float a,float b){


return (a/b);
}
public static void main(String[] args) {
float x = Mathoperation.mul(4.0f, 5.0f);
float y = Mathoperation.div(8.0f, 2.0f);
System.out.println("x= " + x + "\ny= " + y);
}
}

Output:
8) Write a Java program to practice using String class and its methods
public class Stringtest{
public static void main(String[] args){

String s1="Hello world";

String s2="Welcome to string methods";

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

public class circle{


public static final double p1=3.14159;

public static void main(String[] args){

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{

public static void printArray(String strArr[])

for(String string:strArr)

System.out.print(string+" ");

System.out.println();

public static void main(String[] args)

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{

public void disA(){

System.out.println("class A");

class B extends A{

public void disB(){

System.out.println("class B");

class C extends B{

public void disC(){

System.out.println("class C");

public class Test extends C{

public static void main(String[] args){

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.

18.a) Write a Java program on hybrid 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.

//creating the package


//file : publicpackA.java
package publicpack;
public class publicpackA{ //class with public access modifier
public void msg(){
System.out.println("public pack");
}
}
//file : publicpackB.java

//trying to access method


import publicpack.publicpackA;
class publicpackB{
public static void main(String[] args){
publicpackA pa=new publicpackA();
pa.msg();
}
}

Output :
20. Write a Java program on access modifiers.

// java program using protected access modifier


//file : Protect.java
package ProtectPack;
public class Protect{
protected void method1(){
System.out.println("protected");
}
}

//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

// program to read from a file using BufferedReader class

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());

System.out.println("the details are : ");


System.out.println("byte : "+bt);
System.out.println("short : "+sh);
System.out.println("int : "+i);
System.out.println("long : "+ln);
System.out.println("float : "+fl);
System.out.println("double : "+db);
}
}
Output:
24) write a java program on applet life cycle
import java.applet.*;
import java.awt.*;
public class MyAppletSkel extends Applet {
public void init() {
System.out.println("applet initialized");
}
public void start() {
System.out.println("applet started");
}
public void paint(Graphics g) {
g.drawString("paint completed ",50,50);
}
public void stop() {
System.out.println("applet stopped");
}
public void destroy() {
System.out.println("applet terminated");
}
}
/*
<applet code="MyAppletSkel.class" width=600 height=600></applet>
*/
Output :
25) write a java program on all awt components along with events and its listeners

25.a)write a java program on Button Control


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class HandleActionEventExample extends Applet implements ActionListener {
String actionMessage="";
public void init(){
Button b1=new Button("OK");
Button b2=new Button("Cancel");
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void paint(Graphics g){
g.drawString(actionMessage,10,50);
}
public void actionPerformed(ActionEvent e){
String action=e.getActionCommand();
if(action.equals("OK")){
actionMessage="OK button pressed";
}
else if(action.equals("Cancel")){
actionMessage="Cancle button pressed";
}
repaint();
}
}
/*
<applet code="HandleActionEventExample.class" width=600 height=600></applet>
*/
Output :
26)write a java program on mouse and keyboard events
26.a) write a java program on mouse events

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 init()


{
addKeyListener(this);

}
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

class MyThread extends Thread


{
public void run()
{
for(int i=0;i<5;i++)
System.out.println("user thread");
}
}
class ThreadTest
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
for(int i=0;i<5;i++)
System.out.println("main thread");
}
}

Output1: Output2: Output3:

main thread main thread main thread


main thread user thread main thread
main thread main thread user thread
main thread user thread user thread
main thread user thread user thread
user thread user thread user thread
user thread main thread user thread
user thread user thread main thread
user thread main thread main thread
user thread main thread main thread
32(ii) Create a thread using implementing Runnable interface

class MyThread implements Runnable


{
public void run()
{
for(int i=0;i<5;i++)
System.out.println("user thread");
}
}
class ThreadTest
{
public static void main(String[] args)
{
MyThread mt=new MyThread();
Thread t=new Thread(mt);
t.start();
for(int i=0;i<5;i++)
System.out.println("main thread");
}
}

Output1: Output2: Output3:

main thread main thread main thread


main thread user thread main thread
main thread main thread user thread
main thread user thread user thread
main thread user thread user thread
user thread user thread user thread
user thread main thread user thread
user thread user thread main thread
user thread main thread main thread
user thread main thread main thread

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 RunnableDemo implements Runnable {


private Thread t;
private String threadName;

RunnableDemo( String name) {


threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + "
interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}
}
Output:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
33 b) Java program using thread priorities.

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:

main thread starts execution of foo()


child thread starts execution of bar()
main thread trying to call b.last()
child thread trying to call a.last()
_
press (CTRL + C) output console will be exited.
37. Write a Java program to establish connection.

Example to connect to the mysql database in java

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.

2. Connection URL: The connection URL for the mysql database is


jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the
server name on which mysql is running, we may also use IP address, 3306 is the port number and
sonoo is the database name. We may use any database, in such case, you need to replace the
sonoo with your database name.

3. Username: The default username for the mysql database is root.

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.

1. create database sonoo;


2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
Example to Connect Java Application with mysql database

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.

Two ways to load the jar file:


1. paste the mysqlconnector.jar file in jre/lib/ext folder

2. set classpath

1) paste the mysqlconnector.jar file in JRE/lib/ext folder:


Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath: 1.temporary 2.permanent
How to set the temporary classpath
open command prompt and write:
1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;

How to set the permanent classpath


Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as
C:\folder\mysql-connector-java-5.0.8-bin.jar;

Output:

Eno Ename designation

111 aaa clerk

222 bbb manager

333 ccc accountant


38. Write a Java program on different types statements.

a) Using Statement interface

// Java Program illustrating Create Statement in JDBC

// Importing Database(SQL) classes


import java.sql.*;

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Try block to check if any exceptions occur


try {

// Step 2: Loading and registering drivers

// Loading driver using forName() method


Class.forName("com.mysql.cj.jdbc.Driver");

// Registering driver using DriverMananger


Connection con = DriverManager.getConnection(
"jdbc:mysql:///world", "root", "12345");

// Step 3: Create a statement


Statement statement = con.createStatement();
String sql = "select * from people";

// Step 4: Execute the querry


ResultSet result = statement.executeQuery(sql);

// Step 5: Process th results

// Condition check using hasNext() method which


// holds true till there is single element
// remaining in List
while (result.next()) {

// Print name an age


System.out.println(
"Name: " + result.getString("name"));
System.out.println(
"Age:" + result.getString("age"));
}
}

// Catching database exceptions if any


catch (SQLException e) {

// Print the exception


System.out.println(e);
}

// Catching generic ClassNotFoundException if any


catch (ClassNotFoundException e) {

// Print and display the line number


// where exceptio occured
e.printStackTrace();
}
}
}

Output:
38 b) Using Callable Statement

// Java Program illustrating Callable Statement in JDBC

// Step 1: Importing DB(SQL) classes


import java.sql.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Try block to check if any exceptions occurs
try {

// Step 2: Establish a conection

// Step 3: Loading and registering drivers

// Loading driver using forName() method


Class.forName("com.mysql.cj.jdbc.Driver");

// Registering driver using DriverManager


Connection con = DriverManager.getConnection(
"jdbc:mysql:///world", "root", "12345");

// Step 4: Create a statement


Statement s = con.createStatement();

// Step 5: Execute the querry


// select * from people

CallableStatement cs
= con.prepareCall("{call peopleinfo(?,?)}");
cs.setString(1, "Bob");
cs.setInt(2, 64);
cs.execute();
ResultSet result
= s.executeQuery("select * from people");

// Step 6: Process the results

// Condion check using nexxt() method


// to check for element
while (result.next()) {

// Print and dispaly elements (Name and Age)


System.out.println("Name : "
+ result.getString(1));
System.out.println("Age : "
+ result.getInt(2));
}
}

// Catch statement for DB exceptions


catch (SQLException e) {

// Print the exception


System.out.println(e);
}

// Catch block for generic class exceptions


catch (ClassNotFoundException e) {

// Print the line number where exception occured


e.printStackTrace();
}
}
}
Output:
39. Write a Java program to perform DDL and DML statements using JDBC.

// Create a table in database using JDBC API.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class CreateTableExample {

public static void main(String args[]) throws SQLException {

//Registering the Driver

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

//Getting the connection

String mysqlUrl = "jdbc:mysql://localhost/SampleDB";

Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");

System.out.println("Connection established......");

//Creating the Statement

Statement stmt = con.createStatement();

//Query to create a table

String query = "CREATE TABLE CUSTOMERS("

+ "ID INT NOT NULL, "

+ "NAME VARCHAR (20) NOT NULL, "

+ "AGE INT NOT NULL, "

+ "SALARY DECIMAL (18, 2), "

+ "ADDRESS CHAR (25) , "

+ "PRIMARY KEY (ID))";

stmt.execute(query);
System.out.println("Table Created......");

Output :

Table created.
40. Write a Java program on Servlet life cycle.

Life cycle of a Servlet


The entire life cycle of a Servlet is managed by the Servlet container which uses
the javax.servlet.Servlet interface to understand the Servlet object and manage it. So, before
creating a Servlet object, let’s first understand the life cycle of the Servlet object which is
actually understanding how the Servlet container manages the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four stages,
 Loading a Servlet.
 Initializing the Servlet.
 Request handling.
 Destroying the Servlet.

Program to create a servlet


// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {


// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {


// do nothing.
}
}
Compiling a Servlet
javac HelloWorld.java
Servlet Deployment
Web.xml

<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>

Above entries to be created inside <web-app>...</web-app> tags available in web.xml file.


There could be various entries in this table already available, but never mind.
You are almost done, now let us start tomcat server using <Tomcat-installationdirectory>\bin\
startup.bat (on Windows) or <Tomcat-installationdirectory>/bin/startup.sh (on Linux/Solaris
etc.) and finally type http://localhost:8080/HelloWorld in the browser's address box. If
everything goes fine, you would get the following result

Output:
41. Write a Java program to handle HTTP requests and responses using doGet() and
doPost() methods.

HTTP Header Response Example


You already have seen setContentType() method working in previous examples and
following example would also use same method, additionally we would
use setIntHeader() method to set Refresh header.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


public class Refresh extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Set refresh, autoload time as 5 seconds


response.setIntHeader("Refresh", 5);

// Set response content type


response.setContentType("text/html");

// Get current time


Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";

String CT = hour+":"+ minute +":"+ second +" "+ am_pm;

PrintWriter out = response.getWriter();


String title = "Auto Refresh Header Setting";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

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"
);
}

// Method to handle POST method request.


public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}

Output :

Current time is : 03:41:40

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 −

You might also like