Question Bank › Technical › Java › Coding Questions
Write a Java program demonstrating an anonymous inner class that extends a class. Define an abstract class Vehicle with an abstract method run(). In main(), create an anonymous inner class extending Vehicle that implements run() to print "bus is moving", assign it to a Vehicle reference v, and call v.run().
abstract class Vehicle {
abstract void run();
}
class TestAnonymousInner {
public static void main(String[] args) {
Vehicle v = new Vehicle() {
void run() {
System.out.println("bus is moving");
}
};
v.run();
}
}Write a Java program that shows a Java anonymous inner class example using an interface. Define an interface Speaker with a method void speak(). In main, create a Speaker using an anonymous inner class whose speak() prints "hello bharat", then invoke speak().
interface Speaker {
void speak();
}
class TestAnonymousInner2 {
public static void main(String[] args) {
Speaker s = new Speaker() {
public void speak() {
System.out.println("hello bharat");
}
};
s.speak();
}
}Write a Java program that shows how the compiler internally generates a class for an anonymous inner class. Create an abstract class Animal with an abstract method sound(). In main(), create an anonymous inner class that extends Animal and implements sound() to print "sweet mangoes", assign it to an Animal reference variable a, and call a.sound(). Also include a comment-style demonstration (as a static nested class named Demo$1 extending Animal) showing what the compiler generates internally.
abstract class Animal {
abstract void sound();
}
class Demo {
static class Demo$1 extends Animal {
Demo$1() {}
void sound() {
System.out.println("sweet mangoes");
}
}
public static void main(String[] args) {
Animal a = new Animal() {
void sound() {
System.out.println("sweet mangoes");
}
};
a.sound();
}
}Write a Java program that demonstrates how the compiler generates an internal class for an anonymous inner class. Define an interface Greeter with a method void greet(). In main, create a Greeter reference g using an anonymous inner class that implements greet() to print "namaste duniya", then call g.greet().
interface Greeter {
void greet();
}
class TestAnonymousInner {
public static void main(String[] args) {
Greeter g = new Greeter() {
public void greet() {
System.out.println("namaste duniya");
}
};
g.greet();
}
}Write a Java program to demonstrate a class and object. Create a class named 'Book' with two data members: 'bookId' (int) and 'title' (String). In the main method (inside the Book class), create an object of Book using the new keyword and print its data members. The output should be the default values (0 and null).
class Book {
int bookId;
String title;
public static void main(String[] args) {
Book b = new Book();
System.out.println(b.bookId);
System.out.println(b.title);
}
}Write a Java program that initializes objects through a method. Create a class Student with fields rollno (int) and name (String), a method insertRecord(int r, String n) that assigns these values, and a method displayInformation() that prints rollno and name separated by a space. In the main method of class TestStudent4, create two Student objects, initialize them by calling insertRecord with (305, "Ananya") and (406, "Vikram"), then call displayInformation() on both objects.
class Student {
int rollno;
String name;
void insertRecord(int r, String n) {
rollno = r;
name = n;
}
void displayInformation() {
System.out.println(rollno + " " + name);
}
}
class TestStudent4 {
public static void main(String args[]) {
Student s1 = new Student();
Student s2 = new Student();
s1.insertRecord(305, "Ananya");
s2.insertRecord(406, "Vikram");
s1.displayInformation();
s2.displayInformation();
}
}Write a Java program that keeps records of employees using a class and objects. Create a class Employee with fields id (int), name (String) and salary (float), and a method insert(int i, String n, float s) that sets these fields, plus a method display() that prints id, name and salary separated by spaces. In the main method of a public class TestEmployee, create three Employee objects and initialize them by calling insert with (201, "Rohan", 38000), (202, "Meera", 42000) and (203, "Suresh", 51000), then call display() on each object in that order.
class Employee {
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id = i;
name = n;
salary = s;
}
void display() {
System.out.println(id + " " + name + " " + salary);
}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1 = new Employee();
Employee e2 = new Employee();
Employee e3 = new Employee();
e1.insert(201, "Rohan", 38000);
e2.insert(202, "Meera", 42000);
e3.insert(203, "Suresh", 51000);
e1.display();
e2.display();
e3.display();
}
}Write a Java program with a class named Plot that has two integer fields, length and breadth, a method setDimensions(int l, int b) to assign them, and a method printArea() that prints the area (length * breadth). In the main method, create two Plot objects: set the first to length 12 and breadth 4, the second to length 7 and breadth 9, then print the area of each.
class Plot {
int length;
int breadth;
void setDimensions(int l, int b) {
length = l;
breadth = b;
}
void printArea() {
System.out.println(length * breadth);
}
}
class TestPlot {
public static void main(String args[]) {
Plot p1 = new Plot();
Plot p2 = new Plot();
p1.setDimensions(12, 4);
p2.setDimensions(7, 9);
p1.printArea();
p2.printArea();
}
}Write a Java program to demonstrate creating multiple objects of the same class. Create a class `Rectangle` with integer fields `length` and `width`. Include a method `insert(int l, int w)` to set the dimensions and a method `calculateArea()` that prints the area. In the main method, create two Rectangle objects `r1` and `r2` using a single declaration statement (e.g., `Rectangle r1 = new Rectangle(), r2 = new Rectangle();`). Initialize `r1` with length 8 and width 6, and `r2` with length 5 and width 9. Call `calculateArea()` for both objects.
class Rectangle {
int length;
int width;
void insert(int l, int w) {
length = l;
width = w;
}
void calculateArea() {
System.out.println(length * width);
}
}
public class TestRectangle2 {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(), r2 = new Rectangle();
r1.insert(8, 6);
r2.insert(5, 9);
r1.calculateArea();
r2.calculateArea();
}
}Write a Java program to simulate a simple bank account. Create a class `BankAccount` with fields for account number, account holder name, and balance. Include methods to initialize the account details, deposit an amount, withdraw an amount (with insufficient balance check), check the current balance, and display account details. In the main method, create an object of `BankAccount`, initialize it with account number 123456, name "Rahul", and balance 5000. Display the account details, check balance, deposit Rs. 20000, check balance, withdraw Rs. 8000, and check balance again.
class BankAccount {
int accNo;
String name;
double balance;
void insert(int a, String n, double bal) {
accNo = a;
name = n;
balance = bal;
}
void deposit(double amt) {
balance += amt;
System.out.println(amt + " deposited");
}
void withdraw(double amt) {
if (balance < amt) {
System.out.println("Insufficient Balance");
} else {
balance -= amt;
System.out.println(amt + " withdrawn");
}
}
void checkBalance() {
System.out.println("Balance is: " + balance);
}
void display() {
System.out.println(accNo + " " + name + " " + balance);
}
}
public class TestBankAccount {
public static void main(String[] args) {
BankAccount a1 = new BankAccount();
a1.insert(123456, "Rahul", 5000);
a1.display();
a1.checkBalance();
a1.deposit(20000);
a1.checkBalance();
a1.withdraw(8000);
a1.checkBalance();
}
}Write a Java program that creates a custom checked exception named InvalidRollNumberException. The class must extend Exception and have a constructor that accepts a String error message and passes it to the parent class using super(). Include a main method that throws this exception for a roll number less than 1, catches it, and prints the message.
class InvalidRollNumberException extends Exception {
public InvalidRollNumberException(String errorMessage) {
super(errorMessage);
}
}
public class TestRollNumber {
static void validateRoll(int roll) throws InvalidRollNumberException {
if (roll < 1) {
throw new InvalidRollNumberException("Roll number must be positive: " + roll);
}
System.out.println("Valid roll number: " + roll);
}
public static void main(String[] args) {
try {
validateRoll(23);
validateRoll(0);
} catch (InvalidRollNumberException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}Write a Java program that defines a custom checked exception named InvalidMarksException. Its constructor must accept a String error message and pass it to the parent Exception class using super(). Then write a small main method that throws this exception when a student's marks are below 0 or above 100, catches it, and prints the message.
class InvalidMarksException extends Exception {
public InvalidMarksException(String str) {
super(str);
}
}
public class TestMarksException {
static void checkMarks(int marks) throws InvalidMarksException {
if (marks < 0 || marks > 100) {
throw new InvalidMarksException("Marks must be between 0 and 100: " + marks);
}
System.out.println("Valid marks: " + marks);
}
public static void main(String[] args) {
try {
checkMarks(85);
checkMarks(120);
} catch (InvalidMarksException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}Write a Java program that defines a custom exception class named InvalidAgeException (extending Exception). In the main method, read an integer age from the user via Scanner. If the age is less than 18, throw an InvalidAgeException with the message "Not eligible to vote"; otherwise print "Eligible to vote". Handle the exception with try-catch and print the exception message.
import java.util.Scanner;
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}
public class AgeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
try {
if (age < 18) {
throw new InvalidAgeException("Not eligible to vote");
}
System.out.println("Eligible to vote");
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
}
sc.close();
}
}Write a Java program that demonstrates a NullPointerException when calling compareTo() on a null String reference. Declare a String variable named 'city' and initialize it to null. Then attempt to call compareTo("Delhi") on it and print the result. The program should compile and run, but will throw NullPointerException at runtime.public class NullCompareDemo {
public static void main(String[] args) {
String city = null;
// This will throw NullPointerException because city is null
int result = city.compareTo("Delhi");
System.out.println(result);
}
}Write a Java program that demonstrates ArrayIndexOutOfBoundsException. Create an integer array with elements {15, 25, 35, 45} and use a for loop that iterates from 0 to arr.length (inclusive). Inside the loop, print the array element. The program should compile and run, but it will throw ArrayIndexOutOfBoundsException when trying to access an index equal to the array length.public class ArrayExceptionDemo {
public static void main(String[] args) {
int[] arr = {15, 25, 35, 45};
for (int i = 0; i <= arr.length; i++) {
System.out.println(arr[i]);
}
}
}Write a Java program that demonstrates a ClassCastException when comparing incompatible types using compareTo(). Create a class 'Student' with a String name and a constructor. In the main method, create an ArrayList<String> and add "Rahul". Then attempt to cast the ArrayList to a String and call compareTo("Rahul") on it. This will throw ClassCastException at runtime.import java.util.*;
class Student {
private String name;
public Student(String name) {
this.name = name;
}
}
public class ClassCastDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Rahul");
// Attempt to cast ArrayList to String (via Object so it compiles)
String str = (String) (Object) list; // throws ClassCastException at runtime
int result = str.compareTo("Rahul");
System.out.println(result);
}
}Write a Java program: Example 2. Let's consider the following example. Here the try block within nested try block (inner try block 2) do not handle the exception. The control is then transferred to its parent try block (inner try block 1). If it does not handle the exception, then the control is transferred to the main try block (outer try block) where the appropriate catch block handles the exception. It is termed as nesting. NestedTryBlock.java
public class NestedTryBlock {
public static void main(String args[]) {
try {
try {
try {
int arr[] = { 10, 20, 30, 40 };
System.out.println(arr[6]);
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
} catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
} catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}Write a Java program that demonstrates handling a checked exception using a try-catch block. Create a class 'Resource' with a method 'access()' that throws an IOException with the message "Resource unavailable". In the main method, call this method inside a try-catch block that catches Exception and prints "Exception caught". After the try-catch, print "Program continues". The program should compile and run without terminating abnormally.
import java.io.*;
class Resource {
void access() throws IOException {
throw new IOException("Resource unavailable");
}
}
public class ExceptionDemo {
public static void main(String[] args) {
try {
Resource res = new Resource();
res.access();
} catch (Exception e) {
System.out.println("Exception caught");
}
System.out.println("Program continues");
}
}Write a Java program that demonstrates IllegalArgumentException. Create a class named PriorityDemo that extends Thread. In the main method, try to set the priority of the current (main) thread to 15 using Thread.currentThread().setPriority(15). Since valid thread priority ranges from 1 to 10, this call throws an IllegalArgumentException. Catch the exception and print the message "Invalid priority value caught". Also, before setting the priority, print the default priority of the main thread.
public class PriorityDemo extends Thread {
public static void main(String[] args) {
Thread t = Thread.currentThread();
System.out.println("Default priority of main thread: " + t.getPriority());
try {
t.setPriority(15);
} catch (IllegalArgumentException e) {
System.out.println("Invalid priority value caught");
}
System.out.println("Priority after attempt: " + t.getPriority());
}
}Write a Java program that declares an integer array of size 4, then inside a try block tries to print the element at index 7. Add three catch blocks in this order: ArithmeticException (print "Arithmetic problem"), ArrayIndexOutOfBoundsException (print "Index problem"), and Exception (print "General problem"). After the try-catch, print "program continues".
public class MultiCatchDemo {
public static void main(String[] args) {
try {
int marks[] = new int[4];
System.out.println(marks[7]);
} catch (ArithmeticException e) {
System.out.println("Arithmetic problem");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index problem");
} catch (Exception e) {
System.out.println("General problem");
}
System.out.println("program continues");
}
}Write a Java program that declares an integer array of size 3 and, inside a try block, executes the statement a[3] = 50 / 0;. Add catch blocks for ArithmeticException (print "Arithmetic Exception occurs"), ArrayIndexOutOfBoundsException (print "ArrayIndexOutOfBounds Exception occurs") and Exception (print "Parent Exception occurs"). After the try-catch, print "rest of the code".
public class MultiCatchDemo2 {
public static void main(String[] args) {
try {
int a[] = new int[3];
a[3] = 50 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}Write a Java program that demonstrates what happens when catch blocks are NOT ordered from most specific to most general. In the program, inside a try block declare an int array of size 4 and then execute the statement arr[4] = 50 / 0;. Add catch blocks in this order: first catch(Exception e) printing "general task done", then catch(ArithmeticException e) printing "division task done", then catch(ArrayIndexOutOfBoundsException e) printing "index task done". After the try-catch, print "remaining code...". (Note: the program will fail to compile because a more general exception is caught before more specific ones.)
class MultipleCatchOrderDemo {
public static void main(String args[]) {
try {
int arr[] = new int[4];
arr[4] = 50 / 0;
}
catch (Exception e) {
System.out.println("general task done");
}
catch (ArithmeticException e) {
System.out.println("division task done");
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("index task done");
}
System.out.println("remaining code...");
}
}Write a Java program to demonstrate the rule: If the superclass method does not declare an exception, the subclass overridden method cannot declare a checked exception. Create a superclass 'Vehicle' with a method 'display()' that prints "Vehicle method" and does not declare any exception. Then create a subclass 'Car' that overrides 'display()' but attempts to declare a checked exception 'IOException'. Show that this causes a compilation error. (Note: The program should illustrate the rule; you may comment out the erroneous code to show the correct version.)
import java.io.*;
class Vehicle {
void display() {
System.out.println("Vehicle method");
}
}
class Car extends Vehicle {
// Uncommenting the following line will cause a compilation error:
// void display() throws IOException {
// System.out.println("Car method");
// }
// Correct version without checked exception
void display() {
System.out.println("Car method");
}
}
public class TestExceptionChild {
public static void main(String[] args) {
Vehicle v = new Car();
v.display();
}
}Write a Java program to demonstrate that when a subclass overrides a method, it can declare the same exception as the superclass method. Create a class `Animal` with a method `sound()` that throws `Exception` and prints "Animal makes a sound". Then create a subclass `Dog` that overrides `sound()` to also throw `Exception` and prints "Dog barks". In the main method, create a `Dog` object and call `sound()` inside a try-catch block that catches `Exception` and prints "Caught: " followed by the exception message. Use appropriate exception messages.
class Animal {
void sound() throws Exception {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() throws Exception {
System.out.println("Dog barks");
throw new Exception("Dog is upset");
}
}
public class TestExceptionChild3 {
public static void main(String[] args) {
Dog d = new Dog();
try {
d.sound();
} catch (Exception e) {
System.out.println("Caught: " + e.getMessage());
}
}
}Write a Java program to demonstrate that when a subclass overrides a method, it can declare a subclass exception (a more specific checked exception) than the one declared by the superclass method. Create a class `Vehicle` with a method `start()` that throws `Exception` and prints "Vehicle started". Then create a subclass `Car` that overrides `start()` to throw `RuntimeException` (a subclass of Exception) and prints "Car started". In the main method, create a `Car` object and call `start()` inside a try-catch block that catches `Exception` and prints "Caught: " followed by the exception message. Use appropriate exception messages.
class Vehicle {
void start() throws Exception {
System.out.println("Vehicle started");
}
}
class Car extends Vehicle {
@Override
void start() throws RuntimeException {
System.out.println("Car started");
throw new RuntimeException("Car engine failed");
}
}
public class TestExceptionChild4 {
public static void main(String[] args) {
Car c = new Car();
try {
c.start();
} catch (Exception e) {
System.out.println("Caught: " + e.getMessage());
}
}
}Write a Java program named TryCatchFinallyDemo.java. Inside the try block, print "Inside try block" and then attempt to compute 40/0, printing the result. Catch the ArithmeticException, print "Exception handled" and then print the exception object. Add a finally block that prints "finally block always runs". After the try-catch-finally, print "remaining code executes".
public class TryCatchFinallyDemo {
public static void main(String args[]) {
try {
System.out.println("Inside try block");
int result = 40 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Exception handled");
System.out.println(e);
} finally {
System.out.println("finally block always runs");
}
System.out.println("remaining code executes");
}
}Write a Java program that demonstrates the case where an exception occurs inside a try block and is handled by the matching catch block, the finally block still executes, and then the rest of the program continues normally. In the try block, print "Entering try block" and then attempt to compute the value of 48 divided by 0 (store it in an int variable and print it). Catch ArithmeticException, print "Arithmetic exception caught" and print the exception object. In the finally block print "finally block runs always". After the try-catch-finally, print "remaining code executes...". Name the class FinallyDemoHandled.
public class FinallyDemoHandled {
public static void main(String args[]) {
try {
System.out.println("Entering try block");
int result = 48 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception caught");
System.out.println(e);
} finally {
System.out.println("finally block runs always");
}
System.out.println("remaining code executes...");
}
}Write a Java program that demonstrates the case where an exception occurs inside a try block but the catch block does NOT match the exception type, so the exception is not handled. In the try block, print "Entering try block" and then attempt to compute 36 divided by 0 (store it in an int variable and print it). Provide a catch block for NullPointerException that prints the exception object. Add a finally block that prints "finally block runs always". After the try-catch-finally, print "remaining code executes...". Name the class FinallyDemoUnhandled.
public class FinallyDemoUnhandled {
public static void main(String args[]) {
try {
System.out.println("Entering try block");
int result = 36 / 0;
System.out.println(result);
} catch (NullPointerException e) {
System.out.println(e);
} finally {
System.out.println("finally block runs always");
}
System.out.println("remaining code executes...");
}
}Write a Java program that creates a new file named "myNotes.txt" in the current directory. If the file is created successfully, print "File created successfully!"; otherwise, print "File already exists." Handle any IO exceptions by printing the exception message.
import java.io.*;
public class FileCreationDemo {
public static void main(String[] args) {
try {
File file = new File("myNotes.txt");
if (file.createNewFile()) {
System.out.println("File created successfully!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}Write a Java program that lists all file and directory names in the folder "C:\\Users\\Amit\\Documents" using the File class. The program should print each name on a new line.
import java.io.*;
public class FolderLister {
public static void main(String[] args) {
File folder = new File("C:\\Users\\Amit\\Documents");
String[] names = folder.list();
if (names != null) {
for (String name : names) {
System.out.println(name);
}
}
}
}Write a Java program that creates a new file named "myFile.txt" in the current directory, prints its path, then obtains its canonical file, checks if it exists, and prints the absolute path and existence status. Handle any exceptions.
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
try {
File file = new File("myFile.txt");
file.createNewFile();
System.out.println(file);
File canonicalFile = file.getCanonicalFile();
System.out.println(canonicalFile);
boolean exists = canonicalFile.exists();
String path = canonicalFile.getAbsolutePath();
System.out.println(exists);
if (exists) {
System.out.print(path + " Exists? " + exists);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}Write a Java program that demonstrates an instance initializer block. Create a class named `Train` with an integer field `coaches`. The instance initializer block should set `coaches` to 24 (simulating a computation before the constructor runs). The constructor should print "coaches is " followed by the value of `coaches`. In `main`, create two `Train` objects to show that the initializer block runs for each object.
class Train {
int coaches;
Train() {
System.out.println("coaches is " + coaches);
}
{
coaches = 24;
}
public static void main(String args[]) {
Train t1 = new Train();
Train t2 = new Train();
}
}Write a Java program with a class 'Bike' having an int field 'speed', a constructor that prints "constructor is invoked", and an instance initializer block that prints "instance initializer block invoked". In the main method, create two Bike objects. Show which runs first: the instance initializer block or the constructor.
class Bike {
int speed;
Bike() {
System.out.println("constructor is invoked");
}
{
System.out.println("instance initializer block invoked");
}
public static void main(String[] args) {
Bike b1 = new Bike();
Bike b2 = new Bike();
}
}Write a Java program with a parent class 'Vehicle' whose constructor prints "Vehicle constructor called", and a child class 'Car' that extends Vehicle. The Car class should have an instance initializer block that prints "Car initializer block called", and a constructor that calls super() and then prints "Car constructor called". In the main method, create one Car object. Show that the instance initializer block runs after the parent constructor (super()) but before the child constructor body completes.
class Vehicle {
Vehicle() {
System.out.println("Vehicle constructor called");
}
}
class Car extends Vehicle {
Car() {
super();
System.out.println("Car constructor called");
}
{
System.out.println("Car initializer block called");
}
public static void main(String[] args) {
Car c = new Car();
}
}Write a Java program that demonstrates an instance initializer block. Create a parent class P with a constructor that prints "parent constructor called" and an instance block that prints "parent instance block". Create a child class C that extends P, with an instance block printing "child instance block" and a constructor printing "child constructor called". In main, create one object of class C.
class P {
{
System.out.println("parent instance block");
}
P() {
System.out.println("parent constructor called");
}
}
class C extends P {
{
System.out.println("child instance block");
}
C() {
System.out.println("child constructor called");
}
}
public class InstanceBlockDemo {
public static void main(String args[]) {
new C();
}
}Write a Java program to demonstrate an interface with a single method. Create an interface named 'Greetable' with a method 'void greet()'. Implement this interface in a class named 'Greeter'. The greet() method should print "Namaste". In the main method, create an object of Greeter and call greet().
interface Greetable {
void greet();
}
class Greeter implements Greetable {
public void greet() {
System.out.println("Namaste");
}
public static void main(String[] args) {
Greeter obj = new Greeter();
obj.greet();
}
}Write a Java program that demonstrates an interface for shapes. Define an interface Shape with a single method void draw(). Create two classes, Square and Triangle, that implement Shape; Square's draw() prints "drawing square" and Triangle's draw() prints "drawing triangle". In the main method, create a Shape reference pointing to a Triangle object and call draw(). Name the file ShapeDemo.java.
interface Shape {
void draw();
}
class Square implements Shape {
public void draw() {
System.out.println("drawing square");
}
}
class Triangle implements Shape {
public void draw() {
System.out.println("drawing triangle");
}
}
class ShapeDemo {
public static void main(String[] args) {
Shape s = new Triangle();
s.draw();
}
}Write a Java program that demonstrates an interface for banks. Define an interface LoanBank with a method float interestRate(). Create two classes, HDFC and ICICI, that implement LoanBank and return interest rates of 8.5f and 9.25f respectively. In a main method, create a LoanBank reference pointing to an HDFC object and print "Rate: " followed by the interest rate. Name the file BankDemo.java.
interface LoanBank {
float interestRate();
}
class HDFC implements LoanBank {
public float interestRate() {
return 8.5f;
}
}
class ICICI implements LoanBank {
public float interestRate() {
return 9.25f;
}
}
class BankDemo {
public static void main(String[] args) {
LoanBank b = new HDFC();
System.out.println("Rate: " + b.interestRate());
}
}Write a Java program to demonstrate method overloading with type promotion when an exact match is found. Create a class named 'OverloadDemo' with two methods: 'calculate(int x, int y)' that prints "int method called" and 'calculate(long x, long y)' that prints "long method called". In the main method, create an object and call 'calculate(15, 25)'. What is the output?
class OverloadDemo {
void calculate(int x, int y) {
System.out.println("int method called");
}
void calculate(long x, long y) {
System.out.println("long method called");
}
public static void main(String[] args) {
OverloadDemo obj = new OverloadDemo();
obj.calculate(15, 25);
}
}Write a Java program that demonstrates overloading the main() method. Create a class named DemoMain with three overloaded main methods: one taking a String[] argument (prints "main with String[]"), one taking a single String argument (prints "main with String"), and one with no arguments (prints "main without args"). The JVM should invoke only the String[] version when the program runs.
public class DemoMain {
public static void main(String[] args) {
System.out.println("main with String[]");
}
public static void main(String args) {
System.out.println("main with String");
}
public static void main() {
System.out.println("main without args");
}
}Write a Java program to demonstrate method overloading with type promotion. Create a class named 'OverloadPromotion' with two methods: 'add(int a, long b)' that prints the sum a+b, and 'add(int a, int b, int c)' that prints the sum a+b+c. In the main method, create an object and call 'add(10, 20)' and 'add(10, 20, 30)'. What is the output?
class OverloadPromotion {
void add(int a, long b) {
System.out.println(a + b);
}
void add(int a, int b, int c) {
System.out.println(a + b + c);
}
public static void main(String[] args) {
OverloadPromotion obj = new OverloadPromotion();
obj.add(10, 20);
obj.add(10, 20, 30);
}
}Write a Java program to demonstrate method overriding. Create a superclass 'Shape' with a method 'draw()' that prints "Drawing shape". Create a subclass 'Circle' that overrides 'draw()' to print "Drawing circle". In the main method, create an instance of Circle and call draw().
class Shape {
void draw() {
System.out.println("Drawing shape");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing circle");
}
}
public class OverridingExample {
public static void main(String[] args) {
Circle c = new Circle();
c.draw();
}
}Write a Java program that demonstrates why method overriding is needed. Create a parent class named Appliance with a method start() that prints "Appliance is starting". Create a child class named Fan that extends Appliance but does NOT override start(). In the main method, create a Fan object and call start() on it. Show that the parent class version of the method runs even though the object is of the child class.
class Appliance {
void start() {
System.out.println("Appliance is starting");
}
}
class Fan extends Appliance {
public static void main(String[] args) {
Fan obj = new Fan();
obj.start();
}
}Write a Java program to illustrate method overriding. Create a parent class Vehicle with a method run() that prints "Vehicle is running". Create a child class Car that extends Vehicle and overrides run() to print "Car is running safely". In the main method, create a Car object and call run().
class Vehicle {
void run() { System.out.println("Vehicle is running"); }
}
class Car extends Vehicle {
void run() { System.out.println("Car is running safely"); }
public static void main(String[] args) {
Car obj = new Car();
obj.run();
}
}Write a Java program that demonstrates method overriding in a real banking scenario. Create a parent class Bank with a method getRateOfInterest() that returns 0. Create three child classes — HDFC, PNB and BOI — that each override getRateOfInterest() to return 6, 7 and 8 respectively. In the main method, create one object of each child class and print the rate of interest of each bank.
class Bank {
int getRateOfInterest() { return 0; }
}
class HDFC extends Bank {
int getRateOfInterest() { return 6; }
}
class PNB extends Bank {
int getRateOfInterest() { return 7; }
}
class BOI extends Bank {
int getRateOfInterest() { return 8; }
}
public class BankDemo {
public static void main(String[] args) {
Bank b1 = new HDFC();
Bank b2 = new PNB();
Bank b3 = new BOI();
System.out.println("HDFC rate of interest: " + b1.getRateOfInterest());
System.out.println("PNB rate of interest: " + b2.getRateOfInterest());
System.out.println("BOI rate of interest: " + b3.getRateOfInterest());
}
}Write a Java program that demonstrates a nested interface. Define an outer interface called 'Shape' with a method 'draw()' and a nested interface 'Details' with a method 'info()'. Create a class 'Circle' that implements both interfaces. In the main method, create a Circle object, call draw() and info(), and also demonstrate that the nested interface can be implemented separately by creating an anonymous class that implements Shape.Details and calls info().
interface Shape {
void draw();
interface Details {
void info();
}
}
class Circle implements Shape, Shape.Details {
public void draw() {
System.out.println("Drawing a circle");
}
public void info() {
System.out.println("Circle details: radius = 5");
}
}
public class NestedInterfaceDemo {
public static void main(String[] args) {
Circle c = new Circle();
c.draw();
c.info();
Shape.Details d = new Shape.Details() {
public void info() {
System.out.println("Anonymous details");
}
};
d.info();
}
}Write a Java program that demonstrates a nested interface declared inside another interface. Define an interface 'Showable' with a method 'show()' and a nested interface 'Message' with a method 'msg()'. Then create a class 'NestedInterfaceDemo' that implements 'Showable.Message' and provides an implementation of 'msg()' that prints "Hello from nested interface!". In the main method, create an instance of 'NestedInterfaceDemo' and call 'msg()'.
interface Showable {
void show();
interface Message {
void msg();
}
}
class NestedInterfaceDemo implements Showable.Message {
public void msg() {
System.out.println("Hello from nested interface!");
}
public static void main(String[] args) {
NestedInterfaceDemo obj = new NestedInterfaceDemo();
obj.msg();
}
}Write a Java program that demonstrates a nested interface declared inside a class. Define a class 'Outer' that contains an interface 'Greetable' with a method 'greet()'. Then create another class 'GreetingDemo' that implements 'Outer.Greetable' and provides an implementation of 'greet()' that prints "Namaste from nested interface!". In the main method, create an instance of 'GreetingDemo' and call 'greet()'.
class Outer {
interface Greetable {
void greet();
}
}
class GreetingDemo implements Outer.Greetable {
public void greet() {
System.out.println("Namaste from nested interface!");
}
}
public class NestedInterfaceDemo {
public static void main(String[] args) {
GreetingDemo demo = new GreetingDemo();
demo.greet();
}
}Write a Java program that demonstrates infinite recursion by defining a recursive method that prints "Ram Ram" and then calls itself indefinitely. Include a main method that invokes this recursive method.
public class InfiniteRecursion {
static void chant() {
System.out.println("Ram Ram");
chant();
}
public static void main(String[] args) {
chant();
}
}Write a Java program that uses recursion to print the message "Namaste" exactly 4 times, each time followed by the count number (e.g., "Namaste 1", "Namaste 2", etc.). Use a static counter variable to limit the recursion.
public class RecursionCount {
static int count = 0;
static void greet() {
count++;
if (count <= 4) {
System.out.println("Namaste " + count);
greet();
}
}
public static void main(String[] args) {
greet();
}
}Write a Java program that computes the factorial of 7 using a recursive method and prints the result.
public class FactorialRecursion {
static int factorial(int n) {
if (n == 1)
return 1;
else
return (n * factorial(n - 1));
}
public static void main(String[] args) {
System.out.println("Factorial of 7 is: " + factorial(7));
}
}Write a Java program that prints the first 12 terms of the Fibonacci series using recursion. The series starts with 0 and 1.
public class FibonacciRecursion {
static int a = 0, b = 1, c = 0;
static void printFibo(int count) {
if (count > 0) {
c = a + b;
a = b;
b = c;
System.out.print(" " + c);
printFibo(count - 1);
}
}
public static void main(String[] args) {
int count = 12;
System.out.print(a + " " + b);
printFibo(count - 2);
}
}Write a Java program to demonstrate runtime polymorphism. Create a class Vehicle with a method move() that prints "Vehicle is moving". Create a subclass Car that extends Vehicle and overrides move() to print "Car is driving on the road". In the main method, create an object of Car and assign it to a Vehicle reference. Call move() using that reference. What is the output?
class Vehicle {
void move() {
System.out.println("Vehicle is moving");
}
}
class Car extends Vehicle {
@Override
void move() {
System.out.println("Car is driving on the road");
}
public static void main(String[] args) {
Vehicle v = new Car(); // upcasting
v.move();
}
}Write a Java program that demonstrates runtime polymorphism using a base class 'Bank' with a method 'getRateOfInterest()' and subclasses 'HDFC', 'Kotak', and 'PNB' that override the method to return different interest rates: HDFC gives 7.5%, Kotak gives 6.8%, and PNB gives 8.2%. In the main method, create a 'Bank' reference and assign it to each subclass object, then print the rate of interest for each bank. The output should be: HDFC Rate of Interest: 7.5 Kotak Rate of Interest: 6.8 PNB Rate of Interest: 8.2
class Bank {
float getRateOfInterest() {
return 0;
}
}
class HDFC extends Bank {
float getRateOfInterest() {
return 7.5f;
}
}
class Kotak extends Bank {
float getRateOfInterest() {
return 6.8f;
}
}
class PNB extends Bank {
float getRateOfInterest() {
return 8.2f;
}
}
public class TestPolymorphism {
public static void main(String[] args) {
Bank b;
b = new HDFC();
System.out.println("HDFC Rate of Interest: " + b.getRateOfInterest());
b = new Kotak();
System.out.println("Kotak Rate of Interest: " + b.getRateOfInterest());
b = new PNB();
System.out.println("PNB Rate of Interest: " + b.getRateOfInterest());
}
}Write a Java program that demonstrates runtime polymorphism using a base class 'Vehicle' with a method 'move()' and subclasses 'Car', 'Bike', and 'Truck' that override 'move()'. In the main method, create a 'Vehicle' reference and assign it to each subclass object, then call 'move()' on each. The output should be: Car is moving Bike is moving Truck is moving
class Vehicle {
void move() {
System.out.println("Vehicle is moving");
}
}
class Car extends Vehicle {
void move() {
System.out.println("Car is moving");
}
}
class Bike extends Vehicle {
void move() {
System.out.println("Bike is moving");
}
}
class Truck extends Vehicle {
void move() {
System.out.println("Truck is moving");
}
}
public class TestPolymorphism {
public static void main(String[] args) {
Vehicle v;
v = new Car();
v.move();
v = new Bike();
v.move();
v = new Truck();
v.move();
}
}Write a Java program that demonstrates runtime polymorphism with multilevel inheritance. Create a class LivingThing with a method breathe() that prints "LivingThing breathes". Create a class Plant that extends LivingThing and overrides breathe() to print "Plant breathes through leaves". Create a class Tree that extends Plant and overrides breathe() to print "Tree breathes through roots". In the main method of Tree, create three references: LivingThing l1 = new LivingThing(); LivingThing l2 = new Plant(); LivingThing l3 = new Tree(); then call breathe() on each. What is the output?
class LivingThing {
void breathe() {
System.out.println("LivingThing breathes");
}
}
class Plant extends LivingThing {
void breathe() {
System.out.println("Plant breathes through leaves");
}
}
class Tree extends Plant {
void breathe() {
System.out.println("Tree breathes through roots");
}
public static void main(String[] args) {
LivingThing l1 = new LivingThing();
LivingThing l2 = new Plant();
LivingThing l3 = new Tree();
l1.breathe();
l2.breathe();
l3.breathe();
}
}Write a Java program that demonstrates runtime polymorphism with multilevel inheritance. Create a class Vehicle with a method move() that prints "Vehicle is moving". Create a class Car that extends Vehicle and overrides move() to print "Car is driving". Create a class SportsCar that extends Car. In the main method of SportsCar, create a Vehicle reference pointing to a SportsCar object and call move(). What is the output?
class Vehicle {
void move() {
System.out.println("Vehicle is moving");
}
}
class Car extends Vehicle {
void move() {
System.out.println("Car is driving");
}
}
class SportsCar extends Car {
public static void main(String[] args) {
Vehicle v = new SportsCar();
v.move();
}
}Write a Java program that shows the memory advantage of a static variable. Create a class named Learner with fields: int id, String fullName, and a static String institute set to "Sunrise Academy". In the main method, create two Learner objects (id 101 with name "Aarav", and id 102 with name "Diya"), assign only id and fullName for each, and print each learner's id, fullName and institute. The institute value must be stored once as a static field shared by all objects.
class Learner {
int id;
String fullName;
static String institute = "Sunrise Academy";
public static void main(String[] args) {
Learner l1 = new Learner();
l1.id = 101;
l1.fullName = "Aarav";
Learner l2 = new Learner();
l2.id = 102;
l2.fullName = "Diya";
System.out.println(l1.id + " " + l1.fullName + " " + Learner.institute);
System.out.println(l2.id + " " + l2.fullName + " " + Learner.institute);
}
}Write a Java program to demonstrate a static variable. Create a class named Learner with an instance variable rollNo, an instance variable name, and a static variable instituteName set to "Sunrise Academy". The constructor should take rollNo and name as parameters. Add a display() method that prints rollNo, name and instituteName. In the main method, create two Learner objects: (101, "Rohit") and (102, "Meera"), then call display() on both. Show that the single static variable is shared by all objects.
class Learner {
int rollNo; // instance variable
String name; // instance variable
static String instituteName = "Sunrise Academy"; // static variable, shared by all objects
Learner(int r, String n) {
rollNo = r;
name = n;
}
void display() {
System.out.println(rollNo + " " + name + " " + instituteName);
}
}
public class TestStaticVariable {
public static void main(String args[]) {
Learner l1 = new Learner(101, "Rohit");
Learner l2 = new Learner(102, "Meera");
l1.display();
l2.display();
}
}Write a Java program that uses a static variable as a counter. Create a class named Visitor with a static int field total initialized to 0. In the constructor, increment total and print its value. In the main method, create three Visitor objects one after another and show that the counter retains its value across objects.
class Visitor {
static int total = 0;
Visitor() {
total++;
System.out.println(total);
}
public static void main(String[] args) {
Visitor v1 = new Visitor();
Visitor v2 = new Visitor();
Visitor v3 = new Visitor();
}
}Write a Java program named StringBlankCheckExample.java that demonstrates the String isEmpty() method. Create two strings: one empty string and one containing the text "chennai". Print the result of calling isEmpty() on each string.
public class StringBlankCheckExample {
public static void main(String[] args) {
String s1 = "";
String s2 = "chennai";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}
}Write a Java program that checks whether a string starts with an empty string. Use the string "New Delhi" and the startsWith method. If it does, print "The string starts with the empty string." otherwise print "The string does not start with the empty string."
public class StartsWithExample {
public static void main(String[] args) {
String str = "New Delhi";
if (str.startsWith("")) {
System.out.println("The string starts with the empty string.");
} else {
System.out.println("The string does not start with the empty string.");
}
}
}Write a Java program that stores the string "namaste duniya" in a variable, converts it to uppercase using the toUpperCase() method, and prints the result.
public class UpperDemo {
public static void main(String[] args) {
String s = "namaste duniya";
String upper = s.toUpperCase();
System.out.println(upper);
}
}Write a Java program that demonstrates the String trim() method. Create a class named TrimDemo.java. In main(), declare a String s = " namaste india ". First print s concatenated with "welcome" (without trim), then print s.trim() concatenated with "welcome" (with trim).
public class TrimDemo {
public static void main(String[] args) {
String s = " namaste india ";
System.out.println(s + "welcome");
System.out.println(s.trim() + "welcome");
}
}Write a Java program to demonstrate the behavior of compareTo() when one of the strings is empty. Create three strings: s1 = "Java", s2 = "", and s3 = "Programming". Print the results of s1.compareTo(s2) and s2.compareTo(s3). Observe that comparing with an empty string returns the length of the non-empty string (with sign depending on order). Name the file EmptyStringCompare.java.
public class EmptyStringCompare {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "";
String s3 = "Programming";
System.out.println(s1.compareTo(s2));
System.out.println(s2.compareTo(s3));
}
}Write a Java program to check whether the compareTo() method is case-sensitive. Create two strings: one in uppercase and one in lowercase, both containing the same letters in the same order. Compare them using compareTo() and print the result. If the output is 0, the method is not case-sensitive; otherwise, it is case-sensitive. Name the file CaseSensitiveCompare.java.
public class CaseSensitiveCompare {
public static void main(String[] args) {
String str1 = "WELCOME TO INDIA";
String str2 = "welcome to india";
System.out.println(str1.compareTo(str2));
}
}Write a Java program: Java String contains() Method Example. FileName: ContainsExample.java
public class ContainsExample {
public static void main(String[] args) {
String sentence = "India is a beautiful country";
System.out.println(sentence.contains("is a"));
System.out.println(sentence.contains("beautiful"));
System.out.println(sentence.contains("hello"));
}
}Write a Java program that demonstrates the String toUpperCase() and toLowerCase() methods. Create a String variable holding the name "Rohit", print its uppercase form, then its lowercase form, and finally print the original string to show it is unchanged.
public class StringCaseDemo
{
public static void main(String[] args)
{
String name = "Rohit";
System.out.println(name.toUpperCase()); // ROHIT
System.out.println(name.toLowerCase()); // rohit
System.out.println(name); // Rohit (original unchanged)
}
}Write a Java program that demonstrates the charAt() method. Create a String variable named 'city' and initialize it with "Mumbai". Use charAt() to retrieve the character at index 3 and print it. Also, demonstrate that accessing an invalid index throws StringIndexOutOfBoundsException by attempting to access index 10 inside a try-catch block and printing an appropriate message.
public class CharAtDemo {
public static void main(String[] args) {
String city = "Mumbai";
char ch = city.charAt(3);
System.out.println(ch);
try {
char invalid = city.charAt(10);
System.out.println(invalid);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Index out of bounds: " + e.getMessage());
}
}
}Write a Java program that prints the first and last characters of a string using the charAt() method. Use the string "Bharat is my country" and print the first character as: Character at 0 index is: <char> and the last character as: Character at last index is: <char>. Save the program in a file named FirstLastChar.java.
public class FirstLastChar {
public static void main(String[] args) {
String str = "Bharat is my country";
int strLength = str.length();
System.out.println("Character at 0 index is: " + str.charAt(0));
System.out.println("Character at last index is: " + str.charAt(strLength - 1));
}
}Write a Java program that prints the characters located at odd indices of a string using the charAt() method. Use the string "India is a great nation" and print each odd-index character in the format: Char at <index> place <character>. Save the program in a file named OddIndexChars.java.
public class OddIndexChars {
public static void main(String[] args) {
String str = "India is a great nation";
for (int i = 0; i <= str.length() - 1; i++) {
if (i % 2 != 0) {
System.out.println("Char at " + i + " place " + str.charAt(i));
}
}
}
}Write a Java program that demonstrates the String concat() method by joining multiple string objects. Create three strings: "Namaste", "Bharat", and "Readers". First concatenate the first two strings and print the result. Then concatenate all three strings in a chain and print that result. Name the class ConcatDemo.
public class ConcatDemo {
public static void main(String[] args) {
String str1 = "Namaste";
String str2 = "Bharat";
String str3 = "Readers";
// Concatenating two strings
String str4 = str1.concat(str2);
System.out.println(str4);
// Concatenating multiple strings in a chain
String str5 = str1.concat(str2).concat(str3);
System.out.println(str5);
}
}Write a Java program that uses the concat() method to add a string at the beginning of another string. Create a string variable holding "Festival", then build a new string by calling concat() on the literal "Diwali is my " with the variable as argument, and print the result. Name the class ConcatBeginning.
public class ConcatBeginning
{
public static void main(String[] args)
{
String str = "Festival";
String s = "Diwali is my ".concat(str);
System.out.println(s);
}
}Write a Java program that demonstrates string concatenation using the concat() method. Create two strings, "Rohit " and "Sharma", join them with concat(), and print the result.
class TestConcatMethod {
public static void main(String args[]) {
String s1 = "Rohit ";
String s2 = "Sharma";
String s3 = s1.concat(s2);
System.out.println(s3);
}
}Write a Java program that demonstrates comparing strings by content using the equals() method. Create four strings: s1 = "Rohit", s2 = "Rohit", s3 = new String("Rohit"), and s4 = "Kiran". Print the results of s1.equals(s2), s1.equals(s3), and s1.equals(s4) on separate lines.public class StringEqualsDemo {
public static void main(String[] args) {
String s1 = "Rohit";
String s2 = "Rohit";
String s3 = new String("Rohit");
String s4 = "Kiran";
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
}
}Write a Java program that checks if a specific string is present in an ArrayList of strings using the equals() method. The list should contain: "Amit", "Priya", "Rahul", "Sneha". The string to search for is "Priya". If found, print "Priya is present".
import java.util.ArrayList;
public class EqualsExample3 {
public static void main(String[] args) {
String str1 = "Priya";
ArrayList<String> list = new ArrayList<>();
list.add("Amit");
list.add("Priya");
list.add("Rahul");
list.add("Sneha");
for (String str : list) {
if (str.equals(str1)) {
System.out.println("Priya is present");
}
}
}
}Write a Java program that demonstrates the equals() method by comparing strings with objects of different types (Character, Integer, Double, Boolean) and then converting those objects to strings to show equality. Use the following values: String str = "b"; String str1 = "456"; String str2 = "78.12"; String str3 = "true"; Character c = new Character('b'); Integer i = new Integer(456); Double d = new Double(78.12); Boolean b = new Boolean(true). Print the results of str.equals(c), str1.equals(i), str2.equals(d), str3.equals(b), and then print the results after converting c, i, d, and b to strings using toString().public class EqualsExample4 {
public static void main(String[] args) {
String str = "b";
String str1 = "456";
String str2 = "78.12";
String str3 = "true";
Character c = new Character('b');
Integer i = new Integer(456);
Double d = new Double(78.12);
Boolean b = new Boolean(true);
System.out.println(str.equals(c));
System.out.println(str1.equals(i));
System.out.println(str2.equals(d));
System.out.println(str3.equals(b));
System.out.println(str.equals(c.toString()));
System.out.println(str1.equals(i.toString()));
System.out.println(str2.equals(d.toString()));
System.out.println(str3.equals(b.toString()));
}
}Write a Java program that uses the String length() method. Create two strings: one holding "hyderabad" and another holding "java". Print "string length is: " followed by the length of the first string, and then print "string length is: " followed by the length of the second string. Name the file LengthDemo.java.
public class LengthDemo {
public static void main(String args[]) {
String s1 = "hyderabad";
String s2 = "java";
System.out.println("string length is: " + s1.length());
System.out.println("string length is: " + s2.length());
}
}Write a Java program that uses the String length() method to check whether a string is empty or not. Create a string variable holding the value "Bengaluru", and if its length is greater than 0, print "String is not empty and length is: " followed by its length. Then reassign the same variable to an empty string "", and if its length equals 0, print "String is empty now: " followed by its length. Name the file EmptyCheck.java.
public class EmptyCheck {
public static void main(String[] args) {
String city = "Bengaluru";
if (city.length() > 0) {
System.out.println("String is not empty and length is: " + city.length());
}
city = "";
if (city.length() == 0) {
System.out.println("String is empty now: " + city.length());
}
}
}Write a Java program that stores the name of an Indian city in a String variable and prints the number of characters in it using the String length() method. Use the city name "Chennai". The class should be named CityNameLength.
public class CityNameLength
{
public static void main(String[] args)
{
String city = "Chennai";
System.out.println(city.length());
}
}Write a Java program that demonstrates returning 'this' from a method. Create a class named Greeter with a method getGreeter() that returns 'this', and a method greet() that prints "Namaste India". In main(), call new Greeter().getGreeter().greet() so the message is printed.
class Greeter {
Greeter getGreeter() {
return this;
}
void greet() {
System.out.println("Namaste India");
}
}
class MainTest {
public static void main(String args[]) {
new Greeter().getGreeter().greet();
}
}Write a Java program that proves the 'this' keyword refers to the current class instance. Create a class named Student with a method show() that prints 'this'. In main(), create a Student object, print the object reference, then call show(). Both printed values must be the same reference ID.
class Student {
void show() {
System.out.println(this); // prints the same reference ID
}
public static void main(String args[]) {
Student s = new Student();
System.out.println(s); // prints the reference ID
s.show();
}
}Write a Java program that stores a bank account holder's account number, name and balance using a constructor, where the constructor parameters have the SAME names as the instance variables, so the 'this' keyword must be used to resolve the shadowing. Print the details using a display() method.
class Account {
long accNo;
String holderName;
double balance;
Account(long accNo, String holderName, double balance) {
this.accNo = accNo;
this.holderName = holderName;
this.balance = balance;
}
void display() {
System.out.println(accNo + " " + holderName + " " + balance);
}
public static void main(String[] args) {
Account a = new Account(20231001L, "Meera", 7500.50);
a.display();
}
}
Write a Java program that stores an employee's ID, name and salary using a constructor, where the constructor parameters have DIFFERENT names from the instance variables, so the 'this' keyword is not required. Print the details using a display() method.
class Employee {
int empId;
String empName;
double salary;
Employee(int id, String nm, double sal) {
empId = id;
empName = nm;
salary = sal;
}
void display() {
System.out.println(empId + " " + empName + " " + salary);
}
public static void main(String[] args) {
Employee e = new Employee(101, "Ravi", 45000.0);
e.display();
}
}
Write a Java program that demonstrates the interrupt() method. Create a thread that sleeps for 5 milliseconds in a loop 100 times, and catch InterruptedException to print a message. After the loop, print the thread name and that it has finished executing. Use a custom thread class named MyThread that extends Thread and starts in its constructor. The thread should be part of a ThreadGroup named 'GroupA'. After starting the thread, interrupt it from the main thread after a short delay. FileName: InterruptDemo.java
public class InterruptDemo {
public static void main(String[] args) {
ThreadGroup group = new ThreadGroup("GroupA");
MyThread t = new MyThread("Worker", group);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.interrupt();
}
}
class MyThread extends Thread {
MyThread(String name, ThreadGroup group) {
super(group, name);
start();
}
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught: " + e);
}
}
System.out.println(Thread.currentThread().getName() + " thread has finished executing");
}
}Write a Java program that demonstrates interrupting a thread which is sleeping. The thread should sleep for 1500 milliseconds and then print "work done". In the main method, start the thread and immediately interrupt it. Inside the run method, catch the InterruptedException and rethrow it as a RuntimeException with the message "Thread was interrupted: " followed by the exception. The program should compile and run, showing the propagated exception.
class InterruptDemo extends Thread {
public void run() {
try {
Thread.sleep(1500);
System.out.println("work done");
} catch (InterruptedException e) {
throw new RuntimeException("Thread was interrupted: " + e);
}
}
public static void main(String[] args) {
InterruptDemo t = new InterruptDemo();
t.start();
try {
t.interrupt();
} catch (Exception e) {
System.out.println("Exception handled " + e);
}
}
}Write a Java program that demonstrates interrupting a thread which does NOT stop working. In run(), the thread calls Thread.sleep(1500) and then prints "work done". If an InterruptedException occurs, catch it and print "Interrupted caught: " followed by the exception. After the try-catch, always print "thread continues running". In main, start the thread and immediately call interrupt() on it. Name the class HandleInterruptDemo.
class HandleInterruptDemo extends Thread {
public void run() {
try {
Thread.sleep(1500);
System.out.println("work done");
} catch (InterruptedException e) {
System.out.println("Interrupted caught: " + e);
}
System.out.println("thread continues running");
}
public static void main(String args[]) {
HandleInterruptDemo t1 = new HandleInterruptDemo();
t1.start();
t1.interrupt();
}
}Write a Java program that demonstrates interrupting a thread which is NOT in sleeping or waiting state. The thread should print the numbers 1 to 4 in its run() method. In main, start the thread and immediately call interrupt() on it. Since the thread is not sleeping or waiting, the interrupt only sets the interrupted flag to true (it does not throw an exception), and the thread continues printing normally. Name the class FlagInterruptDemo.
class FlagInterruptDemo extends Thread {
public void run() {
for (int i = 1; i <= 4; i++) {
System.out.println(i);
}
}
public static void main(String args[]) {
FlagInterruptDemo t1 = new FlagInterruptDemo();
t1.start();
t1.interrupt();
}
}Write a Java program that demonstrates a final variable. Declare a final integer variable called 'marks' initialized to 72 inside a class 'FinalMarksDemo'. Write a method 'update()' that attempts to reassign marks to 90 (this should cause a compile-time error, so keep it commented out with a note). In main, create an object and print the value of marks.
public class FinalMarksDemo {
// declaring final variable
final int marks = 72;
void update() {
// reassigning value to marks variable
// gives compile time error
// marks = 90;
System.out.println("Marks: " + marks);
}
public static void main(String[] args) {
FinalMarksDemo obj = new FinalMarksDemo();
obj.update();
}
}Write a Java program that demonstrates a final variable. Declare a final int variable named maxMarks with value 80 inside a class named Student. In a method called update(), try to assign 95 to maxMarks. Create an object of Student in main and call update(). (The program will fail to compile because a final variable cannot be reassigned.)
class Student {
final int maxMarks = 80; // final variable
void update() {
maxMarks = 95; // compile-time error: cannot assign a value to final variable
}
public static void main(String args[]) {
Student obj = new Student();
obj.update();
}
}Write a Java program that creates the String str = "Learning Java is fun!", creates a char array of size 30, and sets srcBeginIndex = 9, srcEndIndex = 9, dstBeginIndex = 3. It calls str.getChars(srcBeginIndex, srcEndIndex, chArr, dstBeginIndex) inside a try-catch, prints the char array, and then prints the line "The getChars() method prints nothing as start and end indices are equal."
public class StringGetCharsDemo {
public static void main(String[] args) {
String str = "Learning Java is fun!";
char[] chArr = new char[30];
int srcBeginIndex = 9;
int srcEndIndex = 9;
int dstBeginIndex = 3;
try {
str.getChars(srcBeginIndex, srcEndIndex, chArr, dstBeginIndex);
System.out.println(chArr);
} catch (Exception excpn) {
System.out.println(excpn);
}
System.out.println("The getChars() method prints nothing as start and end indices are equal.");
}
}Write a Java program to demonstrate that an instance variable is NOT shared between objects. Create a class named Ticket with an instance variable named serial initialized to 0. In the constructor, increment serial and print it. In the main method, create three Ticket objects one after another. Show that each object prints 1, because each object gets its own copy of the instance variable.
class Ticket {
int serial = 0; // instance variable: new memory for every object
Ticket() {
serial++; // increments only this object's copy
System.out.println(serial);
}
public static void main(String args[]) {
Ticket t1 = new Ticket();
Ticket t2 = new Ticket();
Ticket t3 = new Ticket();
}
}Write a Java program that demonstrates the use of a static method. Create a class named Employee with fields empId (int) and empName (String), and a static field company set to "Sunrise Tech". Add a static method changeCompany() that sets company to "Sunrise Infotech". Add a constructor to initialize empId and empName, and a display() method that prints empId, empName and company. In the main method, call Employee.changeCompany() without creating an object, then create three Employee objects (101, "Ravi"; 102, "Meera"; 103, "Anil") and call display() on each.
class Employee {
int empId;
String empName;
static String company = "Sunrise Tech";
static void changeCompany() {
company = "Sunrise Infotech";
}
Employee(int id, String name) {
empId = id;
empName = name;
}
void display() {
System.out.println(empId + " " + empName + " " + company);
}
}
public class TestStaticMethod {
public static void main(String[] args) {
Employee.changeCompany();
Employee e1 = new Employee(101, "Ravi");
Employee e2 = new Employee(102, "Meera");
Employee e3 = new Employee(103, "Anil");
e1.display();
e2.display();
e3.display();
}
}Write a Java program named Greeter.java that demonstrates a static method. The program should have a main method that calls a static method named greet() without creating any object of the class. The greet() method should print the line: Hello from a static method!
public class Greeter {
public static void main(String[] args) {
greet();
}
static void greet() {
System.out.println("Hello from a static method!");
}
}Write a Java program that uses a static method to compute the square of a given number. The static method square(int x) should return x*x, and main should call it for the number 7 and print the result.
class Calculator {
static int square(int x) {
return x * x;
}
public static void main(String[] args) {
int result = Calculator.square(7);
System.out.println(result);
}
}Write a Java program with a class named Shop that has a static block printing "Shop class loaded" and a main method printing "Welcome to the shop". Show that the static block runs before the main method.
public class Shop {
static {
System.out.println("Shop class loaded");
}
public static void main(String[] args) {
System.out.println("Welcome to the shop");
}
}Write a Java program that demonstrates that references have a type. Declare a variable of a primitive type int named marks and assign it the value 45. Then declare a reference variable of type Student named s1 (do not assign an object to it). Print the value of marks and print whether s1 is null.
class Student {
}
class Main {
public static void main(String[] args) {
int marks = 45;
Student s1;
System.out.println("Marks: " + marks);
s1 = null;
System.out.println("Is s1 null? " + (s1 == null));
}
}Write a Java program that demonstrates that an object has a type: an object is an instance of a particular Java class, but it is also an instance of its superclass. Create a superclass Vehicle and a subclass Car that extends Vehicle. In the main method, create a Car object and assign it to a Vehicle reference. Use the instanceof operator to check whether the object is an instance of Car and also an instance of Vehicle, and print the results.
class Vehicle {
}
class Car extends Vehicle {
public static void main(String[] args) {
Vehicle v = new Car();
System.out.println("Is the object an instance of Car? " + (v instanceof Car));
System.out.println("Is the object an instance of Vehicle? " + (v instanceof Vehicle));
}
}Write a Java program that demonstrates static binding (early binding). Create a class Fan with a private method spin() that prints "Fan is spinning...". In main, create a Fan object and call spin() from within the class so that the compiler fixes the method call at compile time.
class Fan {
private void spin() {
System.out.println("Fan is spinning...");
}
public static void main(String[] args) {
Fan f = new Fan();
f.spin();
}
}Write a Java program that demonstrates dynamic binding (late binding). Create a base class Vehicle with a method start() that prints "Vehicle is starting...", and a subclass Car that overrides start() to print "Car is starting with a key...". In main, assign a Car object to a Vehicle reference and call start() to show that the method is resolved at run-time.
class Vehicle {
void start() {
System.out.println("Vehicle is starting...");
}
}
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car is starting with a key...");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Car();
v.start();
}
}INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India
contact@intmatedtech.com