Java - Lab File (Shubham Patel - 500053376) PDF
Java - Lab File (Shubham Patel - 500053376) PDF
1) Installation of JDK
2) Setting of path and classpath
3) Introduction to Eclipse
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:
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:
Sample O/P:
// 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());
}
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;
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:
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)+"");
}
}
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;
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 {
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");
}
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
// Main thread
System.out.print(Thread.currentThread().getName());
System.out.println("Main thread priority : "
+ Thread.currentThread().getPriority());
// assume that conn is an already created JDBC connection (see previous examples)
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT foo FROM bar");
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:
}
}
Sample O/P:
Experiment – 11 (JSP)
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++;
}
%>
<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:
</body>
</html>
Sample O/P: