Vous êtes sur la page 1sur 88

JAVA PROGRAMMING LAB MANUAL

RAGHU INSTITUTE OF TECHNOLOGY


Dakamarri (v), Bheemunipatnam (M)
Visakhapatnam Dist, Andhra Pradesh, PIN-531162
(Approved by AICTE, New Delhi, and Affiliated to Jawaharalal Nehru Technological University: Kakinada (AP))

II B. Tech., CSE II - Semester

FACULTY LABORATORY MANUAL

For

JAVA PROGRAMMING

Prepared by

V Hemanth Kumar, Assistant Professor

DEPARTMENT OF

COMPUTER SCIENCE AND ENGINEERING

CSE RIT
JAVA PROGRAMMING LAB MANUAL

RAGHU INSTITUTE OF TECHNOLOGY


(Affiliated to JNTU-KAKINADA)
Visakhapatnam-531162

CERTIFICATE

Name of the Laboratory : Java Programming

Name of the Faculty :V Hemanth Kumar

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.

At the end of this lab session

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

Java programming lab The students will learn to write, compiling


& 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 use interfaces
and inner classes, wrapper classes,
generics.

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

non-recursive functions to print the nth value of the Fibonacci sequence.

4. Write a Java program to give an example for command line arguments.

5. Write a Java program to sort given list of numbers.

6. Write a Java program to implement linear search.

7. Write a Java program to implement binary search.

8. Write a java program to add two given matrices.

9. Write a java program to multiply two given matrices.

10. Write a java program for sorting a given list of names.

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.

17. Write a java program that illustrates the simple inheritance.

18. Write a java program that illustrates the multilevel inheritance.

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.

- A java program to create a dialog box and menu.

- A java program to create a grid layout control.

31. A java program to create a border layout control.

32. A java program to create a padding layout control.

CSE RIT
JAVA PROGRAMMING LAB MANUAL

33. Write an Applet that creates a simple calculator.

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

Step2: declare a class def

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;

static boolean bl;

public static void main(String[] args)

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:

1) What are the default values?

The default values are the values given by the java run time system if we wont specify any values.

2) What are primitive data types in java?

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.

3) What is the default value for characters?

Default values for the characters are the NULL values.

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

Step2: declare a class known as Quadratic.

Step3: declare a main () function inside the class which throws IOException.

Step4: declare the variables x1,x2,disc,a,b and of double data type.

Step5: create an object obj of InputStreamReader class

Step6: create an object br of BufferedReader class.

Step7: Read the values of a. b and c at runtime by using BufferedReader object.

Step8: calculate the disc value using formula b*b-4*a*c.

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

BufferedReader br=new BufferedReader(obj);


System.out.println("enter a,b,c values");

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)

System.out.println("roots are real and equal "); x1=x2=b/(2*a);


System.out.println("roots are "+x1+","+x2);

}
else if(disc>0)

System.out.println("roots are real and unequal");

x1=(-b+Math.sqrt(disc))/(2*a); x2=(b+Math.sqrt(disc))/(2*a);

System.out.println("roots are "+x1+","+x2);

}
else

System.out.println("roots are imaginary");

Expected input and output:

Enter a,b,c values:


4
4
1
Roots are real and equal
Roots are -0.5, -0.5

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Actual Input & Output :

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

3)What is the use of System.out?


Ans. System is pre-define class and out is object. Used to print output on screen.

4)What is println
Ans. It is a output method to result message/data on screen

5)What is the use of readLine function?


Ans. It is input method to read data from Standard Input streams.

6)What is static?
Ans. Static keyword is to declare global members and methods.

7)What is the use of data input stream?


Ans. It is to create object to read data from input devices.

8)What is meant by object oriented programming?


Ans. It is modern approach of writing programs with Classes and Objects.

9)What is a keyword?
Ans. Keyword is reserved word for specific purpose.

10)What is String args[]?


Ans. All Java programs are executed from command prompt. Sending parameter to main() function is called String
args[].

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 :

/*Non Recursive Solution*/

import java.util.Scanner;

