0% found this document useful (0 votes)
21 views78 pages

Lab Record Download

Uploaded by

poyev30140
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views78 pages

Lab Record Download

Uploaded by

poyev30140
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Noida Institute of Engineering & Technology,

Greater Noida

LAB FILE
nt
Branch : Semester :
Ta

Session
: Subject Code :
Aditya Krishna Yadav Faculty Name
Name & Roll No: (2301330120010)
e

:
ra d

Subject Name :
Co

Department of Computer Science


NOIDA INSTITUTE OF ENGINEERING & TECHNOLOGY
19, KNOWLEDGE PARK-II, INSTITUTIONAL AREA,
GREATER NOIDA, (U. P.) - 201 306, INDIA
PROGRAM LIST Session:

Semester:

S.No Program Name Submission Date Grade Signature Remark

nt
e Ta
ra d
Co
Aim:
Below is an example of a simple program written in Java programming language.

Change the text in the below code to make the program print "Hello Java" instead of "Hello
C" and click on
Submit.

We will learn more about the other aspects of the below code in the later sections.

Note: Please don't change the package name.


Program:

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

Output
: case - 1
Test

User Output
nt
Hello Java

Result:
Ta

Thus the above program is executed successfully and the output has
been verified
e
ra d
Co
Aim:
Write a java program to display the default values of all primitive
data types.

Write a class PrimitiveTypes with main(String[ ] args)

method. Write code to produce the below output:

byte default value =


0 short default
value = 0 int
default value = 0
long default value =
0
boolean default value =
false double default
value = 0.0
float default value = 0.0
Note: Please don't change the package name.
Program:

