You are on page 1of 32

Name : B.

Lohita
saveri Roll no :
22124025
Subject:Java Programming Lab
LabCourse Code: ITPC-226
Branch : Information Technology

Submitted to : Dr. Sarla

Dr. B.R. Ambedkar National Institute of Technology Jalandhar


Lab 1

Q1. 1. Write a program to print ―Hello World on the screen.

Source code :

public class helloWorld {


public static void main(String[] args)
{ System.out.println("Hello World");
}
}

Output:

Q2. 2. Write a program to print addition, subtraction, multiplication and


division where input should be taken from command line.

Source code :

import java.util.Scanner;
public class ArithmeticOperation
{ public static void main(String[] args)
{ int num1,num2;
int add,sub,mul;
float div;
Scanner scanner=new Scanner(System.in);
System.out.print("Enter the Two numbers: ");
num1= scanner.nextInt();
num2= scanner.nextInt();
add=num1+num2;
sub=num1-num2;
mul=num1*num2;
div=(float)num1/num2;
System.out.println("Addition of Number: " + add);
System.out.println("Sub of Number: " + sub);
System.out.println("mul of Number: " + mul);
System.out.println("div of Number: " + div);
}
}

Output:

Q3.Write a java program to check whether a number is prime or not.

Source code :

import java.util.Scanner;
public class PrimeNumberOrNot
{ public static void main(String[] args)
{ int number;
Scanner scanner=new Scanner(System.in);
System.out.print("Enter a Number: ");
number= scanner.nextInt();
if(number==1) System.out.print("This Number is Non Prime");
if(number==2) System.out.print("This Number is Prime");
for(int i=2; i<number; i++){
if(number%i==0){
System.out.print("This Number is Non Prime");
break;
}
else{
System.out.print("This Number is Prime");
break;
}
}
}
Output :

Q4. Write a java program to display Fibonacci series up to n.

Source code :

import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args)
{ int firstTerm=1;
int SecondTerm=1;
int nextTerm;
int n;
System.out.print("How Many Terms of Fibonacci Series you want:
");
Scanner s=new Scanner(System.in);
n=s.nextInt();
System.out.print(firstTerm +" "+SecondTerm +" ");
for(int i=0;i<n-2;i++){
nextTerm=firstTerm+SecondTerm;
System.out.print(nextTerm +" ");
firstTerm=SecondTerm;
SecondTerm=nextTerm;
}
}
}

Output:
Q5.Write a java program to find GCD of two numbers.

Source Code:

public class GCD {


public static int findGCD(int a, int b) {
if (b == 0) {
return a;
}
return findGCD(b, a % b);
}
public static void main(String[] args)
{ int num1 = 24, num2 = 36;
System.out.println("GCD of " + num1 + " and " +
num2 + " is: " +
findGCD(num1, num2));
}
}

Output:
LAB 2

Q1.Write a program to create a room class, the attributes of this class


are roomno, roomtype, roomarea and ACmachine. In this class the
member functions are setdata() and displaydata().

Source Code:

import java.util.Scanner;
public class Room
{ private int roomNo;
private String roomType;
private double roomArea;
private boolean acMachine;
public void setData(int roomNo, String roomType, double roomArea,
boolean acMachine) {
this.roomNo = roomNo;
this.roomType = roomType;
this.roomArea = roomArea;
this.acMachine = acMachine;
}
public void displayData() {
System.out.println("Room Number: " + roomNo);
System.out.println("Room Type: " + roomType);
System.out.println("Room Area: " + roomArea + " sq.
ft");
System.out.println("AC Machine: " + (acMachine ?
"Yes" : "No"));
}
public static void main(String[] args)
{ Scanner scanner = new Scanner(System.in);
Room room = new Room();

System.out.print("Enter Room Number:");


int roomNo = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Room Type:");
String roomType = scanner.nextLine();
System.out.print("Enter Room Area (in sq. ft):");
double roomArea = scanner.nextDouble();
scanner.nextLine();
System.out.print("Does the room have AC Machine?
(true/false):");
boolean acMachine = scanner.nextBoolean();
room.setData(roomNo, roomType, roomArea, acMachine);
System.out.println("\nRoom Details:");
room.displayData();
scanner.close();
}
}

Output:

Q2.Create a class ObjectOriented which has methods- abstraction(),


polymorphism() and inheritance(). Create a class JavaLanguage which
inherits from ObjectOriented class and has its own methods
persistence() and interfaces(). Create an object of JavaLanguage class
to access all of its own and parent’s methods.

Source code:

class ObjectOriented
{ public void abstraction()
{
System.out.println("This is an example of abstraction.");}
public void polymorphism(){
System.out.println("This is an example of polymorphism.");}
public void inheritance() {
System.out.println("This is an example of inheritance.");}
}
class JavaLanguage extends ObjectOriented {
public void persistence() {
System.out.println("Java provides various persistence
mechanisms."); }
public void interfaces() {
System.out.println("Java supports interfaces for achieving
abstraction."); }
}
public class OOPS {
public static void main(String[] args)
{ JavaLanguage javaLanguage = new
JavaLanguage(); javaLanguage.abstraction();
javaLanguage.polymorphism();
javaLanguage.inheritance();
javaLanguage.persistence();
javaLanguage.interfaces(); }

Output:
Q3.Write a program to give the example for ‘super’ keyword.

Source code:

class Parent {
String message = "Hello from Parent class";
void display() {
System.out.println(message);
}
}
class Child extends Parent {
String message = "Hello from Child class";
@Override
void display() {
super.display(); // Using 'super' to call the method from the
parent
class
System.out.println(message);
}
}
public class Ques_11 {
public static void main(String[] args)
{ Child child = new Child();
child.display();
}
}

Output:
Q4.Write a program to give the example for method overriding
concepts.

Source code:

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound()
{ System.out.println("Dog
barks");
}
}
public class Ques_10 {
public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
animal.sound(); // Calls the overridden method in Dog class
}
}

Output:
Q5.Write a program to demonstrate static variables, methods, and
blocks.

Source code:

public class Ques_9 {


static int staticVariable = 5;
static {
System.out.println("Static block is executed.");
}
static void staticMethod()
{ System.out.println("Static method is
called.");
}
public static void main(String[] args) {
System.out.println("Value of static variable: " + staticVariable);
staticMethod();
}
}

Output:
LAB 3

Q1.You are given a paragraph consisting of words, Convert this para graph
to tokens (word) to be stored in array of string in sorted order where sorted
array does not have duplicate words.

Source code :

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class WordMain {
public static void main(String[] arg
String paragraph = "You are given a paragraph consisting of words Convert
this
paragraph to tokens word to be stored in array of string in sorted order
where sorted array
does not have duplicate words ";

String[] words = paragraph.split("\\s+");


Set<String> uniqueWordsSet = new HashSet<>(Arrays.asList(words));
String[] uniqueWordsArray = uniqueWordsSet.toArray(new String[0]);
Arrays.sort(uniqueWordsArray);
System.out.println("Sorted words without duplicates:");
for (String word : uniqueWordsArray) {
System.out.println(word);
}
}

Output:
Q2.Write java program to create array of string of 10 elements. Further sort
the array in ascending order. The string comparison can be with or without
case sensitive

import java.util.Arrays;

public class StringArraySorting


{ public static void main(String[] args)
{
String[] strings = {"LION", "TIGER", "DEER", "MONKEY",
"ELEPHANT", "JAGUAR", "PIG",
"CHEETAH", "COW", "HORSE"};
Arrays.sort(strings, String.CASE_INSENSITIVE_ORDER);
System.out.println("Sorted Array:");
for (String str : strings) {
System.out.println(str);
}
}
}

Output :
Q3.You are given a paragraph consisting of words, Convert this para graph
to tokens (word) to be stored in array of string in sorted order where sorted
array does not have duplicate words.

Source code :

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class WordMain {
public static void main(String[] arg
String paragraph = "You are given a paragraph consisting of words Convert
this
paragraph to tokens word to be stored in array of string in sorted order
where sorted array
does not have duplicate words ";

String[] words = paragraph.split("\\s+");


Set<String> uniqueWordsSet = new HashSet<>(Arrays.asList(words));
String[] uniqueWordsArray = uniqueWordsSet.toArray(new String[0]);
Arrays.sort(uniqueWordsArray);
System.out.println("Sorted words without duplicates:");
for (String word : uniqueWordsArray) {
System.out.println(word);
}
}
Output :

Q4.You are given a paragraph consisting continuous alphabets, convert this


para graph to tokens based on occurrence of particular characters. Store the
tokens in array of string in sorted order where sorted array does not have
duplicate words.

Source Code:

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Tokenizer {
public static void main(String[] args) {

String paragraph = "You are given a paragraph consisting continuous


alphabets convert
this paragraph to tokens based on occurrence of particular characters Store
the tokens in
array of string in sorted order where sorted array does not have duplicate
words";
String splitCharacters = "[\\s,.]"
String[] words = paragraph.split(splitCharacters);
Set<String> uniqueWordsSet = new HashSet<>();
for (String word : words) {
if (!word.isEmpty()) {
uniqueWordsSet.add(word.toLowerCase());
}
}
String[] uniqueWordsArray = uniqueWordsSet.toArray(new String[0]);
Arrays.sort(uniqueWordsArray);
System.out.println("Sorted words without duplicates:");
for (String word : uniqueWordsArray) {
System.out.println(word);
}
}
}

Output:
Q5.Write java program to demonstrate the different ways for making an
object eligible for GC when it is no longer needed.

Source Code :

public class ObjectGCExample


{ static class MyClass {
int data;
MyClass(int data) {
this.data = data;
}

@Override
protected void finalize() throws Throwable {
System.out.println("Object with data " + data + " is being garbage
collected");
}
}

public static void main(String[] args)


{ MyClass obj1 = new MyClass(1);
obj1 = null;
MyClass obj2 = new MyClass(2);
MyClass obj3 = new MyClass(3);
obj2 = obj3;
{
MyClass obj4 = new MyClass(4);
}
for (int i = 0; i < 10000; i++)
{ new MyClass(i);
}
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
LAB 4

Q1.Create a package P1 containing a class named Person, which has the


following fields:
id, name, age, phoneNumber, address, and experience. It also has a method
named printDetail(), which prints all the details of the Persons. Create two
classes that belong to the same package P1, Employee and staff, that inherit
the Person class. The Employee and Staff classes have data member
basicSalary and consolidatedSalary, respectively. Create an object of both
the class and print the details. Assume that the salary of an individual is
computed using the following rules:
a. If an individual is an employee with experience below five years, then the
salary = basicSalary + 100% of basic salary as DA +30% of Basic salary as
HRA.
b. If an individual is an employee and has an experience above five years,
then the net salary = basic salary + 100% of basic salary as DA +30% of
Basic salary as HRA + 20% of basic salary * (no. of years of experience
above 5 years).
c. The salary of staff is equal to the consolidatedSalary.

Source code :

class Person
{ protected int id;
protected String name;
protected int age;
protected String phoneNumber;
protected String address;
protected int experience;

public Person(int id, String name, int age, String phoneNumber, String
address, int
experience)
{ this.id = id;
this.name = name;
this.age = age;
this.phoneNumber = phoneNumber;
this.address = address;
this.experience = experience;
}

public void printDetail() {

System.out.println("ID: " + id);


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Phone Number: " + phoneNumber);
System.out.println("Address: " + address);
System.out.println("Experience: " + experience + " years");
}
}

class Employee extends Person


{ private double basicSalary;

public Employee(int id, String name, int age, String phoneNumber, String
address, int
experience, double basicSalary) {
super(id, name, age, phoneNumber, address, experience);
this.basicSalary = basicSalary;
}

public double calculateSalary()


{ double da = basicSalary * 1.0;
double hra = basicSalary * 0.30;

if (experience > 5) {
double extraAllowance = (experience - 5) * (basicSalary * 0.20);
return basicSalary + da + hra + extraAllowance;
} else {
return basicSalary + da + hra;
}
}
}

class Staff extends Person


{ private double
consolidatedSalary;
public Staff(int id, String name, int age, String phoneNumber, String
address, int
experience, double consolidatedSalary) {
super(id, name, age, phoneNumber, address, experience);
this.consolidatedSalary = consolidatedSalary;
}

public double getConsolidatedSalary()


{ return consolidatedSalary;
}
}

public class Main {


public static void main(String[] args) {
Employee emp = new Employee(101, "John Doe", 30, "1234567890",
"Address 1", 3,
50000);
Staff staff = new Staff(201, "Jane Smith", 25, "9876543210", "Address 2", 7,
60000);

System.out.println("Employee Details:");
emp.printDetail();
System.out.println("Salary: $" + emp.calculateSalary());

System.out.println("\nStaff Details:");
staff.printDetail();
System.out.println("Consolidated Salary: $" +
staff.getConsolidatedSalary());
}
}
Output :

Q2.You are required to store a table that contains substance name along
with its parameters such as freezing point and boiling point using 2-D
matrix where each row is corresponding to substance and columns
correspond to parameters. Design a class that takes temperature input using
scanner class and check whether temperature match with freezing point or
boiling point of respective substance and display the result.

Source Code:

import java.util.Scanner;
public class SubstanceTable
{ private String[] substances;
private double[][] parameters;
public SubstanceTable(String[] substances, double[][] parameters)
{ this.substances = substances;
this.parameters = parameters;
}

public void checkTemperature(String substance, double temperature)


{ int index = findSubstanceIndex(substance);
if (index == -1) {
System.out.println("Substance not found in the table.");
return;
}
double freezingPoint = parameters[index][0];
double boilingPoint = parameters[index][1];

if (temperature == freezingPoint) {
System.out.println("The temperature matches the freezing point of " +
substance);
} else if (temperature == boilingPoint) {
System.out.println("The temperature matches the boiling point of " +
substance);

} else {
System.out.println("The temperature does not match either the freezing or
boiling
point of " + substance);
}
}

private int findSubstanceIndex(String substance)


{ for (int i = 0; i < substances.length; i++) {
if (substances[i].equalsIgnoreCase(substance))
{ return i;
}
}
return -1;
}

public void printTable() { System.out.println("Substance\


tFreezing Point\tBoiling Point"); for (int i = 0; i <
substances.length; i++) {
System.out.println(substances[i] + "\t\t" + parameters[i][0] + "\t\t" +
parameters[i][1]);
}
}

public static void main(String[] args) {


String[] substances = {"Water", "Ethanol", "Mercury"};
double[][] parameters = {{0.0, 100.0}, {-114.1, 78.37}, {-38.83, 356.73}};

SubstanceTable table = new SubstanceTable(substances, parameters);


Scanner scanner = new Scanner(System.in);

System.out.print("Enter substance name: ");


String substance = scanner.nextLine();

System.out.print("Enter temperature: ");


double temperature = scanner.nextDouble();

table.checkTemperature(substance, temperature);

System.out.println("\nTable of Substances:");
table.printTable();

scanner.close();
}
}

OUTPUT :

Q3.Take a JaggedArray representing 2-D matrix as an input from the user.


Write a program that transpose the Jagged matrix. Merge the original and
transpose Jagged matrix. Display all the matrices.

Source Code :

import java.util.Scanner;

public class JaggedMatrixTranspose {


public static void main(String[] args)
{ Scanner scanner = new Scanner(System.in);

System.out.println("Enter the number of rows in the jagged matrix:");


int rows = scanner.nextInt();

int[][] jaggedMatrix = new int[rows][];

for (int i = 0; i < rows; i++) {


System.out.println("Enter the number of elements in row " + (i + 1) + ":");
int cols = scanner.nextInt();
jaggedMatrix[i] = new int[cols];
System.out.println("Enter the elements for row " + (i + 1) + ":");
for (int j = 0; j < cols; j++) {
jaggedMatrix[i][j] = scanner.nextInt();
}
}

int[][] transposedMatrix = transpose(jaggedMatrix);

int[][] mergedMatrix = merge(jaggedMatrix, transposedMatrix);

System.out.println("Original Matrix:");
displayMatrix(jaggedMatrix);
System.out.println("Transposed Matrix:");
displayMatrixWithSpace(transposedMatrix);
System.out.println("Merged Matrix:");
displayMatrixWithSpace(mergedMatrix);
}

private static int[][] transpose(int[][] matrix)


{ int rows = matrix.length;
int maxCols = 0;
for (int[] row : matrix) {
maxCols = Math.max(maxCols, row.length);
}
int[][] transposedMatrix = new int[maxCols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < matrix[i].length; j++) {
transposedMatrix[j][i] = matrix[i][j];
}
}
return transposedMatrix;
}

private static int[][] merge(int[][] matrix1, int[][] matrix2)


{ int[][] mergedMatrix = new int[matrix1.length][];
for (int i = 0; i < matrix1.length; i++) {
int cols = matrix1[i].length + matrix2[i].length;
mergedMatrix[i] = new int[cols];
System.arraycopy(matrix1[i], 0, mergedMatrix[i], 0, matrix1[i].length);
System.arraycopy(matrix2[i], 0, mergedMatrix[i], matrix1[i].length,
matrix2[i].length);
}
return mergedMatrix;
}

private static void displayMatrix(int[][] matrix)


{ for (int[] row : matrix) {

for (int num : row)


{ System.out.print(num + "
");
}
System.out.println();
}
}

private static void displayMatrixWithSpace(int[][] matrix)


{ for (int[] row : matrix) {
for (int num : row)
{ if (num != 0) {
System.out.print(num + " ");
} else {
System.out.print(" "); // Replace 0 with space
}
}
System.out.println();
}
}
}
OUTPUT:

Q4.Write a Java programs to demonstrate (i) 0-arguments constructor (ii)


parameterized constructor (iii) constructor overloading (iv) constructor
calling using super keyword (v) Automatic constructor creation of parent
class while creating the instance of child
class. Also represent various error messages due to inappropriate use of
constructor

Source code :

class Parent
{ public Parent() {
System.out.println("Parent: 0-arguments constructor");
}
public Parent(String message) {
System.out.println("Parent: Parameterized constructor with message: " +
message);
}
public Parent(int number) {
System.out.println("Parent: Constructor overloading with number: " +
number);
}

}
class Child extends Parent {
public Child()
{ super("Hello from
parent");
System.out.println("Child: Constructor");
}
}
public class ChildMain {
public static void main(String[] args) {

Child child = new Child();


}
}

Output :

Q5.You are given a paragraph consisting continuous alphabets, convert this


para graph to tokens based on occurrence of particular characters. Store the
tokens in array of string in sorted order where sorted array does not have
duplicate words.

Source code :

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Tokenizer {
public static void main(String[] args) {

String paragraph = "You are given a paragraph consisting continuous


alphabets convert
this paragraph to tokens based on occurrence of particular characters Store
the tokens in
array of string in sorted order where sorted array does not have duplicate
words";
String splitCharacters = "[\\s,.]"
String[] words = paragraph.split(splitCharacters);
Set<String> uniqueWordsSet = new HashSet<>();
for (String word : words) {
if (!word.isEmpty()) {
uniqueWordsSet.add(word.toLowerCase());
}
}
String[] uniqueWordsArray = uniqueWordsSet.toArray(new String[0]);
Arrays.sort(uniqueWordsArray);
System.out.println("Sorted words without duplicates:");
for (String word : uniqueWordsArray) {
System.out.println(word);
}
}
}

Output :

You might also like