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

OOPs Java Lab Manual

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

OOPs Java Lab Manual

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

[Approved by AICTE, Govt. of India & Affiliated to Dr.

APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

LAB MANUAL
Course: Object Oriented Programming with Java Lab
Code: BCS452
Session: 2023-24

Semester: 4th

1
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

BCS452- Object Oriented Programming with Java

List of Experiments (Indicative & not limited to)

1. Use Java compiler and eclipse platform to write and execute java program.
2. Creating simple java programs using command line arguments
3. Understand OOP concepts and basics of Java programming.
4. Create Java programs using inheritance and polymorphism.
5. Implement error-handling techniques using exception handling and multithreading.
6. Create java program with the use of java packages.
7. Construct java program using Java I/O package.
8. Create industry oriented application using Spring Framework.
9. Test RESTful web services using Spring Boot.
10. Test Frontend web application with Spring Boot

2
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

LAB PLAN
Object oriented with Java Programming Lab(BCS 452)
S.No. Contents Experiments Lab Turn

1 Simple
Programs  print the text “Hello”
Turn-01
without classes  Write a program to display the default
andobjects, values of all Primitive data types.
methods
 Programs based on Decision, Control and
Branch Statements
2 Program based on  Object instantiation
the concepts of  Constructors
classes and  Types of constructor
Turn-02
objects,  Constructor overloading
constructor,  Methods
 Parameter passing tomethods
parameterized
constructor
3 Single level &  Single level Inheritance
Multi level  Multiple inheritance Turn-03
inheritance  Method overloading
Method  Method overriding
overloading,
constructor
overloading

4  Super
Super, Final,  Final keyword
Abstraction  program to demonstrate Interfaces and
Turn-04
Abstract classes

5 Array and String  Simple programs using


Array and String Turn-05
3
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

6 Packages &  Making own package


Exception handling  Exception handling through-
Turn-06
 Try ,Catch ,Throw
 Finally

7 Multithreading  Simple programs of multithreading


 Thread Synchronization Turn-07

8 I/O& File  Input from user


Handling  Creation of file Turn-8
Reading data from file
Writing data in to file
9 Collections  Array List
 Stack Turn-9
 Queue
 Hash Set
 Tree Set
10 Spring  Create industry oriented application
Framework  Test RESTful & Frontend web application Turn-10
with Spring Boot

COURSE OBJECTIVES:

 To write programs using abstract classes.


 To write programs for solving real world problems using java collection frame
work.
 To write multithreaded programs.
 To write GUI programs using swing controls in Java.
 To introduce java compiler and eclipse platform.
 To impart hands on experience with java programming.

COURSE OUTCOMES:

 Able to write programs for solving real world problems using java collection
frame work.
4
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

 Able to write programs using abstract classes.


 Able to write multithreaded programs.
 Able to write GUI programs using swing controls in Java.

5
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Lab Turn1
Java Basic.
Program No. - 1

Objective : Write a Program to print the text “Hello to World of Java”. Save it with
name Hello.java in your folder.

class Hello {
public static void main (String args[]) {
System.out.println("Hello to world of Java");
}
}

Output :

Keshav Dhama
2201921530082

6
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. - 2

Objective : Write a Program to print the area of triangle. Save it with name
Area.java in your

class Area
{
public static void main(String args[])
{
int height = 10, base = 6;
float area = 0.5F*base* height;
System.out.println("area of triangle = "+area);
}
}

Output :

Keshav Dhama
2201921530082

7
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. – 3

Objective : Write a java Program to check the number is Prime or not.

import java.util.Scanner;
class Prime {
public static void main(String arr[]) {
int c;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number to be tested for prime ");
int n = in.nextInt( );

for (c = 2; c <= n - 1; c++) {


if (n % c == 0) {
System.out.println(n + ">>>>> not prime");
break;
}
}
if (c == n)
System.out.println(n + ">>>>Number is prime.");
}
}

Output :

Keshav Dhama
2201921530082

8
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. - 4
Objective : Write a java Program to generate a Fibonacci Series

class FibonacciExample1{
public static void main(String args[]){
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1

for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed


{
n3=n1+n2 ;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}

Output :

Keshav Dhama
2201921530082

9
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. – 5

Objective : Write a java Program to generate a Ladder of number.

import java.util.Scanner;
class Ladder
{
public static void main(String arr[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of rows");
int a=in.nextInt();
for(int i=1;i<=a;i++)
{
for(int j=1;j<=i;j++)
System.out.print(j);
for(int k=i-1;k>=1;k--)
System.out.print(k);
System.out.print("\n");
}
}
}

Output :

Keshav Dhama
2201921530082

10
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. - 6
Objective : Write a java Program to Convert any decimal number into its binary
equivalent

public class Convert


{
public static void main(String[] args)
{
int decimal = 10;
String binary = decimalToBinary(decimal);
System.out.println("Decimal: " + decimal);
System.out.println("Binary: " + binary);
}
public static String decimalToBinary(int n)
{
int remainder, quotient = n;
String binaryNum = "";
while (quotient > 0) {
remainder = quotient % 2;
binaryNum
= Integer.toString(remainder) + binaryNum;
quotient = quotient / 2;
}
return binaryNum;
}
}

Output :

Keshav Dhama
2201921530082

11
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Lab Turn 2
Program based on the concepts of classes and objects, constructor,
parameterized constructor
Program No. - 7

Objective : Write a program to create a class Student with data ‘name, city and age’
along with method printData to display the data. Create the two objects s1 ,s2 to
declare and access the values.

class Student
{
String name, city; int age;
static int m;
void printData()
{
System.out.println("Student name = "+name);
System.out.println("Student city = "+city);
System.out.println("Student age = "+age);
}
}
class Stest
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.name="Amit";
s1.city="Dehradun";
s1.age=22;
s2.name="Kapil";
s2.city="Delhi";
s2.age=23;
s2.printData();
s1.printData();
s1.m=20;
s2.m=22;
Student.m=27;
System.out.println("s1.m = "+s1.m);
System.out.println("s2.m = "+s2.m);
System.out.println("Student.m ="+Student.m);
12
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

}
}

Output :

Keshav Dhama
2201921530082

13
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. – 8

Objective : Write a program to create a class Student2 along with two method
getData(),printData() to get the value through argument and display the data in
printData. Create the two objects s1 ,s2 to declare and access the values from class
STtest.
class Student2
{
private String name, city;
private int age;
public void getData(String x, String y, int t)
{
name=x;
city=y;
age=t;
}
public void printData()
{
System.out.println("Student name ="+name);
System.out.println("Student city ="+city);
System.out.println("Student age ="+age);
}
}
class STtest
{
public static void main(String args[])
{
Student2 s1=new Student2();
Student2 s2=new Student2();
s2.getData("Kapil","Delhi",23);
s2.printData();
s1.getData("Amit","Dehradun",22);
s1.printData();
}
}
Output :

14
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. - 9
Objective : WAP using parameterized constructor with two parameters id and name.
While creating the objects obj1 and obj2 passed two arguments so that this constructor
gets invoked after creation of obj1 and obj2.

class Employee
{
int empId;
String empName; //parameterized constructor with two parameters
Employee(int id, String name)
{
this.empId = id;
this.empName = name;
}
void info()
{
System.out.println("Id: "+empId+" Name: "+empName);
}
public static void main(String args[])
{
Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
obj1.info();
obj2.info();
}
}

Output :

Keshav Dhama
2201921530082

15
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Lab Turn 3
Method overloading, constructor overloading
Program No. – 10
Objective : Write a program in JAVA to demonstrate the method and constructor
overloading.

class Cs
{
int p,q;
public Cs(){}
public Cs(int x, int y)
{
p=x; q=y;
}
public int add(int i, int j)
{
return (i+j);
}
public int add(int i, int j, int k)
{
return (i+j+k);
}
public float add(float f1, float f2)
{
return (f1+f2);
}
public void printData()
{
System.out.print("p = "+p);
System.out.println(" q = "+q);
}
}
class ConstructorOverlaoding
{
public static void main(String args[])
{
int x=2, y=3, z=4;
Cs c=new Cs();
Cs c1=new Cs(x, z );
c1.printData();
float m=7.2F, n=5.2F;
int k=c.add(x,y);

16
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

int t=c.add(x,y,z);
float ft=c.add(m, n);
System.out.println("k = "+k);
System.out.println("t = "+t);
System.out.println("ft = "+ft);
}
}

Output :

Keshav Dhama
2201921530082

17
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. - 11

Objective : Write a program in JAVA to create a class Bird also declares the different
parameterized constructor to display the name of Birds.

class Bird
{
int age;
String name ;
Bird()
{
System.out.println("this is the perrot");
}
Bird(String x)
{
name=x;
System.out.println("this is the "+name);
}
Bird(int y,String z)
{
age=y;
name=z;
System.out.println("this is the "+age+"years\t"+name);
}

public static void main(String arr[])


{
Bird a=new Bird();
Bird b=new Bird("maina");
Bird c=new Bird(20,"sparrow");
}
}

Output :

Keshav Dhama
220192153008
18
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. – 12
Objective : Write a program in java to generate an abstract class A also class B inherits
the class A. generate the object for class B and display the text “call me from B”.

abstract class A
{
abstract void call();
}
class B extends A
{
public void call()
{
System.out.println("call me from B");
}
public static void main(String arr[])
{
B b=new B();
b.call();
}
}

Output :

Keshav Dhama
2201921530082

19
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. – 13

Objective : Write a java program in which you will declare two interface sum and
Add inherits these interface through class A1 and display their content

interface sum
{
int sm= 70;
void sum();
}
interface add
{
int ad= 55;
void add();
}
class A1 implements add ,sum
{
public void sum()
{
System.out.println(+sm);
}
public void add()
{
System.out.println(+ad);
}
public static void main(String arr[])
{
A1 n= new A1();
n.add();
n.sum();
}
}

Output :

20
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Lab Turn 4
Single level & Multi level inheritance , Method Overriding

Program No. - 14

Objective : Java program to illustrate the concept of single inheritance

import java.lang.*;

class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
class two extends one
{
public void print_for()
{
System.out.println("for");
}
}
// Driver class
public class Main {
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

21
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Output :

Keshav Dhama
2201921530082

22
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. - 15

Objective : Java program to illustrate the concept of Multilevel inheritance

import java.lang.*;
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
class two extends one
{
public void print_for()
{
System.out.println("for");
}
}
class three extends two
{
public void print_geek()
{
System.out.println("Geeks");
}
}
// Derived class
class classMain
{
public static void main(String args[])
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output :

23
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. – 16
Objective : A Simple Java program to demonstrate method overriding in java

class Parent
{
void show()
{
System.out.println("Parent's show()");
}
}
class Child extends Parent
{ // This method overrides show() of Parent @Override
void show()
{
System.out.println("Child's show()");
}
}
// Driver class
class Main
{
public static void main(String[] args)
{
// If a Parent type reference refers // to a Parent object, then Parent's // show is called
Parent obj1 = new Parent();
obj1.show();
// If a Parent type reference refers // to a Child object Child's show()
// is called. This is called RUN TIME // POLYMORPHISM.

Parent obj2 = new Child();


obj2.show();
}
}
Output :

Keshav Dhama
220192153008

24
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. – 17

Objective : Super Keyword in Java Use of super with variables

class Vehicle
{
int maxSpeed = 150;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{ /* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: "+ super.maxSpeed);
}
}
/* Driver program to test */

class classTest
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

Output :

Keshav Dhama
2201921530082

25
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Lab Turn 5
Array and String
Program No. - 18
Objective : Write a Java Program to to find maximum in arr[]

// Driver Class
class Test
{
// array declared
static int arr[] = {10, 324, 45, 90, 9808};

// Method to find maximum in arr[]


static int largest()
{
int i;

// Initialize maximum element


int max = arr[0];

// Traverse array elements from second and


// compare every element with current max
for (i = 1; i < arr.length; i++)
if (arr[i] > max)
max = arr[i];

return max;
}

// Driver method
public static void main(String[] args)
{
System.out.println("Largest in given array is " + largest());
}
}
Output :

Keshav Dhama

26
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. – 19
Objective : Implementation of the sort() function across different scenarios of the
Arrays class

import java.util.Arrays;

class GFG {
public static void main(String args[])
{
int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
System.out.println("The original array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
Arrays.sort(arr);
System.out.println("\nThe sorted array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}

Output :

Keshav Dhama
2201921530082

27
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. – 20
Objective : Java program for addition of two matrices

import java.io.*;
class GFG {

// Function to print Matrix


static void printMatrix(int M[][],
int rowSize,
int colSize)
{
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++)
System.out.print(M[i][j] + " ");

System.out.println();
}
}

// Function to add the two matrices


// and store in matrix C
static int[][] add(int A[][], int B[][],
int size)
{
int i, j;
int C[][] = new int[size][size];

for (i = 0; i < size; i++)


for (j = 0; j < size; j++)
C[i][j] = A[i][j] + B[i][j];

return C;
}

// Driver code
public static void main(String[] args)
{
int size = 4;

int A[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },

28
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices A
System.out.println("\nMatrix A:");
printMatrix(A, size, size);

int B[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices B
System.out.println("\nMatrix B:");
printMatrix(B, size, size);

// Add the two matrices


int C[][] = add(A, B, size);

// Print the result


System.out.println("\nResultant Matrix:");
printMatrix(C, size, size);
}
}

Output :

Keshav Dhama
2201921530082
29
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. - 21
Objective : Java program to reverse a word

import java.io.*;
import java.util.Scanner;

class GFG {
public static void main (String[] args) {

String str= "Geeks", nstr="";


char ch;

System.out.print("Original word: ");


System.out.println("Geeks"); //Example word

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


{
ch= str.charAt(i); //extracts each character
nstr= ch+nstr; //adds each character in front of the existing string
}
System.out.println("Reversed word: "+ nstr);
}
}

Output :

Keshav Dhama
2201921530082

30
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Lab Turn 6
Exception handling & Packages
Program No. – 2

Objective : Write a program in java if number is less than 10 and greater than 50
it generate the exception out of range. Else it displays the square of number

/ Define the custom exception


class OutOfRangeException extends Exception {
public OutOfRangeException(String message) {
super(message);
}
}

// Main class
public class CustomTest {

// Method to check the number and calculate the square


public static int calculateSquare(int number) throws OutOfRangeException {
if (number < 10 || number > 50) {
throw new OutOfRangeException("Number is out of range. It should be between 10
and 50.");
}
return number * number;
}

// Main method
public static void main(String[] args) {
int[] testNumbers = {5, 15, 30, 55}; // Test numbers to demonstrate functionality

for (int number : testNumbers) {


try {
int result = calculateSquare(number);
System.out.println("The square of " + number + " is " + result);
} catch (OutOfRangeException e) {
System.out.println(e.getMessage());
}
}
}
}

31
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Output :

Keshav Dhama
2201921530082

32
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. 23
Objective : Write a program in java to enter the number through command line argument if first and
second number is not entered it will generate the exception. Also divide the first number with second
number and generate the arithmetic exception.

class Divide2
{
public static void main(String arr[])
{
try
{
if(arr.length<2)

throw(new Exception("two argument must be provided"));


int a= Integer.parseInt(arr[0]);
int b=Integer.parseInt(arr[1]);
if(b==0)
throw(new Exception("second argument should be non zero"));
int c=a/b;
System.out.println("result:"+c);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output :

Keshav Dhama
2201921530082

33
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Objectiv : Example of package that import the packagename.*


package Pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
package MyPack;
import Pack.*;
public class B {
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Output :

Keshav Dhama
2201921530082

34
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No, - 25
Objective : Example of package by import fully qualified name

//save by A.java
package pack;
public class A{
public void msg()
{
System.out.println("Hello");}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
} }

Output: Hello

35
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Lab Turn7
Multithreading

Program No. - 26

26 Write a java program in which thread sleep for 5 sec and change the name of
thread.
public class ThreadNameChange extends Thread {

public ThreadNameChange(String name) {


super(name); // Set the initial name of the thread
}

@Override
public void run() {
try {
System.out.println("Thread " + this.getName() + " is going to sleep for 5 seconds.");
Thread.sleep(5000); // Sleep for 5 seconds
this.setName("NewThreadName"); // Change the thread name
System.out.println("Thread name changed to " + this.getName());
} catch (InterruptedException e) {
System.out.println("Thread was interrupted.");
}
}

public static void main(String[] args) {


ThreadNameChange thread = new ThreadNameChange("InitialThreadName");
System.out.println("Starting thread with name: " + thread.getName());
thread.start();
}
}

Output :

36
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. - 27

Objective : Write a java program for multithread in which user thread and thread started from
main method invoked at a time each thread sleep for 1 sec.
class UserThread extends Thread
{
public void run()
{
Thread t=Thread.currentThread();
System.out.println("run() is invoked in " +t.getName()+" thread..."); for(int i=1;i<=10;i++)
{
System.out.println("run:"+i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{ }
}
System.out.println("run() is completed");
}
}
class ThredTest
{
public static void main(String arr[])
{
System.out.println("main() started creating an object of user Thread.");
UserThread t=new UserThread(); System.out.println("directly invoking run() of user
thread");
t.run();
System.out.println("control back in main()");
System.out.println("launching new thread for run() of user thread.");
t.start();
for(int i=10;i>0;i--)

37
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

{
System.out.println("main:"+i); try
{
Thread.sleep(1000);
}
catch(Exception e){}
}System.out.println("main() completed");
}
}
Output :

38
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. – 28
Objective : Write a java program for to solve producer consumer problem in which a producer
produce a value and consumer consume the value before producer generate the next value.
class Buffer
{
int value;
boolean produced=false;
public synchronized void produce(int x)
{
if(produced)
{
System.out.println("producer enter monitor out of turn..suspend. ");
try
{
wait();
}catch(Exception e)
{}
}
value=x;
System.out.println(value+"is produced"); produced=true;
notify();
}
public synchronized void consume()
{
if(! produced)
{
System.out.println("consumer enterd the monitor out of turn,suspend.");
try
{
wait();
}
catch(Exception e)
{ }
}
System.out.println(value+"is consumed"); produced=false;
39
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

notify();
}
}
class Producer extends Thread {
Buffer buffer;

public Producer(Buffer b) {
buffer = b;
}
public void run() {
{
System.out.println("producer started ,producing value. ");
for (int i = 1; 1 <= 10; i++)
buffer.produce(i);
}
}
}
class Consumer extends Thread {
Buffer buffer;

public Consumer(Buffer b) {
buffer = b;
}
public void run() {
System.out.println("consumer started,consuming value. ");
for (int i = 1; i <= 10; i++) buffer.consume();
}
}
class PC1 {
public static void main(String arr[]) {
Buffer b = new Buffer();
Producer p = new Producer(b);
Consumer c = new Consumer(b);
p.start();
c.start();
}
40
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

}
Output :

41
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Lab Turn 8

I/O and File Handling


Program No. – 29
Objective : Write a java program to create a file and write the text in it and save the file.

import java.io.*;

class CreateFile {

public static void main(String arr[]) {

if (arr.length < 1) {

System.out.println("Usage: java CreateFile <file name>");

System.exit(0);

try {

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

PrintStream fos = new PrintStream(new FileOutputStream(arr[0]));

System.out.println("Enter text (type 'end' to save and exit):");

PrintStream temp = System.out;

System.setOut(fos);

while (true) {

String str = b.readLine();

if (str.equalsIgnoreCase("end")) {

break;

System.out.println(str);

42
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

System.setOut(temp);

fos.close();

b.close();

System.out.println("File successfully created.");

} catch (Exception ex) {

System.out.println(ex);

Output :

Keshav Dhama

2201921530082

43
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Program No. - 30
Objective : Write a java program to read a file and display the content on screen.

import java.io.*;

class Input {

public static void main(String args[]) {

FileInputStream fis = null;

try

fis = new FileInputStream("./src/file.txt");

String a = String.valueOf(fis.read());

System.out.println(a);

catch (IOException e) {

e.printStackTrace();

finally {

if (fis != null) {

try

fis.close();

44
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

catch (IOException e) {

e.printStackTrace();

Output :

Keshav Dhama

2201921530082

45
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ Abdul
GL BAJAJ
Institute of Technologies & Management
Kalam Technical University, Lucknow, U.P., India]
Department of Applied Computational Science & Engineering
Greater Noida

Lab Turn 9

Collections in Java

import java.util.*;

public class AList{


public static void main(String args[]){
//creating an ArrayList
ArrayList<String> str= new ArrayList<String>();

//displaying the initial size


System.out.println("Size at the beginning "+str.size());

//add elements
str.add("Hello");
str.add("Hi");
str.add("Namaste");
str.add("Bonjour");

//displaying the ArrayList


System.out.println(str)

//displaying the size


System.out.println("Size after addition "+str.size());

//remove element at index 0


str.remove(0);

//display the new ArrayList


System.out.println(str);

//display the new size


System.out.println("Size after removal "+str.size());
}
}

46

You might also like