class Fib {

public static void main(String args[ ])


{
Scanner input=new Scanner(System.in);
int i,a=1,b=1,c=0,t;
System.out.println("Enter value of t:");
t=input.nextInt();

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

Expected Input and output:

Enter the value of t: 5


11235

Actual Input & Output :

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

Step6: create an object obj of InputStreamReader class


Step7: create an object br of BufferedReader class.

Step8: enter the last number.

Step9: function call to demo() class.

Step10: print the series upto given value.

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 {

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


InputStreamReader obj=new
InputStreamReader(System.in);
BufferedReader br=new BufferedReader(obj); System.out.println("enter last number");
int n=Integer.parseInt(br.readLine());

Demo ob=new Demo();

System.out.println("fibonacci series is as follows");

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

System.out.println(n+"th value of the series is "+res);

Expected Input and output:


Enter the value of t: 5
11235

Input & Output :

Viva voice:

1) What is meant by Fibonacci sequence?


The Fibonacci sequence is a set of numbers that starts with a one or a zero, followed by a one, and
proceeds based on the rule that each number (called a Fibonacci number) is equal to the sum of the
preceding two numbers.

2) Can we implement Fibonacci sequence using recursion?


Yes, we can implement Fibonacci sequence using recursion?

3) Is byte code similar to .obj file in c?

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.

4) What is a byte code?


Ans: Byte code consists of machine independent code, which is translated at runtime of program.

5) What are the features of java?


Ans: Architecture Neutral, Multi threaded, Portability, Dynamic, Robust etc.,.

6) What is an object?
Ans: It is a runtime entity, which is instance of class

7) What is the use of while loop?


Ans: While loop is a pre-test loop. Repeats a set of statements until given condition will become false.

8) What is an interface?
Ans: Interface is pure abstract class, which will be implemented by sub-classes.

9) What is the difference between class and interface?


Ans: Class contains data members and well defined methods. Interface contains final data members and
prototypes of functions.

10) What is the difference between print and println?


Ans: print prints output on same line. Println- prints output on new line

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Program 4:

Write a Java program to give an example for command line arguments.


Algorithm:

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

public static void main(String[] args)

if(args.length==0)

System.out.println("no command line arguments");


else

{
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

Expected input and output:

Java com yes no


Number of command line arguments are 2
They are:
Yes no

Actual Input & Output :

1) What is Integer.parseInt?
Ans: Integer is a Wrapper class associated to int data type. parseInt() function converts String data to integer.

2)Is String a data type?


Ans: No! String is a pre-defined class associated with members and methods.

3)Is java invented for internet?


Ans: No! the objective of Java invention is to develop platform independent programs for all electronic devices.

4)How many datatypes are there in java?


Ans: We have 08-data types in Java. Listed that - byte, short, int, long, float, double, char, Boolean

5)How can we save a java program?


Ans: Inside gedit. Select File menusave/save as option.

6) How we execute a java program?


Ans: After compiling of .java file. Execute by the command: $java <classfilename>

7)What is javac?
Ans: javac is java compiler. To compile source program to byte code file.

8)What are access specifiers?


Ans: Access specifiers are used to provide security constraints to data members and member functions.

9)What is the difference between public and private?


Ans: public specifies properties can be accessed from any part of program. Private specifies only with in the class
properties are visibile.

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:

Write a Java program to sort given list of numbers.

Algorithm:

Step1: start.

Step2: declare a class sorting.

Step3: declare a main() function inside the class.

Step4: initialize an array number with some elements in it.

Step5: initialize and declare n as number of length.

Step6: print the given list and goto step7.

Step7: initialize i from 0 to n.

Step8: while condition number[i]<number[j]


Step8.1: initialize a variable temp.
Step8.2: swap temp,number[i] and number[j].

Step9: display the sorted list of given numbers.

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

Expected input and output:


Given list
23
12
45
67
70
Sorted list
70
67
45
23
12
Actual Input & Output

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.

2)What are java buzz words?


Ans: Java buzz words are java features like Arch.neutral, Robust, Dynamic and Multi threaded etc.,

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

4)What is new feature in control statements comparing with c?


Ans: All control statement are available. Except new feature of JDK 1.7 is String can be compared using switch and for
loop can be used for array collections.

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.

7)What is data hiding?


Ans: Protecting data members/methods from unauthorized objects is hiding of data.

8)What are construcrors?


Ans: Constructor is spl. Function that is invoked as soon as object is created.

9)What are destructors?


Ans: It is also function invoked before object is destroyed/released.

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:

Write a Java program to implement linear search.

Algorithm:

Step1: start
Step2: declare a class linear .
Step3: declare a main() function inside the class.

Step4: intialize an array number with some elements in it.

Step5: intialize i from 0 to length of array.


Step5.1: display array elements.

Step6: declare variables search_element=44 and find_index=-1.

Step7: intialize j from 0 to array.length-1.

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 :

public class linear

public static void main(String[] args)

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

System.out.println("\t\t\t\t\t Array[" + i + "] = " + array[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

System.out.println("\n The search element is not found in the array.");

Expected Input & Output :

The contents of the array are:


Array[0]=16
Array[1]=5
Array[2]=46
The search element is 5
It is found in the array at position :1

Actual Input & Output :

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Viva voice:

1) What is meant by Searching?


Identifying the data item in a list of items. If the element is found then we can say that search is
successful, otherwise unsuccessful.

2) Among the searching techniques which one is the best one?


Binary search is the best searching technique with a time complexity of O(log n).

3) How many types of Search mechanisms are there?


There are three types of search techniques. They are: Linear search, binary search and Fibonacci search.

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Program 7:

Write a Java program to implement binary search.

Algorithm:
Step1: start.

Step2: declare a class known as binary.

Step3: declare a main() function inside the class which throws IOException.

Step4: create an object obj of DataInputStream class

Step5: intialize an array of some elements in it.

Step6: enter the element to be searched.

Step7: intialize a variable index that call calls a function search().


Step7.1: goto step9.

Step8: if index != -1display that the searched element is not found.

Step9: declare a search function and intialilze an array ar[] and a variable find.

Step10: declare integer variables start = 0, end = ar.length -1, mid.


Step11: while start <= end

Step11.1: calculate mid = (start + end) / 2

Step12: if ar[mid] equals find.

Step12.1: return mid.

Step12.2: else if ar[mid] is smaller then find, then


Step12.2.1: calculate start = mid + 1
Step12.3: else if ar[mid] is greater then find, then
Step12.3.1: calculate end = mid 1
Step13: return -1 value.
Step14: stop.

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Source code :

import java.io.*;
public class binary{

public static void main(String arg[]) throws IOException {


DataInputStream br = newDataInputStream(System.in);
int a[] = {5,6,8,2,88,62,4};
System.out.println("Enter the element to search");
int find = Integer.parseInt(br.readLine());

int index = search(a, find);


if (index != -1) {

System.out.println("Element found at positin: " + index); } else {

System.out.println("Element not found");


}

}
public static int search(int ar[], int find) {
int start = 0;

int end = ar.length -1;


int mid;

while (start <= end) { mid = (start + end) / 2; if (ar[mid] == find) {

return mid;

} else if (ar[mid] < find) { start = mid + 1;

} else if (ar[mid] > find) { end = mid - 1;

}
}

return -1;

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Expected Input & Output :

Enter the element to search: 8


Element found at position 2

Actual Input & Output :

Viva voice:

1) What is binary search?


Binary search is a search mechanism which is used to search the data item in a given list by identifying
the mid location and if the element is less than the mid location change the upper boundary value, if the
element is greater than the mid location then increase the lower value and proceed recursively .

2) Why Binary search is considered as the best searching technique?


As this follows the divide and conquer strategy.

3) What is the minimum condition to implement binary search?


All the elements must be in the sorted order.

4) What is the time complexity of binary search?


The time complexity of binary search is O (logn).

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Program 8:

Write a java program to add two given matrices.

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.

Step5: intialize variable i from 0 to 2


Step5.1: intialize variable j from 0 to 2.
Step5.2: enter the first matrix elements for a[][].

Step6: repeat step 5 for another array b[][].

Step7: intialize i from 0 to 2 and calculate sum of the matrixes.

Step8: display the resultant matrix.

Step9: stop.

Source code :

import java.util.*;
public class matrixsum {

public static void main (String[] args)

int i,j,a[][] = new int[10][10],b[][]= new int[10][10];


Scanner input = new Scanner(System.in);
for(i=0;i<2;i++)

for(j=0;j<2;j++)

System.out.println("Enter Number :");


a[i][j] = input.nextInt();

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]+" ");

Expected Input & Output :

Enter number:
1
Enter number:
2
Enter number:
3
Enter number:
4

Enter other matrix

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:

Write a java program to multiply two given matrices.

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.

Step11:variables r1,r2,c1,c2 are intialized using this pointer.

Step12: initialization of an two dimensional array for c and r variables.

Step13: intialize variable i from 0 to r.

Step14: intialize variable j from 0 to c.

Step15: take input elements for array and return arr.

Step16: a function call to main function is done for matrix mul.

Step17: initialization of an two dimensional array for c2 and r1 variables.

Step19: intialize variable i from 0 to r1.

Step20: intialize variable j from 0 to c2.

Step21: intialize variable k from 0 to r2.

Step22: calculate c[i][j]=c[i][j]+a[i][k]*b[k][j] and return c.


