Jaimin_Labmanual_Java
Jaimin_Labmanual_Java
L. D. College of Engineering
LABORATORY MANUAL
MCA
Semester I
Year 2024-25
Jaimin D Chandarana
(245160694005)
L. D. College of Engineering
Ahmedabad -380015
Practical 1
AIM: Install the JDK (Download the JDK and install it.)
Set path of the jdk/bin directory.
Create the java program
Compile and run the java program
Write a simple “Hello World” java program, compilation, debugging, executing using java
compiler and interpreter.
Program
Code:
System.out.println("Hello world!");
}
}
Output:
Practical 2
AIM: Write a program to pass Starting and Ending limit and print all prime numbers
and Fibonacci numbers between this ranges.
Program
Code:
import java.util.Scanner;
public class PrimeAndFibonacci {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Prime numbers between " + start + " and " + end + ":");
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
System.out.println("\nFibonacci numbers between " + start + " and " + end + ":");
int a = 0, b = 1;
while (a <= end) {
if (a >= start) {
System.out.print(a + " ");
}
int next = a + b;
a = b;
b = next;
}
}
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Output:
Practical 3
AIM: Write a java program to check whether number is palindrome or not. Input: 528 Output: It is
not palindrome number Input: 545 Output: It is not palindrome number
Program
Code:
import java.util.Scanner;
if (isPalindrome(number)) {
System.out.println(number + " is a palindrome number.");
} else {
System.out.println(number + " is not a palindrome number.");
}
}
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
Output:
Practical 4
AIM: Write a java program to print value of x^n. Input: x=5 Input: n=3 Output: 125
Program
Code:
import java.util.Scanner;
Output:
Practical 5
AIM: Write a java program to check Armstrong number. Input: 153 Output: Armstrong number
Input: 22 Output: not Armstrong number
Program
Code:
import java.util.Scanner;
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
while (num != 0) {
int digit = num % 10;
sum += Math.pow(digit, digits);
num /= 10;
}
Output:
Practical 6
AIM: Write a program in Java to find minimum of three numbers using conditional operator.
Program
Code:
import java.util.Scanner;
int min = (num1 < num2) ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 : num3);
Output:
Practical 7
AIM: Write a java program which should display maximum number of given 4 numbers..
Program
Code:
import java.util.Scanner;
Output:
Practical 8
AIM: Write a program in Java to multiply two matrix. Declare a class Matrix where 2D array
is declared as instance variable and array should be initialized, within class.
Program
Code:
import java.util.Scanner;
class Matrix {
int[][] matrix;
int rows, cols;
System.out.print("Enter the number of rows and columns for the first matrix: ");
int rows1 = scanner.nextInt();
int cols1 = scanner.nextInt();
System.out.print("Enter the number of rows and columns for the second matrix: ");
int rows2 = scanner.nextInt();
int cols2 = scanner.nextInt();
if (cols1 != rows2) {
System.out.println("Matrix multiplication not possible with the given dimensions.");
return;
}
class Matrix {
int[][] matrix;
int rows;
Output:
Practical 11
AIM: Write a Java application to count and display frequency of letters and digits from the String
given by user as command-line argument.
Program
Code:
public class FrequencyCounter {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a string as a command-line argument.");
return;
}
System.out.println("Frequency of letters:");
for (int i = 0; i < letterCount.length; i++) {
if (letterCount[i] > 0) {
System.out.println((char) (i + 'a') + ": " + letterCount[i]);
}
}
System.out.println("Frequency of digits:");
for (int i = 0; i < digitCount.length; i++) {
if (digitCount[i] > 0) {
System.out.println(i + ": " + digitCount[i]);
}
}
}
}
Output:
Practical 12
AIM: Create a class “Student” that would contain enrollment No, name, and gender and marks as
instance variables and count as static variable which stores the count of the objects; constructors
and display(). Implement constructors to initialize instance variables. Also demonstrate constructor
chaining. Create objects of class “Student” and displays all values of objects.
Program
Code:
class Student {
private int enrollmentNo;
private String name;
private String gender;
private int marks;
private static int count = 0;
public Student() {
this(0, "Unknown", "Unknown", 0);
}
System.out.println("Student 1:");
s1.display();
System.out.println();
System.out.println("Student 2:");
s2.display();
System.out.println();
System.out.println("Student 3:");
s3.display();
System.out.println();
Output:
Practical 13
AIM: Write a program in Java to demonstrate use of this keyword. Check whether this can
access the Static variables of the class or not. [Refer class student in Q12 to perform the task]
Program
Code:
public class Student {
private String enrollmentNo;
private String name;
private String gender;
private int marks;
private static int count = 0; // Static variable to count objects
public Student() {
this("Unknown", "Unknown", "Unknown", 0); // Call the primary constructor
}
static {
System.out.println("Static initializer block executed.");
count = 0;
}
{
System.out.println("Initializer block executed.");
length = 0;
width = 0;
}
public Rectangle() {
this(1.0, 1.0);
}
Output:
Practical 15
AIM: Write a java program static block which will be executed before main ( ) method in a Class.
Program
Code:
public class StaticBlockDemo {
static {
System.out.println("Static block executed.");
}
Output:
Practical 16
AIM:. Write programs in Java to use Wrapper class of each primitive data types.
Program
Code:
public class WrapperClassesDemo {
public static void main(String[] args) {
Byte byteWrapper = Byte.valueOf((byte) 10);
byte bytePrimitive = byteWrapper.byteValue();
System.out.println("Byte Wrapper: " + byteWrapper);
System.out.println("Byte Primitive: " + bytePrimitive);
static {
System.out.println("Static initializer block executed.");
}
{
System.out.println("Initializer block executed.");
}
public Circle() {
this(1.0); // Calls the parameterized constructor
count++;
}
System.out.println("Total number of Circle objects created using the default constructor: " +
Circle.getCount());
}
}
Output:
Practical 18
AIM: Create a class “Vehicle” with instance variable vehicle_type. Inherit the class in a class
called “Car” with instance model_type, company name etc. display the information of the vehicle
by defining the display() in both super and sub class [Method Overriding]
Program
Code:
class Vehicle {
protected String vehicleType;
@Override
public void display() {
super.display(); // Call the display method of the superclass (Vehicle)
System.out.println("Model Type: " + modelType);
System.out.println("Company Name: " + companyName);
}
}
Output:
Practical 19
AIM: Create a class “Account” containing accountNo, and balance as an instance variable. Derive
the Account class into two classes named “Savings” and “Current”. The “Savings” class should
contain instance variable named interestRate, and the “Current” class should contain instance
variable called overdraftLimit. Define appropriate methods for all the classes to enable
functionalities to check balance, deposit, and withdraw amount in Savings and Current account.
[Ensure that the Account class cannot be instantiated.]
Program
Code:
abstract class Account {
protected int accountNo;
protected double balance;
@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Invalid withdrawal amount.");
}
}
@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance + overdraftLimit) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Invalid withdrawal amount.");
}
}
savingsAccount.deposit(1000);
savingsAccount.withdraw(2000);
savingsAccount.display();
System.out.println();
currentAccount.deposit(2000);
currentAccount.withdraw(4000);
currentAccount.display();
}
}
Output:
Practical 20
AIM: Write a program in Java in which a subclass constructor invokes the constructor of the
super class and instantiate the values. [ refer class Account and sub classes savingAccount and
CurrentAccount in Q 19 for this task]
Program
Code:
abstract class Account {
protected int accountNo;
protected double balance;
@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Invalid withdrawal amount.");
}
}
@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance + overdraftLimit) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Invalid withdrawal amount.");
}
}
savingsAccount.deposit(1000);
savingsAccount.withdraw(2000);
savingsAccount.display();
System.out.println();
currentAccount.deposit(2000);
currentAccount.withdraw(4000);
currentAccount.display();
}
}
Output:
Practical 21
AIM: Write a program in Java to demonstrate the use of 'final' keyword in the field
declaration. How it is accessed using the objects.
Program
Code:
public class FinalKeywordDemo {
Output:
Practical 22
AIM: Write a java program to illustrate how to access a hidden variable. Class A declares a static
variable x. The class B extends A and declares an instance variable x. display ( ) method in B
displays both of these variables.
Program
Code:
class A {
static int x = 10;
}
class B extends A {
int x = 20;
Output:
Practical 23
AIM: Describe abstract class called Shape which has three subclasses say Triangle, Rectangle, and
Circle. Define one method area () in the abstract class and override this area () in these three
subclasses to calculate for specific object i.e. area () of Triangle subclass should calculate area of
triangle etc. Same for Rectangle and Circle
Program
Code:
abstract class Shape {
// Abstract method to calculate area
public abstract double area();
}
@Override
public double area() {
return 0.5 * base * height;
}
}
@Override
public double area() {
return length * width;
}
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
Output:
Practical 24
AIM: Write a java program to implement an interface called Exam with a method Pass (int mark)
that returns a boolean. Write another interface called Classify with a method Division (int average)
which returns a String. Write a class called Result which implements both Exam and Classify. The
Pass method should return true if the mark is greater than or equal to 50 else false. The Division
method must return “First” when the parameter average is 60 or more, “Second” when average is
50 or more but below 60, “No division” when average is less than 50.
Program
Code:
interface Exam {
boolean Pass(int mark);
}
interface Classify {
String Division(int average);
}
@Override
public String Division(int average) {
if (average >= 60) {
return "First";
} else if (average >= 50) {
return "Second";
} else {
return "No division";
}
}
mark = 45;
System.out.println("Mark: " + mark + " - Pass: " + result.Pass(mark));
average = 55;
System.out.println("Average: " + average + " - Division: " + result.Division(average));
average = 45;
System.out.println("Average: " + average + " - Division: " + result.Division(average));
}
}
Output:
Practical 25
AIM: Assume that there are two packages, student and exam. A student package contains Student
class and the exam package contains Result class. Write a program that generates mark sheet for
students.
Program
Code:
package student;
package exam;
import student.Student;
import student.Student;
import exam.Result;
import java.util.Scanner;
result.displayResult();
scanner.close();
}
}
Output:
Directory structure:
Final Output:
Practical 26
AIM: Define a class A in package apack. In class A, three variables are defined of access modifiers
protected, private and public. Define class B in package bpack which extends A and write display
method which accesses variables of class A. Define class C in package cpack which has one method
display() in that create one object of class A and display its variables. Define class ProtectedDemo
in package dpack in which write main () method. Create objects of class B and C and class display
method for both these objects.
Program
Code:
package apack;
public class A {
public int publicVar = 10;
protected int protectedVar = 20;
private int privateVar = 30;
package bpack;
import apack.A;
package cpack;
import apack.A;
public class C {
public void display() {
A a = new A();
System.out.println("Public Variable: " + a.publicVar);
System.out.println("Private Variable (via getter): " + a.getPrivateVar());
}
}
package dpack;
import bpack.B;
import cpack.C;
Directory structure:
Output:
Practical 27
AIM: Write a java program to implement Generic class Number_1 for both data type int and float in
java.
Program
Code:
public class Number_1<T extends Number> {
private T number;
public T getNumber() {
return number;
}
Output:
Practical 28
AIM: Write a java program to accept string to check whether it is in Upper or Lower case. After
checking, case will be reversed.
Program
Code:
import java.util.Scanner;
if (input.equals(input.toUpperCase())) {
System.out.println("The string is in uppercase.");
} else if (input.equals(input.toLowerCase())) {
System.out.println("The string is in lowercase.");
} else {
System.out.println("The string contains both uppercase and lowercase characters.");
}
scanner.close();
}
return reversedCase.toString();
}
}
Output:
Practical 29
AIM: Write a java program to use important methods of String class.
Program
Code:
public class StringMethodsDemo {
public static void main(String[] args) {
String str = "Hello, World!";
Output:
Practical 30
AIM: Write a program in Java to demonstrate use of final class, final variable and final
method
Program
Code:
public final class FinalClass {
public final int finalVariable = 100;
finalClass.display();
}
}
Output:
Practical 31
AIM: Write a program in Java to develop user defined exception for 'Divide by
Zero' error
Program
Code:
public class DivideByZeroException extends Exception {
public DivideByZeroException(String message) {
super(message);
}
}
import java.util.Scanner;
try {
double result = Division.divide(numerator, denominator);
System.out.println("Result: " + result);
} catch (DivideByZeroException e) {
System.out.println("Error: " + e.getMessage());
}
scanner.close();
}
}
Output:
Practical 32
AIM: Write a program in Java to demonstrate throw, throws, finally, multiple try block and
exception.
multiple catch
Program
Code:
import java.util.Scanner;
try {
System.out.print("Enter a number: ");
int number = scanner.nextInt();
checkNumber(number);
try {
int result = 10 / number;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: Division by zero is not allowed.");
}
try {
int[] arr = new int[5];
arr[10] = 50; // This will cause ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException: Index out of bounds.");
}
} catch (CustomException e) {
System.out.println("CustomException: " + e.getMessage());
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
scanner.close();
}
}
Output:
Practical 33
AIM: Write a small application in Java to develop Banking Application in which user deposits the
amount Rs 1000.00 and then start withdrawing of Rs 400.00, Rs 300.00 and it throws exception
"Not Sufficient Fund" when user withdraws Rs. 500 thereafter.
Program
Code:
public class NotSufficientFundException extends Exception {
public NotSufficientFundException(String message) {
super(message);
}
}
try {
account.deposit(1000.00);
account.withdraw(400.00);
account.withdraw(300.00);
account.withdraw(500.00); // This should throw NotSufficientFundException
} catch (NotSufficientFundException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Practical 34
AIM: Write a program to write at least 10 objects of the Circle class in a File and to perform basic
operations: adding, retrieving, updating, removing elements.
Program
Code:
import java.io.Serializable;
@Override
public String toString() {
return "Circle [radius=" + radius + "]";
}
}
import java.io.*;
import java.util.ArrayList;
import java.util.List;
try {
// Clear the file before adding new circles
manager.clearFile();
// Add 10 circles
for (int i = 1; i <= 10; i++) {
manager.addCircle(new Circle(i * 1.0));
}
manager.removeCircle(3);
System.out.println("\nAfter removing circle at index 3:");
circles = manager.readCircles();
for (Circle circle : circles) {
System.out.println(circle);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Practical 35
AIM: Write a program for Java Generics class for Sorting operations:
1. Sorting a list according to natural ordering of elements
2. Reversing sort order
3. Sorting a list whose elements of a custom type
4. Sorting a list using a Comparator. [desirable]
Program
Code:
import java.util.*;
@Override
public int compareTo(Person other) {
return this.name.compareTo(other.name);
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class Main {
public static void main(String[] args) {
Sorter<Integer> intSorter = new Sorter<>();
List<Integer> intList = Arrays.asList(5, 3, 8, 1, 9);
Output:
Practical 36
AIM: Write a program in Java to create, write, modify, read operations on a Text file.
Program
Code:
import java.io.*;
import java.util.Scanner;
try {
System.out.print("Enter content to write to the file: ");
String content = scanner.nextLine();
fileOps.createAndWriteFile(content);
System.out.println("File created and written successfully.");
} catch (IOException e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
}
Output:
Practical 37
AIM: Write a java program to illustrate use of standard input stream to read the user input.
Program
Code:
import java.util.Scanner;
System.out.println("\nUser Input:");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Favorite Number: " + favoriteNumber);
scanner.close();
}
}
Output:
Practical 38
AIM: Write a java program to checks the existence of a specified file.
Program
Code:
import java.io.File;
import java.util.Scanner;
if (file.exists()) {
System.out.println("The file " + fileName + " exists.");
} else {
System.out.println("The file " + fileName + " does not exist.");
}
scanner.close();
}
}
Output:
Practical 39
AIM: Write a java program to create a file to the specified location.
Program
Code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
try {
if (file.exists()) {
System.out.println("The file " + filePath + " already exists.");
} else {
if (file.createNewFile()) {
System.out.println("The file " + filePath + " has been created successfully.");
} else {
System.out.println("Failed to create the file " + filePath + ".");
}
}
} catch (IOException e) {
System.out.println("An error occurred while creating the file: " + e.getMessage());
}
scanner.close();
}
}
Output:
Practical 40
AIM: Write a java program to demonstrate the way contents are read from a file.
Program
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
scanner.close();
}
}
Output:
Practical 41
AIM: Write a program in Java to demonstrate use of synchronization of threads when multiple
threads are trying to update common variable for “Account” class.
Program
Code:
public class Account {
private int balance;
@Override
public void run() {
if (deposit) {
account.deposit(amount);
} else {
account.withdraw(amount);
}
}
}
public class Main {
public static void main(String[] args) {
Account account = new Account(1000);
t1.start();
t2.start();
t3.start();
t4.start();
try {
t1.join();
t2.join();
t3.join();
t4.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
int lineCount = 0;
scanner.close();
}
}
Output:
Practical 43
AIM: Write a generic method to count the number of elements in a collection that have a specific
property (for example, odd integers, prime numbers, palindromes).
Program
Code:
import java.util.*;
import java.util.function.Predicate;
scanner.close();
}
}
Output:
Practical 44
AIM: Write a generic method to exchange the positions of two different elements in an array.
Program
Code:
import java.util.Arrays;
import java.util.Scanner;
if (type.equals("integer")) {
System.out.print("Enter the integer array elements (space-separated): ");
String[] intInput = scanner.nextLine().split(" ");
Integer[] intArray = new Integer[intInput.length];
for (int i = 0; i < intInput.length; i++) {
intArray[i] = Integer.parseInt(intInput[i]);
}
} else if (type.equals("string")) {
System.out.print("Enter the string array elements (space-separated): ");
String[] strArray = scanner.nextLine().split(" ");
} else {
System.out.println("Invalid array type.");
}
scanner.close();
}
}
Output: