0% found this document useful (0 votes)
568 views

Java - Lab File (Shubham Patel - 500053376) PDF

Java Lab File for UPES students.

Uploaded by

Shubham Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
568 views

Java - Lab File (Shubham Patel - 500053376) PDF

Java Lab File for UPES students.

Uploaded by

Shubham Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Experiment – 1 (Introduction to Java Environment)

1) Installation of JDK
2) Setting of path and classpath
3) Introduction to Eclipse

Q1) Write a program to print Hello World


Code
public class HelloWorld{
public static void main(String []args)
{
System.out.println("\n\nHello, I am Shubham Patel");
}
}

Sample O/P:

Q2) Write a program to understand public and default access modifier class.
Code
class HelloWorld{
public static void main(String []args)
{
System.out.println("\n\nHello, I am Shubham Patel");
}
}

Sample O/P:
Q3) Write a program to understand local and instance variable initialization.
a) When the values of the variables have not been initialized
Code
public class HelloWorld{
int a;
public static void main(String [] args)
{
HelloWorld z= new HelloWorld();
int b,c;
System.out.println(b+c);
System.out.println(z.a);
}
}
Sample O/P:
b) When the values of the variables have been initialized
Code
public class HelloWorld{
int a;
public static void main(String [] args)
{
HelloWorld z= new HelloWorld();
int b=1,c=10;
System.out.println(b+c);
System.out.println(z.a);
}
}

Sample O/P:

Experiment – 2 , 3 (Basic Java Programming)

Q1) Write a program to find the largest of 3 numbers.


Code
import java.util.Scanner;
class Largest
{
public static void main(String args[])
{
int x, y, z;
System.out.println("Enter three integers");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
if (x > y && x > z)
System.out.println("First number is largest.");
else if (y > x && y > z)
System.out.println("Second number is largest.");
else if (z > x && z > y)
System.out.println("Third number is largest.");
else
System.out.println("The numbers are not distinct.");
}
}

Sample O/P:

Q2) Write a program to add two number using command line arguments.
Code
class Add
{
public static void main(String[] args) {
int a,b,c;
Scanner sc=new Scanner(System.in);
a=Integer.parseInt(args[0]);
System.out.println("number one is : "+a);
b=Integer.parseInt(args[1]);
System.out.println("number two is : "+b);
c=a+b;
System.out.println("Addition of two numbers is : "+c);
}
}

Sample O/P:

Q3) Write a program to print Fibonacci series using loop.


Code
public class FibonacciExample {
public static void main(String[] args)
{
int maxNumber = 10;
int previousNumber = 0;
int nextNumber = 1;

System.out.print("Fibonacci Series of "+maxNumber+" numbers:");


for (int i = 1; i <= maxNumber; ++i)
{
System.out.print(previousNumber+" ");
int sum = previousNumber + nextNumber;
previousNumber = nextNumber;
nextNumber = sum;
}
}
}

Sample O/P:

Q4) Write a program using classes and object in java.


Code
public class Dog
{
// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// method 1
public String getName()
{
return name;
}

// method 2
public String getBreed()
{
return breed;
}

// method 3
public int getAge()
{
return age;
}

// method 4
public String getColor()
{
return color;
}

@Override
public String toString()
{
return("Hi my name is "+ this.getName()+
".\nMy breed,age and color are " +
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
}

public static void main(String[] args)


{
Dog tuffy = new Dog("tuffy","papillon", 5, "white");
System.out.println(tuffy.toString());
}
}

Sample O/P:
Q5) Write a program to accept 10 student’s marks in an array, arrange it into ascending order,
convert into the following grades and print marks and grades in the tabular form.
Between 40 and 50 : PASS
Between 51 and 75 : MERIT
and above : DISTINCTION
Code
import java.util.Scanner;

public class JavaExample


{
public static void main(String args[])
{
int marks[] = new int[6];
int i;
float total=0, avg;
Scanner scanner = new Scanner(System.in);
for(i=0; i<6; i++) {
System.out.print("Enter Marks of Subject"+(i+1)+":");
marks[i] = scanner.nextInt();
total = total + marks[i]; }
scanner.close();
avg = total/6;
System.out.print("The student Result is: ");
if(avg>75)
{
System.out.print("DISTINCTION");
}
else if(avg>=40 && avg<50)
{
System.out.print("PASS");
}
else if(avg>=50 && avg<=75)
{
System.out.print("MERIT");
}}
}
Sample O/P:
Q6) Write a program to accept three digits (i.e. 0 - 9) and print all its possible combinations.
(For example if the three digits are 1, 2, 3 than all possible combinations are : 123, 132,
213, 231, 312, 321.)
Code
import java.util.Random;
import java.util.Scanner;

public class Permute_All_List_Numbers


{
static void permute(int[] a, int k)
{
if (k == a.length)
{
for (int i = 0; i < a.length; i++)
{
System.out.print(" [" + a[i] + "] ");
}
System.out.println();
}
else {
for (int i = k; i < a.length; i++) {
int temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1);
temp = a[k];
a[k] = a[i];
a[i] = temp;
} }}
public static void main(String args[])
{
Random random = new Random();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the length of list: ");
int N = sc.nextInt();
int[] sequence = new int[N];
for (int i = 0; i < N; i++)
sequence[i] = Math.abs(random.nextInt(100));
System.out.println("The original sequence is: ");
for (int i = 0; i < N; i++)
System.out.print(sequence[i] + " ");
System.out.println("\nThe permuted sequences are: ");
permute(sequence, 0);
sc.close();
} }

Sample O/P:
Q7) Write a Java Program to accept 10 numbers in an array and compute the square of each
number. Print the sum of these numbers.
Code
import java.io.*;
class GFG {
static int squaresum(int n)
{
// Iterate i from 1 and n
// finding square of i and add to sum.
int sum = 0;
for (int i = 1; i <= n; i++)
sum += (i * i);
return sum;
}
public static void main(String args[]) throws IOException
{
int n = 10;
System.out.println(squaresum(n));
}
}

Sample O/P:
Q9) Write a program to find the sum of all integers greater than 40 and less than 250 that are
divisible by 5.
Code
class SumOfDigit{
public static void main(String args[]){
int result=0;
for(int i=40;i<=250;i++){
if(i%5==0)
result+=i;
}
System.out.println("Output of Program is : "+result);
} }

Sample O/P:

Experiment – 4 (Inheritance)

Q1) Write a Java program to show that private member of a super class cannot be accessed from
derived classes.
Code
class room
{
private int l,b;
room(int x,int y)
{ l=x; b=y;}
int area()
{return(l*b);}
}
class class_room extends room
{ int h;
class_room(int x,int y,int z)
{
super(x,y);
h=z;
}
int volume()
{
return(area()*h);
}
}
class s04_01
{
public static void main(String args[])
{
class_room cr=new class_room(10,20,15);
int a1=cr.area();
int v1=cr.volume();
System.out.println("Area of Room : "+a1);
System.out.println("Volume of Room : "+v1);
}
}

Sample O/P:
Q2) Write a program in Java to create a Player class. Inherit the classes Cricket _Player, Football
_Player and Hockey_ Player from Player class.
Code
class player
{
String name;
int age;
player(String n,int a)
{ name=n; age=a; }
void show()
{
System.out.println("\n");
System.out.println("Player name : "+name);
System.out.println("Age : "+age);
}
}
class criket_player extends player
{
String type;
criket_player(String n,String t,int a)
{
super(n,a);
type=t;
}
public void show()
{
super.show();
System.out.println("Player type : "+type);
}
}
class football_player extends player
{
String type;
football_player(String n,String t,int a)
{
super(n,a);
type=t;
}
public void show()
{
super.show();
System.out.println("Player type : "+type);
}
}
class hockey_player extends player
{
String type;
hockey_player(String n,String t,int a)
{
super(n,a);
type=t;
}
public void show()
{
super.show();
System.out.println("Player type : "+type);
}
}
//--------- main -----------
class s04_02
{
public static void main(String args[])
{
criket_player c=new criket_player("Ameer","criket",25);
football_player f=new football_player("arun","football",25);
hockey_player h=new hockey_player("Ram","hockey",25);
c.show();
f.show();
h.show();
}
}

Q3) Write a class Worker and derive classes DailyWorker and SalariedWorker from it. Every
worker has a name and a salary rate. Write method ComPay (int hours) to compute the week pay
of every worker. A Daily Worker is paid on the basis of the number of days he/she works. The
Salaried Worker gets paid the wage for 40 hours a week no matter what the actual hours are.
Test this program to calculate the pay of workers. You are expected to use the concept of
polymorphism to write this program.
Code
class worker
{
String name;
int empno;
worker(int no,String n)
{ empno=no; name=n; }
void show()
{
System.out.println("\n--------------------------");
System.out.println("Employee number : "+empno);
System.out.println("Employee name : "+name);
}
}
class dailyworker extends worker
{
int rate;
dailyworker(int no,String n,int r)
{
super(no,n);
rate=r;
}
void compay(int h)
{
show();
System.out.println("Salary : "+rate*h);
}
}
class salariedworker extends worker
{
int rate;
salariedworker(int no,String n,int r)
{
super(no,n);
rate=r;
}
int hour=40;
void compay()
{
show();
System.out.println("Salary : "+rate*hour);
}
}
//--------- main -----------
class s04_03
{
public static void main(String args[])
{
dailyworker d=new dailyworker(254,"Arjun",75);
salariedworker s=new salariedworker(666,"Unni",100);
d.compay(45);
s.compay();
}
}
Sample O/P:

Q4) Consider the trunk calls of a telephone exchange. A trunk call can be ordinary, urgent or
lightning. The charges depend on the duration and the type of the call. Write a program using the
concept of polymorphism in Java to calculate the charges.
Code
import java.io.*;
class call
{
float dur;
String type;
float rate()
{
if(type.equals("urgent"))
return 4.5f;
else if(type=="lightning")
return 3.5f;
else
return 3f;
}
}
class bill extends call
{
float amount;
DataInputStream in=null;
bill()
{
try
{
in=new DataInputStream(System.in);
}
catch(Exception e)
{ System.out.println(e); }
}
void read()throws Exception
{
String s;
System.out.println("enter call type(urgent,lightning,ordinary):");
type=in.readLine();
System.out.println("enter call duration:");
s=in.readLine();
dur=Float.valueOf(s).floatValue();
}
void calculate()
{
if(dur<=1.5)
amount=rate()*dur+1.5f;
else if(dur<=3)
amount=rate()*dur+2.5f;
else if(dur<=5)
amount=rate()*dur+4.5f;
else
amount=rate()*dur+5f;
}
void print()
{
System.out.println("**********************");
System.out.println(" PHONE BILL ");
System.out.println("**********************");
System.out.println(" Call type : "+type);
System.out.println(" Duration : "+dur);
System.out.println(" CHARGE : "+amount);
System.out.println("**********************");
}
}
class s04_04
{
public static void main(String arg[])throws Exception
{
bill b=new bill();
b.read();
b.calculate();
b.print();
}
}

Sample O/P:

Q5) Design a class employee of an organization. An employee has a name, empid, and salary.
Write the default constructor, a constructor with parameters (name, empid, and salary) and
methods to return name and salary. Also write a method increaseSalary that raises the
employee’s salary by a certain user specified percentage. Derive a subclass Manager from
employee. Add an instance variable named department to the manager class. Supply a test
program that uses theses classes and methods.
Code
public class Employee
{
private String name;
private double salary;
public Employee (String employeeName, double currentSalary)
{
name = employeeName;
salary = currentSalary;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public void raiseSalary(double byPercent)
{
}
}

Sample O/P:

Experiment – 5 (Interface)

Q1) Write a program to create interface named test. In this interface the member function is
square. Implement this interface in arithmetic class. Create one new class called ToTestInt. In this
class use the object of arithmetic class.
Code
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}

Sample O/P:

Q2) Write a program to create interface A, in this interface we have two method meth1 and meth2.
Implements this interface in another class named MyClass.
Code
interface MyInterface
{
public void method1();
public void method2();
}
class Demo implements MyInterface
{
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new Demo();
obj.method1();
}
}

