Java Lab Manual
Java Lab Manual
For
JAVA PROGRAMMING
Prepared by
DEPARTMENT OF
CSE RIT
JAVA PROGRAMMING LAB MANUAL
CERTIFICATE
Department : CSE
Program : B.TECH
Year : II
Semester : II
IQAC Members:
Name(s):
Signature(s):
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Course Objectives
To develop skills to design and analyze the applications with respect to java programming.
To strengthen the ability to identify and apply the suitable object oriented concept for the given real
world problem.
To gain knowledge in practical applications using concepts of event handling and swings.
The students will learn to write, compile & execute basic java program.
The student will learn the use of data types & variables, decision control structures: if, nested if etc.
The student will learn to use loop control structures: do, while, for etc and will be able to create classes
and objects and use them in their program.
The student will learn the use of oop concept i.e data abstraction & data hiding, encapsulation,
inheritance, polymorphism.
The student will be able create and use threads, handle exceptions and write applets and will learn the
user interfaces and inner classes, wrapper classes, generics.
CO to PO MAPPING:
A B C D E F G H I J K L
CSE RIT
JAVA PROGRAMMING LAB MANUAL
LIST OF EXPERIMENTS
1. Write a program to display the default value of all primitive data types in Java.
2. Write a Java program that prints all real solutions to the quadratic equation ax 2+bx+c = 0. Read in a, b, c
and use the quadratic formula. If the discriminate b2-4ac is negative, display a message stating that there
are no real solutions.
3. The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are 1, 1. Every
subsequent value is the sum of the 2 values preceding it. Write a Java program that uses both recursive and
11. Write a java program that checks whether a given string is a palindrome or not. Ex: MADAM is a
palindrome.
12. Write a java program that prompts the user for an integer and then prints out all the prime numbers up
to that Integer.
13. Write a java program that performs call by value and call by reference.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
14. Write a java program that gives an example for this operator and the use of this keyword.
15. Write a java program that gives an example for super keyword.
16. Write a java program that gives demonstration of static variables and methods.
19. Write a java program that demonstrates the difference between method overloading and overriding.
20. Write a java program that demonstrates the difference between method overloading and constructor
overloading.
21. Write a java program that describes the exception handling mechanism.
22. Write a java program that uses try and catch blocks and check whether the given array size is negative or
not.
23. Write a java program that describes the user defined exception.
24. Write a java program that illustrates the creation of threads by using runnable class.
25. Write a java program that illustrates the creation of threads by extending Thread class a constructor that
calls the base class constructor, using super and starts the thread. Run method of the class starts after this.
It can be observed by both main thread and created child thread is executed concurrently.
26. Write a java program that illustrates the multiple inheritances by using interfaces.
27. Write a java program to create a package named p1, and implement this package in ex1 class.
28. Write a java program to create a package named my pack, and import it in circle class.
29. Write a java program that illustrates the example for abstract class.
30. Write a java program that describes the life cycle of an applet.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
34. Write a java program that displays the x and y position of the cursor movement using Mouse.
35. Write a java program that displays the number of characters, lines and words in a text file.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
SCHEDULE/CYCLE CHART
SI NO PROGRAM NAME/NUMBER DATE
1 Primitive data types in java
2 Roots of a Quadratic equation
3 Fibonacci sequence
4 Command line arguments
5 Sorting integer numbers
6 Linear search
7 Binary search
8 Addition of two matrices
9 Multiplication of two matrices
10 Sorting list of names
11 Palindrome
12 Range of n numbers
13 Call by value and call by reference
14 This keyword
15 Super keyword
16 Static blocks and variables
17 Simple inheritance
18 Multilevel inheritance
19 Method overloading and overriding
20 Method overloading and constructor overloading
21 Creation of threads using runnable class
22 Creation of threads extending Thread class
23 Multiple Inheritance using interfaces
24 Abstract classes
25 Exception handling
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 1:
Write a program to display the default value of all primitive data types in Java.
Algorithm:
Step1: start
Step3: declare some static variables b, s, l, f, d, char c and bl of different data types.
Step4: declare a function main() and print the default values of all the data types which we declared.
Step5: stop
Source code:
class def
{
static byte b;
static short s;
static int i;
static long l;
static float f;
static double d;
static char c;
System.out.println("Byte:"+b);
System.out.println("Short :"+s);
System.out.println("Int :"+i);
System.out.println("Long :"+l);
System.out.println("Float :"+f);
System.out.println("Double :"+d);
CSE RIT
JAVA PROGRAMMING LAB MANUAL
System.out.println("Char :"+c);
System.out.println("Boolean :"+bl);
}
}
Expected output:
Byte :0
Short: 0
Int: 0
Long : 0
Float: 0
Double:0
Boolean : false
Actual Input&output :
VIVA VOICE:
The default values are the values given by the java run time system if we wont specify any values.
A variable of a non-primitive type doesn't contain the value directly; instead, it is a reference
(similar to a pointer) to an object. (It is not possible in Java to create user-defined value types).
Java has eight primitive types: byte, short, int, long, char, Boolean, float and double.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 2:
Write a Java program that prints all real solutions to the quadratic equation ax 2+bx+c = 0. Read in a, b, c and
use the quadratic formula. If the discriminate b2-4ac is negative, display a message stating that there are no real
solutions.
Algorithm:
Step1: start
Step3: declare a main () function inside the class which throws IOException.
Step9: if the disc value is zero then print the values are real and equal.
Step10: if the disc value is greater than zero then print the values are real and unequal.
Step11: if the above step 9 and 10 fails then print the statement as roots are imaginary.
Step12: Stop
Source code:
import java.io.*;
class Quadratic
{
public static void main(String args[])throwsIOException
{
double x1,x2,disc,a,b,c;
InputStreamReader obj=new InputStreamReader(System.in);
CSE RIT
JAVA PROGRAMMING LAB MANUAL
a=Double.parseDouble(br.readLine());
b=Double.parseDouble(br.readLine());
c=Double.parseDouble(br.readLine());
disc= (b*b)-(4*a*c);
if (disc==0)
}
else if(disc>0)
x1=(-b+Math.sqrt(disc))/(2*a); x2=(b+Math.sqrt(disc))/(2*a);
}
else
CSE RIT
JAVA PROGRAMMING LAB MANUAL
VIVA QUESTIONS:
1)What is a class?
Ans. Class is a blue print/template, encapsulated with data members and methods
.
2)What is public?
Ans. It is a access specifier to access properties from any part of program
4)What is println
Ans. It is a output method to result message/data on screen
6)What is static?
Ans. Static keyword is to declare global members and methods.
9)What is a keyword?
Ans. Keyword is reserved word for specific purpose.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 3:
The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are 1, 1. Every
subsequent value is the sum of the 2 values preceding it. Write a Java program that uses both recursive and
non-recursive functions to print the nth value of the Fibonacci sequence.
Algorithm:
Step1: start
Step2: declare a class known as Fib.
Step3: declare the main() function inside the class.
Step4: intialize the variables I,a=1,b=1,c=0,t.
Step4: take the value of t.
Step5: print a and b.
Step6: intialize the value of i from 0 to t-2.
Step7: value of sum of a and b is stored in c and swap.
Step8: print the value of c.
Step9: print the series upto given value.
Step10: stop
Source code :
import java.util.Scanner;
class Fib {
System.out.print(a);
System.out.print(" "+b);
for(i=0;i<t-2;i++) {
c=a+b;
a=b;
CSE RIT
JAVA PROGRAMMING LAB MANUAL
b=c;
System.out.print(" "+c);
}
System.out.println();
System.out.print(t+"th value of the series is: "+c);
/* Recursive Solution*/
Algorithm:
Step1: start
Step2: declare a class demo.
Step3: define a function fib.
Step3.1: if n equals 1 and return 1.
Step3.2: elseif n equals 2 and return 1.
Step3.3: else return (fib(n-1)+fib(n-2))
Step4: declare a class recfibdemo.
Step5: declare a main() function inside the class which throws IOException.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Step11: stop
Source code:
import java.io.*;
import java.lang.*;
class Demo {
int fib(int n) {
if(n==1)
return (1);
else if(n==2)
return (1);
else
return (fib(n-1)+fib(n-2));
}
class RecFibDemo {
CSE RIT
JAVA PROGRAMMING LAB MANUAL
int res=0;
for(int i=1;i<=n;i++)
{
res=ob.fib(i);
System.out.println(" "+res);
System.out.println();
Viva voice:
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Ans: No! Byte code consists of machine independent code, which is translated at runtime of program. But .obj
file consists of machine language, which is machine dependent.
6) What is an object?
Ans: It is a runtime entity, which is instance of class
8) What is an interface?
Ans: Interface is pure abstract class, which will be implemented by sub-classes.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 4:
Step1: start
Step2: declare a class com.
Step3: declare a function main() function.
Step4: if the length of the arguments equals 0.
Step4.1: print no command line arguments.
Step5: else print the number of command line arguments length.
Step6: initialize i value from 0 to arguments length obtained.
Step7: stop.
Source code :
class com
if(args.length==0)
{
System.out.println("number of command line arguments");
System.out.println(args.length);
System.out.println("they are:"); for (int i = 0; i < args.length; i++)
{
System.out.println(args[i]);
}
}
}
}
CSE RIT
JAVA PROGRAMMING LAB MANUAL
1) What is Integer.parseInt?
Ans: Integer is a Wrapper class associated to int data type. parseInt() function converts String data to integer.
7)What is javac?
Ans: javac is java compiler. To compile source program to byte code file.
10)What is a package?
Ans: Package is collection of classes/interfaces and compartmented as folders/directories.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 5:
Algorithm:
Step1: start.
Step10: stop.
Source code :
class sorting
{
public static void main(String args[])
{
int number[]={55,40,80,65,71};
int n=number.length; System.out.println("given list");
for(int i=0;i<n;i++)
System.out.println(""+number[i]);
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
CSE RIT
JAVA PROGRAMMING LAB MANUAL
{
if(number[i]<number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
}}
}
System.out.println("sorted list");
for(int i=0;i<n;i++)
System.out.println(""+number[i]);
System.out.println("");
CSE RIT
JAVA PROGRAMMING LAB MANUAL
VIVA-VOCE
1)What is an array?
Ans: Array is a collection of homogenous data elements. Each of it is referred by index value.
3)What is the difference between structured programming and object oriented programming?
Ans: Structured programming consists principles of Modularity, Top-down approach and unit/system testing. But OOP
contains along with SOP features there are Inheritance, polymorphism and Data hiding etc.,.
5)What is hierarchy?
Ans: Hierarchy is a top-down approach. A top module/class controls/inherits into all sub-classes/modules.
6)What is abstraction?
Ans: Defining overview of generic methods is abstract. Abstraction is not full details only sigantures.
10)What is CLASSPATH?
Ans: Classpath defines default package roots. Every class it checks from specified root.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 6:
Algorithm:
Step1: start
Step2: declare a class linear .
Step3: declare a main() function inside the class.
Step8: if the array element equals search element then display the element and break.
Step8.1: if find_index!=-1 display the position of search element found.
Step8.2: elseif display search element not found.
Step9: stop.
Source code :
int[] array={10,1,28,13,44,5,36,97,18,11};
System.out.println(" The contents of the Array are :");
for(int i=0;i<array.length;i++)
int search_element=44;
int find_index=-1;
for(int j=0;j<(array.length-1);j++)
CSE RIT
JAVA PROGRAMMING LAB MANUAL
if(array[j]==search_element)
find_index=j;
break;
}
if(find_index!=-1)
{
System.out.println(" The search element is : " + search_element);
System.out.println(" It is found in the array at position : " + find_index);
}
else
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 7:
Algorithm:
Step1: start.
Step3: declare a main() function inside the class which throws IOException.
Step9: declare a search function and intialilze an array ar[] and a variable find.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Source code :
import java.io.*;
public class binary{
}
public static int search(int ar[], int find) {
int start = 0;
return mid;
}
}
return -1;
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 8:
Algorithm:
Step1: start
Step2: declare a class known as matrixsum.
Step3: declare a main() function inside the class matrixsum.
Step4: intialize variables i, j and two dimensional arrays for a and b.
Step9: stop.
Source code :
import java.util.*;
public class matrixsum {
for(j=0;j<2;j++)
CSE RIT
JAVA PROGRAMMING LAB MANUAL
}
System.out.println("Enter Other Matrix");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
System.out.println("Enter Number :");
b[i][j] = input.nextInt();
}
}
System.out.println("Sum :-");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++) System.out.print(a[i][j]+b[i][j]+" ");
Enter number:
1
Enter number:
2
Enter number:
3
Enter number:
4
Enter number:
1
Enter number:
2
Enter number:
3
Enter number:
4
Sum is:
CSE RIT
JAVA PROGRAMMING LAB MANUAL
2468
Actual Input & Output :
Viva voice:
1) Can we perform matrix addition for matrices with different rows and columns?
Yes we can perform matrix addition for matrices with different rows and columns.
2) What is the minimum condition to perform matrix addition?
The row column element of the first matrix must be added with the row column element of the second
matrix.
The value is stored in the corresponding row column element.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 9:
Algorithm:
Step1: start
Step2: declare a class known as matrixmul.
Step3: declare a main() function inside the class matrixmul which throws IOException.
Step4: intialize arrays x[][], y[][], z[][] and test function is call using objects obj1 and obj2.
Step5: create obj1 for matrix1 i.e., x and obj2 for matrix 2 i.e., y.
Step6: arrayz[][] stores the resultant value of findmul() for x and y.
Step7: goto step9 to step 23.
Step8: display the resultant matrix.
Step9: declare a class known as test.
Step10: intialize variables r1,c1,r2,c2.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Source code :
this.c1=c1;
this.r2=r2;
this.c2=c2;
}
int[ ][ ] getArray(int r,int c) {
int arr[][]=new int[r][c];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
arr[i][j]=input.nextInt();
return arr;
}
int[ ][ ] findMul(int a[ ][ ],int b[ ][ ]) {
int c[][]=new int[r1][c2];
}
return c;
CSE RIT
JAVA PROGRAMMING LAB MANUAL
System.out.println();
System.out.println("MATRIX-2:");
y=obj2.getArray(3,2);
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
1) Can we perform matrix multiplication for matrices with different rows and columns?
Yes we can perform matrix multiplication for matrices with different rows and columns.
The column number of first matrix must have the same row number of second matrix.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 10:
Write a java program for sorting a given list of names.
Algorithm:
Step1: start
Step3: declare a main() function inside the class which throws IOException.
Step4: create an obj1 that calls functions Test(4), getArray() , obj1.check() , and obj1.display().
Step13: declare a function inside the class which throws ArrayIndexOutBound Exception.
Step15: compare arr[i] with arr[j] and swap strin s1, arr[i], arr[j] and return arr.
Step16: declare a function inside the class which throws ArrayIndexOutBound Exception.
Step18: stop.
Source code:
import java.io.*;
class Test {
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Test(int n) {
len=n;
arr=new String[n];
}
String[ ] getArray()throws IOException {
return arr;
if ((arr[i].compareTo(arr[j]))>0)
{
String s1=arr[i];
arr[i]=arr[j];
arr[j]=s1;
return arr;
}
void display()throws ArrayIndexOutOfBoundsException
{
System.out.println ("Sorted list is---");
CSE RIT
JAVA PROGRAMMING LAB MANUAL
for (i=0;i<len;i++)
System.out.println(arr[i]);
class Ascend
{
obj1.getArray();
obj1.check();
obj1.display();
Gerbil
Hamster
Mouse
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
3) What are the various in built functions that are available on strings?
Strlen(), Strcmp(), Strcat() are some of the functions that are used to manipulate the strings.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 11:
Write a java program that checks whether a given string is a palindrome or not.
Algorithm:
Step1:start
Step3: declare a main() function inside the class which throws IOException.
Step11: stop.
Source code:
import java.io.*;
class Palind {
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string to check for palindrome:");
String s1=br.readLine();
StringBuffer sb=new StringBuffer();
sb.append(s1);
sb.reverse();
CSE RIT
JAVA PROGRAMMING LAB MANUAL
String s2=sb.toString();
if(s1.equals(s2))
System.out.println("palindrome");
else
System.out.println("not palindrome");
Viva voice:
1) What is a palindrome?
If we reverse the characters of a given string then we should get the same string, that particular string is
called a palindrome.
2) What is the inbuilt function that is available in java to perform string reversal?
Reverse () is the inbuilt function that is available in java to perform string reversal.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 12 :
Write a java program that prompts the user for an integer and then prints out all the numbers up to that Integer.
Algorithm:
Step1: start.
Step12: stop.
Source code:
import java.util.*;
Class test
{
void check(int num)
{
CSE RIT
JAVA PROGRAMMING LAB MANUAL
if(i%j==0)
break;
else if((i%j!=0)&&(j==i-1))
System.out.print( +i);
}
}
{
public static void main(String args[ ]) {
Test obj1=new Test();
Scanner input=new Scanner(System.in);
System.out.println("Enter the value of n:");
int n=input.nextInt();
obj1.check(n);
}
Viva voice:
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 13 :
Write a java program that performs call by value and call by reference.
Algorithm for call by value:
Step1: start.
Step2: declare a class known as byvalue.
Step3: intialize and declare the integer variable data with value 50.
Step4: declare a function change with integer variable data.
Step5: calculate data=data+100.
Step6: declare a main function inside the class byvalue.
Step7: create an object op in class byvalue.
Step8: display the value of data before change.
Step9: make a function call to change() using operator op.
Step10: display the value of data after change.
Step11: stop.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Before change 50
After change 50
Step1: start
Step11: stop.
class Operation2
{
int data=50;
CSE RIT
JAVA PROGRAMMING LAB MANUAL
}
public static void main(String args[])
{
Operation2 op=new Operation2();
System.out.println("before change "+op.data);
op.change(op);//passing object
Before change: 50
After change: 150
Viva voice:
CSE RIT
JAVA PROGRAMMING LAB MANUAL
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 14 :
Algorithm:
Step1: start.
Step3: intialize variables length and breadth using access specifier private.
Step4: make a function call to function named same as class name, rectangle with one formal parameter.
Step7: make a function call to function named same as class name, rectangle with two formal parameters.
Step13: create an object rect and values to the class rectangle is given.
Step15: stop.
Source code:
class Rectangle
{
private int length;
private int breadth;
Rectangle(int length)
{
this.length = length;
CSE RIT
JAVA PROGRAMMING LAB MANUAL
{
this(length);
this.breadth = breadth;
}
public int area()
{
return (length*breadth);
}
}
public class ThisTest
{
public static void main(String [] args)
{
Rectangle rect = new Rectangle(5,5);
Viva voice:
1) Why we use This keyword in java?
To resolve the name ambiguity between the member of a class and the field of a function.
2) How can we assign the value to a data member using this keyword?
By using the dot operator( period operator).
CSE RIT
JAVA PROGRAMMING LAB MANUAL
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 15:
Algorithm:
Step 1: start
Step 2: declare a class vehicle
Step 3: initialize variable speed=50
Step 4: declare a class Bike extended from Vehicle
Step 5: initialize the variable speed=100
Step 6: Start a function display
Step 7: Print the value of speed using super keyword.
Step 8: Start the main class\
Step 9: Create an object for class Bike
Step 10: Call the function display using object of Bike
Step 11: Stop
Source code:
class Vehicle
{ int speed=50;
}
class Bike extends Vehicle{
int speed=100;
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Algorithm:
Source code:
Class Vehicle{
Vehicle ()
{
System.out.println("Vehicle is created");}
}
class Bike extends Vehicle{
Bike()
{
super();//will invoke parent class constructor System.out.println("Bike is created");
}
public static void main(String args[]){
Bike b=new Bike();
}
}
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Algorithm:
Source code:
class Person{
void message()
{
System.out.println("welcome");
}
}
class Student extends Person{
void message()
{
System.out.println("welcome to java");
}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student s=new Student();
s.display();
}
}
Welcome to java
welcome
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
4. In a case where there are no instance variables what does the default constructor initialize?
Ans. Java expects the superclass ( Object Class ) constructor to be called while creation of any object.
So super constructor is called in case there are no instance variables to initialize.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 16:
Algorithm:
Step 1: Start
Step 2: declare a class StaticDemo
Step 3: initialise static variables x=10 and y=5.
Step 4: Declare the main class.
Step 5: Create an object instance1 for the class StaticDemo.
Step 6: Create an object instance2 for the class StaticDemo.
Step 7: print the values of instance1.
Step 8: Print the values of instance2.
Step 9: initialise x=10 and y=15 of instance1.
Step 10: Print the values of instance1 and instance2.
Step 11: stop.
Source code:
instance1.Y = 10;
}
Expected Input & Output :
instance1.x = 10 instance1.y = 5
instance2.x = 10 instance2.y = 5
after updating x value to 15 and y value to 10 from instance1 :
instance1.x = 15 instance1.y = 10
instance2.x = 15 instance2.y = 5
Actual Input & Output :
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
Method which is having static in its method definition is known as static method
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 17:
Write a java program that illustrates the simple inheritance.
Algorithm:
Step 1: start
Step 2: declare a class A
Step 3: declare variables i and j.
Step 4: define a constructor of A with arguments a and b.
Step 5: initialize i=a and j=b.
Step 6: define a function Show.
Step 7: print the values of i and j.
Step 8: Declare a class B extended from A
Step 9: Declare a variable k.
Step 10: Define a constructor for B with arguments a,b, and c.
Step 11: Invoke super(a,b)
Step 12: initialize k=c.
Step 13: Define a function show
Step 14: Print the value of k.
Step 15: Declare the class Override
Step 16: Declare the main class.
Step 17: create an object for the class B.
Step 18: invoke the function show using the object of B.
Step 19: stop.
Source code:
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
void show()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
CSE RIT
JAVA PROGRAMMING LAB MANUAL
}
void show(String msg)
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show("This is k");
subOb.show();
}
}
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
1) What is inheritence?
Inheritence is the property of acquiring the contents from one class to the another class.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 18:
Step 1: start.
Step 2: Declare a class Student.\
Step 3: declare the variables rollno and name.
Step 4: Define a constructor of Student with arguments r of integer type and n of string
Step 5: initialize rollno=r and name=n.
Step 6: Define a function dispdata
Step 7: print rollno and name.
Step 8: Declare a class marks extended from Student.
Step 9: Declare the variable total.
Step 10: create a constructor of marks with r, n of type string and t.
Step 11: invoke super|(r,n).
Step 12: initialize total=t.
Step 13: Define function dispdatam.
Step 14: print total.
Step 15: Declare a class Percentage extended from marks
Step 16: Create the constructor of Percentage with arguments r,n,t,p.
Step 17: invoke super(r,n,t).
Step 18: initialize p=per.
Step 19: Define a function dispdatap.
Step 20: Print per.
Step 21: Declare class MultiLevel.
Step 22: Declare the main class.
Step 23: call constructor of class percentage.
Step 24: invoke dispdatap.
Step 25: Stop.
Source code:
class student
{
int rollno;
String name;
student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas()
{
CSE RIT
JAVA PROGRAMMING LAB MANUAL
class Multilevel
{
public static void main(String args[])
{
percentage stu = new percentage(1912, "SAM", 350, 50); //call constructor percentage stu.dispdatap();
}
}
Expected Input & Output :
Rollno =1912
Name=SAM
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Total=350
Percentage=50
Actual Input & Output :
Viva voice:
1) What is inheritance?
Inheritance is the property of acquiring the contents from one class to another class.
If the derived class is obtained from a base class and the derived class itselfacts as a base class and
derives the further subclass is called multilevel inheritance.
The Different forms of inheritance are:Single, Multiple, Multilevel, Hybrid and Hierarchical.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 19:
Write a java program that demonstrates the difference between method overloading and
Overriding.
Algorithm:
Step 1: Start
Step 2: Declare a class OverloadingOverridingTest
Step 3: Declare the main class.
Step 4: Create an CheapLoan object for the class Loan.
Step 5: Create an object VeryCheapLoan for the class Loan
Step 6: Create an object personalLoan for the class Loan.
Step 7: take the value of personalLoan.
Step 8: Declare a class Loan.
Step 9: Declare the variables interestRate,customer and lender.
Step 10: Create an object fro the cl;ass Loan.
Step 11: initialize the value of lender and interestRate.
Step 12: return loan.
Step 13: Declare a class Personal loan extending Loan.
Step 14: return string.
Step 15: stop.
Source code:
public class OverloadingOverridingTest {
public static void main(String[] args) {
// Example of method overloading in Java
// Loan cheapLoan = Loan.createLoan("HSBC");
Loan veryCheapLoan = Loan.createLoan("Citibank");
// Example of method overriding in Java
Loan personalLoan = new PersonalLoan();
personalLoan.toString();
System.out.println(" loan by citi bank");
}
}
class Loan {
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 20:
Write a java program that demonstrates the difference between method overloading and
Constructor overloading.
Method overloading:
Algorithm:
Step 1: start
Step 2: Declare a class MethodOverloading.
Step 3: Define a method add with a,b as arguments.
Step 4: compute sum=a+b.
Step 5: print sum.
Step 6: Define a method add with a,b,c as arguments.
Step 7: compute sum=a+b+c.
Step 8: Print sum.
Step 9: Declare the main class.
Step 10: Create an object for the class MethodOverloading.
Step 11: invoke add(int a, int b)
Step 12: invoke add(int a,int b,int c)
Step 13: stop
Source code:
class MethodOverloading
{
int sum=a+b;
System.out.println("Sum of two numbers = "+sum);
}
void add(int a,int b,int c)
{
int sum=a+b+c;
CSE RIT
JAVA PROGRAMMING LAB MANUAL
overloading.add(5,6);
overloading.add(5,6,7);
Constructor overloading:
Algorithm:
Step 1: start
Step 2: Declare a class Language.
Step 3: declare variable name.
Step 4: Create a constructor for the class Language.
Step 5: Create a constructor for the class Language with t of type string as argument.
Step 6: initialize name=t.
Step 7: Declare the main class.
Step 8: Create the object cpp for the class Language.
Step 9: Create an object java for the class Language.
Step 10: invoke the method setName with cpp.
Step 11: invoke the method setName with java.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Source code:
Language() {
Language(String t) {
name = t;
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 21:
Write a java program that illustrates the creation of threads by using runnable class.
Algorithm:
Step 1: start
Step 2: Declare the class FirstThread implementing runnable
Step 3: Define function run()
Step 4: for i=1to 10
Step 4.1: print message from FirstThread i.
Step 4.2: Start try
Step 4.2.1:invoke Thread.sleep(1000)
Step 4.3: Catch Interrupted Exception
Step 4.3.1: print interrupted exception
Step 5: Declare SecondThread implementing runnable.
Step 6: Define run()
Step 7: for i=1 to 10
Step 7.1: print message from SecondThread
Step 7.2: start try
Start 7.3: invoke Thread.sleep(1000)
Step 7.4: Catch Interrupted Exception
Step 7.5: : print interrupted exception
Step 8: Declare class ThreadDemo
Step 9: Declare the main class
Step 10: Create object for FirstThread.
Step 11: Create object for SecondThread
Step 12: create object thread1 of class Thread.
Step 13: invoke start() using object thread1
Source code:
CSE RIT
JAVA PROGRAMMING LAB MANUAL
try
{
Thread.sleep (1000);
}
try
{
Thread.sleep(1000);
CSE RIT
JAVA PROGRAMMING LAB MANUAL
}
}
}
public class ThreadDemo
{
public static void main(String args[])
}
Expected Input & Output :
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
1) What is a thread?
A program which contains two or more parts that can run concurrently. Each part of a such program is
called thread.
There are two types of multitasking : process based multitasking and thread based multitasking
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 22:
Write a java program that illustrates the creation of threads by extending the Thread class
Algorithm:
Step 1: start
Step 2: Declare a class firstThread extended by Thread.
Step 3: start run()
Step 4: for i=1 to 1<=5
Step 4.1: print message from thread i.
Step 4.2: start try
Step 4.3: sleep(1000)
Step 4.4: Catch InterruptedException.
Step 4.5: print InterruptedException.
Step 5: Declare a class SecondThread
Step 6: start run()
Step 7: for i=1 to i<=5
Step 7.1: print message from thread i
Step 7.2: start try
Step 7.3: sleep(1000)
Step 7.4: Catch InterruptedException
Step 7.5: print InterruptedException.
Step 8: Declare class ThreadDemo
Step 9: Declare main class
Step 10: Create object for FirstThread.
Step 11: Create object for SecondThread.
Step 12: invoke start() using object of class FirstThread.
Step 13: invoke start() using object of SecondThread.
Step 14: stop.
Source code:
Thread.sleep(1000);
CSE RIT
JAVA PROGRAMMING LAB MANUAL
}
catch (InterruptedException interruptedException)
{
System.out.println( "First Thread is interrupted when it is sleeping" +interruptedException);
{
public void run()
{
for (int i=1; i<=6; i++)
{
System.out.println( "Messag from Second Thread : " +i);
try
{
Thread.sleep (1000);
}
catch (InterruptedException interruptedException)
{
System.out.println( "Second Thread is interrupted when it is sleeping" +interruptedException);
}
public class ThreadDemo
CSE RIT
JAVA PROGRAMMING LAB MANUAL
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 23:
Write a java program that illustrates the multiple inheritances by using interfaces.
Algorithm:
Source code:
interface A{
void method();
}
interfaceB{
void method();
}
class C implements A, B{
public void method(){
System.out.println(" executed method ");
}
public static void main(String[] args){ C c = new C();
c.method(); //been called and prints sysout message.
}
}
Executed method
Actual Input & Output :
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
1) What is an interface?
Interface is the property which is used to specify what a class must do, but not how to do
3) What is the access specifier that must be used to implement an interface method?
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 24:
Source code:
{
System.out.println("You are using circle class");
}
CSE RIT
JAVA PROGRAMMING LAB MANUAL
{
void display()
{
System.out.println("You are using rectangle class");
}
}
{
void display()
class AbstractClassDemo
{
public static void main(String args[])
{
Shape sobj = new Circle(); sobj.display();
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Viva voice:
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Program 25:
Algorithm:
Source code:
public class exceptions
{
public static void main(String Args[]){ int[] array = new int[3];
try
{
for(int i=0;i<3;++i){ array[i] = i;
}
array[0] = 2/0;
}
catch(ArrayIndexOutOfBoundsException e){ System.out.println("Oops, we went to far, better go back
to 0!");
}
catch(ArithmeticException e){ System.out.println("Cannot Divide by Zero!");
}
catch(Exception e){
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Finally
{
System.out.println(array);
}
}
}
Viva voice:
1) What is an exception?
An exception is an abnormal condition that arises in the code sequence at run time.
Any code that absolutely must be executed before a method returns is placed in the finally block.
CSE RIT
JAVA PROGRAMMING LAB MANUAL
Additional experiments:
ALGORITHM
Step 1:start
Step 2: declare class Integerr
Step 3: declare wrapper class Integer y=new Integer(567);
Step 4: print before fixing precision print y
Step 5: set int x=y.intValue();
Step 6: Increment x;
Step 7: assign y=new Integer(x);
Step 8:print after fixing precision print y
Step 9: stop
PROGRAM:
import java.lang.*;
import java.math.*;
class Integerr
{
public static void main(String[] args)
{
Integer y=new Integer(567);
int x=y.intValue();
x++;
y=new Integer(x);
System.out.println("y=" +y);
}
}
CSE RIT
JAVA PROGRAMMING LAB MANUAL
ALGORITHM:
Step1: Start.
Step2: Create a class Stack1.
Step3: Initialise a[], n, top
Step4: Call a method with parameter x.
Step4.1: Assign x to n, top=0 and n to a.
Step5: Push() method.
Step5.1: If top==n then display stack is overflow.
Step5.2: else enter the data using x.
Step5.2.1: Assign element to a[top] and increment top.
Step6: display() method.
Step6.1: If top==0 then display stack is empty.
Step6.2: else display the element in a[i].
Step7: pop() method.
Step7.1: If top==0 then display stack is underflow.
Step7.2: else decrement the top and print the element in stack.
Step8: Create a class Stack.
Step8.1: Create a main function with string argument.
Step8.2: Initialise n and assign the array size.
Step8.3: Create an object t for the Stack1.
Step8.4: Check condition while(true).
Step8.4.1: Initialise ch and display enter your choice 1. Push\n 2. Pop\n 3.Display\n 4.
Exit.
Step8.4.2: Using switch case we can call methods.
PROGRAM:
import java.io.*;
import java.util.*;
class Stack1
{
int top=-1,st[]=new int[5];
void push(int el)
{
st[++top]=el;
}
int pop()
{
return(st[top--]);
}
CSE RIT
JAVA PROGRAMMING LAB MANUAL
void display()
{
System.out.println("\nStack elements from top to bottom\n");
for(int i=top;i>=0;i--)
System.out.println(st[i]);
}
boolean isFull()
{
return(top==5-1);
}
boolean isEmpty()
{
return(top==-1);
}
}
class Stack
{
public static void main(String a[])
{
Scanner sc=new Scanner(System.in);
Stack1 s=new Stack1();
int el=0,ch=1;
while(ch!=4)
{
System.out.println("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT");
System.out.println("ENTER YOUR CHOICE");
ch=sc.nextInt();
switch(ch)
{
case 1:if(s.isFull())
System.out.println("\nstack is full");
else
{
System.out.println("Enter element");
el=sc.nextInt();
s.push(el);
}break;
case 2:if(s.isEmpty())
System.out.println("\nstack is empty");
else
{
el=s.pop();
System.out.println("\nDeleted element = "+el);
}break;
case 3:if(s.isEmpty())
System.out.println("\nstack is empty");
else
s.display();
break;
case 4:break;
CSE RIT
JAVA PROGRAMMING LAB MANUAL
CSE RIT
JAVA PROGRAMMING LAB MANUAL
CSE RIT