Step 23: display the resulatant multiplication matrix.
Step24: stop.

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Source code :

import java.util.*; class Test {


int r1,c1,r2,c2;

Test(int r1,int c1,int r2,int c2) { this.r1=r1;

this.c1=c1;

this.r2=r2;

this.c2=c2;

}
int[ ][ ] getArray(int r,int c) {
int arr[][]=new int[r][c];

System.out.println("Enter the elements for "+r+"X"+c+" Matrix:");


Scanner input=new Scanner(System.in);

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

for (int i=0;i<r1;i++)

for (int j=0;j<c2;j++) {


c[i][j]=0;

for (int k=0;k<r2;k++)


c[i][j]=c[i][j]+a[i][k]*b[k][j];

}
return c;

void putArray(int res[ ][ ]) {

CSE RIT
JAVA PROGRAMMING LAB MANUAL

System.out.println ("The resultant "+r1+"X"+c2+" Matrix is:");


for (int i=0;i<r1;i++) {

for (int j=0;j<c2;j++)


System.out.print(res[i][j]+" ");

System.out.println();

} //end of Test class


class MatrixMul {

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


Test obj1=new Test(2,3,3,2);
test obj2=new Test(2,3,3,2);
int x[ ][ ],y[ ][ ],z[ ][ ];
System.out.println("MATRIX-1:");

x=obj1.getArray(2,3); //to get the matrix from user

System.out.println("MATRIX-2:");

y=obj2.getArray(3,2);

z=obj1.findMul(x,y); //to perform the multiplication

obj1.putArray(z); // to display the resultant matrix


}

Expected Input & Output :


Enter the elements for the 2*3 matrix
111111
Enter the elements for the 3*2 matrix
111111
The resultant 2*2 matrix is
33
33

Actual Input & Output :

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.

2) What is the minimum condition to perform matrix multiplication?

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

Step2: declare a class known as Ascend.

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

Step5: declare a class known as test.


Step6: intialize variables i, j and array arr[].

Step7: declare len =n and arr = new string[n].

Step8: declare a function inside the class which throws IOException.

Step9: create an object obj of InputStreamReader class

Step10: create an object br of BufferedReader class.

Step11: intialization of variable i from 0 to len.

Step12: read arr[i] using br object and return arr.

Step13: declare a function inside the class which throws ArrayIndexOutBound Exception.

Step14: intialization of variable i from 0 to len-1.


Step14.1: intialization of variable j from i+1 to len.

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.

Step17: display the obtained sorted list.

Step18: stop.

Source code:

import java.io.*;
class Test {

int len,i,j; String arr[ ];

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Test(int n) {
len=n;
arr=new String[n];

}
String[ ] getArray()throws IOException {

BufferedReader br=new BufferedReader (new InputStreamReader(System.in));


System.out.println ("Enter the strings U want to sort----");

for (int i=0;i<len;i++)


arr[i]=br.readLine();

return arr;

String[ ] check()throws ArrayIndexOutOfBoundsException {


for (i=0;i<len-1;i++)
{
for(int j=i+1;j<len;j++)
{

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
{

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


Test obj1=new Test(4);

obj1.getArray();

obj1.check();

obj1.display();

Expected Input & Output:

Enter the strings u wants to sort


Mouse
Gerbil
Hamster

Sorted list is:

Gerbil
Hamster
Mouse

Actual Input & Output:

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Viva voice:

1) What are strings?


A string can be defined as the collection of characters. We can also say that as a character array.

2) What is the default character for each and every string?


For each and every string the default character is NULL character.

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

Step2: declare a class known as Palind.

Step3: declare a main() function inside the class which throws IOException.

Step4: create an object obj of InputStreamReader class

Step5: create an object br of BufferedReader class.

Step6: Read the string s1at runtime by using BufferedReader object.

Step7: A new object known as sb is created and sb is appended to s1.

Step8: object sb is reversed.

Step9: take the value of string s2 using object sb.

Step10: if s1 equals s2 the print its palindrome.


Step10.1: else its not palindrome.

Step11: stop.

Source code:

import java.io.*;
class Palind {

public static void main(String args[ ])throws IOException

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

Expected Input and output:


Enter the string to check for palindrome:
Madam
Palindrome

Actual Input and output:

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.

3) List out some of the examples of palindromes?


Dad, Madam, pop is some of the examples of palindromes.

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.

Step2: declare a class known as test.

Step3: declare a function named check() with integer variable num.

Step4: take prime numbers upto some limit.

Step5: intialize an integer variable i from 1 to num.


Step5.1: intialize an intezer variable j from 2 to i.

Step6: if i modulo j equals 0 then break.


Step6.1: if i modulo j not equals 0 and j equals i-1 then print value of i.

Step7: declare a class known as prime.

Step8: declare a main function inside a class .

Step9: create an object obj1 and call class test.

Step10: scan the input n taken using class Scanner input.

Step11: variable n makes an function call to check() function.

Step12: stop.

Source code:

import java.util.*;
Class test
{
void check(int num)
{

System.out.println ("Prime numbers up to "+num+" are:");

for (int i=1;i<=num;i++)


for (int j=2;j<i;j++)
{

CSE RIT
JAVA PROGRAMMING LAB MANUAL

if(i%j==0)

break;

else if((i%j!=0)&&(j==i-1))

System.out.print( +i);
}
}

} //end of class Test


class Prime

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

Expected Input & Output :

Enter the value of n:


10
Prime numbers up to 10 are:
357
Actual Input & Output :

Viva voice:

1) What are prime numbers?


The numbers which are divisible by one and itself are called prime numbers.

2) How can we read the values at runtime?


The values can be entered at runtime by using nextInt() with the Scanner class object.

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.

Source code for call by value:


class byvalue
{
int data=50;
void change(int data)
{
data=data+100; //changes will be in the local variable only

public static void main(String args[])


{
byvalue op=new byvalue();
System.out.println("before change "+op.data);
op.change(500);

System.out.println("after change "+op.data);

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Expected Input & Output :

Before change 50
After change 50

Actual Input & Output :

Algorithm for call by reference:

Step1: start

Step2: declare a class known as operation2.

Step3: intialize and declare variable data with value 50.

Step4: declare a function change with an object op of class operation2.

Step5: calculate the value of data=data+100 using object op.

Step6: declare a main function in class operation2.

Step7: create an object op in class operation2.

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.

Source code for call by reference:

class Operation2
{
int data=50;

CSE RIT
JAVA PROGRAMMING LAB MANUAL

void change(Operation2 op)

op.data=op.data+100;//changes will be in the instance variable

}
public static void main(String args[])
{
Operation2 op=new Operation2();
System.out.println("before change "+op.data);

op.change(op);//passing object

System.out.println("after change "+op.data);

Expected Input & Output :

Before change: 50
After change: 150

Actual Input & Output :

Viva voice:

1) What are formal arguments?


The values which are present in the function definition are called formal arguments.

2) What are Actual arguments?


The values which are present in the function call are called formal arguments.

CSE RIT
JAVA PROGRAMMING LAB MANUAL

3) What is meant by call by value?


The logic that is written inside the function definition will not be reflected in the function call after
making the necessary modifications.

4) What is meant by call by reference?


The logic that is written inside the function definition will be reflected in the function call after making
the necessary modifications.

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Program 14 :

Write a java program that implements the usage of this keyword.

Algorithm:

Step1: start.

Step2: declare a class known as rectangle.

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.

Step5: intialize a variable length.

Step6: value of length is intialized using this pointer.

Step7: make a function call to function named same as class name, rectangle with two formal parameters.

Step8: intialize a variable breadth.

Step9: value of breadth is intialized using this pointer.

Step10: declare a function known as area().


Step10.1: return the value of length*breadth.

Step11: declare a class known as thistest.

Step12: declare a main function in class thistest.

Step13: create an object rect and values to the class rectangle is given.

Step14: display the area of rectangle obtained.

Step15: stop.

Source code:
class Rectangle
{
private int length;
private int breadth;
Rectangle(int length)
{

this.length = length;

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Rectangle(int length, int breadth)

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

System.out.println("The Area of rectangle is : "+ + rect.area());


}

Expected Input & Output :

The area of triangle is : 25

Actual Input & Output :

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

3) How the assignment will be done using this keyword?


The left hand side data member of a class value is assigned to the field of a function at that instance.

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Program 15:

W rite a java program that implements the usage of super keyword.

1. super is used to refer immediate parent class instance variable.

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

Expected Input & Output :


50
Actual Input & Output :

2. super() is used to invoke immediate parent class constructor.

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Algorithm:

Step 1: Declare a class Vehicle


Step 2: define a constructor for Vehicle.
Step3: Declare class Bike extended from Vehicle
Step 4: create a constructor for Bike
Step 5: invoke super()
Step 6: start main class
Step 7: create an object for class Bike.
Step 8: Stop

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

Expected Input & Output :


Vehicle is created
Bike is created
Actual Input & Output :

3. super is used to invoke immediate parent class method

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Algorithm:

Step 1: declare a class Person


Step 2: define a function message
Step 3: declare a class Student extended from Person
Step 4: override the funtion message
Step 5: define a function display
Step 6: invoke the function message.
Step 7: Invoke message function using super keyword.
Step 8: declare the main class
Step 9: Create an objrct for class Student
Step 10: invoke the function display.

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

Expected Input & Output :

Welcome to java
welcome

Actual Input & Output :

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Viva voice:

1. What is "super" used for ?


Ans. Used to access members of the base class.

2. Can we use both "this" and "super" in a constructor ?


Ans. No, because both this and super should be the first statement.

3. Difference Between this() and super() ?


Ans.
1.this is a reference to the current object in which this keyword is used whereas super is a reference used
to access members specific to the parent Class.
2.this is primarily used for accessing member variables if local variables have same name, for
constructor chaining and for passing itself to some method whereas super is primarily used to initialize
base class members within derived class constructor.

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:

Write a java program that gives demonstration of static variables.

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:

public class StaticDemo {


static intx=10,y=5;
public static void main(String[] args) {
StaticDemo instance1 = new StaticDemo();
StaticDemo instance2 = new StaticDemo();
System.out.println("instance1.X = " + instance1.X + " instance1.Y = " + instance1.Y);
System.out.println("instance2.X = " + instance2.X + " instance2.Y = " + instance2.Y); instance1.X = 15;

instance1.Y = 10;

System.out.println("After updating X value to 15 and Y value to 10 from intance1 :");


System.out.println("instance1.X = " + instance1.X + " instance1.Y = " + instance1.Y);
System.out.println("instance2.X = " + instance2.X + " instance2.Y = " + instance2.Y);

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

1) What is static variable in java?


Variables declared with static keyword is known as static variables.

2) When the memory will be allocated for the static variables?


Static variables gets memory on class loading.

3) Can we declare local variables as static?


We can not declare local variables as static it leads to compile time error "illegal start of expression".

4) What is static method in java?

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

B(int a, int b, int c)


{
super(a, b);
k= c;

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

Expected Input & Output :


k: 3
i and j: 1 2

Actual Input & Output :

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.

2) What is simple inheritence?


If the derived class is obtained from only one base class then it is called simple inheritence.

3) What are the various types of inheritence avilable?


The Different forms of inheritance are:

Single, Multiple, Multilevel, Hybrid and Hierarchical.

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Program 18:

Write a java program that illustrates the multilevel inheritance.


Algorithm:

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

System.out.println("Rollno = " + rollno); System.out.println("Name = " + name);


}
}