Sample O/P:

Q3) Write a program in Java to show the usefulness of Interfaces as a place to keep constant value
of the program
Code
interface area
{
static final float pi=3.142f;
float compute(float x,float y);
}
class rectangle implements area
{
public float compute(float x,float y)
{return(x*y);}
}
class circle implements area
{
public float compute(float x,float y)
{return(pi*x*x);}
}
class s05_02
{
public static void main(String args[])
{
rectangle rect=new rectangle();
circle cr=new circle();
area ar;
ar=rect;
System.out.println("Area of the rectangle= "+ar.compute(10,20));
ar=cr;
System.out.println("Area of the circle= "+ar.compute(10,0));
}
}

Sample O/P:

Q4) Write a program to create an Interface having two methods division and modules. Create a
class, which overrides these methods.
Code
interface course
{
void division(int a);
void modules(int b);
}
class stud implements course
{
String name;
int div,mod;
void name(String n)
{ name=n; }
public void division(int a)
{ div=a; }
public void modules(int b)
{ mod=b; }
void disp()
{
System.out.println("Name :"+name);
System.out.println("Division :"+div);
System.out.println("Modules :"+mod);
}
}
//--------main---------------
class s05_03
{
public static void main(String args[])
{ stud s=new stud();
s.name("Arun");
s.division(5);
s.modules(15);
s.disp();
}
}

Sample O/P:
Experiment – 6 (Package)

Q1) Write a Java program to implement the concept of importing classes from user defined package
and created packages.
Code
package upes3;
public class sup
{
sup()
{
System.out.println(“CCVT”);
}
public static void main(String [] args)
{
next a = new next();
}
}
class next extends sup
{
next()
{
super();
}
}

Sample O/P:
Q2) Write a program to make a package Balance. This has an Account class with Display_Balance
method. Import Balance package in another program to access Display_Balance method of Account
class.
Code
class s05_01
{
public static void main(String ar[])
{
try
{
balance.account a=new balance.account();
a.read();
a.disp();
}
catch(Exception e)
{ System.out.println(e); }
}
}
package balance;
import java.io.*;
public class account
{
long acc,bal;
String name;
public void read()throws Exception
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the name :");
name=in.readLine();
System.out.println("Enter the account number :");
acc=Long.parseLong(in.readLine());
System.out.println("Enter the account balance :");
bal=Long.parseLong(in.readLine());
}
public void disp()
{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("--- Account Details ---");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Name :"+name);
System.out.println("Account number :"+acc);
System.out.println("Balance :"+bal);
}
}
Sample O/P:

Experiment – 7 (Exceptions)

Q1) Write a program in Java to display the names and roll numbers of students. Initialize
respective array variables for 10 students. Handle ArrayIndexOutOfBoundsExeption, so that any
such problem doesn’t cause illegal termination of program.
Code
package exception;
public class q1 {
public static void main(String[] args) {
String name[] = new String[10];{
name[0] = "Shashank";
name[1] = "Shambhavi";
name[2] = "Rahul";
name[3] = "Shikhar";
name[4] = "Rohit";
name[5] = "Vedanshi";
name[6] = "Shubham";
name[7] = "Shyam";
name[8] = "Ram";
}
int roll[] = new int[10];
roll[0] = 145;
roll[1] = 11;
roll[2] = 57;
roll[3] = 74;
roll[4] = 54;
roll[5] = 67;
roll[6] = 48;
roll[7] = 10;
roll[8] = 100;
try{
roll[9] = 50;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("Names: " );
for(String element: name){
System.out.println(element);
}
System.out.println("Roll Number: ");
for (int k: roll){
System.out.println(k);
}
}
}

Sample O/P:

Q2) Write a Java program to enable the user to handle any chance of divide by zero exception.
Code
class zeroexc
{
public static void main(String ar[])
{
int no=0,m=10,result=0;
try
{
result=m/no;
}
catch(ArithmeticException e)
{
System.out.println(" division by zero ");
System.out.println(" value of result has been set as one");
result=1;
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Result :"+result);
}
}

Sample O/P:

Q3) Create an exception class, which throws an exception if operand is nonnumeric in calculating
modules. (Use command line arguments).
Code
package exception;
import java.util.Scanner;
public class q3 {
static String x;
static String y;
static void comp(String x, String y) throws Exception {
int a = Integer.parseInt(x);
int b = Integer.parseInt(y);
System.out.println("Addition is: " + (a + b));
System.out.println("Subtration is " + (a - b));
}
public static void main(String[] args) {
Scanner ts = new Scanner(System.in);
System.out.println("First Character:");
x = ts.nextLine();
System.out.println("Second Character:");
y = ts.nextLine();
ts.close();
try {
comp(x, y);
}
catch (Exception e) {
System.out.println("Alphanumeric values are not allowed.");
}}}

