0% found this document useful (0 votes)
2 views

Java_Lab_Programs_Solutions

The document contains 15 Java programs demonstrating various programming concepts including command line arguments, arrays, classes and objects, constructors, method overloading, method overriding, inner classes, inheritance, interfaces, exception handling, packages, and multithreading. Each program is presented with its source code and expected output. The examples serve as practical illustrations of fundamental Java programming principles.

Uploaded by

shreyassupe346
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java_Lab_Programs_Solutions

The document contains 15 Java programs demonstrating various programming concepts including command line arguments, arrays, classes and objects, constructors, method overloading, method overriding, inner classes, inheritance, interfaces, exception handling, packages, and multithreading. Each program is presented with its source code and expected output. The examples serve as practical illustrations of fundamental Java programming principles.

Uploaded by

shreyassupe346
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Program No: 01

Write a Java Program to demonstrate the Command Line Arguments.


class CommandLine
{
public static void main(String[] args)
{
int n = Integer.parseInt(args[0]);
if((n%2)==0)
{
System.out.println(n+" Number is Even");
}
else
{
System.out.println(n+" Number is Odd");
}
}
}

OUTPUT
Program No: 02
Write a Java Program to demonstrate Arrays.
class Array
{
public static void main(String[] args)
{
int number[];
number=new int[5];
for(int i=0;i<args.length;i++)
{
number[i]=Integer.parseInt(args[i]);
}
for(int i=0;i<args.length;i++)
{
for(int j=0;j<args.length;j++)
{
if(number[i]<number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
System.out.println("Sorted array");
for(int i=0;i<args.length;i++)
{
System.out.println(number[i]);
}
}
}

OUTPUT
Program No: 03
Write a Java Program to demonstrate the concept of Class and Object (Display Student
Information).
class Student
{
String Student_Name;
int Student_Rollno;
int Age;
float Marks;

void StudentInfo()
{
System.out.println("Student_Name : "+Student_Name);
System.out.println("Student_Rollno : "+Student_Rollno);
System.out.println("Age : "+Age);
System.out.println("Marks : "+Marks);
}

public static void main(String[] args)


{
Student std = new Student();
std.Student_Name="Jyothi";
std.Student_Rollno=222343;
std.Age=50;
std.Marks=99.99f;
std.StudentInfo();
}
}

OUTPUT
Program No: 04
Write a Java Program to demonstrate the concept of Constructor and Constructor
Overloading.
class Box
{
double width, height, depth;
Box()
{
width = height = depth = 0;
}
Box(double len)
{
width = height = depth = len;
}
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
double volume()
{
return width * height * depth;
}
}
class Test
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mycube = new Box(7);
Box mybox2 = new Box(10, 20, 15);

double vol;

vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);

vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);

vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
}
}
OUTPUT
Program No: 05
Write a Java Program to demonstrate the concept of Method Overloading.
class Transaction
{
void Deposit( double amt,String name)
{
System.out.println("Wel-Come "+name+" to your savings account");
if(amt>=500 && amt<=50000)
{

System.out.println(amt+" deposited successfully\n");


}
else
{
System.out.println("please deposit the amount within 500 to 50000
limit\n");
}
}
void Deposit(String name, double amt)
{
System.out.println("Wel-Come "+name+" to your current account");
if(amt>=500 && amt<=200000)
{

System.out.println(amt+" Deposited Successfully");


}
else
{
System.out.println("Please deposit the amount within 500 to 200000
limit");
}
}
}
class Bank
{
public static void main(String[] args)
{
System.out.println("Wel-Come to City Bank\n");
Transaction tr = new Transaction();
tr.Deposit(4000,"Jyothi");
tr.Deposit("Jyothi",3000);
}
}
OUTPUT
Program No: 06
Write a Java Program to demonstrate the Method Overriding.
class Employee
{
float salary = 40000;

void increment()
{
System.out.println("The Employee incremented salary is :" +(salary + (salary * 0.2)) );
}
}
class PermanentEmp extends Employee
{
double hike = 0.5;

void increment()
{
System.out.println("The Permanent Employee incremented salary is :" +(salary +
(salary * hike)) );
}
}
class TemporaryEmp extends Employee
{
double hike = 0.35;

void increment()
{
System.out.println("The Temporary Employee incremented salary is :" +(salary +
(salary * hike)) );
}
}
public class EmpSalHike
{
public static void main(String args[])
{
Employee e = new Employee( );
PermanentEmp p = new PermanentEmp();
TemporaryEmp t = new TemporaryEmp();

e.increment();
p.increment();
t.increment();
}
}
OUTPUT
Program No: 07

Write a Java Program to implement Inner class and demonstrate its Access
Protections.
public class Car
{
private String model;
protected int year;
private Engine engine;
Engine eng = new Engine();

public Car(String model, int year)


{
this.model = model;
this.year = year;
}

public void start()


{
System.out.println("Starting the " + model + " car "+year);
eng.startEngine();
}

public void drive()


{
System.out.println("Driving the " + model + " car "+year);
eng.accelerate();
}

public void stop()


{
System.out.println("Stopping the " + model + " car "+year);
eng.stopEngine();
}

private class Engine


{
private void startEngine()
{
System.out.println("Engine of the " + model + " car started
"+year+"\n");
}

private void stopEngine()


{
System.out.println("Engine of the " + model + " car stopped
"+year+"\n");
}
protected void accelerate()
{
System.out.println("Accelerating the " + model + " car
"+year+"\n");
}
}
public static void main(String[] args)
{
Car car = new Car("Audi R8", 2022);
car.start();
car.drive();
car.stop();
}
}

OUTPUT
Program No: 08
Write a Java Program to demonstrate the working of this and super keyword.
class Person
{
private String name;
private int age;

public Person(String name, int age)


{
this.name = name;
this.age = age;
}
public void display()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
class Student extends Person
{
private int grade;
public Student(String name, int age, int grade)
{
super(name, age);
this.grade = grade;
}
public void display()
{
super.display();
System.out.println("Grade: " + grade);
}
}
public class InheritanceDemo
{
public static void main(String[] args)
{
Person person = new Person("John Doe", 30);
person.display();

System.out.println();

Student student = new Student("Jane Smith", 18, 12);


student.display();
}
}
OUTPUT
Program No: 09
Write a Java Program to demonstrate the working of multiple catch blocks.
public class MultipleCatchDemo
{
public static void main(String[] args)
{
try
{
int[] numbers = { 1, 2, 3 };
int result = numbers[5] / 0;
System.out.println("Result: " + result);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bounds: " + e.getMessage());
}
catch (ArithmeticException e)
{
System.out.println("Arithmetic exception occurred: " +
e.getMessage());
}
catch (Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
}
}
}

OUTPUT
Program No: 10
Write a Java Program to demonstrate Abstract Classes and Abstract Methods.
abstract class Shape
{
protected String color;
public Shape(String color)
{
this.color = color;
}

public abstract double area();

public void display()


{
System.out.println("Shape color: " + color);
}
}

class Circle extends Shape


{
private double radius;
public Circle(String color, double radius)
{
super(color);
this.radius = radius;
}

public double area()


{
return Math.PI * radius * radius;
}
}

class Rectangle extends Shape


{
private double length;
private double width;

public Rectangle(String color, double length, double width)


{
super(color);
this.length = length;
this.width = width;
}
public double area()
{
return length * width;
}
}

public class AbstractClass


{
public static void main(String[] args)
{
Circle circle = new Circle("Red", 5.0);
circle.display();
System.out.println("Circle area: " + circle.area());

Rectangle rectangle = new Rectangle("Blue", 4.0, 6.0);


rectangle.display();
System.out.println("Rectangle area: " + rectangle.area());
}
}

OUTPUT
Program No: 11

Write a Java Program to demonstrate Inheritance.


class Person
{
protected String name;

public Person(String name)


{
this.name = name;
}

public void displayInfo()


{
System.out.println("Name: " + name);
}
}

class Student extends Person


{
private int studentId;
public Student(String name, int studentId)
{
super(name);
this.studentId = studentId;
}

public void displayStudentInfo()


{
System.out.println("Student ID: " + studentId);
}
}

class GraduateStudent extends Student


{
private String thesisTopic;
public GraduateStudent(String name, int studentId, String thesisTopic)
{
super(name, studentId);
this.thesisTopic = thesisTopic;
}
public void displayThesisTopic()
{
System.out.println("Thesis Topic: " + thesisTopic);
}
}
class Teacher extends Person
{
private String subject;

public Teacher(String name, String subject)


{
super(name);
this.subject = subject;
}
public void displaySubject()
{
System.out.println("Subject: " + subject);
}
}

public class Inheritance


{
public static void main(String[] args)
{
Person person = new Person("John Doe");
person.displayInfo();

Student student = new Student("Alice Smith", 1001);


student.displayInfo();
student.displayStudentInfo();

GraduateStudent graduateStudent = new GraduateStudent("Bob Johnson",


2001, "Computer Science");
graduateStudent.displayInfo();
graduateStudent.displayStudentInfo();
graduateStudent.displayThesisTopic();

Teacher teacher = new Teacher("Emma Davis", "Mathematics");


teacher.displayInfo();
teacher.displaySubject();
}
}
OUTPUT
Program No: 12

Write a Java Program to demonstrate the Multiple Inheritance using Interfaces.


interface Depositable
{
void deposit(double amount);
}

interface Withdrawable
{
void withdraw(double amount);
}

class BankAccount implements Depositable, Withdrawable


{
private String accountNumber;
private double balance;

public BankAccount(String accountNumber)


{
this.accountNumber = accountNumber;
this.balance = 0.0;
}

public String getAccountNumber()


{
return accountNumber;
}

public double getBalance()


{
return balance;
}

public void deposit(double amount)


{
balance += amount;
System.out.println("Deposited $" + amount + " into account " +
accountNumber);
}

public void withdraw(double amount)


{
if (balance >= amount)
{
balance -= amount;
System.out.println("Withdrawn $" + amount + " from account " +
accountNumber);
}
else
{
System.out.println("Insufficient balance in account " +
accountNumber);
}
}
}

public class Main


{
public static void main(String[] args)
{
BankAccount account1 = new BankAccount("123456789");
account1.deposit(1000);
account1.withdraw(500);

BankAccount account2 = new BankAccount("987654321");


account2.deposit(2000);
account2.withdraw(1500);
}
}

OUTPUT
Program No: 13

Write a Java program to demonstrate the working of try, catch and finally
block in exception handling.
import java.util.Scanner;

public class ExceptionHandlingExample


{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the book title: ");
String bookTitle = scanner.nextLine();
System.out.print("Enter the book price: ");
double bookPrice = scanner.nextDouble();
try
{
purchaseBook(bookTitle, bookPrice);
System.out.println("Book purchased successfully.");
}
catch (InvalidBookException ex)
{
System.out.println("Invalid book: " + ex.getMessage());
}
catch (Exception ex)
{
System.out.println("An error occurred during the purchase: " +
ex.getMessage());
}
finally
{
scanner.close();
System.out.println("Purchase process completed.");
}
}

public static void purchaseBook(String title, double price) throws


InvalidBookException
{
if (price <= 0)
{
throw new InvalidBookException("Invalid book price.");
}
System.out.println("Purchasing book: " + title + " for $" + price);
}
}
class InvalidBookException extends Exception
{
public InvalidBookException(String message)
{
super(message);
}
}

OUTPUT
Program No: 14
Write Java Program to demonstrate the Packages.

Department.java
package department;
public class Department
{
private String departmentName;

public Department(String departmentName)


{
this.departmentName = departmentName;
}

public String getDepartmentName()


{
return departmentName;
}
}

Contact.java
package contacts;
import department.Department;

public class Contact


{
private String name;
private String email;
private Department department;

public Contact(String name, String email, Department department)


{
this.name = name;
this.email = email;
this.department = department;
}

public String getName()


{
return name;
}
public String getEmail()
{
return email;
}

public Department getDepartment()


{
return department;
}

public void display()


{
System.out.println("Name: " + name);
System.out.println("Email: " + email);
System.out.println("Department: " + department.getDepartmentName());
}
}

Main.java
import contacts.Contact;
import department.Department;
public class Main
{
public static void main(String[] args)
{
Department department = new Department("Computer Science");

Contact contact = new Contact("John Doe", "[email protected]",


department);

System.out.println("Contact Details:");
contact.display();
}
}
OUTPUT
Program No: 15

Write a Java Program to create and start a thread.


class A extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("implementing thread by Extending Thread Class");
}
}
}
class B implements Runnable
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Implementing Thread by Runnable Interface");
}
}
}
class C
{
public static void main(String args[])
{
A t1 = new A();
B t2 = new B();
Thread t3 = new Thread(t2);
for(int i=0;i<5;i++)
{
System.out.println("Main thread");
}
t3.start();
t1.start();
}
}
OUTPUT

You might also like