class marks extends student


{
int total;
marks(int r, String n, int t)
{
super(r,n);
total = t;
}
void dispdatam()
{
dispdatas();
System.out.println("Total = " + total);
}
}
class percentage extends marks
{
int per;
percentage(int r, String n, int t, int p)
{
super(r,n,t);
per = p;
}
void dispdatap()
{
dispdatam(); System.out.println("Percentage = " +
per);
}
}

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.

2) What is multilevel inheritance?

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.

3) What are the various types of inheritance available?

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 {

private double interestRate; private String


customer; private String lender;

public static Loan createLoan(String lender) {


Loan loan = new Loan();

loan.lender = lender; return loan;


}

public static Loan createLoan(String lender, double interestRate) {

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Loan loan = new Loan();

loan.lender = lender; loan.interestRate =


interestRate;
return loan;
}

public String toString() {


return "This is Loan by Citibank";
}
}
class PersonalLoan extends Loan {
public String toString() {
return "This is Personal Loan by Citibank";
}
}
Expected Input & Output :
Loan by citi bank
Actual Input & Output :

Viva voice:

1) What is method overloading?


The concept in which it is uses the same method name to exhibit different behaviours and this depends
on the number and type of arguments we are passing in the method.

2) What is method overriding?


The subclass which provides the specific implementation of method that has been provided by one of

its parent class is called method overriding.

3) What is the advantage in using method overriding?


Method overriding is used to achieve runtime polymorphism.

4) List the rules for method overriding?


Method name must have the same name as in the parent class.
Method must have the same parameter as in the parent class.

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
{

public void add(int a, int b)


{

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;

System.out.println("Sum of three numbers = "+sum);


}

public static void main(String args[])

CSE RIT
JAVA PROGRAMMING LAB MANUAL

MethodOverloading overloading = new MethodOverloading();


double result;

overloading.add(5,6);

overloading.add(5,6,7);

Expected Input & Output :

Sum of two numbers=11


Sum of three numbers=18

Actual Input & Output :

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

Step 12: invoke the method getName with cpp.


Step 13: Define the function setName.
Step 14: initialize name=t.
Step 15: Define the function getName.
Step 16: print name.
Step 17: Stop.

Source code:

class Language { String name;

Language() {

System.out.println("Constructor method called.");

Language(String t) {
name = t;

public static void main(String[] args) {

Language cpp = new Language();


Language java = new Language("Java");
cpp.setName("C++");
java.getName();
cpp.getName();

void setName(String t) { name = t;


}
void getName() {
System.out.println("Language name: " + name);

Expected Input & Output :

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Constructor method called


Language name: java
Language name: c++

Actual Input & Output :

Viva voice:

1) What is method overloading?


The concept in which it is uses the same method name to exhibit different behaviours and this depends
on the number and type of arguments we are passing in the method.

2) What is constructor overloading?


The concept in which it is uses the same constructor name to exhibit different behaviours and this
depends on the number and type of arguments we are passing to the constructor.

3) What is the important point to consider with respect to constructors?


The constructor name and the constructor name which is declared in the class must be the same.

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

Step 14: create object for SecondThread.


Step 15: invoke start() using object of SecondThread.

Source code:

class FirstThread implements Runnable

public void run()


{

CSE RIT
JAVA PROGRAMMING LAB MANUAL

for ( int i=1; i<=10; i++)


{

System.out.println( "Message from First Thread : " +i);

try
{

Thread.sleep (1000);
}

catch (InterruptedException interruptedException)


{

System.out.println( "First Thread is interrupted when it is sleeping" +interruptedException);

class SecondThread implements Runnable


{

public void run()


{

for ( int i=1; i<=10; i++)


{

System.out.println( "Messag from Second Thread : " +i);

try
{

Thread.sleep(1000);

CSE RIT
JAVA PROGRAMMING LAB MANUAL

catch (InterruptedException interruptedException)

System.out.println( "Second Thread is interrupted when it is sleeping" +interruptedException);

}
}

}
public class ThreadDemo

{
public static void main(String args[])

FirstThread firstThread = new FirstThread();

SecondThread secondThread = new SecondThread();

Thread thread1 = new Thread(firstThread); thread1.start();

Thread thread2 = new Thread(secondThread); thread2.start();

}
Expected Input & Output :

Message from first thread : 1


Message from second thread: 1
Message from first thread : 2
Message from second thread: 2
Message from first thread : 3
Message from second thread: 3
Message from first thread : 4
Message from second thread: 4
Message from first thread : 5
Message from second thread: 5

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Message from first thread : 6


Message from second thread: 6
Message from first thread : 7
Message from second thread: 7
Message from first thread : 8
Message from second thread: 8
Message from first thread : 9
Message from second thread: 9
Message from first thread : 10
Message from second thread: 10

Actual Input & Output :

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.

2) How the multithreading is considered with multitasking?


Multithreading is the specialized form of multi tasking.

3) How many types of multitasking are there?

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:

class FirstThread extends Thread


{
public void run()
{
for (int i=1; i<=5; i++)
{
System.out.println( "Messag from First Thread : " +i);
try
{

Thread.sleep(1000);

CSE RIT
JAVA PROGRAMMING LAB MANUAL

}
catch (InterruptedException interruptedException)
{
System.out.println( "First Thread is interrupted when it is sleeping" +interruptedException);

class SecondThread extends Thread

{
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

public static void main(String args[])


{

CSE RIT
JAVA PROGRAMMING LAB MANUAL

FirstThread firstThread = new FirstThread();


SecondThread secondThread = new SecondThread();
firstThread.start();
secondThread.start();
}
}
Expected Input & Output :

Message from first thread : 1


Message from second thread: 1
Message from second thread : 2
Message from first thread: 2
Message from second thread : 3
Message from first thread: 3
Message from first thread : 4
Message from second thread: 4
Message from second thread : 5
Message from first thread: 5
Message from second thread : 6
Message from second thread: 6
Actual Input & Output :

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Viva voice:

1) In how many ways the threads can be created?


The threads can be created in two ways:

By implementing runnable interface


By extending the thread class.
2) What is the use of run() method in multithreading?
The run() method will establishes the entry point another concurrent thread with in the program.

3) What is the use of start() method in multithreading?


The start() method is used to start the thread execution beginning at the run() method

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Program 23:

Write a java program that illustrates the multiple inheritances by using interfaces.

Algorithm:

Step 1: Create an interface A


Step 2: Declare the function method() in interface A.
Step 3: Create an interface B.
Step 4: Declare the function methof() in interface B.
Step 5: Declare a class C implementing interface A,B.
Step 6: Define the function method().
Step 7: print executed method.
Step 8: Declare the main class
Step 9: Create an object of C.
Step10: invoke method using object of C.
Step 11: Stop.

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

Expected Input & Output :

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

2) Can we extend the interfaces?


Yes, interfaces can be extended and inherited from one class to another by using extends keyword.

3) What is the access specifier that must be used to implement an interface method?

To implement an interface method it must be declared as public access specifier.

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Program 24:

Write a java program that illustrates the concept of abstract classes.


Algorithm:

Step 1: Declare an abstract class Shape


Step 2: Define a function display().
Step 3: Declare a class Circle extended from Shape.
Step 4: Define function display().
Step 5: Print you are using circle class.
Step 6: Declare a class Rectangle extended from Shape.
Step 7: Define the function display().
Step 8: print you are in class Rectangle.
Step 9: Declare a class Triangle extended from shape.
Step 10: Define the function display().
Step 11: print you are using triangle class.
Step 12: Declare a class AbstracttClassDemo
Step 13: Declare the main class.
Step 14: Create an object for the class Circle.
Step 15: invoke display().
Step 16: Create an object for the class Rectangle
Step 17: invoke display().
Step 18: Create an object for the class Triangle.
Step 19: invoke display().
Step 20: stop.

Source code:

abstract class Shape


{
void display()
{
}
}

class Circle extends Shape


{
void display()

{
System.out.println("You are using circle class");
}

CSE RIT
JAVA PROGRAMMING LAB MANUAL

class Rectangle extends Shape

{
void display()
{
System.out.println("You are using rectangle class");
}
}

class Triangle extends Shape

{
void display()

System.out.println("You are using triangle class");

class AbstractClassDemo

{
public static void main(String args[])

{
Shape sobj = new Circle(); sobj.display();

sobj = new Rectangle(); sobj.display();

sobj = new Triangle(); sobj.display();

Expected Input & Output :

You are using circle class


You are using rectangle class
You are using triangle class
Actual Input & Output :

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Viva voice:

1) What is an abstract class?


It is considered as the class property in which it provides only the structure of a given abstraction
without providing its implementation of every method.

2) What is the advantage in using the abstract classes?


It provides the flexibility for the methods to leave the implementation side with respect to its own
derived class.

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Program 25:

Write a java program that describes the exception handling mechanism.

Algorithm:

Step 1: Declare a class exceptions.


Step 2: Declare the main class.
Step 3: declare an array.
Step 4: start try
Step 5: for i=0 to 3
Step 5.1: initialize array[i]=i
Step 6: initialize array[0]= 2/0
Step 7: Catch ArrayIndexOutOfBound exception
Step 8: print we went too far.
Step 9: Catch ArithematicException.
Step 10: print cannot divide by 0.
Step 11: Exception
Step 12: print an unknown error has occurred.
Step 13: start finally
Step 14: print array.
Step 15: stop.

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

System.out.println("An Unknown Error has Occured"); e.printStackTrace();

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Finally
{
System.out.println(array);
}
}
}

Expected Input & Output :

Cant divide by zero


[I@3e25a5

Actual Input & Output :

Viva voice:

1) What is an exception?
An exception is an abnormal condition that arises in the code sequence at run time.

2) What is the use of try block?


Program statements that that whatever want to monitor for exceptions are contained in the try block.

3) What is the use of throw statement?


If an exception occurs within a try block it is thrown by using the throw statement.

4) What is the use of catch block?


Whatever the code we write that can catch the exceptions using catch block and try to fix it.

5) What is the use of finally block?

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:

WAJP to demonstrate wrapper classes, and to fix the precision.

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

INPUT & OUTPUT:

CSE RIT
JAVA PROGRAMMING LAB MANUAL

Write a Java program that implements stack ADT

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.

Step8.4.2.1: Call Push() method and break.


Step8.4.2.2: Call Pop() method and break.
Step8.4.2.3: Call Display() method and break.
Step8.4.2.4: print exit and break.
Step8.5: End
Step9: Stop

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

default:System.out.println("\nEnter correct choice");


}
}
}
}
INPUT & OUTPUT

CSE RIT
JAVA PROGRAMMING LAB MANUAL

CSE RIT

Vous aimerez peut-être aussi