Sample O/P:

Q4) On a single track two vehicles are running. As vehicles are going in same direction there is no
problem. If the vehicles are running in different direction there is a chance of collision. To avoid
collisions, write a Java program using exception handling. You are free to make necessary
assumptions.
Code
package exception;
public class q4 {
String dir;
q4(String dir){
this.dir=dir;
}
static void compare(q4 a,q4 b) throws Exception {
if(a.dir!=b.dir){
throw new Exception("Accident may occur");
}
else{
System.out.println("You are SAFE");
}
}
public static void main(String[] args) {
q4 car=new q4("North");
q4 truck=new q4("South");
try{
compare(car,truck);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}}}

Sample O/P:

Q5) Write a java program to throw an exception for an employee details.


• If an employee name is a number, a name exception must be thrown.
• If an employee age is greater than 50, an age exception must be thrown.
• Or else an object must be created for the entered employee details
Code
package exception;
public class q5 {
String name;
int age;
static int flag = 0;
q5(String name, int age) {
this.name = name;
this.age = age;}
static void show(q5 obj) throws Exception {
if (obj.age < 50) {
System.out.println("Eligible");}
else {
throw new Exception("Not eligible");}}
static void show1(q5 obj1) throws Exception {
if (obj1.age < 50) {
System.out.println("Eligible");}
else {
throw new Exception("Not eligible");}}
static void display(q5 obj) throws Exception {
int temp = Integer.parseInt(obj.name);
if (temp % 1 == 0) {
flag = 1;
throw new Exception("The name is not valid");}}
static void display1(q5 obj1) throws Exception {
flag=0;
int temp = Integer.parseInt(obj1.name);
if (temp % 1 == 0) {
flag = 1;
throw new Exception("The name is not valid");}}
public static void main(String[] args) {
q5 obj = new q5("89", 45);
q5 obj1 = new q5("Shashank", 54);
try {
show(obj);
} catch (Exception e) {
System.out.println(e);}
try {
show1(obj1);} catch (Exception e) {
System.out.println(e.getMessage());}
try {
display(obj);
} catch (Exception e) {
if (flag == 1) {
System.out.println("The name is not valid");
} else {
System.out.println("The name is valid");}
try {
display1(obj1);
} catch (Exception f) {
if (flag == 1) {
System.out.println(f);} else {
System.out.println("The name is valid");}}}}}

Sample O/P:
Experiment – 8 (Strings Handling and Wrapper Class)

Q1) Write a program for searching strings for the first occurrence of a character or substring and
for the last occurrence of a character or substring.
Code
import java.io.*;
class GFG
{
public static void main (String[] args)
{
String str = "My name is Shubham Patel";
int firstIndex = str.indexOf('a');
System.out.println("First occurrence of char 's'" + " is found at : " + firstIndex);
int lastIndex = str.lastIndexOf('a');
System.out.println("Last occurrence of char 'a' is" + " found at : " + lastIndex);
int first_in = str.indexOf('s', 10);
System.out.println("First occurrence of char 'a'" + " after index 10 : " + first_in);
int last_in = str.lastIndexOf('a', 20);
System.out.println("Last occurrence of char 'a'" + " after index 20 is : " + last_in);
int char_at = str.charAt(20);
System.out.println("Character at location 20: " + char_at);
}
}

