0% found this document useful (0 votes)
3 views22 pages

JAVA LAB PROGRAMS

The document contains a series of Java programming exercises covering various concepts such as looping statements, arrays, string handling, classes and objects, constructors, inheritance, interfaces, multithreading, exceptional handling, and the collection framework. Each exercise includes an aim, algorithm, program code, output, and a result statement indicating successful execution. The document serves as a comprehensive guide for learning and practicing Java programming fundamentals.

Uploaded by

Ram prasath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views22 pages

JAVA LAB PROGRAMS

The document contains a series of Java programming exercises covering various concepts such as looping statements, arrays, string handling, classes and objects, constructors, inheritance, interfaces, multithreading, exceptional handling, and the collection framework. Each exercise includes an aim, algorithm, program code, output, and a result statement indicating successful execution. The document serves as a comprehensive guide for learning and practicing Java programming fundamentals.

Uploaded by

Ram prasath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

EX.

No: 1 PROGRAMS ON LOOPING STATEMENTS

Aim:

Write a Java sample programs on looping statements

Algorithm:

Step1: Start the program.

Step 2:Declare an integer variable sum and set it to 0. This variable will store the sum of all
integers from 1 to n.

Step 3:Declare an integer variable n and set it to 1000. This represents the upper limit of the
range of integers to be summed.

Step 4:Start a for loop with the loop variable i initialized to the value of n.

Step 5: Set the loop condition to execute the loop as long as i is greater than or equal to 1.Within
the loop, add the current value of i to the sum variable.

Step 6:Decrement i by 1 in each iteration to move to the next integer in the range.Repeat steps 6
to 7 until the loop condition becomes false.

Step 7: After the loop completes, the sum variable will contain the sum of all integers from 1 to
n.Print the result using System.out.println(), showing the message "Sum = " followed by the
value of the sum variable.

Step 8:End the program.

Program:

import java.io.*;

import java.util.*;

