0% found this document useful (0 votes)
54 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 PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 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 PDF, TXT or read online on Scribd
You are on page 1/ 78

Noida Institute of Engineering & Technology,

Greater Noida

LAB FILE
tra
Branch : Semester :
n

Session : Subject Code :


Ta

Aditya Krishna Yadav Faculty Name :


Name & Roll No: (2301330120010)
de

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

n tra
Ta
de
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:
Test case - 1

User Output
tra
Hello Java

Result:
n

Thus the above program is executed successfully and the output has been verified
Ta
de
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 = 0;
tra
static short l = 0;
static int s = 0;
static long a = 0;
static boolean b = false;
n
static double d = 0.0;
static float f = 0.0f;
Ta
de

public static void main(String[] args) {


System.out.println("byte default value = " + m);
System.out.println("short default value = " + l);
System.out.println("int default value = " + s);
Co

System.out.println("long default value = " + a);


System.out.println("boolean default value = " + b);
System.out.println("double default value = " + d);
System.out.println("float default value = " + f);
}
}

Output:
Test case - 1

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

n tra
Ta
de
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:
tra
q10817/TotalAndAvgMarks.java

package q10817;
public class TotalAndAvgMarks {
public static void main(String[] args) {
n

String name = args[0];


float marks1 = Float.parseFloat(args[1]);
Ta

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


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

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


System.out.println("Marks1 = " + marks1);
System.out.println("Marks2 = " + marks2);
System.out.println("Marks3 = " + marks3);
Co

System.out.println("Total Marks = " + total);


System.out.println("Average Marks = " + avg);
}
}

Output:
Test case - 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

n tra
Ta
de
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
Sufficient 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 {
public void checkBalance(double balance) {
if (balance<1000) {
tra
System.out.println("Balance is low");

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

}
}
Ta

q10850/BalanceMain.java
de

package q10850;
public class BalanceMain{
public static void main(String[] args){
double balance = Double.parseDouble(args[0]);
Co

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

n tra
Ta
de
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[] args) {
tra
Scanner sc = new Scanner(System.in);
int a = Integer.parseInt(args[0]);
int fact = factorial(a);
System.out.print("Factorial of "+ a + " is "+fact+"\n");
n
}
}
Ta

Output:
de

Test case - 1

User Output
Factorial of 5 is 120
Co

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.

For example
Cmd Args : 333
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;
reversedNumber = reversedNumber *10 + remainder;
tra
number /=10;
}
if(originalNumber == reversedNumber ) {
System.out.println(originalNumber + " is a palindrome");
n
} else {
System.out.println(originalNumber + " is not a palindrome");
Ta

}
//Write your code here

}
de

q10894/NumberPalindromeMain.java
Co

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:
Test case - 1

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

n tra
Ta
de
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;
}
}
tra
}

Output:
n

Test case - 1
Ta

User Output
0 1 1 2 3 5
de

Test case - 2

User Output
Co

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) {
Main ob = new Main();
ob.print();
}
}

Output:
Test case - 1
tra
User Output
Enter a string:
Hello
n

The entered string is: Hello


Ta

Test case - 2
de

User Output
Enter a string:
Hello CodeTantra
The entered string is: Hello CodeTantra
Co

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:

q11287/AbstractExample.java
n tra
Ta
de
Co
package q11287;
abstract class Shape {
abstract void numberOfSides();
}
class Trapezoid extends Shape {
void numberOfSides() {
System.out.println("Number 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("Number of sides in a hexagon are 6\n");
}
}

public class AbstractExample {


public static void main(String[] args) {
Shape s;
s = new Trapezoid();
s.numberOfSides();
tra
// Call the method
s = new Triangle();
s.numberOfSides();
// Call the method
s = new Hexagon();
n

s.numberOfSides();
// Call the method
Ta

}
}
de

Output:
Test case - 1
Co

User 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

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;
StaticFieldDemo(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 = "+this.c+", aStaticField =
"+StaticFieldDemo.a+"]");
System.out.println("A.aStaticField = "+StaticFieldDemo.a);
}
tra
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a StaticField number");
n
a = sc.nextInt();
int b = sc.nextInt();
Ta

int c = sc.nextInt();
StaticFieldDemo obj = new StaticFieldDemo(b,c);
obj.getvalue();
}
de

Output:
Co

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

n tra
Ta
de
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;
StaticClassDemo(int a,int b)
{
this.a = a;
this.b = b;
}
public void getvalue()
{
System.out.println("a1 = A [value = "+this.a+"]");
System.out.println("a2 = A [value = "+this.b+"]");
}
public static void main(String[] args)
{
tra
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number:");
int a = sc.nextInt();
int b = sc.nextInt();
n
StaticClassDemo st = new StaticClassDemo(a,b);
st.getvalue();
Ta

}
}
de

Output:
Test case - 1
Co

User Output
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

n tra
Ta
de
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().

For example, if the input is given as [10, 20, 30, 40] then the output should be:
tra
This is sub class show() method
This is super class show() method
value1 = 10
value2 from super class = 20
n

value3 = 30
value4 = 40
Ta
de

Note: Please don't change the package name.


Program:

q11274/AccessUsingSuper.java
Co
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() {
System.out.println("This is sub class show() method");
super.show();
System.out.println("value2 from super class = "+this.value2);
tra
System.out.println("value3 = "+this.value3);
System.out.println("value4 = "+this.value4);
}
n

}
Ta

public class AccessUsingSuper {


public static void main(String[] args) {
SubClass obj = new SubClass(Integer.parseInt(args[0]),
de

Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3]));


obj.show();
}
}
Co

Output:
Test case - 1

User 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(String s);
}
class First extends Show
{
void show(String s)
{
System.out.println("First class string is: "+s);
}
}
class Second extends Show
{
void show(String s)
{
System.out.println("Second class string is: "+s);
}
}
public class SingleInheritance
tra
{
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first class string: ");
n
String s1 = sc.nextLine();
Show sh = new First();
Ta

sh.show(s1);
System.out.print("Enter the second class string: ");
String s2 = sc.nextLine();
Show sh2 = new Second();
de

sh2.show(s2);}
}
Co

Output:
Test case - 1

User Output
Enter the first class string:
Hello
First class string is: Hello
Enter the second class string:
World!
Second class string is: World!
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

n tra
Ta
de
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", "78.5", "72"
then the program should print the output as:

Id : 99
tra
Name : Lakshmi
Java marks : 55.5
C marks : 78.5
Cpp marks : 72.0
Total : 206.0
n

Avg : 68.666664
Ta

Note: Please don't change the package name.


de

Program:

q11264/MultilevelInheritanceDemo.java
Co
package q11264;
class Student
{
int id;
String name;
void setData(int id,String name)
{
this.id = id;
this.name = name;
}
void displayData()
{
System.out.println("Id : "+id);
System.out.println("Name : "+name);
}
}
class Marks extends Student
{
float javaMarks, cMarks, cppMarks;
void setMarks(float a, float b, float c)
{
this.javaMarks = a;
this.cMarks = b;
this.cppMarks = c;
}
tra
void displayMarks()
{
System.out.println("Java marks : "+javaMarks);
System.out.println("C marks : "+cMarks);
System.out.println("Cpp marks : "+cppMarks);
n

}
}
Ta

class Result extends Marks


{
float total,avg;
de

void compute()
{
this.total = javaMarks + cMarks + cppMarks;
this.avg = total /3;
Co

}
void showResult()
{
System.out.println("Total : "+total);
System.out.println("Avg : "+avg);
}
}
class MultilevelInheritanceDemo
{
public static void main(String[] args)
{
int id = Integer.parseInt(args[0]);
String name = args[1];
Float javaMarks = Float.parseFloat(args[2]);
Float cMarks = Float.parseFloat(args[3]);
Float cppMarks = Float.parseFloat(args[4]);
Result r = new Result();
r.setData(id,name);
r.displayData();
r.setMarks(javaMarks,cMarks,cppMarks);
r.displayMarks();
r.compute();
r.showResult();
}
}

Output:
Test case - 1

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

Test case - 2

User Output
de

Id : 199
Name : Lakshmi
Java marks : 55.5
C marks : 78.5
Co

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

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.
tra
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
n

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 the implementing classes or
Ta

sub interfaces.

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


de

public default void methodName() {


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

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.out.println("Applying brake on "+getName());
}
static Car getFastestCar(Car car1, Car car2){
if(car1.getMaxSpeed() >=car2.getMaxSpeed()){
return car1;
}
else{
return car2;
}
}

}
class BMW implements Car {
String carName;
int MaxSpeed;
public BMW(String name, int MaxSpeed){
this.carName=name;
this.MaxSpeed=MaxSpeed;
}
public String getName(){
tra
return this.carName;
}
public int getMaxSpeed(){
return this.MaxSpeed;
}
n

}
class Audi implements Car {
Ta

String carName;
int MaxSpeed;
public Audi(String name, int maxSpeed){
de

this.carName = name;
this.MaxSpeed = maxSpeed;
}
public String getName(){
Co

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

}
}

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

n tra
Ta
de
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;
tra
}
}

q11161/StudentMain.java
n

package q11161;
public class StudentMain {
Ta

public static void main(String[] args) {


Student st = new Student("2", "Lakshmi", 26, 'F');
System.out.println("Good Job ! ");
de

}
Co

Output:
Test case - 1

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.println("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:
tra
Test case - 1

User Output
n

Vehicle is running
Ta

Bike is running safely

Result:
de

Thus the above program is executed successfully and the output has 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);
o.addition(a, b, c);
}
tra
}

Output:
n

Test case - 1
Ta

User Output
Enter three numbers:
486
de

Addition of two numbers: 12


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
false
tra
Note: Please don't change the package name.
Program:
n

q11075/CountOfTwoNumbers.java
Ta
de
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]==args1){
f1=i;
break;
}
}
for(i=len-1;i>=0;i--) {
if(arr[i]==args2) {
f2=i;
break;
tra
}
}
if(f1>f2) {
return true;
} else {
n

return false;
}
Ta

}
}
de

q11075/CountOfTwoNumbersMain.java
Co
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:
tra
Test case - 1

User Output
n

Enter no of elements in the array:


6
Ta

Enter elements in the array seperated by space:


122352
de

Enter the arg1 element:


2
Enter the arg2 element:
5
Co

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:
tra
99
Enter the arg2 element:
99
false
n
Ta

Result:
Thus the above program is executed successfully and the output has been verified
de
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();
}
tra
}
for(int k=0;k<m;k++) {
for(int l=0;l<n;l++) {
System.out.print(a[k][l]+" ");
n
}
System.out.println();
Ta

}
}
}
de

Output:
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
n tra
Ta
de
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
tra
Matrix 1:
Enter number of rows: 2
Enter number of columns: 2
Enter 2 numbers separated by space
n

Enter row 1: 1 2
Enter row 2: 3 4
Ta

Matrix 2:
Enter number of rows: 3
Enter number of columns: 2
de

Enter 2 numbers separated by space


Enter row 1: 1 2
Enter row 2: 4 5
Enter row 3: 2 3
Co

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]+=matrix1[i][k]*matrix2[k][j];
}
}
}
return c;
}
/*Return the result if the matrix1 coloumn size is equal to matrix2 row
size and print the result.
* @Return null.
tra
*/
// Write your logic here for matrix multiplication
}
}
n

q11106/MultiplicationOfMatrixMain.java
Ta
de
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;
for (int j = 0; j < c; j++) {
String spacer = j == c - 1 ? "\n" : " ";
tra
System.out.print(multi[i][j] + spacer);
}
}
}
}
n

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


Ta

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


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

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

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
tra
Test case - 2

User Output
n

Matrix 1:
Enter number of rows:
Ta

2
Enter number of columns:
2
de

Enter 2 numbers separated by space


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

n tra
Ta
de
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:
tra
q11329/Division.java

package q11329;
public class Division {
public static void main(String[] args){
n

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

try{
int result=(a/b);
System.out.println("Result = "+result);
de

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

}
}

Output:
Test case - 1

User Output
Result = 4

Test case - 2

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

n tra
Ta
de
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
tra
User Output
Starting of try block
Catch Block
MyException Occurred: This is My error Message
n
Ta

Result:
Thus the above program is executed successfully and the output has been verified
de
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
tra
Note: Please don't change the package name.
n

Program:
Ta

q11330/MyFinallyBlock.java
de
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");
}
finally{
System.out.println("Inside the 2nd finally block");
}
}
}
tra
Output:
Test case - 1
n

User Output
Ta

Result of integer values division : 2


Inside the 1st finally block
Result of float values division : 0.8333333
de

Inside the 2nd finally block

Test case - 2
Co

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

n tra
Ta
de
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]);
tra
System.out.println(arr[index]/index);
}
catch(ArithmeticException e){
System.out.println("Division by zero exception occurred");
}
n

catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index out of bounds exception
Ta

occurred");
}
catch(Exception e){
de

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

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
tra
User Output
Enter no of elements in the array:
3
n
Enter elements in the array seperated by space:
123
Ta

Enter the index element:


3
Array index out of bounds exception occurred
de

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
tra
1

Result:
Thus the above program is executed successfully and the output has been verified
n
Ta
de
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.


tra
Program:

q11335/ThrowExample.java
package q11335;
n

public class ThrowExample {


public static void main(String args[]) {
Ta

System.out.println("Welcome to the Registration process!!");


try {
de

checkEligibilty(Integer.parseInt(args[0]),Integer.parseInt(args[1])); // 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

n tra
Ta
de
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
tra
Enter your age:
23
value is 23
n

Test case - 2
Ta

User Output
Enter your age:
de

5
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());
System.out.println(locale.getISO3Language());
System.out.println(locale.getLanguage());
System.out.println(locale.getCountry());
}
}
tra
Output:
Test case - 1
n

User Output
Ta

Enter name
it
Italy
de

Italian
Italian (Italy)
ITA
ita
Co

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

n tra
Ta
de
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;
int l=Arg.length();
for(int i=0; i<l; i++)
{
ch = Arg.charAt(i);
if(ch>='A'&&ch<='Z')
tra
store+=ch;
}
System.out.println("The result is: "+store);
}
}
n

Output:
Ta

Test case - 1
de

User Output
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 String("AB");
System.out.print("In Strings before concatenation Hash Code is: ");
System.out.println(s.hashCode());
s += "C";
tra
// print hash code after concatenating

StringBuilder sb = new StringBuilder("AB");


// print hash code before concatenating
n

// add string C to AB
Ta

// print hash code after concatenating

// and observe the output


de

}
}
Co

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;
public class StringbufferExample {
public static void main (String args[]) {
StringBuffer s= new StringBuffer();
System.out.println("Initial capacity is: "+s.capacity());
s = new StringBuffer(args[0]);
System.out.println("Capacity after passing parameter is:
tra
"+s.capacity());
StringBuffer s1 = new StringBuffer(50);
System.out.println("Creating a StringBuffer object with the given
capacity: "+s1.capacity());
n
// create instance of StringBuffer
// find the initial capacity
//find the capactiy after passing a parameter args[0] using command line
Ta

argument
// find the capatity by intializing capatity to 50
}
de

Output:
Co

Test case - 1

User Output
Initial capacity is: 16
Capacity after passing parameter is: 27
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

n tra
Ta
de
Co
Aim:
Write a JAVA program to implement even and odd threads by using Thread class and Runnable interface.
Program:

q124/OddEvenPrintMain.java

n tra
Ta
de
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();
}
}
System.out.println("Odd Thread :" +count);
count++;
odd = false;
tra
notify();
}
}
}
public void printEven(){
n

try{
Thread.sleep(20);
Ta

}
catch(InterruptedException e1){
e1.printStackTrace();
de

}
synchronized(this){
while(count<MAX){
System.out.println("Checking even loop");
Co

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){
e.printStackTrace();
tra
}
}
}