Sample O/P:
Q2) Write a program that converts all characters of a string in capital letters. (Use StringBuffer to
store a string). Don’t use inbuilt function.
Code
class Test{
static void convertOpposite(StringBuffer str)
{
int ln = str.length();
for (int i=0; i<ln; i++)
{
Character c = str.charAt(i);
if (Character.isLowerCase(c))
str.replace(i, i+1, Character.toUpperCase(c)+"");
else
str.replace(i, i+1, Character.toLowerCase(c)+"");

}
}

public static void main(String[] args)


{
StringBuffer str = new StringBuffer("My Name Is Shubham Patel");
convertOpposite(str);

System.out.println(str);
}
}

Sample O/P:

Q3) Write a program in Java to read a statement from console, convert it into upper case and
again print on console. (Don’t use inbuilt function)
Code
import java.io.*;
class file
{
public static void main(String a[]) throws IOException
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter file Statement:");
String s1=in.readLine();
System.out.println(s1.toUpperCase());
}
}

Sample O/P:

Q4) Write a program in Java to create a String object. Initialize this object with your name. Find
the length of your name using the appropriate String method. Find whether the character ‘a’ is in
your name or not; if yes find the number of times ‘a’ appears in your name. Print locations of
occurrences of ‘a’ .Try the same for different String objects
Code
package strings;
class ex4 {
String name;
ex4(String n){
name=n;
}
void disp()
{
System.out.println("Name:"+name);
int count=0;
int len=name.length();
for(int i=0;i<len;i++)
if(name.charAt(i)=='A'||name.charAt(i)=='a')
{
count++;
System.out.println("Occurance:"+count);
System.out.println("Position:"+(i+1));
}
if(count==0)
System.out.println("There is no 'A' available in your name");
}
}
class name
{
public static void main(String ar[])
{
ex4 q=new ex4("Shubham Patel");
q.disp();
}
}

Sample O/P:
Q5) Write a Java code that converts int to Integer, converts Integer to String, converts String to
int, converts int to String, converts String to Integer converts Integer to int.

Code
public class StringToIntExample1{
public static void main(String args[]){
String s="200";
int i=Integer.parseInt(s);
System.out.println(i);
}}

Sample O/P:

Q6) Write a Java code that converts float to Float converts Float to String converts String to float
converts float to String converts String to Float converts Float to float.
Code
package com.beginnersbook.string;

public class FloatToString {


public static void main(String[] args) {
float fvar = 1.17f;
String str = String.valueOf(fvar);
System.out.println("String is: "+str);
float fvar2 = -2.22f;
String str2 = Float.toString(fvar2);
System.out.println("String 2 is: "+str2);
}
}
Sample O/P:

Experiment – 9 (Threads and Collections)

Q1) Write a program to implement the concept of threading by extending Thread Class and
Runnable interface.
Code
class Test extends Thread
{
public void run()
{
System.out.println("Run method executed by child Thread");
}
public static void main(String[] args)
{
Test t = new Test();
t.start();
System.out.println("Main method executed by main thread");
}
}

Sample O/P:
Q2) Write a program for generating 2 threads, one for printing even numbers and the other for
printing odd numbers.
Code
public class Mythread {

public static void main(String[] args) {


Runnable r = new Runnable1();
Thread t = new Thread(r);
t.start();
Runnable r2 = new Runnable2();
Thread t2 = new Thread(r2);
t2.start();
}
}

class Runnable2 implements Runnable{


public void run(){
for(int i=0;i<11;i++){
if(i%2 == 1)
System.out.println(i);
}
}
}

class Runnable1 implements Runnable{


public void run(){
for(int i=0;i<11;i++){
if(i%2 == 0)
System.out.println(i);
}
}
}

Sample O/P:

Q3) Write a program to launch 10 threads. Each thread increments a counter variable. Run the
program with synchronization.
Code
class s07_02
{
public static void main(String arg[])throws Exception
{
data d1=new data();
data d2=new data();
data d3=new data();
data d4=new data();
data d5=new data();
data d6=new data();
data d7=new data();
data d8=new data();
data d9=new data();
data d10=new data();
System.out.println(d10.count);
}
}
//---------------------------
class item { static int count=0; }
class data extends item implements Runnable
{
item d=this;
Thread t;
data()
{
t=new Thread(this);
t.start();
}
public void run()
{ d=syn.increment(d); }
}
//==============================
class syn
{
synchronized static item increment(item i)
{
i.count++;
return(i);
}
}