q10815/PrimitiveTypes.java
package q10815;
class PrimitiveTypes {
static byte m =
nt
0; static short
l = 0; static
int s = 0;
static long a =
0;
Ta

static boolean b =
false; static double d
= 0.0;
static float f = 0.0f;
e
ra d

public static void


Co

main(String[]
args) {
System.out.println("byte default value = " +
m); System.out.println("short default value
= " + l);
System.out.println("int default value = " +
s); System.out.println("long default value
= " + a);

b);
Output
System.out.println("boolean default value = " +
System.out.println("double default value =
" + d); :
System.out.println("float default
Test case - 1
value = " + f);
}
User Output
}
byte default value = 0
short default value = 0
int default value = 0
long default value = 0
double default value = 0.0
float default value = 0.0

Result:
Thus the above program is executed successfully and the output has been verified

nt
e Ta
ra d
Co
Aim:
Write the code in the below main() method to calculate and print the Total and Average
marks scored by a student from the input given through the command line arguments.

Assume that four command line arguments name , marks1 , marks2 , marks3 will be passed
to the main()
method in the below class with name TotalAndAvgMarks .

Sample Input and Output:


For example, if the command line arguments to the main() method are :
Narmada 75.50 67.75 78.25 .
The program should print the result
as: Name = Narmada
Marks1 = 75.5
Marks2 = 67.75
Marks3 = 78.25
Total Marks = 221.5
Average Marks = 73.833336

Note: Consider the three marks passed in


the command line arguments as floats .

Note: Please don't change the package


name.
Program:
nt
q10817/TotalAndAvgMarks.java
package q10817;
Ta

public class TotalAndAvgMarks {


public static void main(String[]
args) { String name =
args[0];
float marks1 = Float.parseFloat(args[1]);
e

float marks2 =
Float.parseFloat(args[2]); float
ra d

marks3 = Float.parseFloat(args[3]);
float total = marks1 + marks2 +
Co

marks3;
float avg = total/3;
System.out.println("Name = " + name);
System.out.println("Marks1 = " + marks1);
System.out.println("Marks2 = " +
marks2);
System.out.println("Marks3 = " + marks3);
System.out.println("Total Output
Marks= " + total);
System.out.println("Average
avg);
: caseMarks
Test -1
= " +

}
} User Output
Name = Narmada
Marks1 = 78.5
Marks2 = 67.75
Marks3 = 71.2
Total Marks = 217.45
Average Marks = 72.48333
Test case - 2

User Output
Name = Nile
Marks1 = 67.0
Marks2 = 81.0
Marks3 = 50.0
Total Marks = 198.0
Average Marks = 66.0

Result:
Thus the above program is executed successfully and the output has been verified

nt
e Ta
ra d
Co
Aim:
Write code which uses if-then-else statement to check if a given account balance is greater
or lesser than the minimum balance.

Write a class BalanceCheck with public method checkBalance that takes one parameter
balance of type
double .

Use if-then-else statement and print Balance is low if balance is less than 1000.
Otherwise, print
Suffi cient balance.

Note: You need not write the main method. You can directly write the checkBalance(double
balance)
method in the BalanceCheck class.

Use System.out.println() instead of System.out.print().

Note: Please don't change the package name.


Program:

q10850/BalanceCheck.java
package q10850;
class BalanceCheck {
nt
public void checkBalance(double
balance) { if (balance<1000) {
System.out.println("Balance is
low");
Ta

} else {
System.out.println("Sufficient
balance");
}
e

}
}
ra d

q10850/BalanceMain.java
Co

package q10850;
public class BalanceMain{
public static void main(String[] args){
double balance = Double.parseDouble(args[0]);
BalanceCheck bc= new BalanceCheck();
bc.checkBalance(balance);
}

}
Output
:
Test case - 1

User Output
Balance is low

Test case - 2
User Output
Sufficient balance

Test case - 3

User Output
Sufficient balance

Result:
Thus the above program is executed successfully and the output has been verified

nt
e Ta
ra d
Co
Aim:
Write a class Factorial with a main method. The method takes one command line argument.
Write a logic to find the factorial of a given argument and print the output.

For example:
Cmd Args : 5
Factorial of 5 is
120

Note: Please don't change the package name.


Program:

q10886/Factorial.java
package q10886;
import java.util.*;
public class Factorial {
static int factorial(int a)
{ if(a ==1 || a ==
0) {
return 1;
}
return a * factorial(a-1);

}
public static void main(String[]
nt
args) {
Scanner sc = new Scanner(System.in);
int a =
Integer.parseInt(args[0]);
Ta

int fact = factorial(a);


System.out.print("Factorial of "+ a + "
is "+fact+"\n");
}
Output
e

}
:
Test case - 1
ra d

User Output
Co

Factorial of 5 is 120

Test case - 2

User Output
Factorial of 0 is 1

Result:
Thus the above program is executed successfully and the output has
been verified
Aim:
Write a class NumberPalindrome with a public method isNumberPalindrome that takes
one parameter
number of type int . Write a code to check whether the given number is palindrome or
not.

Cmd Args : 333


For example
333 is a
palindrome

Note: Please don't change the package name.


Program:

q10894/NumberPalindrome.java
package q10894;

public class NumberPalindrome {

public void isNumberPalindrome(int


number) { int originalNumber =
number;
int reversedNumber = 0; int
remainder;
while (number !=0) {
remainder = number %
10;
nt
reversedNumber = reversedNumber *10 + remainder;
number /=10;
}
Ta

if(originalNumber == reversedNumber ) {
System.out.println(originalNumber + " is a
palindrome");
} else {
System.out.println(originalNumber + " is not a
e

palindrome");
}
//Write your code here
ra d

}
Co

q10894/NumberPalindromeMain.java
package q10894;
public class NumberPalindromeMain{
public static void main(String[]
args){ if (args.length < 1)
{
System.out.println("Usage: java NumberPalindromeMain <number>");
System.exit(-1);
}
try {
int number = Integer.parseInt(args[0]);
NumberPalindrome nPalindrome = new NumberPalindrome();
nPalindrome.isNumberPalindrome(number);
} catch(NumberFormatException nfe) {
System.out.println("Usage: java NumberPalindromeMain
<number>\n\tage: an integer representing number");
}

}
}
Output
: case - 1
Test

User Output
333 is a palindrome

Test case - 2

User Output
567 is not a palindrome

Result:
Thus the above program is executed successfully and the output has
been verified

nt
e Ta
ra d
Co
Aim:
Write a class FibonacciSeries with a main method. The method receives one command line
argument. Write a program to display fibonacci series i.e. 0 1 1 2 3 5 8 13 21.....

For example:
Cmd Args : 80
0 1 1 2 3 5 8 13 21 34
55

Note: Please don't change the package name.


Program:

q10896/FibonacciSeries.java
package q10896;
class FibonacciSeries {
public static void main(String
args[]) { int n,a=0,
b=1,s=a+b;
n= Integer.parseInt(args[0]);
System.out.print(a);
while(s<=n) {
System.out.print(" "+s); s=
a+b;
a=b;
b=s;
}
nt
}
}

Output
Ta

:
Test case - 1

User Output
0 1 1 2 3 5
e
ra d

Test case - 2
Co

User Output
0 1 1 2 3 5 8 13 21 34 55

Test case - 3

User Output
0 1 1 2 3 5 8

Result:
Thus the above program is executed successfully and the output has
been verified
Aim:
Write a JAVA program to implement a class mechanism. Create a class, methods and invoke
them inside the main method.
Program:

q116/Main.java
package q116;
import
java.util.*;
public class Main
{
public
void
print() {
Scanner sc = new
Scanner(System.in);
System.out.print("Enter a string:
");
String str = sc.nextLine();
System.out.println("The entered
string is: "+str);
}
public static void main(String[]
args) { Output
Main ob = new Main();
ob.print(); :
Test case - 1
}
nt
}
User Output
Enter a string:
Hello
Ta

The entered string is: Hello

Test case - 2
e

User Output
ra d

Enter a string:

Hello CodeTantra
Co

The entered string is: Hello CodeTantra

Result:
Thus the above program is executed successfully and the output has
been verified
Aim:
Write a Java program to illustrate the abstract class concept.

Create an abstract class Shape , which contains an empty method numberOfSides().

Define three classes named Trapezoid , Triangle and Hexagon extends the class Shape ,
such that each one of the classes contains only the method numberOfSides(), that
contains the number of sides in the
given geometrical figure.

Write a class AbstractExample with the main() method, declare an object to the class
Shape , create instances of each class and call numberOfSides() methods of each class.

Sample Input and Output:

Number of sides in a trapezoid


are 4 Number of sides in a
triangle are 3 Number of sides
in a hexagon are 6

Note: Please don't change the package


name.
Program:
nt
q11287/AbstractExample.java
e Ta
ra d
Co
package q11287;
abstract class Shape {
abstract void numberOfSides();
}
class Trapezoid extends Shape
{ void
numberOfSides() {
System.out.println("N
umber of sides
in a trapezoid
are 4");
}
}
class Triangle extends Shape
{ void
numberOfSides() {
System.out.println("
Number of
sides in a
triangle are
3");
}
}
class Hexagon extends Shape
{ void
numberOfSides() {
System.out.print("Nu
mber of sides
in a hexagon
nt
are 6\n");
}
}
Ta

public class AbstractExample {


public static void main(String[]
args) { Shape s;
s = new Trapezoid();
e

s.numberOfSides();
// Call the method
ra d

s = new Triangle();
s.numberOfSides()
; Test case - 1
Co

// Call the method


User Output
s = new Hexagon();
Number of sidess.numberOfSides()
in a trapezoid are 4
;
Number of sides in a triangle are 3
// Call the method
Number of sides in a hexagon are 6
}
}

Output:

Result:
Thus the above program is executed successfully and the output has been verified
Aim:
In a Java class, the fields which are marked as static are called static fields and those that
are not marked as static are called as instance fields or simply fields
Program:

q11291/StaticFieldDemo.java
package q11291;
import java.util.*;
class StaticFieldDemo
{
static int
a; int b,c;
StaticFieldD
emo(int
b,int c)
{
this.b =
b; this.c
= c;
}
public void
getvalue()
{
System.out.println("a1 = A [instanceField = "+this.b+",
aStaticField = "+StaticFieldDemo.a+"]");
System.out.println("a2 = A [instanceField =
nt
"+this.c+", aStaticField =
"+StaticFieldDemo.a+"]");
System.out.println("A.aStaticField =
"+StaticFieldDemo.a);
Ta

}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a
e

StaticField number"); a = sc.nextInt();


int
ra d

b = sc.nextInt();
int c =
sc.nextInt();
Co

Output
StaticFieldDemo obj = new
StaticFieldDemo(b,c); obj.getvalue();
} :
Test case - 1

User Output }

Enter a StaticField number


569
a1 = A [instanceField = 6, aStaticField = 5]
a2 = A [instanceField = 9, aStaticField = 5]
A.aStaticField = 5

Test case - 2

User Output
Enter a StaticField number
a1 = A [instanceField = 48, aStaticField = 52]
a2 = A [instanceField = 63, aStaticField = 52]
A.aStaticField = 52

Result:
Thus the above program is executed successfully and the output has been verified

nt
e Ta
ra d
Co
Aim:
In a Java class, the fields which are marked as static are called static fields and those that
are not marked as static are called as instance fields or simply fields.
A Java class which is marked as static is called a static class
Program:

q11293/StaticClassDemo.java
package q11293;
import java.util.*;
class StaticClassDemo
{
int
a;
int
b;
Stati
cClas
sDemo
(int
a,int
b)
{
this.a =
a; this.b
= b;
}
public void
nt
getvalue()
{
System.out.println("a1 = A [value =
"+this.a+"]"); System.out.println("a2 = A
Ta

[value = "+this.b+"]");
}
public static void main(String[] args)
{
e

Scanner sc = new
Scanner(System.in);
System.out.print("Enter
Output a
ra d

number:"); int a = sc.nextInt();


int b = sc.nextInt();:
Test case - 1
Co

StaticClassDemo st = new
User Output StaticClassDemo(a,b); st.getvalue();

Enter a number:
}
}56 89
a1 = A [value = 56]
a2 = A [value = 89]

Test case - 2

User Output
Enter a number:

94
a1 = A [value = 9]
a2 = A [value = 4]
Test case - 3

User Output
Enter a number:
200 874
a1 = A [value = 200]
a2 = A [value = 874]

Result:
Thus the above program is executed successfully and the output has been verified

nt
e Ta
ra d
Co
Aim:
Write a Java program to access the class members using super Keyword.

Create a class called SuperClass with the below members:


• declare two member fields value1 and value2 of type int
• a parameterized constructor with two arguments, which assigns two arguments to
the members respectively
• a method called show() which will print This is super class show() method as
well as the value of
value1.
Create another class called SubClass which is derived from the class SuperClass , and
has the below members:
• declare two member fields value3 and value4 of type int
• a parameterized constructor with four arguments, which assigns the first two
arguments with
SuperClass members and next two values with SubClass members
• a method called show() which
1. will print This is sub class show() method
2. will call show() of SuperClass
3. will print value2 from SuperClass
4. will print value3 of SubClass
5. will print value4 of SubClass
Write a class AccessUsingSuper with the main() method, create an object to SubClass
which calls the method show().
nt
For example, if the input is given as [10, 20, 30, 40] then the output should be:

This is sub class show() method


This is super class show()
Ta

method value1 = 10
value2 from super class = 20
value3 = 30
value4 = 40
e

Note: Please don't change the package


ra d

name.
Program:
Co

q11274/AccessUsingSuper.java
package q11274;
class SuperClass {
int value1, value2;
// Write the
code void
show() {
System.out.println("This is super class show()
method"); System.out.println("value1 =
"+this.value1);
}

class SubClass extends


SuperClass { int value3,
value4;
// Write the code
public SubClass(int a1, int a2, int a3, int
a4) { this.value1 = a1;
this.value2 = a2;
this.value3 = a3;
this.value4 =
a4;
}
void show() {
nt
System.out.println("This is sub class show() method");
super.show();
System.out.println("value2 from super class = "+this.value2);
System.out.println("value3 = "+this.value3);
Ta

System.out.println("value4 = "+this.value4);
}

}
e

public class AccessUsingSuper {


ra d

public static void main(String[] args) {


SubClass obj = new SubClass(Integer.parseInt(args[0]),
Integer.parseInt(args[1]), Integer.parseInt(args[2]),
Co

Integer.parseInt(args[3])); obj.show();
}
}

Test case - 1

User Output Output:


This is sub class show() method
This is super class show() method
value1 = 10
value2 from super class = 30
value3 = 40
value4 = 50

Result:
Thus the above program is executed successfully and the output has been verified
Aim:
Write a JAVA program to implement Single Inheritance.
Program:

SingleInheritance.java
import
java.util.*;
abstract class
Show
{
abstract
void
show(Strin
g s);
}
class First
extends Show
{
void
show(Strin
g s)
{
Sy
st
em
.o
ut
.p
nt
ri
nt
ln
("
Fi
Ta

rs
t
cl
as
s
st
e

ri
ng
is
ra d

:
"+
s)
Co

;
}
}
class Second
extends Show
{
void
show(Strin
Output
g s) :
Test case - 1
{
Sy
User Output st
Enter the firstemclass string:
.o
Hello ut
.p
First class string is: Hello
ri
Enter the second
nt class string:
ln
World! ("
Second class string
Se is: World!
co
nd
cl
as
s
st
ri
ng
is
:
"+
s)
;
}
}
public class
SingleInheritance
{
public
static
void
main(Strin
Test case - 2

User Output
Enter the first class string:
Hey! Jack
First class string is: Hey! Jack
Enter the second class string:

How are you?


Second class string is: How are you?

Result:
Thus the above program is executed successfully and the output has been verified

nt
e Ta
ra d
Co
Aim:
Write a Java program to illustrate the multilevel inheritance concept.

Create a class Student


• contains the data members id of int data type and name of string type
• write a method setData() to initialize the data members
• write a method displayData() which will display the given id and name
Create a class Marks which is derived from the class Student
• contains the data members javaMarks, cMarks and cppMarks of float data type
• write a method setMarks() to initialize the data members
•write a method displayMarks() which will display the
given data Create another class Result which is derived
from the class Marks
• contains the data members total and avg of float data
type
• write a method compute() to find total and average of
the given marks
• write a method showResult() which will display the
total and avg marks
Write a class MultilevelInheritanceDemo with the main() method which will receive five
arguments as id, name, javaMarks, cMarks and cppMarks.

Create object only to the class Result to access the methods.

If the input is given as command line arguments to the main() as "99", "Lakshmi", "55.5",
nt
"78.5", "72"
then the program should print the output as:

Id : 99
Name : Lakshmi
Ta

Java marks :
55.5 C
marks : 78.5
Cpp marks :
e

72.0 Total :
Note:
206.0Please don't change the package name.
Program:
ra d

Avg :
68.666664
q11264/
Co

MultilevelInheritanceDemo.java
package
q11264; class
Student
{
int
id;
String
name;
void
setDat
a(int
id,Str
ing
name)
{
t
h
i
s
.
i
d

i
d
;
t
h
i
s
nt
.
n
a
m
e
Ta

n
a
m
e

e
;
}
ra d

void
displa
yData(
Co

)
{
S
y
s
t
e
m
.
o
u
t
.
p
r
i
n
t
l
n
(
"
I
d

"
+
i
d
)
;
S
y
s
t
e
m
.
o
u
t
.
p
r
i
r.displayData();
r.setMarks(javaMarks,cMarks,cppMark
s); r.displayMarks();
r.compute();
r.showResult();
}
}

Output:
Test case - 1

User Output
Id : 99
Name : Geetha
Java marks : 56.0
nt
C marks : 75.5
Cpp marks : 66.6
Total : 198.1
Avg : 66.03333
Ta

Test case - 2
e

User Output
Id : 199
ra d

Name : Lakshmi
Java marks : 55.5
Co

C marks : 78.5
Cpp marks : 78.0
Total : 212.0
Avg : 70.666664

Result:
Thus the above program is executed successfully and the output has been verified
Aim:
Write a Java program that implements an interface.

Create an interface called Car with two abstract methods String getName() and int
getMaxSpeed() . Also declare one default method void applyBreak() which has the code
snippet

System.out.println("Applying break on " + getName());

In the same interface include a static method Car getFastestCar(Car car1, Car car2) ,
which returns car1
if the maxSpeed of car1 is greater than or equal to that of car2, else should return car2.

Create a class called BMW which implements the interface Car and provides the
implementation for the abstract methods getName() and getMaxSpeed() (make sure to
declare the appropriate fields to store name and maxSpeed and also the constructor to
initialize them).

Similarly, create a class called Audi which implements the interface Car and provides the
implementation for the abstract methods getName() and getMaxSpeed() (make sure to
declare the appropriate fields to
store name and maxSpeed and also the constructor to initialize them).
nt
Create a public class called MainApp with the main() method.
Take the input from the command line arguments. Create objects for the classes BMW and
Audi then print the fastest car.
Ta

Note:
Java 8 introduced a new feature called default methods or defender methods, which allow
developers to add new methods to the interfaces without breaking the existing
implementation of these interface. These
e

default methods can also be overridden in the implementing classes or made abstract in the
extending interfaces. If they are not overridden, their implementation will be shared by all
ra d

the implementing classes or sub interfaces.


Co

Below is the syntax for declaring a default method in an interface :

public default void methodName() {


System.out.println("This is a default method in interface");
}

Similarly, Java 8 also introduced static methods inside interfaces, which act as regular static
methods in classes. These allow developers group the utility functions along with the
interfaces instead of defining them in a separate helper class.

Below is the syntax for declaring a static method in an interface :

public static void methodName() {


System.out.println("This is a static method in interface");
}

Note: Please don't change the package name.


Program:

q11284/MainApp.java
package
q11284;
interface Car
{
String
getName(); int
getMaxSpeed();
default void
applyBreak() {
System.ou
t.println
("Applyin
g brake
on
"+getName
());
}
static Car
getFastestCar(Ca
r car1, Car
car2){
if(car1.getMaxSpeed()
>=car2.getMaxSpeed()){ return
car1;
}
else{
return car2;
}
}
nt
}
class BMW implements Car {
String carName; int
Ta

MaxSpeed;
public BMW(String
name, int
MaxSpeed){
this.carName=n
e

ame;
this.MaxSpeed=
MaxSpe
ra d

ed;
}
Co

public String
getName(){
return
this.c
arName
;
}
public int
getMaxSpeed(){
return
this.M
axSpee
d;
}
}
class Audi implements Car
{ String
carName;
int MaxSpeed;
public Audi(String name, int
maxSpeed){ this.carName =
name;
this.MaxSpeed = maxSpeed;
}
public String getName(){
return this.carName;
}
public int getMaxSpeed(){
return this.MaxSpeed;
}
}
public class MainApp {
public static void main(String args[]) {
BMW bmw = new BMW(args[0],
Integer.parseInt(args[1]));
Audi audi = new Audi(args[2], Integer.parseInt(args[3]));
System.out.println("Fastest car is :
"+Car.getFastestCar(bmw,audi).getName());
Test case - 1

User Output
Fastest car is : BMW

Test case - 2

User Output
Fastest car is : Maruthi

Result:
Thus the above program is executed successfully and the output has been verified

nt
e Ta
ra d
Co
Aim:
A constructor must be written inside the class body (i.e. inside the open brace { and the
closing brace } of the class body).

Identify the errors and correct them.

Note: Please don't change the package name


Program:

q11161/Student.java
package q11161;
public class Student {
private String id;
private String
name; private int
age;
private char
gender;

public Student(String name, String rollNo, int age, char


gender) { this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
nt
}
}

q11161/StudentMain.java
Ta

package q11161;
public class StudentMain {
public static void
main(String[] args) {
e

Student st = new Student("2", "Lakshmi", 26, 'F');


System.out.println("Good Job ! ");
ra d

}
Co

Output
: case - 1
Test

User Output
Good Job !

Result:
Thus the above program is executed successfully and the output has
been verified
Aim:
Write a JAVA program to implement method overriding.
Program:

Bike2.java
class Vehicle{
void run(){
System.out.println("Vehicle is running");
}
}
class Bike extends
Vehicle{ void
run(){
System.out.printl
n("Bike is
running
safely");
}
}
public class Bike2{
public static void main(String[]
args){ Vehicle a = new
Vehicle();
a.run();
Vehicle b = new Bike();
b.run();
Output
nt
}
} :
Test case - 1

User Output
Ta

Vehicle is running
Bike is running safely
e

Result:
Thus the above program is executed successfully and the output has
ra d

been verified
Co
Aim:
Write a JAVA program to implement method overloading.
Program:

TestOverloading1.java
import java.util.*;
class TestOverloading1{
public void addition(int a, int
b){ int c = a+b;
System.out.println("Addition of
two numbers: "+c);
}
public void addition(int a, int b, int
c) { int d = a+b+c;
System.out.println("Addition of three
numbers: "+d);
}
public static void main(String[] atgs) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int a = sc.nextInt();
int b = sc.nextInt(); int
c = sc.nextInt();
TestOverloading1 o = new
TestOverloading1();
o.addition(a, b);
nt
o.addition(a, b, c);
}
}
Output
Ta

:
Test case - 1

User Output
Enter three numbers:
e

486
Addition of two numbers: 12
ra d

Addition of three numbers: 18


Co

Test case - 2

User Output
Enter three numbers:
101 301 501
Addition of two numbers: 402
Addition of three numbers: 903

Result:
Thus the above program is executed successfully and the output has
been verified
Aim:
Write a class CountOfTwoNumbers with a public method compareCountOf that takes three
parameters one is arr of type int[] and other two are arg1 and arg2 are of type int
and returns true if count of arg1 is greater than arg2 in arr . The return type of
compareCountOf should be boolean .

Assummptions:
6. arr is never null
7. arg1 and arg2 may be same
Here are an example:
Enter no of elements in the
array: 6
Enter elements in the array seperated by
space: 1 2 2 3 5 2
Enter the arg1 element:
2
Enter the arg2 element:
5
true
Enter no of elements in the
array: 4
Enter elements in the array seperated by
space: 99 -10 99 -1
Enter the arg1 element:
99
Enter the arg2
element: 99
nt
false

Note: Please don't change the package


name.
Ta

Program:

q11075/CountOfTwoNumbers.java
e
ra d
Co
package q11075;

public class CountOfTwoNumbers {


/**
* Find the count of arg1 is more than arg2 in the arr or not
*
*
*
* @return result
*/

public boolean compareCountOf(int[] arr, int args1, int args2) {


//write your code here
int i,len,f1=-1,f2=-
1; len= arr.length;
for(i=len-
1;i>=0;i--) {
if(arr[i]==ar
gs1){
f1=i;

break
;
}
}
for(i=len-
1;i>=0;i--) {
nt
if(arr[i]==args2)
{ f2=i;
break;
}
Ta

}
if(f1>f2) {
return true;
} else {
return false;
e

}
ra d

}
}
Co

q11075/CountOfTwoNumbersMain.java
package q11075;
import java.util.Scanner;
public class CountOfTwoNumbersMain{
public static void main(String[]
args){ Scanner s = new
Scanner(System.in);
System.out.println("Enter no of elements in the
array:"); int n = s.nextInt();
int[] arr = new int[n];
System.out.println("Enter elements in the array seperated by
space:"); for(int i = 0; i < n; i++)
{
arr[i] = s.nextInt();
}
System.out.println("Enter the arg1
element:"); int arg1 = s.nextInt();
System.out.println("Enter the arg2
element:"); int arg2 = s.nextInt();
CountOfTwoNumbers cNum = new
CountOfTwoNumbers();
boolean result = cNum.compareCountOf(arr, arg1,
arg2); System.out.println(result);
}
}

Output:
nt
Test case - 1

User Output
Ta

Enter no of elements in the array:


6
Enter elements in the array seperated by space:
e

122352
Enter the arg1 element:
ra d

2
Enter the arg2 element:
Co

5
true

Test case - 2

User Output
Enter no of elements in the array:
3
Enter elements in the array seperated by space:

80 56 56
Enter the arg1 element:
80
Enter the arg2 element:

56
false
Test case - 3

User Output
Enter no of elements in the array:
6
Enter elements in the array seperated by space:
32 36 31 31 32 31
Enter the arg1 element:

32
Enter the arg2 element:
31
false

Test case - 4

User Output
Enter no of elements in the array:
4
Enter elements in the array seperated by space:
99 -10 99 -1
Enter the arg1 element:
nt
99
Enter the arg2 element:
99
false
Ta

Result:
Thus the above program is executed successfully and the output has been verified
e
ra d
Co
Aim:
Write a program that prints a multidimensional array of integers

package name to be used: q10946


Class name to be used: MultiDimArrayPrinter
Program:

q10946/MultiDimArrayPrinter.java
package q10946;
import java.util.Scanner;
public class MultiDimArrayPrinter{
public static void main(String args[]) {
Scanner sc= new
Scanner(System.in); int J;
System.out.print("Enter Number of rows: ");
int m= sc.nextInt();
System.out.print("Enter Number of columns: ");
int n= sc.nextInt();
int a[][]= new int[m][n];
for(int i=0;i<m;i++)
{ J=i+1;
System.out.print("Enter row "+J+": ");
for(int j=0;j<n;j++) {
a[i][j]=sc.nextInt();
}
}
nt
for(int k=0;k<m;k++) {
for(int l=0;l<n;l++) {
System.out.print(a[k][l]+" ");
Ta

}
System.out.println();
}
}
}
e

Output
ra d

:
Test case - 1
Co

User Output
Enter Number of rows:
3
Enter Number of columns:

3
Enter row 1:
123
Enter row 2:

456
Enter row 3:
789
1 2 3
4 5 6
7 8 9
Test case - 2

User Output
Enter Number of rows:
3
Enter Number of columns:
4
Enter row 1:

4561
Enter row 2:
9425
Enter row 3:

76 3 7 69
4 5 6 1
9 4 2 5
76 3 7 69

Result:
Thus the above program is executed successfully and the output has been verified
nt
e Ta
ra d
Co
Aim:
Write a class MultiplicationOfMatrix with a public method multiplication which
returns the
multiplication result of its arguments. if the first argument column size is not equal to the
row size of the second argument, then the method should return null.

Consider the following example for your understanding

Matrix 1:
Enter number of rows: 3
Enter number of columns: 2
Enter 2 numbers separated by
space Enter row 1: 1 2
Enter row 2: 4 5
Enter row 3: 7 8
Matrix 2:
Enter number of rows: 2
Enter number of columns: 3
Enter 3 numbers separated by
space Enter row 1: 1 2 3
Enter row 2: 4 5 6
Multiplication of the two given matrices
is: 9 12 15
24 33 42
39 54 69
nt
Matrix 1:
Enter number of rows: 2
Enter number of columns: 2
Ta

Enter 2 numbers separated by


space Enter row 1: 1 2
Enter row 2: 3 4
Matrix 2:
e

Enter number of rows: 3


Enter number of columns: 2
Enter 2 numbers separated by
ra d

space Enter row 1: 1 2


Enter row 2: 4 5
Co

Enter row 3: 2 3
Multiplication of matrices is
not possible

Note: Please don't change the package


name.
Program:

q11106/
MultiplicationOfMatrix.java
package q11106;
public class MultiplicationOfMatrix{
public int[][] multiplication(int[][] matrix1, int[][]
matrix2) { int row1 = matrix1.length;
int col1 = matrix1[0].length;
int row2 = matrix2.length;
int col2 = matrix2[0].length;
if(row2!= col1) {
return(null);
} else {
int c[][] = new int[row1][col2]; int
i,j,k;
for(i=0;i<row1;i++) {
for(j=0;j<col2;j++) {
c[i][j]=0;
for(k=0;k<row2;k++) {
c[i][j]
+=matri
x1[i]
[k]*mat
rix2[k]
[j];
}
}
}
return c;
}
nt
/*Return the result if the matrix1 coloumn size is equal to
matrix2 row size and print the result.
* @Return null.
*/
Ta

// Write your logic here for matrix multiplication


}
}

q11106/MultiplicationOfMatrixMain.java
e
ra d
Co
package q11106;
import java.util.Scanner;
public class MultiplicationOfMatrixMain {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
MultiplicationOfMatrix multiplier = new MultiplicationOfMatrix();

System.out.println("Matrix
1:"); int[][] m1 =
readMatrix(s);

System.out.println("Matrix
2:"); int[][] m2 =
readMatrix(s);

int[][] multi = multiplier.multiplication(m1,

m2); if (multi == null) {


System.out.println("Multiplication of
matrices is not
possible");
} else {
System.out.println("Multiplication of
the two given matrices
is:");
for (int i = 0; i < multi.length; i+
+) { int c = multi[i].length;
nt
for (int j = 0; j < c; j++) {
String spacer = j == c - 1 ? "\n" : " ";
System.out.print(multi[i][j] +
spacer);
Ta

}
}
}
}
e

public static int[][] readMatrix(Scanner s) {


System.out.print("Enter number of rows: ");
ra d

int r = s.nextInt();
System.out.print("Enter number of columns: ");
Co

int c = s.nextInt();
int[][] m = new int[r][c];
System.out.println("Enter " + c + " numbers separated by space");
for (int i = 0; i < r; i++) {
System.out.print("Enter row " + (i + 1) + ": ");
for (int j = 0; j < c; j++) {
m[i][j] = s.nextInt();
}
}
return m;
}
}

Output:
Test case - 1

User Output
Matrix 1:
Enter number of rows:

2
3
Enter 3 numbers separated by space
Enter row 1:
123
Enter row 2:

456
Matrix 2:
Enter number of rows:

3
Enter number of columns:
2
Enter 2 numbers separated by space
Enter row 1:

12
Enter row 2:
34
Enter row 3:
56
Multiplication of the two given matrices is:
22 28
49 64
nt
Test case - 2

User Output
Ta

Matrix 1:
Enter number of rows:
2
Enter number of columns:
e

2
Enter 2 numbers separated by space
ra d

Enter row 1:

12
Co

Enter row 2:
34
Matrix 2:
Enter number of rows:

2
Enter number of columns:
2
Enter 2 numbers separated by space
Enter row 1:

56
Enter row 2:
78
Multiplication of the two given matrices is:
19 22
43 50
Result:
Thus the above program is executed successfully and the output has
been verified

nt
e Ta
ra d
Co
Aim:
Write a Java program to handle an ArithmeticException divide by zero using exception
handling.

Write a class called Division with a main() method. Assume that the main() method
will receive two arguments which have to be internally converted to integers.

Write code in the main() method to divide the first argument by the second (as integers) and
print the result (i.e the quotient).

If the command line arguments to the main() method are "12", "3", then the program
should print the output as:

Result = 4

If the command line arguments to the main() method are "55", "0", then the program
should print the output as:

Exception caught : divide by zero occurred

Note: Please don't change the package name.


Program:
nt
q11329/Division.java
package q11329;
public class Division {
public static void main(String[] args){
Ta

int a=
Integer.parseInt(args[0]);
int b=
Integer.parseInt(args[1]);
e

try{
int result=(a/b);
ra d

System.out.println("Res
ult = "+result);
Co

}catch(ArithmeticException e){
System.out.println("Exc
eption caught : divide
by zero
occurred");
}

}
Output
} : case - 1
Test

User Output
Result = 4

Test case - 2

User Output
Result:
Thus the above program is executed successfully and the output has
been verified

nt
e Ta
ra d
Co
Aim:
Write a program to implement User-Defined Exception in Java.
Program:

Example1.java
public class Example1{
public static void main(String[]
args){ try{
int a=0,b=1;
System.out.println("Starting of try block");
int c=b/a;
}catch(Exception e) {
System.out.println("Catch Block");
}finally{
System.out.println("MyException Occurred: This
is My error
Message");
}
}
}

Output
:
Test case - 1

User Output
nt
Starting of try block
Catch Block
MyException Occurred: This is My error Message
Ta

Result:
Thus the above program is executed successfully and the output has
been verified
e
ra d
Co
Aim:
Write a Java program to handle an ArithmeticException divided by zero by using try,
catch and finally
blocks.

Write the main() method with in the class MyFinallyBlock which will receive four arguments
and convert the first two into integers, the last two into float values.

Write the try, catch and finally blocks separately for finding division of two integers and
two float values.

If the input is given as command line arguments to the main() as "10", "4", "10", "4"
then the program should print the output as:

Result of integer values division


: 2 Inside the 1st finally block
Result of float values division :
2.5 Inside the 2nd finally block

If the input is given as command line arguments to the main() as "5", "0", "3.8", "0.0"
then the program should print the output as:

Inside the 1st catch block


Inside the 1st finally block
Result of float values division :
Infinity Inside the 2nd finally block
nt
Note: Please don't change the package
Ta

name.
Program:

q11330/MyFinallyBlock.java
e
ra d
Co
package q11330;
public class MyFinallyBlock {
public static void main(String args[]){
int a =
Integer.parseInt(args[0]); int
b = Integer.parseInt(args[1]);
Float c =
Float.parseFloat(args[2]); Float
d = Float.parseFloat(args[3]);
try{
System.out.println("Result
of integer values division
: "+a/b);
}
catch(ArithmeticException e ){
System.out.println("Inside
the 1st catch block");
}finally {
System.out.println("Inside
the 1st finally block");
}try{
System.out.println("Result
of float values division :
"+c/d);
}
catch(ArithmeticException e ) {
System.out.println("Inside
of the 2nd catch block");
nt
}
finally{
System.out.println("Inside
the 2nd finally block");
Test case - 1
Ta

}
}
User Output
}
Result of integer values division : 2
Inside the 1st finally block
e

Output:
Result of float values division : 0.8333333
Inside the 2nd finally block
ra d
Co

Test case - 2

User Output
Inside the 1st catch block
Inside the 1st finally block
Result of float values division : 2.8666668
Inside the 2nd finally block

Test case - 3

User Output
Inside the 1st catch block
Inside the 1st finally block
Result of float values division : Infinity
Inside the 2nd finally block
Result:
Thus the above program is executed successfully and the output has
been verified

nt
e Ta
ra d
Co
Aim:
Write a Java program to illustrate multiple catch blocks in exception handling.

Write a method multiCatch(int[] arr, int index) in the class MultiCatchBlocks where arr
contains integer array values and index contains an integer value.

Write the code in try block to print the value of arr[index] and also print the division value of
arr[index] by
index.

Write the catch blocks for


8. ArithmeticException which will print "Division by zero exception occurred"
9. ArrayIndexOutOfBoundsException which will print "Array index out of bounds
exception occurred".
10.Exception (which catches all exceptions) will print "Exception occurred"

Note: Please don't change the package name.


Program:

q11331/MultiCatchBlocks.java
package q11331;
public class MultiCatchBlocks {
public void multiCatch(int [] arr, int
index){ try{
System.out.println(arr[index]);
nt
System.out.println(arr[index]/
index);
}
catch(ArithmeticException e){
Ta

System.out.println("Division by
zero exception occurred");
}
catch(ArrayIndexOutOfBoundsException e){
e

System.out.println("Array index out


of bounds exception
occurred");
ra d

}
catch(Exception e){
Co

System.out.println("Exception
occurred");
}
}
// Write the code
}

q11331/MultiCatchBlocksMain.java
package q11331;
import java.util.Scanner;
public class MultiCatchBlocksMain {
public static void main(String[]
args){ Scanner s = new
Scanner(System.in);
System.out.println("Enter no of elements in the
array:"); int n = s.nextInt();
int[] arr = new int[n];
System.out.println("Enter elements in the array seperated by
space:"); for(int i = 0; i < n; i++)
{
arr[i] = s.nextInt();
}
System.out.println("Enter the index
element:"); int x = s.nextInt();

MultiCatchBlocks mb = new
MultiCatchBlocks(); mb.multiCatch(arr,
x);
}
}

Output:
Test case - 1
nt
User Output
Enter no of elements in the array:
3
Ta

Enter elements in the array seperated by space:

123
Enter the index element:
3
e

Array index out of bounds exception occurred


ra d

Test case - 2
Co

User Output
Enter no of elements in the array:
3
Enter elements in the array seperated by space:
654
Enter the index element:

1
5
5

Test case - 3

User Output
Enter no of elements in the array:
Enter elements in the array seperated by space:
684
Enter the index element:
0
6
Division by zero exception occurred

Test case - 4

User Output
Enter no of elements in the array:

5
Enter elements in the array seperated by space:
1
2
3
4
5
Enter the index element:
2
3
1
nt
Result:
Thus the above program is executed successfully and the output has been verified
e Ta
ra d
Co
Aim:
Write a Java program for creation of illustrating throw.

Write a class ThrowExample contains a method checkEligibilty(int age, int weight) which
throws an
ArithmeticException with a message "Student is not eligible for registration" when age
< 12 and weight
< 40, otherwise it prints "Student Entry is Valid!!".

Write the main() method in the same class which will receive two arguments as age and
weight, convert them into integers.

For example, if the given data is 9 and 35 then the output should be:

Welcome to the Registration process!!


java.lang.ArithmeticException: Student is not eligible for registration

For example, if the given data is 15 and 41 then the output should be:

Welcome to the Registration


process!! Student Entry is
Valid!!
Have a nice day

Note: Please don't change the package name.


nt
Program:

q11335/ThrowExample.java
package q11335;
Ta

public class ThrowExample {


public static void main(String args[]) {
System.out.println("Welcome to the Registration
process!!"); try {
e

checkEligibilty(Integer.parseInt(args[0]),Integer.parseInt(args[1])); //
ra d

Fill the missing code


System.out.println("Have a nice day");
}
Co

catch(Exception e) { // Fill the missing code


System.out.println(e); // Fill the missing code
}
}
static void checkEligibilty(int age, int weight) {
if(age < 12 && weight < 40) { // Write the condition
throw new ArithmeticException("Student is not
eligible for registration"); // Fill the missing code
} else {
System.out.println("Student
Entry is Valid!!");
}
}
}

Output
:
Test case - 1
User Output
Welcome to the Registration process!!
java.lang.ArithmeticException: Student is not eligible for registration

Test case - 2

User Output
Welcome to the Registration process!!
Student Entry is Valid!!
Have a nice day

Result:
Thus the above program is executed successfully and the output has been verified

nt
e Ta
ra d
Co
Aim:
Write a program to implement the concept of Assertions in JAVA programming language.
Program:

q122/AssertionExample.java
//program to implement the concept of Assertions in JAVA programming language.
//use command prompt for enabling assertions and compilation can be done
using cmd package q122;
import java.util.Scanner;
public class AssertionExample{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age:
"); int value = sc.nextInt();
assert value>=0:"Not vaslid";
System.out.println("value is
"+value);
}
}

Output
:
Test case - 1

User Output
nt
Enter your age:
23
value is 23
Ta

Test case - 2

User Output
e

Enter your age:


5
ra d

value is 5
Co

Result:
Thus the above program is executed successfully and the output has
been verified
Aim:
Write a java program to implement the concept of localization.
Program:

q123/LocaleExample.java
//Implement the concept of Localization in JAVA programming
language
//Read locality name as input
(es,fr..) package q123;
import java.util.*;
class LocaleExample{
public static void
main(String args[]){
Scanner sc = new
Scanner(System.in);
System.out.println("Enter name");
String name = sc.next();
Locale locale = new
Locale(name,name);
System.out.println(locale.getDisplayCountry(
));
System.out.println(locale.getDisplayLanguage
());
System.out.println(locale.getDisplayName());
System.out.println(locale.getISO3Country()
);
nt
Output
System.out.println(locale.getISO3Language(
));
:
System.out.println(locale.getLanguage(
Test case - 1
));
Ta

System.out.println(locale.getCountry()
User Output
);
Enter name
}
}it
e

Italy
Italian
ra d

Italian (Italy)
ITA
Co

ita
it
IT

Test case - 2

User Output
Enter name

fr
France
French
French (France)
FRA
fra
fr
FR
Result:
Thus the above program is executed successfully and the output has
been verified

nt
e Ta
ra d
Co
Aim:
The program has a class Example with the main method. The program takes input from the
command line argument. Print the output by appending all the capital letters in the input.

Sample Input and Output:

Cmd Args :
HYderaBad The
result is: HYB

Program:

q24212/
Example.java
package q24212;
public class
Example
{
public
static void
main(String
args[])
{
String
store="",Arg=args[0];
char ch;
nt
int l=Arg.length();
for(int i=0; i<l; i++)
{
ch =
Ta

Arg.charAt(i);
if(ch>='A'&&ch<='Z
') Output
store+=ch;
}
:
System.out.println("The
Test case - 1
e

result is: "+store);


}
User Output
ra d

}
The result is: HYB
Co

Test case - 2

User Output
The result is: CT

Result:
Thus the above program is executed successfully and the output has
been verified
Aim:
The below code is used to understand the difference between String and StringBuilder
objects. When we try to concatenate two strings using string operations a new object is
created without changing the old one. In StringBuilder existing object is modified. In the
below program this can be illustrated by comparing Hash Code for String object after every
concat operation. Fill the missing code in the below
program and observe the output.

Sample Input and Output:

In Strings before concatenation Hash Code is:


2081 In Strings after concatenation Hash
Code is: 64578
In StringBuilder before concatenation Hash Code is:
321001045 In StringBuilder after concatenation Hash
Code is: 321001045

Program:

q24216/StringBuilderDemo.java
package q24216;
public class StringBuilderDemo {
public static void main(String
args[]) { String s = new
nt
String("AB");
System.out.print("In Strings before
concatenation Hash Code is:
");
System.out.println(s.hashCode()); s
Ta

+= "C";
// print hash code after concatenating

StringBuilder sb = new
StringBuilder("AB");
e

// print hash code before


concatenating
ra d

// add string C to AB
Co

// print hash code after concatenating


Output
// and observe the output
:
Test case - 1
}
User Output
}
In Strings before concatenation Hash Code is: 2081
In Strings after concatenation Hash Code is: 64578
In StringBuilder before concatenation Hash Code is: 1338823963
In StringBuilder after concatenation Hash Code is: 1338823963

Result:
Thus the above program is executed successfully and the output has
been verified
Aim:
The below program explains different StringBuffer constructors. Follow the comments given
below and write the missing code.

The below program has a class StringbufferExample with main method. The program takes
input from the command line arguments. Print the output as follows.

Sample Input and Output:

Cmd Args : Hello


World Initial
capacity is: 16
Capacity after
passing parameter is:
27
Creating a
StringBuffer object
with the given
capacity: 50

Program:

q24215/
StringbufferExample
.java
package q24215;
nt
public class
StringbufferExample {
public static void main (String args[])
{ StringBuffer s= new
Ta

StringBuffer();
System.out.println("Initial capacity is:
"+s.capacity());
s = new StringBuffer(args[0]);
System.out.println("Capacity after
e

passing parameter is:


"+s.capacity());
ra d

StringBuffer s1 = new StringBuffer(50);


System.out.println("Creating a StringBuffer object with the
given capacity: "+s1.capacity()); Output
Co

//
//
: thecase
create instance of StringBuffer
Test
find - 1 capacity
initial
//find the capactiy after passing a parameter
User Output args[0] using command line
argument
Initial capacity is: 16
// find the capatity by intializing capatity
Capacity after passing parameter is: 27
to 50
Creating a StringBuffer
} object with the given capacity: 50
}

Test case - 2

User Output
Initial capacity is: 16
Capacity after passing parameter is: 28
Creating a StringBuffer object with the given capacity: 50
Thus the above program is executed successfully and the output has
been verified

nt
e Ta
ra d
Co
Aim:
Write a JAVA program to implement even and odd threads by using Thread class and
Runnable interface.
Program:

q124/OddEvenPrintMain.java

nt
e Ta
ra d
Co
package q124;
import java.util.Scanner;
public class
OddEvenPrintMain
{ boolean odd;
int count = 1;
static int MAX;
public void printOdd(){
synchronized (this) {
while
(count
<MAX){
System.out.println("Checking odd loop");
while(!odd){
try{
System.out.println("Odd
waiting : "
+count);
wait();
System.out.println("Notified
odd :"
+count);
}
catch(InterruptedException
e)
{ e.printStackTrace
();
nt
}
}
System.out.println("Odd Thread :" +count);
count++;
Ta

odd = false;
notify();
}
}
}
e

public void printEven(){


try{
ra d

Thread.sleep(20);
}
Co

catch(InterruptedException
e1)
{ e1.printStackTrace
();
}
synchronized(this){
while(count<MAX){
System.out.println("Checking even loop");
while(odd){
try{
System.out.println("Even
waiting: "
+count);
wait();
System.out.println("Notified
even:"
+count);
}
catch(InterruptedException
e)
{ e.printStackTrace
();
}
}
System.out.println("Even thread :" +count);
count++;
odd = true;
notify();
}
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter MAX value:
"); MAX = sc.nextInt();
OddEvenPrintMain oep = new
OddEvenPrintMain(); oep.odd = true;
Thread t1 = new Thread(new
Runnable(){ public void
run(){
oep.printEven();
}
});
Thread t2 = new Thread(new
Runnable(){ public void
run(){
oep.printOdd();
}
});
t1.start();
t2.start(); try{
t1.join();
t2.join();
}
catch(InterruptedException
e)
nt
{ e.printStackTrace
();
}
}
Ta

Output:
Test case - 1
e

User Output
Enter MAX value:
ra d

10
Checking odd loop
Co

Odd Thread :1
Checking odd loop
Odd waiting : 2
Checking even loop
Even thread :2
Checking even loop
Even waiting: 3
Notified odd :3
Odd Thread :3
Checking odd loop
Odd waiting : 4
Notified even:4
Even thread :4
Checking even loop
Even waiting: 5
Notified odd :5
Odd Thread :5
Checking odd loop
Odd waiting : 6
Notified even:6
Even thread :6
Checking even loop
Even waiting: 7
Notified odd :7
Odd Thread :7
Checking odd loop
Odd waiting : 8
Notified even:8
Even thread :8
Checking even loop
Even waiting: 9
Notified odd :9
Odd Thread :9
Notified even:10
Even thread :10

Test case - 2

User Output
Enter MAX value:
nt
20
Checking odd loop
Odd Thread :1
Ta

Checking odd loop


Odd waiting : 2
Checking even loop
Even thread :2
e

Checking even loop


Even waiting: 3
ra d

Notified odd :3
Odd Thread :3
Co

Checking odd loop


Odd waiting : 4
Notified even:4
Even thread :4
Checking even loop
Even waiting: 5
Notified odd :5
Odd Thread :5
Checking odd loop
Odd waiting : 6
Notified even:6
Even thread :6
Checking even loop
Even waiting: 7
Notified odd :7
Odd Thread :7
Checking odd loop
Notified even:8
Even thread :8
Checking even loop
Even waiting: 9
Notified odd :9
Odd Thread :9
Checking odd loop
Odd waiting : 10
Notified even:10
Even thread :10
Checking even loop
Even waiting: 11
Notified odd :11
Odd Thread :11
Checking odd loop
Odd waiting : 12
Notified even:12
Even thread :12
Checking even loop
Even waiting: 13
Notified odd :13
Odd Thread :13
Checking odd loop
Odd waiting : 14
nt
Notified even:14
Even thread :14
Checking even loop
Ta

Even waiting: 15
Notified odd :15
Odd Thread :15
Checking odd loop
e

Odd waiting : 16
Notified even:16
ra d

Even thread :16


Checking even loop
Co

Even waiting: 17
Notified odd :17
Odd Thread :17
Checking odd loop
Odd waiting : 18
Notified even:18
Even thread :18
Checking even loop
Even waiting: 19
Notified odd :19
Odd Thread :19
Notified even:20
Even thread :20

Test case - 3
Enter MAX value:
5
Checking odd loop
Odd Thread :1
Checking odd loop
Odd waiting : 2
Checking even loop
Even thread :2
Checking even loop
Even waiting: 3
Notified odd :3
Odd Thread :3
Checking odd loop
Odd waiting : 4
Notified even:4
Even thread :4
Notified odd :5
Odd Thread :5

Result:
Thus the above program is executed successfully and the output has been verified
nt
e Ta
ra d
Co
Aim:
Write a JAVA program to synchronize the threads by using Synchronize statements and
Synchronize block
Program:

q125/TestSynchronizedBlock1.java

nt
e Ta
ra d
Co
//JAVA program to synchronize the threads by using Synchronize
statements and Synchronize block
//Read input from the
user package q125;
import
java.util.Scanner;
class Table{
void
PrintTable(int
n){
synchroni
zed
(this){
System.out.println("-----
Current Thread:"+Thread.currentThread().getName()
+"-------");
for
(int i = 1;i<=5; i++){
S
ystem.out.println(n*i)
; try{
T
hread.sleep(100
);
}
catch(Exception e){
S
ystem.out.print
ln(e);
nt
}
}
}
}
Ta

}
class MyThread1 extends
Thread { Table t;
MyThread1(Table t){
this.t = t;
e

}
public void run(){
ra d

Scanner s = new
Scanner(Sy
stem.in);
Co

System.out.println("enter number to print its table:");


int n = s.nextInt();
t.PrintTable(n);
}
}
class MyThread2 extends
Thread { Table t;
MyThread2(Table t){
this.t = t;
}
public void run(){
Scanner s = new
Scanner(Sy
stem.in);
System.out.println("enter number to print its table:");
int n = s.nextInt();
t.PrintTable(n);
}
}
public class TestSynchronizedBlock1{
public static void main(String args
[]) { Table obj = new
Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new
MyThread2(obj); t1.start();
t2.start();
}
}

Output:
Test case - 1

User Output
-----Current Thread:Thread-0-------
enter number to print its table:
5
5
10
15
20
25
-----Current Thread:Thread-1-------
enter number to print its table:
7
7
14
21
28
35

Test case - 2
nt
User Output
-----Current Thread:Thread-0-------
enter number to print its table:
Ta

8
8
16
24
e

32
40
ra d

-----Current Thread:Thread-1-------
enter number to print its table:
23
Co

23
46
69
92
115

Result:
Thus the above program is executed successfully and the output has been verified
Aim:
Demonstrate the concept of type annotations in the JAVA programming language.
Program:

q128/MyClass.java
//Demonstrate the concept of type annotations in the JAVA programming language.
//Use annotation and read the string from
user package q128;
import java.util.Scanner;
import java.lang.annotation.*
;@Target(ElementType.TYPE_USE)@interface
TypeAnnoDemo
{}
public class MyClass{
public static void main(String[]
args){
Scanner obj = new
Scanner(System.in);
System.out.print("Enter String :
"); String x = obj.nextLine();
@TypeAnnoDemo String s =
x;
System.out.println(s);
myMethod();
}
static @TypeAnnoDemo int
nt
myMethod(){
System.out.println("There
is a use of annotation
with the return type of
the function"); Output
Ta

return 0;
} :
Test case - 1
}
User Output
e

Enter String :

hii
ra d

hii
There is a use of annotation with the return type of the function
Co

Test case - 2

User Output
Enter String :

hello! Good Morning


hello! Good Morning
There is a use of annotation with the return type of the function

Result:
Thus the above program is executed successfully and the output has
been verified
Aim:
Demonstrate the concept of user-defined annotations in the JAVA programming language
Program:

TestCustomAnnotation1.java
//create, apply and access annotation
//Create annotion having value 10 in class
hello import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTI
ME) @interface MyAnnotation{
int value();
}

class Hello{

@MyAnnotation(value=1
0) public void
sayHello(){
System.out.pri
ntln("hello
annotation");
}
}
nt
//Create class and access the defined
annotation class TestCustomAnnotation1
{
public static void main(String args[])throws
Ta

Exception{ Hello h = new Hello();


Method m = h.getClass().getMethod("sayHello");
MyAnnotation manno =
m.getAnnotation(MyAnnotation.class);
e

//Use manno as Object


ra d

System.out.println("value is: "+manno.value());


}
Output
Co

}
:
Test case - 1

User Output
value is: 10

Result:
Thus the above program is executed successfully and the output has
been verified
Aim:
Write a JAVA program to implement the concept of Generic and classes.
Program:

Main.java
import
java.util.Scanner;
class Test<T>{
T obj;
Test(T obj){
this.obj
= obj;
}
public T
getObject(){
return
this.obj
;
}
}
class Main{
public static
void
main(String
args[]){
Scanner sc = new
Scanner(System.in);
nt
System.out.print("Enter a string:
"); String str = sc.nextLine();
Test<String> sObj = new
Test<String>(str);
Ta

System.out.println("The string is:


"+sObj.getObject()); Output
System.out.print("Enter an
integer: ");
int a =
:
Test case - 1
sc.nextInt();
Test<Integer> iObj = new Test<Integer>(a);
e

User Output System.out.println("The integer is:


"+iObj.getObject());
Enter a string:
ra d

}
}
CodeTantra
The string is: CodeTantra
Co

Enter an integer:

56
The integer is: 56

Test case - 2

User Output
Enter a string:

Learn Coding
The string is: Learn Coding
Enter an integer:
37
The integer is: 37

Resul
t:
Thus the above program is executed successfully and the output has
been verified

nt
e Ta
ra d
Co
Aim:
Write a JAVA program to implement the concept of Collection classes.
Program:

q132/AddingElements.java
//JAVA program to implement the concept of Collection
classes.
//Read three array list values and add them
//Print
values
package q132;
import
java.util.*;
class
AddingElement
s{
publi
c
stati
c
void
main(
Strin
g
args[
]){
S
c
a
nt
n
n Output
e
r :
Test case - 1
Ta

s
User Output c

Enter any three


= collections:
apple
n
e

ball e
w
cat
ra d

apple ball cat S


c
a
Co

n
n
e
Test case - 2
r
User Output (
S
Enter any threey collections:
dog s
t
elephant e
m
fox .
i
dog elephant fox
n
)
;
Result: L
i
Thus the above program is executed successfully and the output has
s
been verified
t
<
S
t
r
i
n
g
>
i
t
e
m
s

n
e
w

A
r
r
a
y
L
i
Co
ra d
e Ta
nt

You might also like