Output:
n
Ta

Test case - 1

User Output
de

Enter MAX value:


10
Checking odd loop
Odd Thread :1
Co

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
tra
Enter MAX value:
20
Checking odd loop
Odd Thread :1
n

Checking odd loop


Odd waiting : 2
Ta

Checking even loop


Even thread :2
Checking even loop
de

Even waiting: 3
Notified odd :3
Odd Thread :3
Checking odd loop
Co

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
tra
Odd waiting : 14
Notified even:14
Even thread :14
Checking even loop
n

Even waiting: 15
Notified odd :15
Ta

Odd Thread :15


Checking odd loop
Odd waiting : 16
de

Notified even:16
Even thread :16
Checking even loop
Even waiting: 17
Co

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
n tra
Ta
de
Co
Aim:
Write a JAVA program to synchronize the threads by using Synchronize statements and Synchronize block
Program:

q125/TestSynchronizedBlock1.java

n tra
Ta
de
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){
synchronized (this){
System.out.println("-----Current
Thread:"+Thread.currentThread().getName()+"-------");
for (int i = 1;i<=5; i++){
System.out.println(n*i);
try{
Thread.sleep(100);
}catch(Exception e){
System.out.println(e);
}
}
}
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t){
this.t = t;
tra
}
public void run(){
Scanner s = new Scanner(System.in);
System.out.println("enter number to print its table:");
int n = s.nextInt();
n

t.PrintTable(n);
}
Ta

}
class MyThread2 extends Thread {
Table t;
de

MyThread2(Table t){
this.t = t;
}
public void run(){
Co

Scanner s = new Scanner(System.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
tra
User Output
-----Current Thread:Thread-0-------
enter number to print its table:
8
n

8
Ta

16
24
32
de

40
-----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 myMethod(){
System.out.println("There is a use of annotation with the return type of
the function");
return 0;
tra
}
}

Output:
n

Test case - 1
Ta

User Output
Enter String :
de

hii
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.RUNTIME)
@interface MyAnnotation{
int value();
}

class Hello{

@MyAnnotation(value=10)
public void sayHello(){
System.out.println("hello annotation");
}
}

//Create class and access the defined annotation


class TestCustomAnnotation1 {
tra
public static void main(String args[])throws Exception{
Hello h = new Hello();
Method m = h.getClass().getMethod("sayHello");
MyAnnotation manno = m.getAnnotation(MyAnnotation.class);
n
Ta

//Use manno as Object


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

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);
System.out.print("Enter a string: ");
String str = sc.nextLine();
Test<String> sObj = new Test<String>(str);
System.out.println("The string is: "+sObj.getObject());
System.out.print("Enter an integer: ");
int a = sc.nextInt();
Test<Integer> iObj = new Test<Integer>(a);
tra
System.out.println("The integer is: "+iObj.getObject());
}
}
n

Output:
Ta

Test case - 1

User Output
de

Enter a string:
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

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

n tra
Ta
de
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 AddingElements{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
List<String>items = new ArrayList<>();
System.out.print("Enter any three collections: ");
String a = sc.nextLine();
String b = sc.nextLine();
String c = sc.nextLine();
Collections.addAll(items,a,b,c);
for(int i = 0; i<items.size();i++){
System.out.print(items.get(i)+" ");
}
}
}
tra
Output:
Test case - 1
n

User Output
Ta

Enter any three collections:


apple
ball
de

cat
apple ball cat
Co

Test case - 2

User Output
Enter any three collections:
dog
elephant
fox
dog elephant fox

Result:
Thus the above program is executed successfully and the output has been verified
Co
de
Ta
ntra

You might also like