[Go to site: main page, start]

0% found this document useful (0 votes)
35 views28 pages

Java Programming Concepts Explained

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views28 pages

Java Programming Concepts Explained

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Program No: 01

Write a Java Program to demonstrate the Command Line Arguments.


class CommandLine
{
public static void main(String[] args)
{
int n = [Link](args[0]);
if((n%2)==0)
{
[Link](n+" Number is Even");
}
else
{
[Link](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<[Link];i++)
{
number[i]=[Link](args[i]);
}
for(int i=0;i<[Link];i++)
{
for(int j=0;j<[Link];j++)
{
if(number[i]<number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
[Link]("Sorted array");
for(int i=0;i<[Link];i++)
{
[Link](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()
{
[Link]("Student_Name : "+Student_Name);
[Link]("Student_Rollno : "+Student_Rollno);
[Link]("Age : "+Age);
[Link]("Marks : "+Marks);
}

public static void main(String[] args)


{
Student std = new Student();
std.Student_Name="Jyothi";
std.Student_Rollno=222343;
[Link]=50;
[Link]=99.99f;
[Link]();
}
}

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 = [Link]();
[Link](" Volume of mybox1 is " + vol);

vol = [Link]();
[Link](" Volume of mycube is " + vol);

vol = [Link]();
[Link](" 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)
{
[Link]("Wel-Come "+name+" to your savings account");
if(amt>=500 && amt<=50000)
{

[Link](amt+" deposited successfully\n");


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

[Link](amt+" Deposited Successfully");


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

void increment()
{
[Link]("The Employee incremented salary is :" +(salary + (salary * 0.2)) );
}
}
class PermanentEmp extends Employee
{
double hike = 0.5;

void increment()
{
[Link]("The Permanent Employee incremented salary is :" +(salary +
(salary * hike)) );
}
}
class TemporaryEmp extends Employee
{
double hike = 0.35;

void increment()
{
[Link]("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();

[Link]();
[Link]();
[Link]();
}
}
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)


{
[Link] = model;
[Link] = year;
}

public void start()


{
[Link]("Starting the " + model + " car "+year);
[Link]();
}

public void drive()


{
[Link]("Driving the " + model + " car "+year);
[Link]();
}

public void stop()


{
[Link]("Stopping the " + model + " car "+year);
[Link]();
}

private class Engine


{
private void startEngine()
{
[Link]("Engine of the " + model + " car started
"+year+"\n");
}

private void stopEngine()


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

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)


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

[Link]();

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


[Link]();
}
}
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;
[Link]("Result: " + result);
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("Array index out of bounds: " + [Link]());
}
catch (ArithmeticException e)
{
[Link]("Arithmetic exception occurred: " +
[Link]());
}
catch (Exception e)
{
[Link]("An error occurred: " + [Link]());
}
}
}

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)
{
[Link] = color;
}

public abstract double area();

public void display()


{
[Link]("Shape color: " + color);
}
}

class Circle extends Shape


{
private double radius;
public Circle(String color, double radius)
{
super(color);
[Link] = radius;
}

public double area()


{
return [Link] * radius * radius;
}
}

class Rectangle extends Shape


{
private double length;
private double width;

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


{
super(color);
[Link] = length;
[Link] = width;
}
public double area()
{
return length * width;
}
}

public class AbstractClass


{
public static void main(String[] args)
{
Circle circle = new Circle("Red", 5.0);
[Link]();
[Link]("Circle area: " + [Link]());

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


[Link]();
[Link]("Rectangle area: " + [Link]());
}
}

OUTPUT
Program No: 11

Write a Java Program to demonstrate Inheritance.


class Person
{
protected String name;

public Person(String name)


{
[Link] = name;
}

public void displayInfo()


{
[Link]("Name: " + name);
}
}

class Student extends Person


{
private int studentId;
public Student(String name, int studentId)
{
super(name);
[Link] = studentId;
}

public void displayStudentInfo()


{
[Link]("Student ID: " + studentId);
}
}

class GraduateStudent extends Student


{
private String thesisTopic;
public GraduateStudent(String name, int studentId, String thesisTopic)
{
super(name, studentId);
[Link] = thesisTopic;
}
public void displayThesisTopic()
{
[Link]("Thesis Topic: " + thesisTopic);
}
}
class Teacher extends Person
{
private String subject;

public Teacher(String name, String subject)


{
super(name);
[Link] = subject;
}
public void displaySubject()
{
[Link]("Subject: " + subject);
}
}

public class Inheritance


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

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


[Link]();
[Link]();

GraduateStudent graduateStudent = new GraduateStudent("Bob Johnson",


2001, "Computer Science");
[Link]();
[Link]();
[Link]();

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


[Link]();
[Link]();
}
}
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)


{
[Link] = accountNumber;
[Link] = 0.0;
}

public String getAccountNumber()


{
return accountNumber;
}

public double getBalance()


{
return balance;
}

public void deposit(double amount)


{
balance += amount;
[Link]("Deposited $" + amount + " into account " +
accountNumber);
}

public void withdraw(double amount)


{
if (balance >= amount)
{
balance -= amount;
[Link]("Withdrawn $" + amount + " from account " +
accountNumber);
}
else
{
[Link]("Insufficient balance in account " +
accountNumber);
}
}
}

public class Main


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

BankAccount account2 = new BankAccount("987654321");


[Link](2000);
[Link](1500);
}
}

OUTPUT
Program No: 13

Write a Java program to demonstrate the working of try, catch and finally
block in exception handling.
import [Link];

public class ExceptionHandlingExample


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

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