Sample O/P:

Q4) Write a Java program to create five threads with different priorities. Send two threads of the
highest priority to sleep state. Check the aliveness of the threads and mark which thread is long
lasting
Code
import java.lang.*;
class ThreadDemo extends Thread
{
public void run()
{
System.out.println("Inside run method");
}

public static void main(String[]args)


{
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();

System.out.println("t1 thread priority : " +


t1.getPriority()); // Default 5
System.out.println("t2 thread priority : " +
t2.getPriority()); // Default 5
System.out.println("t3 thread priority : " +
t3.getPriority()); // Default 5

t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);

// t3.setPriority(21); will throw IllegalArgumentException


System.out.println("t1 thread priority : " +
t1.getPriority()); //2
System.out.println("t2 thread priority : " +
t2.getPriority()); //5
System.out.println("t3 thread priority : " +
t3.getPriority());//8

// Main thread
System.out.print(Thread.currentThread().getName());
System.out.println("Main thread priority : "
+ Thread.currentThread().getPriority());

// Main thread priority is set to 10


Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : "
+ Thread.currentThread().getPriority());
}
}
Sample O/P:

Experiment – 10 (JDBC and Servlets)


Q1) JDBC: Using JDBC statement objects to execute SQL.
Code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

// assume that conn is an already created JDBC connection (see previous examples)

Statement stmt = null;


ResultSet rs = null;

try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT foo FROM bar");

// or alternatively, if you don't know ahead of time that


// the query will be a SELECT...

if (stmt.execute("SELECT foo FROM bar")) {


rs = stmt.getResultSet();
}

// Now do something with the ResultSet ....


}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed

if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore

rs = null;
}

if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore

stmt = null;
}
}

Sample O/P:

Q2) Servlet: a) ServletContext interface b)getParameterValues( ) of Servlet Request


Code
import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServletDemo extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
PrintWriter pwriter=res.getWriter(); res.setContentType("text/html");
Enumeration en=req.getParameterNames();
while(en.hasMoreElements())
{
Object obj=en.nextElement();
String param=(String)obj;
String pvalue=req.getParameter(param);
pwriter.print("Parameter Name: "+param+
" Parameter Value: "+pvalue);
}
pwriter.close();

}
}

Sample O/P:

Experiment – 11 (JSP)

Q1) Write a JSP page to display current date of the server.


Code
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru current Date</title>
</head>
<body>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</body>
</html>

Sample O/P:

Q2) Write a JSP page to which include the two other JSP page through of include directives
feature provided in JSP.
Code
<%!
int pageCount = 0;
void addCount() {
pageCount++;
}
%>

<% addCount(); %>

<html>
<head>
<title>The include Directive Example</title>
</head>
<body>
<center>
<h2>The include Directive Example</h2>
<p>This site has been visited <%= pageCount %> times.</p>
</center>
<br/><br/>
<br/><br/>
<center>
<p>Copyright © 2010</p>
</center>

<center>
<p>Thanks for visiting my page.</p>
</center>
</body>
</html>

Sample O/P:

Q3) Write a JSP page to create a simple calculator.


Code
<html>
<title>calculator</title>
<head><h1><center>Basic Calculator</center></h1></head>
<body>
<center>
<form action="calculator.jsp" method="get">

<label for="num1"><b>Number 1</b></label>


<input type="text" name ="num1"><br><br>
<label for = "num2"><b>Number 2</b></label>
<input type="text" name="num2"><br><br>

<input type ="radio" name = "r1" value="Add">+


<input type = "radio" name = "r1" value="Sub">-<br>
<input type="radio" name="r1" value ="mul">*
<input type = "radio" name="r1" value="div">/<br><br>

<input type="submit" value="submit">


</center>

</body>
</html>

Sample O/P:

You might also like