Lab Record Download
Lab Record Download
Greater Noida
LAB FILE
tra
Branch : Semester :
n
Subject Name :
Co
Semester:
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.
FirstProgram.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.
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
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 .
Note: Consider the three marks passed in the command line arguments as floats .
package q10817;
public class TotalAndAvgMarks {
public static void main(String[] args) {
n
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.
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
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
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
q10894/NumberPalindrome.java
package q10894;
}
//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
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
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.
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.
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");
}
}
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.
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
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);
}
}
Ta
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.
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
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
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
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
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).
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.
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.
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).
q11161/Student.java
package q11161;
public class Student {
private String id;
private String name;
private int age;
private char gender;
q11161/StudentMain.java
n
package q11161;
public class StudentMain {
Ta
}
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
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
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;
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
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
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.
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
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);
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
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
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 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:
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:
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:
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
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.
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();
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
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:
For example, if the given data is 15 and 41 then the output should be:
q11335/ThrowExample.java
package q11335;
n
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
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.
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.
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
// add string C to AB
Ta
}
}
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.
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
Test case - 2
User Output
tra
Enter MAX value:
20
Checking odd loop
Odd Thread :1
n
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
Notified even:16
Even thread :16
Checking even loop
Even waiting: 17
Co
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
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
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
class Hello{
@MyAnnotation(value=10)
public void sayHello(){
System.out.println("hello annotation");
}
}
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
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