Java_Questions_Answers
Java_Questions_Answers
int → 0
boolean → false
Create a simple class Book with two fields: title and author.
class Book {
String title;
String author;
}
What is inheritance?
Inheritance allows a class to inherit properties and methods from another class.
Integer: 10
Character: 'A'
String: "Hello"
int n = 5;
if (n % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
Write a program using switch to display day names (1=Monday, ..., 7=Sunday).
int day = 3;
switch(day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
// ...
default: System.out.println("Invalid");
}
class Calculator {
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
}
class Student {
String name;
int age;
Student() { }
Student(String n) { name = n; }
Student(String n, int a) { name = n; age = a; }
}
class A {
A() { System.out.println("A’s constructor"); }
}
class B extends A {
B() {
super();
System.out.println("B’s constructor");
}
}
class A { }
class B extends A { }
class C extends B { }
Tough Level
Create an abstract class Shape and implement it in Circle and Rectangle.
class A {
final void display() { System.out.println("Hello"); }
}
class B extends A {
// void display() {} // Error
}
Explain object reference assignment and how changes affect objects.
Used for cleanup before object is garbage collected. Deprecated due to unpredictable
behavior.
class A {
void show() { System.out.println("From A"); }
}
class B extends A {
void show() { System.out.println("From B"); }
}
A obj = new B();
obj.show();
Explain how memory leaks can occur even with garbage collection.
If objects are still referenced (e.g., in static lists) but no longer used, they won't be collected.