InvalidBookException
{
if (price <= 0)
{
throw new InvalidBookException("Invalid book price.");
}
[Link]("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.

[Link]
package department;
public class Department
{
private String departmentName;

public Department(String departmentName)


{
[Link] = departmentName;
}

public String getDepartmentName()


{
return departmentName;
}
}

[Link]
package contacts;
import [Link];

public class Contact


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

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


{
[Link] = name;
[Link] = email;
[Link] = department;
}

public String getName()


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

public Department getDepartment()


{
return department;
}

public void display()


{
[Link]("Name: " + name);
[Link]("Email: " + email);
[Link]("Department: " + [Link]());
}
}

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

Contact contact = new Contact("John Doe", "[Link]@[Link]",


department);

[Link]("Contact Details:");
[Link]();
}
}
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++)
{
[Link]("implementing thread by Extending Thread Class");
}
}
}
class B implements Runnable
{
public void run()
{
for(int i=0;i<5;i++)
{
[Link]("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++)
{
[Link]("Main thread");
}
[Link]();
[Link]();
}
}
OUTPUT

Common questions

Powered by AI

Constructors and constructor overloading in the Box program facilitate object instantiation with different initial states. The default constructor initializes the Box dimensions to zero, while overloaded constructors allow setting dimensions either as a cube with equal sides or with specified width, height, and depth. This flexibility in object creation processes helps in building and maintaining reusable code, adapting to various instantiation requirements. Constructor overloading provides a way to offer multiple pathways to instantiate objects with various parameter configurations, making the code more adaptable to different usage scenarios .

The use of interfaces in Java, as demonstrated in the BankAccount program, allows multiple inheritance by implementing multiple interfaces such as Depositable and Withdrawable. Each interface defines a contract that the implementing class must fulfill, ensuring that an object can have behaviors defined by multiple types. The advantage lies in overcoming the limitations of single inheritance by providing a way to define methods to be used by different classes, enhance modularity, and promote code reuse. In the BankAccount program, both deposit and withdraw actions are decoupled from the actual account operations, allowing more flexible and scalable design .

The AbstractClass program uses abstract classes and methods to define a general concept of a Shape with a color and an abstract area method. Each subclass, such as Circle and Rectangle, must implement the area method, which calculates the area specific to that shape. This approach provides a common interface for all shapes while allowing each subclass to define its implementation details. It enhances code reusability and enforces a consistent API for different shape types, as inherited classes are required to specify their calculation logic for the area while maintaining shared characteristics .

Method overloading in the Java Transaction program allows the Deposit method to be defined with different parameter types and arrangements. One version accepts a double and a String, while the other accepts a String and a double. This enables the program to differentiate between depositing into a savings account with specific parameters and a current account with a different parameter order. The flexibility comes from the ability to handle deposits differently based on the account type or limits, thus enabling more versatile functionality within the same class .

The Inheritance program illustrates the relationship between base and derived classes by having Person as the base class and defining subclasses like Student, GraduateStudent, and Teacher. Each subclass inherits the attributes and methods of the base class while introducing specific functionalities, such as student IDs and thesis topics for students and subjects for teachers. This hierarchical organization leads to improved code clarity by separating generic properties applicable to all persons, like names, from role-specific information, promoting a more organized and scalable code structure. It underscores polymorphism, where different subclasses can be treated uniformly yet perform specialized tasks .

Multiple catch blocks in Java permit distinct handling for different exceptions, as shown in the MultipleCatchDemo program. When an exception is thrown within the try block, only the catch block corresponding to the exception type is executed. The provided program includes catch blocks for ArrayIndexOutOfBoundsException, ArithmeticException, and a generic Exception. This approach allows the program to precisely react to specific issues, such as array boundary errors or division by zero, and provide clear error messages. This method enhances robustness and clarity in error handling by segregating actions based on exception-type encounters .

The ExceptionHandlingExample program employs a structured approach to exception handling by using try-catch-finally blocks and custom exceptions like InvalidBookException. The program demonstrates robust error handling by catching specific exceptions like custom-defined InvalidBookException for invalid book price and general exceptions for unexpected scenarios. The use of a finally block ensures resource deallocation (closing scanner) happens regardless of exceptions, improving reliability. Using custom exceptions enhances code readability and provides contextual error messages, although it requires additional classes, thereby increasing complexity. Overall, these design choices lead to more maintainable, understandable, and robust error-handling mechanisms .

Encapsulation in the Car program is achieved by using access modifiers to restrict access to class members and inner classes. The Car class contains private attributes such as model and an inner Engine class. The Engine class methods like startEngine and stopEngine are private, ensuring that engine operations cannot be accessed externally and are controlled by the Car class only. The use of protected for the accelerate method allows access within the package or subclasses, underlining further control over its usage. This controlled access ensures that the internal representation and state are protected against unauthorized access or modification .

The Java program demonstrates command line arguments by accepting arguments passed to the main method, parsing the first argument to an integer, and determining its parity. It uses Integer.parseInt(args[0]) to convert the first command line argument to an integer, assigns it to the variable n, and checks if n is even or odd using the modulus operator (n%2). If the result is 0, it prints that the number is even; otherwise, it prints that the number is odd .

Inheritance in the Java programs allows for hierarchical structuring of classes, where the PermanentEmp and TemporaryEmp classes extend the Employee class. This means both derived classes inherit the Employee's properties and methods, such as salary and increment, and can override these methods to provide specific implementations. PermanentEmp and TemporaryEmp classes override the increment method to apply different salary hikes. This demonstrates polymorphism, allowing objects to be treated as instances of their superclass while executing subclass-specific methods, which improves code reusability and flexibility .

You might also like