class Main {

public static void main(String[] args) {

int sum = 0;

int n = 1000;

1
for (int i = n; i >= 1; --i)

sum += i;

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

Output:

Sum = 500500

Result:

Thus the java program using looping statements has been executed successfully

2
EX.No: 2 PROGRAMS ON ARRAY

Aim:

Write a Java sample programs on Array

Algorithm:

Step 1:Start the program.

Step 2:Declare an integer array variable age and initialize it with three elements: 12, 4, and
5.Print the message "Using for Loop:" to the console.

Step 3:Start a for loop with the loop variable i initialized to 0.Set the loop condition to execute
the loop as long as i is less than the length of the age array.

Step 4:Within the loop, print the element of the age array at the index i.

Step 5:Increment i by 1 in each iteration to move to the next element in the array.Repeat steps 6
to 7 until the loop condition becomes false.

Step 6:End the Program

Program:

import java.io.*;

import java.util.*;

class Main {

public static void main(String[] args) {

int[] age = {12, 4, 5};

System.out.println("Using for Loop:");

for(int i = 0; i < age.length; i++)

System.out.println(age[i]);

3
}

Output:

Using for Loop:

12

Result:

Thus the java program using array has been executed successfully

4
EX.No: 3 PROGRAMS ON STRING HANDLING

Aim:

Write a Java Program on String Handling

Algorithm:

Step 1:Start the program.

Step 2:Define a class named "TestString".

Step 3:Inside the "TestString" class:

a. Declare four string instance variables: str1, str2, str3, and str4.

b. Initialize str1 with the value "string".

c. Initialize str2 with the value "string".

d. Initialize str3 with the value "jai".

e. Initialize str4 with the value "sandy".

f. Define a public method named "stringComparison" with no parameters.

g. Inside the "stringComparison" method:

 Print the result of comparing str1 and str2 using the compareTo method of the String
class.
 Print the result of comparing str1 and str3 using the compareTo method.
 Print the result of comparing str3 and str4 using the compareTo method.

Step 4:Define another public class named "StringComparisonExample3".Inside


the"StringComparisonExample3" class:

a. Define the main method with the parameter args.

b. Inside the main method:

Step 5:Create an object of the "TestString" class named obj.Call the "stringComparison" method
on the obj object.

Step 6:End the program.

5
Program:

import java.io.*;

import java.util.*;

Class TestString{

String str1 = "string";

String str2 = "string";

String str3 = "jai";

String str4 = "sandy";

public void stringComparison(){

System.out.println(str1.compareTo(str2));

System.out.println(str1.compareTo(str3));
System.out.println(str3.compareTo(str4));
}}
public class StringComparisonExample3 {
public static void main(String args[]){
TestString obj = new TestString();
obj.stringComparison();
}}
Output:

13

-9

Result: Thus the java program using string handling has been demonstrated and executed
successfully.

6
EX.No: 4 PROGRAMS ON CLASSES AND OBJECTS

Aim:

Write a Java Program to calculate Area of Rectangle using classes and object

Algorithm:

Step 1:Start the program.

Step 2:Define a class named "Rectangle" with two double instance variables: length and breadth.

Step 3:Define another class named "RectangleDemo."

Step 4:Inside the "RectangleDemo" class, define the main method with the parameter args.

Step 5:Inside the main method:

a. Create an object of the "Rectangle" class named myrect.

b. Declare a double variable named area.

c. Set the length of the myrect object to 10. Set the breadth of the myrect object to 20.

d. Calculate the area by multiplying the length and breadth of the myrect object and store it in
the area variable.

e. Print the result using System.out.println(), showing the message "Area is " followed by the
value of the area variable.

Step 6:End the program.

Program:

import java.io.*;

import java.util.*;

class Rectangle {

double length;

double breadth;

7
classRectangleDemo {

public static void main(String args[]) {

Rectangle myrect = new Rectangle();

double area;

myrect.length = 10;

myrect.breadth = 20;

area = myrect.length * myrect.breadth ;

System.out.println("Area is " + area);

Output:-

Area is 200.0

Result:

Thus the java program using classes and objects has been demonstrated and executed
successfully

8
EX.No: 5 PROGRAMS ON CONSTRUCTORS

Aim:

Write a Java Program to implement Constructors.

Algorithm:

Step 1:Start the program.

Step 2:Define a public class named "constructoremp."

Step 3:Inside the "constructoremp" class:

a. Declare two instance variables: eid (integer type) and ename (string type).

b. Define a default constructor "Constructoremp" with no parameters.

 Inside the constructor, set the value of eid to 111 and ename to "HARI."

c. Define a method named "disp" with no parameters and a void return type.

 Inside the "disp" method, print the "emp id=" followed by the value of eid.
 Print the "emp name=" followed by the value of ename.

Step 4:Define the main method with the parameter args.

Step 5:Inside the main method:

a. Create an object of the "constructoremp" class named e using the default constructor.

b. Call the "disp" method on the e object.

Step 6: End the program.

Program:

import java.io.*;

import java.util.*;

public class constructoremp

Int eid;

9
String ename;

Constructoremp(){

eid=111;

ename="HARI";

voiddisp(){

System.out.println("emp id=" +eid);

System.out.println("emp name=" +ename);

public static void main(String[] args){

constructoremp e=new constructoremp();

e.disp();

}}

output:-

emp id=111

emp name=HARI

Result:

Thus the java program using constructors has been executed successfully

10
EX.No: 6 PROGRAMS ON INHERITANCE

Aim:

Write Java program on use of inheritance.

Algorithm:

Step 1:Start the program.

Step 2:Define a class named "Vehicle."

Step 3:Inside the "Vehicle" class:

a. Declare three instance variables: color (string type), speed (integer type), and size (integer
type).

b. Define a method named "attributes" with no parameters and a void return type.

 Inside the "attributes" method, print "Color: " followed by the value of color.
 Print "Speed: " followed by the value of speed.
 Print "Size: " followed by the value of size.

Step 4:Define another class named "Car" which extends the "Vehicle" class.

Step 5:Inside the "Car" class:

a. Declare two additional instance variables: CC (integer type) and gears (integer type).

b. Define a method named "attributescar" with no parameters and a void return type.

 Inside the "attributescar" method, call the "attributes" method from the superclass
("Vehicle") to print the common attributes.
 Print "CC of Car: " followed by the value of CC.
 Print "No of gears of Car: " followed by the value of gears.

Step 6:Define a public class named "Test."

Step 7:Inside the "Test" class, define the main method with the parameter args.

Step 8:Inside the main method:

a. Create an object of the "Car" class named b1.

b. Set the values of the instance variables of b1: color, speed, size, CC, and gears.

11
c. Call the "attributescar" method on the b1 object to print all the attributes of the car.

Step 9:End the program.

Program:

import java.io.*;

import java.util.*;

class Vehicle {

String color;

int speed;

int size;

void attributes() {

System.out.println("Color : " + color);

System.out.println("Speed : " + speed);

System.out.println("Size : " + size);

}}

class Car extends Vehicle {

int CC;

int gears;

voidattributescar() {

System.out.println("Color of Car : " + color);

System.out.println("Speed of Car : " + speed);

System.out.println("Size of Car : " + size);

System.out.println("CC of Car : " + CC);

12
System.out.println("No of gears of Car : " + gears);

}}

public class Test {

public static void main(String args[]) {

Car b1 = new Car();

b1.color = "Blue";

b1.speed = 200 ;

b1.size = 22;

b1.CC = 1000;

b1.gears = 5;

b1.attributescar();

}}

Output :-

Color of Car : Blue

Speed of Car : 200

Size of Car : 22

CC of Car : 1000

No of gears of Car : 5

Result:

Thus the java program using inheritance has been executed successfully.

13
EX.No: 7 PROGRAMS ON INTERFACE

Aim:

Write a Java program on implementing interface

Algorithm:

Step 1:Start the program.

Step 2:Define an interface named "MyInterface" with two abstract methods: method1 and
method2.

Step 3:Define a class named "Demo" that implements the "MyInterface" interface.

Step 4:Inside the "Demo" class:

a. Implement the method1 method from the "MyInterface" interface.

 Inside the method1 implementation, print "implementation of method1".

b. Implement the method2 method from the "MyInterface" interface.

 Inside the method2 implementation, print "implementation of method2".

Step 5:Define a public class named "Test".

Step 6:Inside the "Test" class, define the main method with the parameter args.

Step 7:Inside the main method:

a. Create an object of the "Demo" class and assign it to a reference variable of type
"MyInterface" named obj.

b. Call the method1 method on the obj object.

Step 8:End the program.

Program:

import java.io.*;

import java.util.*;

interfaceMyInterface{

14
public void method1();

public void method2();

class Demo implements MyInterface{

public void method1(){

System.out.println("implementation of method1");

public void method2(){

System.out.println("implementation of method2");

public static void main(String arg[]) {

MyInterfaceobj = new Demo();

obj.method1();

}}

Output:

implementation of method1

Result:

Thus the java program for implementing interface has been executed successfully

15
EX.No: 8 PROGRAMS ON MULTITHREADING

Aim:

To write Java program on multithreading.

Algorithm:

Step 1:Start the program.

Step 2:Define a class named "MultithreadingDemo" that extends the Thread class.

Step 3:Inside the "MultithreadingDemo" class, override the run method:

a. In the run method, try the following:

i. Get the ID of the current thread using Thread.currentThread().getId().

ii. Print a message indicating that the thread with the obtained ID is running.

b. If any exceptions occur while running the thread, catch and handle them by printing
"Exception is caught."

Step 4:Define a public class named "Multithread."

Step 5:Inside the "Multithread" class, define the main method with the parameter args.

Step 6:Inside the main method:

a. Declare an integer variable n and set it to 8. This represents the number of threads to be
created.

b. Use a for loop to create and start n threads:

i. Create an object of the "MultithreadingDemo" class named object.

ii. Call the start() method on the object to start the thread.

Step 7:End the program.

Program:

import java.io.*;

import java.util.*;

class MultithreadingDemo extends Thread {

16
public void run() {
try {
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
System.out.println("Exception is caught"); }
}}
public class Multithread {
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
} }}
Output:

Thread 15 is running

Thread 14 is running

Thread 16 is running

Thread 12 is running

Thread 11 is running

Thread 13 is running

Thread 18 is running

Thread 17 is running

Result:

Thus the java program for multi threading has been executed successfully

17
EX.No: 8 PROGRAMS ON EXCEPTIONAL HANDLING

Aim:

To write Java program on Exceptional Handling.

Algorithm:

Step 1:Start the program.

Step 2:Define a public class named "Main."

Step 3:Inside the "Main" class, define the main method with the parameter args.

Step 4:Inside the main method, start a try-catch block:

a. Try to execute the following code:

 Declare an integer variable divideByZero and attempt to perform the operation 5 / 0,


which will result in an arithmetic exception (division by zero).
 Print "Rest of code in try block" to the console. b. If an "ArithmeticException" occurs
during the execution of the try block, catch the exception and execute the catch block:
 Declare a variable of type "ArithmeticException" named e to capture the exception
object.
 Print "ArithmeticException => " followed by the exception message obtained from
e.getMessage() to the console.

Step 5:End the program.

Program:

import java.io.*;

import java.util.*;

class Main {

public static void main(String[] args)

try {

int divideByZero = 5 / 0;

18
System.out.println("Rest of code in try block");

catch (ArithmeticException e) {

System.out.println("ArithmeticException => " + e.getMessage());

Output:

ArithmeticException => / by zero

Result:

19
Thus the java program using exceptional handling has been executed successfully

EX.No: 10 PROGRAMS ON COLLECTION FRAMEWORK

Aim:

To write Java program on Collection Framework.

Algorithm:

Step 1:Start the program.

Step 2:Import the required classes (java.io.* and java.util.*) at the beginning of the program.

Step 3:Define a public class named "CollectionDemo."

Step 4:Inside the "CollectionDemo" class, define the main method with the parameter args.

Step 5:Inside the main method:

a. Declare and initialize an integer array arr with four elements: 1, 2, 3, and 4.

b. Create a Vector named v to store integers.

c. Create a Hashtable named h to store key-value pairs of integers and strings.

d. Add elements to the Vector and Hashtable:

i. Add 1 and 2 to the Vector using v.addElement(1) and v.addElement(2).

ii. Add key-value pairs (1, "collection") and (2, "collections") to the Hashtable using

h.put(1, "collection") and h.put(2, "collections").

e. Print the first element of the array arr to the console using System.out.println(arr[0]).

f. Print the first element of the Vector v to the console using System.out.println(v.elementAt(0)).

g. Print the value associated with the key 1 in the Hashtable h to the console using
System.out.println(h.get(1)).

Step 6:End the program.

Program:

import java.io.*;

20
import java.util.*;

class CollectionDemo {

public static void main(String[] args)

int arr[] = new int[] { 1, 2, 3, 4 };

Vector<Integer> v = new Vector();

Hashtable<Integer, String> h = new Hashtable();

v.addElement(1);

v.addElement(2);

h.put(1, "collection");

h.put(2, "collections");

System.out.println(arr[0]);

System.out.println(v.elementAt(0));

System.out.println(h.get(1));

Output:

Collections

Result:

21
Thus the java program using collection framework has been executed successfully

22

You might also like