Q1) Write a short note on default constructor with an example
Answer:
A default constructor is a no-argument constructor that initializes a new object with
default values.
If you do not write any constructor in a class, the Java compiler inserts a default (no-
arg) constructor automatically.
As soon as you declare any constructor (even parameterized), the compiler does not
generate the default one.
Default values given by the JVM: numeric types → 0, 0.0; char → '\u0000'; boolean →
false; object references → null.
Example:
class Student {
int id; // 0
String name; // null
// No constructor written → compiler provides default no-arg constructor
}
public class Demo {
public static void main(String[] args) {
Student s = new Student(); // calls compiler-generated default constructor
System.out.println(s.id); // 0
System.out.println(s.name); // null
}
}
Key points: no parameters, auto-generated only when none is written, sets fields to default
JVM values.
Q2) Explain Hybrid Inheritance in detail
Answer:
Hybrid inheritance is a combination of two or more basic types of inheritance
(single, multilevel, hierarchical).
Java does not support multiple inheritance of classes (to avoid ambiguity), but it
does support hybrid patterns using interfaces.
Typical hybrid shape in Java:
Classes use single/multilevel/hierarchical inheritance.
Interfaces add the multiple inheritance part (a class can implement multiple
interfaces).
Diagram (conceptual):
BaseClass → SubClass (single/multilevel) + InterfaceA, InterfaceB → SubClass implements
InterfaceA, InterfaceB (multiple via interfaces).
Example:
interface Payable { double pay(); }
interface Identifiable { String id(); }
class Employee { // base class (single inheritance)
String name;
Employee(String name) { this.name = name; }
void work() { System.out.println(name + " works"); }
}
// Hybrid: class + multiple interfaces
class FullTimeEmployee extends Employee implements Payable, Identifiable {
double salary;
FullTimeEmployee(String name, double salary) {
super(name); // multilevel/single part
this.salary = salary;
}
public double pay() { return salary; } // from Payable
public String id() { return "EMP-" + name; } // from Identifiable
}
Benefits: flexibility, code reuse, clean separation of behavior.
Caution: resolve default method conflicts explicitly if two interfaces define the same default
method.
Q3) Differentiate between Abstract Classes & Interfaces
Answer (tabular points):
Purpose:
o Abstract class: for “is-a” relationships with shared state + behavior.
o Interface: for capabilities/contract (what a type can do).
Members:
o Abstract class: can have fields, constructors, concrete methods, abstract
methods.
o Interface: fields are implicitly public static final; methods are abstract by default;
can also have default, static, and (since Java 9) private helper methods; no
constructors.
Inheritance:
o Abstract class: class can extend only one abstract class.
o Interface: class can implement multiple interfaces (supports multiple
inheritance of type).
Access Modifiers:
o Abstract class: members can be private/protected/public.
o Interface: methods are public (or private helper); fields are public static final.
Use when:
o Abstract class: you need shared state and partial implementation.
o Interface: you need common API across unrelated classes.
Mini Example:
abstract class Shape {
String color;
Shape(String color){ this.color = color; } // constructor allowed
abstract double area();
void describe(){ System.out.println("Color: " + color); }
}
interface Drawable {
void draw();
}
class Circle extends Shape implements Drawable {
double r;
Circle(String c, double r){ super(c); this.r = r; }
double area(){ return Math.PI * r * r; }
public void draw(){ System.out.println("Drawing circle"); }
}
Q4) Explain Exception Handling in detail
Answer:
An exception is an event that disrupts normal flow of a program (e.g., divide by
zero, file not found).
Goals: detect, handle, recover gracefully without crashing.
Keywords & Concepts:
1. try — wraps risky code.
2. catch — handles a particular exception type.
3. finally — code that always runs (resource cleanup).
4. throw — explicitly throws an exception.
5. throws — declares that a method may throw exception(s).
6. Checked exceptions (must be handled/declared) vs Unchecked (RuntimeException
and its subclasses).
7. Try-with-resources (best for AutoCloseable resources).
Example: multiple catch + finally
public static int safeDivide(String a, String b) {
try {
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
return x / y; // may throw ArithmeticException
} catch (NumberFormatException e) {
System.out.println("Invalid number: " + e.getMessage());
return 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
return 0;
} finally {
System.out.println("Done dividing"); // always executes
}
}
Try-with-resources example:
import java.io.*;
public static String readFirstLine(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
} // br auto-closed even if exception occurs
}
Custom exception (checked):
class LowBalanceException extends Exception {
LowBalanceException(String msg){ super(msg); }
}
Q5) What is a Java program to create a method which uses return?
Answer:
The return statement exits a method and optionally returns a value matching the
method’s return type.
Example:
public class MathUtil {
// returns the maximum of two numbers
static int max(int a, int b) {
if (a >= b) return a; // return value and exit
return b;
}
// returns nothing (void) but can return early
static void printIfPositive(int n) {
if (n <= 0) return; // early exit
System.out.println("Positive: " + n);
}
public static void main(String[] args) {
int m = max(10, 20); // m = 20
System.out.println("Max = " + m);
printIfPositive(-5); // prints nothing
printIfPositive(7); // prints "Positive: 7"
}
}
Q6) Write a short note on Dynamic Method Dispatch
Answer:
Dynamic Method Dispatch is the mechanism by which a call to an overridden
method is resolved at runtime based on the actual object type, not the reference
type.
Enables runtime polymorphism.
Example:
class Animal { void speak(){ System.out.println("Animal"); } }
class Dog extends Animal { void speak(){ System.out.println("Bark"); } }
class Cat extends Animal { void speak(){ System.out.println("Meow"); } }
public class Test {
public static void main(String[] args) {
Animal a; // reference type
a = new Dog(); a.speak(); // "Bark"
a = new Cat(); a.speak(); // "Meow"
}
}
Notes:
Works only for instance methods (not static, not fields).
Chosen method depends on the object created with new.
Q7) Write a Java program to explain String functions
(i) toString() (ii) equals() (iii) replace() (iv) toLowerCase()
Answer:
public class StringFunctionsDemo {
// (i) toString(): defined in Object; many classes override it.
static class Point {
int x, y;
Point(int x, int y){ this.x = x; this.y = y; }
@Override
public String toString(){ // custom readable string
return "Point(" + x + ", " + y + ")";
}
}
public static void main(String[] args) {
// toString()
Point p = new Point(3, 4);
System.out.println(p.toString()); // Point(3, 4)
// equals(): content comparison for strings
String s1 = "Hello";
String s2 = new String("Hello");
System.out.println(s1.equals(s2)); // true (same content)
System.out.println(s1 == s2); // false (different objects)
// replace(): replace characters or sequences
String text = "banana";
System.out.println(text.replace('a','o')); // bonono
System.out.println(text.replace("na","NA")); // baNANA
// toLowerCase(): convert to lower case using default locale
String mixed = "JaVa ProGRamMing";
System.out.println(mixed.toLowerCase()); // "java programming"
}
}
Summary:
toString() → readable representation of an object.
equals() → content equality, not reference equality.
replace() → returns a new string; original is unchanged (Strings are immutable).
toLowerCase() → lower-case version; original string remains unchanged.
Q8) Explain the following with reference to Java
(a) Java Virtual Machine (JVM)
JVM is the runtime that loads, verifies, and executes Java bytecode.
Main components:
1. Class Loader Subsystem (loads .class files).
2. Runtime Data Areas:
Method Area (class metadata, constants), Heap (objects),
Java Stacks (frames per thread), PC Register, Native Method Stack.
3. Execution Engine: Interpreter, JIT compiler, Garbage Collector.
Benefits: Write Once, Run Anywhere (platform independence), memory management,
security (bytecode verifier & sandboxing).
(b) finalize method
protected void finalize() was called by GC before reclaiming an object.
It has been deprecated since Java 9 and should not be used; finalization is unsafe
and unpredictable.
Use instead: try-with-resources / AutoCloseable, or Cleaner/PhantomReference
patterns for advanced cases.
(c) Abstract Class
Declared with abstract keyword; cannot be instantiated.
May contain abstract methods (no body) and concrete methods; can have fields
and constructors.
Used for shared state + partial implementation across subclasses.
(d) Predefined Streams
Java provides three standard I/O streams in System:
1. System.in → standard input (keyboard by default), type InputStream.
2. System.out → standard output (console), type PrintStream.
3. System.err → standard error (console), type PrintStream.
Example:
System.out.println("Message"); // normal output
System.err.println("Error"); // error output
Q9) Explain Java’s concept of Overloading Methods
Answer:
Method Overloading = same method name, different parameter lists (type,
number, or order).
Resolved at compile time (compile-time polymorphism).
Cannot overload by return type alone or by only changing access modifiers.
Overloading interacts with type promotion, varargs, and autoboxing.
Example:
class OverloadDemo {
void print(int x) { System.out.println("int: " + x); }
void print(double x) { System.out.println("double: " + x); }
void print(String x) { System.out.println("String: " + x); }
void print(int x, int y) { System.out.println("two ints"); }
void print(Integer x) { System.out.println("Integer: " + x); }
void print(int... nums) { System.out.println("varargs length=" + nums.length); }
public static void main(String[] args) {
OverloadDemo d = new OverloadDemo();
d.print(5); // int
d.print(5.0); // double
d.print("five"); // String
d.print(1, 2); // two ints
d.print(Integer.valueOf(10)); // Integer
d.print(1,2,3,4); // varargs
}
}
Best practices: keep overloaded methods consistent in behavior and document differences
clearly.
Q10) How can interfaces be used to support multiple inheritance?
Answer:
Java forbids multiple inheritance of classes but allows a class to implement multiple
interfaces.
This provides multiple inheritance of type/behavior (contracts).
Example with conflict resolution:
interface A {
default void hello(){ System.out.println("Hello from A"); }
}
interface B {
default void hello(){ System.out.println("Hello from B"); }
}
class C implements A, B {
// must resolve default method conflict explicitly
@Override
public void hello() {
A.super.hello(); // or B.super.hello(); or custom logic
System.out.println("...and C");
}
}
public class TestMI {
public static void main(String[] args) {
new C().hello();
}
}
Notes:
A class can implement many interfaces: class X implements I1, I2, I3 {}
Interfaces can extend other interfaces (even multiple): interface I extends J, K {}
Use interfaces to model capabilities (e.g., Comparable, Runnable, AutoCloseable),
enabling flexible designs without the diamond problem.
Q11) What is Inheritance? List the Benefits of Inheritance.
Answer:
Definition: Inheritance is an OOP mechanism where a new class (subclass/child)
acquires the properties and behaviors (fields and methods) of an existing class
(superclass/parent).
Syntax: class Child extends Parent { ... }
Types in Java:
o Single (A → B), Multilevel (A → B → C), Hierarchical (A → B and A → C).
o Java does not support multiple inheritance of classes; it uses interfaces to
achieve multiple type inheritance.
Benefits:
1. Code Reuse: Common code lives in the base class; children reuse it.
2. Extensibility: Add/override behavior in subclasses without changing base.
3. Polymorphism: Parent references can point to child objects (runtime dispatch).
4. Maintainability: Centralized fixes and enhancements in base class.
5. Abstraction & Specialization: Model general→specific relationships cleanly.
Q12) Java program to calculate & print Area & Perimeter of Rectangle
(Assume suitable length & breadth). Class = Rectangle, methods = voidRectCalc(float,float)
and voidRectShow().
Answer (Program):
class Rectangle {
private float length, breadth;
private float area, perimeter;
// Calculates and stores area and perimeter
void voidRectCalc(float l, float b) {
this.length = l;
this.breadth = b;
this.area = l * b;
this.perimeter = 2 * (l + b);
}
// Displays the results
void voidRectShow() {
System.out.println("Length : " + length);
System.out.println("Breadth : " + breadth);
System.out.println("Area : " + area);
System.out.println("Perimeter : " + perimeter);
}
}
public class RectDemo {
public static void main(String[] args) {
Rectangle r = new Rectangle();
r.voidRectCalc(10.5f, 5.2f); // assume suitable values
r.voidRectShow();
}
}
Q13) What is Method Overriding? Explain with example.
Answer:
Definition: When a subclass provides its own implementation of a method that is
already defined in its superclass with the same signature.
Rules:
1. Same method name, parameters, and compatible (covariant) return type.
2. Access level cannot be more restrictive than the superclass method.
3. Only instance methods can be overridden (not static, not final, not private).
4. Use @Override to catch mistakes at compile time.
Example (shows runtime polymorphism):
class Vehicle {
void move() { System.out.println("Vehicle moves"); }
}
class Car extends Vehicle {
@Override
void move() { System.out.println("Car drives"); }
}
class Boat extends Vehicle {
@Override
void move() { System.out.println("Boat sails"); }
}
public class OverrideDemo {
public static void main(String[] args) {
Vehicle v; // parent reference
v = new Car(); v.move(); // Car drives
v = new Boat(); v.move(); // Boat sails
}
}
Q14) Java program: Convert Decimal to Hexadecimal using class conversion and
method void d2h(int) (use multiple catch).
Answer (Program):
import java.util.Scanner;
class conversion {
// Convert decimal integer to hexadecimal (uppercase) and print it
void d2h(int n) {
String sign = (n < 0) ? "-" : "";
String hex = Integer.toHexString(Math.abs(n)).toUpperCase();
System.out.println("Hexadecimal: " + sign + hex);
}
}
public class D2HApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
conversion c = new conversion();
try {
System.out.print("Enter a decimal integer: ");
String input = sc.nextLine().trim();
int n = Integer.parseInt(input); // may throw NumberFormatException
c.d2h(n);
} catch (NumberFormatException e) {
System.out.println("Invalid number format. Please enter a valid integer.");
} catch (NullPointerException e) {
System.out.println("No input provided.");
} catch (Exception e) { // generic fallback
System.out.println("Unexpected error: " + e.getMessage());
} finally {
sc.close();
}
}
}
Q15) Program: Read a string from user and print pattern
Example input: SHUBHAM → output:
SHUBHAM
SHUBHA
SHUBH
SHUB
SHU
SH
S
Answer (Program):
import java.util.Scanner;
public class StringPattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String s = sc.nextLine().trim().toUpperCase();
for (int i = s.length(); i >= 1; i--) {
System.out.println(s.substring(0, i));
}
sc.close();
}
}
Q16) Explain the following with reference to Java
(a) Bytecode
Intermediate, platform-independent instructions generated by the Java compiler
(.class files).
Executed by the JVM, enabling Write Once, Run Anywhere.
Verified for safety before execution.
(b) Polymorphism
Ability of a single interface to represent multiple forms.
Compile-time polymorphism: method overloading.
Runtime polymorphism: method overriding via dynamic dispatch (method chosen by
the actual object type at runtime).
(c) Exception Handling
Mechanism to handle runtime anomalies using try, catch, finally, throw, throws.
Checked exceptions must be handled/declared; unchecked (RuntimeException) are
optional.
Try-with-resources auto-closes AutoCloseable resources.
(d) Stream class (Java I/O)
I/O is modeled as streams of data.
Byte streams: InputStream / OutputStream (e.g., FileInputStream).
Character streams: Reader / Writer (e.g., BufferedReader, FileWriter).
Decorators like BufferedInputStream, DataOutputStream, ObjectInputStream add
features (buffering, primitives, object serialization).
Q17) Differences between C++ and Java
Answer:
Paradigm: C++ supports procedural + OOP (and manual memory); Java is pure
OOP-centric (everything inside classes; primitives exist).
Compilation: C++ compiles to machine code; Java compiles to bytecode and runs
on the JVM.
Multiple Inheritance: C++ supports multiple inheritance of classes; Java
disallows it for classes (uses interfaces instead).
Memory Management: C++ uses manual memory (new/delete); Java has
automatic GC (no delete).
Pointers: C++ has raw pointers and pointer arithmetic; Java has references only
(no pointer arithmetic).
Operator Overloading: C++ allows it; Java generally does not (except + for strings).
Templates vs Generics: C++ templates are compile-time; Java generics use type
erasure at runtime.
Preprocessor: C++ uses #include, macros; Java no preprocessor (uses
packages/imports).
Platform: C++ is platform-dependent binaries; Java is platform-independent via JVM.
Standard Library: C++ STL (containers/algorithms); Java Collections Framework, rich
standard APIs (I/O, networking, concurrency).
Q18) Explain the Jump Statements in Java
Answer:
1. break
o Exits the nearest loop or switch.
o Labeled break can exit an outer loop.
2. outer:
3. for (int i=0;i<3;i++) {
4. for (int j=0;j<3;j++) {
5. if (i==1 && j==1) break outer; // exits both loops
6. }
7. }
8. continue
o Skips the current iteration and proceeds to the next iteration of the loop.
o Can also be labeled to continue an outer loop.
9. for (int i=0;i<5;i++) {
10. if (i%2==0) continue; // skip even
11. System.out.println(i); // prints 1,3
12.}
13.return
o Exits the current method; may return a value if the method’s return type isn’t
void.
14.int findPosOrMinusOne(int[] a, int key){
15. for (int i=0;i<a.length;i++) if (a[i]==key) return i;
16. return -1;
17.}
Q19) What is the use of the this keyword?
Answer:
Refers to the current object (its fields/methods).
Disambiguates shadowed names (parameter vs field).
Passes the current object to other methods/constructors.
Constructor chaining: call another constructor in the same class using this(...) (must
be first statement).
Can be returned from a method to enable method chaining.
Example:
class Account {
private String name;
private double balance;
Account() { this("Unknown", 0.0); } // constructor chaining
Account(String name, double balance) {
this.name = name; // disambiguation
this.balance = balance;
}
Account deposit(double amt) {
this.balance += amt;
return this; // enable chaining
}
}
Q20) Explain Java’s Access Specifies
Answer:
Java provides four access levels for classes/members:
Same Subclass (diff Other
Modifier Class visibility
package package) packages
public Yes Yes Yes Yes
— (not for top-level Yes (through No (except via
protected Yes
classes) inheritance) subclass)
default (no Yes (package-private for
Yes No No
modifier) top-level class)
No (only within
private No (top-level) No No
same class)
Notes:
Top-level classes can be only public or default (package-private).
Members (fields, methods, constructors) can use all four.
Use private to encapsulate state; public for API; protected for subclass customization;
default for package-internal APIs.
Illustration:
public class A {
public int x = 1;
protected int y = 2;
int z = 3; // package-private (default)
private int w = 4;
public void show() {
System.out.println(x + " " + y + " " + z + " " + w); // all visible here
}
}
Q21) What is the final keyword? Explain its uses.
Answer:
final is a non-access modifier in Java that restricts further change.
Where you can use it & what it means:
1. final variable → value cannot change after initialization (constant).
2. final double PI = 3.14159; // must be assigned once
Blank final: assigned later (e.g., in constructor).
class Config {
final int PORT;
Config(int p){ this.PORT = p; } // set exactly once
}
3. final method → cannot be overridden in subclasses.
4. class Base { final void log(){ System.out.println("Base"); } }
5. class Child extends Base { /* cannot override log() */ }
6. final class → cannot be extended (subclassed).
7. public final class MathUtil { /* ... */ } // no class can extend MathUtil
8. final parameter / local variable → cannot be reassigned inside method.
9. void setRate(final double r){ /* r is read-only here */ }
10.Effectively final (no final written but never reassigned) → required by
lambda/anonymous classes.
Why use final: immutability, thread-safety (constants shared safely), defensive design (avoid
unintended overrides), and clearer APIs.
Q22) Explain Method Overriding in detail with example.
Answer:
Definition: In a subclass, providing a new implementation for a method having the
same signature as in the superclass.
Rules:
o Same name + parameter list; return type must be same or covariant.
o Access level not more restrictive than parent method.
o Cannot override static, private, or final methods.
o Use @Override to catch mistakes at compile time.
Runtime polymorphism: The method call is resolved by the actual object type
(dynamic dispatch).
Example:
class Shape { double area(){ return 0; } }
class Circle extends Shape {
double r;
Circle(double r){ this.r = r; }
@Override double area(){ return Math.PI * r * r; }
}
class Rectangle extends Shape {
double l,b; Rectangle(double l,double b){ this.l=l; this.b=b; }
@Override double area(){ return l * b; }
}
public class OverrideDemo {
public static void main(String[] args) {
Shape s = new Circle(3);
System.out.println(s.area()); // Circle.area()
s = new Rectangle(4,5);
System.out.println(s.area()); // Rectangle.area()
}
}
Q23) Explain different String functions with example.
Answer:
public class StringFunctions {
public static void main(String[] args) {
String s = " Java Programming ";
System.out.println(s.length()); // length
System.out.println(s.charAt(2)); // ' '
String t = s.trim(); // "Java Programming"
System.out.println(t.substring(0,4)); // "Java"
System.out.println(t.toUpperCase()); // "JAVA PROGRAMMING"
System.out.println(t.toLowerCase()); // "java programming"
System.out.println(t.indexOf("Program")); // 5
System.out.println(t.lastIndexOf("a")); // last 'a' position
System.out.println("Java".equals("java")); // false
System.out.println("Java".equalsIgnoreCase("java")); // true
System.out.println(t.startsWith("Java")); // true
System.out.println(t.endsWith("ing")); // true
System.out.println(t.contains("Pro")); // true
System.out.println(t.replace("Java", "Kava")); // replace substring
System.out.println("1,2,3".replace(',', ';')); // replace char
String digits = "A1 B2 C3";
System.out.println(digits.replaceAll("\\d","*")); // regex replace
String[] parts = "red,green,blue".split(",");
System.out.println(parts[1]); // "green"
System.out.println(String.join("-", "2025","08","18")); // "2025-08-18"
// Strings are immutable; use StringBuilder for many edits
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World").insert(0,"Say: ").reverse();
System.out.println(sb.toString());
}
}
Q24) Define Abstract Class. Explain with example.
Answer:
An abstract class is declared with abstract, may contain abstract methods (no body)
and concrete methods, and cannot be instantiated.
Used when you want shared state + partial implementation, letting subclasses
complete the behavior.
Example:
abstract class Account {
double balance;
Account(double bal){ this.balance = bal; }
abstract void withdraw(double amt); // must be implemented
void deposit(double amt){ balance += amt; }
double getBalance(){ return balance; }
}
class Savings extends Account {
Savings(double bal){ super(bal); }
@Override void withdraw(double amt){
if(amt <= balance) balance -= amt;
else System.out.println("Insufficient funds");
}
}
public class AbstractDemo {
public static void main(String[] args) {
Account a = new Savings(1000);
a.deposit(500); a.withdraw(300);
System.out.println(a.getBalance());
}
}
Q25) Define Exception. List five common exceptions.
Answer:
An exception is an event that disrupts normal program flow during execution. Java
handles exceptions via try, catch, finally, throw, throws.
Five common exceptions:
1. NullPointerException – using a null reference.
2. ArrayIndexOutOfBoundsException – invalid array index access.
3. NumberFormatException – invalid numeric string to number.
4. ArithmeticException – arithmetic error (e.g., division by zero).
5. IOException – I/O operation fails (checked exception).
Q26) What are input and output streams? Explain with examples.
Answer:
A stream is a sequence of data.
o Input stream: read data into a program.
o Output stream: write data out of a program.
Byte streams handle raw bytes: InputStream / OutputStream.
Character streams handle text (Unicode): Reader / Writer.
Example 1 – Copy a binary file (byte streams):
import java.io.*;
public class CopyFile {
public static void main(String[] args) {
if (args.length < 2) { System.out.println("Usage: java CopyFile src dst"); return; }
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(args[0]));
BufferedOutputStream out = new BufferedOutputStream(new
FileOutputStream(args[1]))) {
int b;
while ((b = in.read()) != -1) out.write(b);
} catch (IOException e) { System.out.println("I/O error: " + e.getMessage()); }
}
}
Example 2 – Read text lines and print (character streams):
import java.io.*;
public class ReadLines {
public static void main(String[] args) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = br.readLine()) != null) System.out.println(line);
}
}
}
Q27) Class FACTORIAL with method int intfact(int); read an integer from command
line, print factorial with steps.
Answer (Program):
class FACTORIAL {
int intfact(int n) {
if (n < 0) throw new IllegalArgumentException("Negative not allowed");
int f = 1;
for (int i = 2; i <= n; i++) f *= i; // (note: may overflow for large n)
return f;
}
}
public class FactorialApp {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java FactorialApp <non-negative integer>");
return;
}
try {
int n = Integer.parseInt(args[0]);
FACTORIAL fac = new FACTORIAL();
int ans = fac.intfact(n);
// Build step string: e.g., 5*4*3*2*1 = 120 and print final
StringBuilder steps = new StringBuilder();
if (n == 0) {
steps.append("0! = 1");
} else {
for (int i = n; i >= 1; i--) {
steps.append(i);
if (i > 1) steps.append("*");
}
steps.append(" = ").append(ans);
}
System.out.println(steps.toString());
System.out.println("Factorial = " + ans);
} catch (NumberFormatException e) {
System.out.println("Please enter a valid integer.");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
Example run: java FactorialApp 5 → 5*4*3*2*1 = 120
Q28) Program to throw and catch ArrayIndexOutOfBoundsException and
NegativeArraySizeException.
Answer (Program):
public class ArrayExceptionDemo {
public static void main(String[] args) {
// NegativeArraySizeException
try {
int size = -3; // invalid
int[] a = new int[size]; // triggers NegativeArraySizeException
} catch (NegativeArraySizeException e) {
System.out.println("Caught NegativeArraySizeException: " + e.getMessage());
}
// ArrayIndexOutOfBoundsException
try {
int[] b = new int[3];
b[5] = 10; // invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
}
// Combined demonstration with user-friendly handling
try {
int[] c = new int[2];
for (int i = 0; i < 4; i++) c[i] = i * 10; // will overflow indices
} catch (ArrayIndexOutOfBoundsException | NegativeArraySizeException e) {
System.out.println("Handled array exception: " + e);
}
System.out.println("Program continues...");
}
}
Q29) Accept a string from command line and print it in pyramid format.
Answer (Program):
public class PyramidText {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java PyramidText <word>");
return;
}
String s = args[0]; // take the first argument
int n = s.length();
// Centered pyramid
for (int i = 1; i <= n; i++) {
int spaces = n - i;
System.out.println(" ".repeat(spaces) + s.substring(0, i));
}
// (Optional) Left-aligned pyramid:
// for (int i = 1; i <= n; i++) System.out.println(s.substring(0, i));
}
}
Example: java PyramidText SHUBHAM
S
SH
SHU
SHUB
SHUBH
SHUBHA
SHUBHAM
Q30) What is a constructor? Explain types with examples.
Answer:
A constructor is a special method used to initialize new objects.
Name = class name; no return type; called automatically via new.
Types & Examples:
1. Default (compiler-provided) constructor
o Provided only if you don’t declare any constructor.
o Initializes fields to default values (0, false, null, etc.).
2. class A { int x; String s; } // default ctor inserted by compiler
3. No-arg (explicit) constructor
4. class B {
5. int x; String s;
6. B(){ x = 10; s = "hello"; }
7. }
8. Parameterized constructor
9. class C {
10. int id; String name;
11. C(int id, String name){ this.id = id; this.name = name; }
12.}
13.Constructor overloading (multiple constructors with different params)
14.class D {
15. int a; int b;
16. D(){ this(0,0); } // chaining to another constructor
17. D(int a){ this(a, 0); }
18. D(int a, int b){ this.a=a; this.b=b; }
19.}
20.Copy constructor pattern (Java doesn’t auto-generate; you define one)
21.class E {
22. int id; String name;
23. E(int id, String name){ this.id=id; this.name=name; }
24. E(E other){ this(other.id, other.name); } // copy fields
25.}
26.Private constructor (e.g., Singleton / utility classes)
27.class Util {
28. private Util() {} // prevent instantiation
29. static int add(int a,int b){ return a+b; }
30.}
Notes:
Use this(...) for constructor chaining within the same class; super(...) to call parent
constructor (must be the first statement).
Constructors are not inherited, but they are invoked across the hierarchy via super().
(Extra) Rectangle Program (from earlier pattern, for your reference)
class Rectangle {
private float length, breadth, area, perimeter;
void voidRectCalc(float l, float b){ length=l; breadth=b; area=l*b; perimeter=2*(l+b); }
void voidRectShow(){
System.out.println("Length: "+length+"\nBreadth: "+breadth+
"\nArea: "+area+"\nPerimeter: "+perimeter);
}
}
If you’d like, I can bundle all examples into a single .zip or .docx with formatted headings and
a table of contents.
Q31) Explain different String functions with examples
Answer (steps + example):
Strings in Java are immutable objects of class String. Commonly used methods:
length() — returns number of characters.
charAt(int index) — character at given index (0-based).
substring(int beginIndex) / substring(int begin, int end) — get substring.
indexOf(String/char) / lastIndexOf(...) — find first/last occurrence index (-1 if not found).
startsWith(String) / endsWith(String) — prefix/suffix check.
contains(CharSequence) — if substring present.
equals(Object) / equalsIgnoreCase(String) — content equality (case sensitive /
insensitive).
compareTo(String) — lexicographic comparison (negative / zero / positive).
concat(String) or + — append/concatenate.
replace(char old, char new) / replace(CharSequence, CharSequence) — simple replace.
replaceAll(String regex, String repl) — regex-based replace.
split(String regex) — split into array by regex.
toUpperCase() / toLowerCase() — case conversion.
trim() — remove leading/trailing whitespace.
isEmpty() — true if length is 0.
toCharArray() — convert to char[].
format(...) / valueOf(...) — conversions/formatting.
intern() — returns canonical string from string pool.
matches(String regex) — boolean match for regex.
Complete example program demonstrating many functions:
public class StringFunctionsDemo {
public static void main(String[] args) {
String s = " Java Programming ";
System.out.println("Original: '" + s + "'");
System.out.println("1) length(): " + s.length());
System.out.println("2) trim(): '" + s.trim() + "'");
System.out.println("3) toUpperCase(): " + s.toUpperCase());
System.out.println("4) toLowerCase(): " + s.toLowerCase());
System.out.println("5) charAt(2): " + s.charAt(2));
System.out.println("6) substring(2,6): '" + s.substring(2,6) + "'");
System.out.println("7) indexOf(\"Pro\"): " + s.indexOf("Pro"));
System.out.println("8) lastIndexOf('g'): " + s.lastIndexOf('g'));
System.out.println("9) startsWith(\" Ja\"): " + s.startsWith(" Ja"));
System.out.println("10) endsWith(\"ming \"): " + s.endsWith("ming "));
System.out.println("11) contains(\"gram\"): " + s.contains("gram"));
System.out.println("12) equals(\"Java Programming\"): " + s.equals("Java Programming"));
System.out.println("13) equalsIgnoreCase(\" java programming \"): " +
s.equalsIgnoreCase(" java programming "));
System.out.println("14) replace('a','o'): " + s.replace('a','o'));
System.out.println("15) replaceAll(\"\\\\s+\",\"-\"): " + s.replaceAll("\\s+","-"));
String csv = "red,green,blue";
String[] parts = csv.split(",");
System.out.println("16) split(',') -> " + java.util.Arrays.toString(parts));
System.out.println("17) isEmpty() on \"\": " + "".isEmpty());
System.out.println("18) toCharArray(): " + java.util.Arrays.toString("abc".toCharArray()));
System.out.println("19) format example: " + String.format("Hello %s, %d", "Alice",
2025));
System.out.println("20) matches regex (\\\\w+): " + "Hello123".matches("\\w+"));
}
}
Q32) Java program — accept integer and test whether it is prime or not
Answer (detailed steps + program):
Steps to decide primality (simple, correct for moderate n):
1. If n <= 1 ⇒ not prime.
2. Check divisibility by 2 separately (optional).
3. Check odd divisors from 3 to sqrt(n) (inclusive). If any divisor found ⇒ not prime.
4. If none found ⇒ prime.
Program:
import java.util.Scanner;
public class PrimeTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = sc.nextInt();
sc.close();
boolean isPrime = isPrime(n);
if (isPrime) System.out.println(n + " is a prime number.");
else System.out.println(n + " is not a prime number.");
}
// Efficient enough for moderate n
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
int limit = (int) Math.sqrt(n);
for (int i = 3; i <= limit; i += 2) {
if (n % i == 0) return false;
}
return true;
}
}
Notes: For very large numbers use optimized algorithms (sieve, Miller–Rabin, etc.), but above
is sufficient for typical class assignments.
Q33) Java program — accept string from command line and print in pyramid format
Answer (steps + program):
Steps:
1. Read first command-line argument as the word.
2. For i from 1 to word.length() print leading spaces and then word.substring(0,i) to make a
centered pyramid.
Program (command-line):
public class PyramidFromCommand {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java PyramidFromCommand <word>");
return;
}
String s = args[0];
int n = s.length();
for (int i = 1; i <= n; i++) {
int spaces = n - i;
System.out.println(" ".repeat(spaces) + s.substring(0, i));
}
}
}
Example: java PyramidFromCommand SHUBHAM prints:
S
SH
SHU
SHUB
SHUBH
SHUBHA
SHUBHAM
Q34) Java program — handle NumberFormatException, accept number from
command line and test Positive / Negative / Zero
Answer (steps + program):
Steps:
1. Read args[0].
2. Use Integer.parseInt() inside try — catches NumberFormatException for invalid input.
3. Check sign and print message.
Program:
public class SignCheckFromCmd {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java SignCheckFromCmd <integer>");
return;
}
try {
int n = Integer.parseInt(args[0]);
if (n > 0) System.out.println(n + " is Positive.");
else if (n < 0) System.out.println(n + " is Negative.");
else System.out.println("Number is Zero.");
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid integer.");
}
}
}
Tip: Use Long.parseLong or BigInteger for larger ranges.
Q35) Explain all types of constructors with examples
Answer (detailed list + examples):
1. Default constructor (compiler-provided)
o If you declare no constructors, Java provides a no-arg default constructor that
sets fields to default values.
2. class A { int x; } // default constructor A() exists implicitly
3. No-argument constructor (explicit)
o You write it yourself to initialize fields to chosen defaults.
4. class B {
5. int x;
6. B() { x = 10; }
7. }
8. Parameterized constructor
o Accepts parameters used to initialize the object.
9. class C {
10. int id; String name;
11. C(int id, String name) { this.id = id; this.name = name; }
12.}
13.Constructor overloading
o Multiple constructors with different parameter lists.
14.class D {
15. D() { this(0); }
16. D(int a) { /* init using a */ }
17. D(int a, int b) { /* init using a and b */ }
18.}
19.Copy constructor (user-defined)
o Java has no automatic copy ctor; create one manually to copy fields.
20.class E {
21. int id; String name;
22. E(int id, String name){ this.id=id; this.name=name; }
23. E(E other){ this(other.id, other.name); } // copy
24.}
25.Private constructor
o Prevents instantiation from outside (useful for singletons or utility classes).
26.class Util {
27. private Util() {}
28. public static int add(int a, int b) { return a+b; }
29.}
30.Constructor chaining
o Use this(...) to call another constructor in same class; super(...) to call parent
constructor. Must be first statement.
31.class Parent {
32. Parent(int x) { /* ... */ }
33.}
34.class Child extends Parent {
35. Child() { super(5); } // call parent constructor
36. Child(int a) { this(); /* then more */ } // calls Child()
37.}
Notes:
Constructors have no return type.
They cannot be static or final.
If you define any constructor, compiler does not generate default constructor.
Q36) Explain the role of the Java Virtual Machine (JVM) in brief
Answer (concise, key responsibilities):
The JVM is the runtime engine that executes Java bytecode. Main roles:
1. Loads classes — Class Loader subsystem loads .class files (bytecode).
2. Verifies bytecode — Bytecode verifier checks code for security/safety before
execution.
3. Provides runtime data areas — Method Area, Heap (objects), Java Stacks (frames per
thread), PC Registers, Native Method Stack.
4. Executes code — Interpreter executes bytecode; HotSpot JIT compiles hot methods to
native machine code for performance.
5. Memory management & GC — Automatic garbage collection reclaims unused objects.
6. Provides native interface — JNI for calling native code when required.
7. Enforces security & sandboxing — class verifier & security manager (legacy)
restricts untrusted code.
Why important: JVM makes Java platform-independent: compile once to bytecode, run
anywhere a compatible JVM exists.
Q37) Explain different types of access specifiers available for packages & classes
Answer (clear table + details):
Java access levels (for classes and members):
public
o Visible everywhere (same class, package, subclasses, other packages).
o Top-level classes can be public.
protected
o Visible in same package and in subclasses (even if subclass is in different
package).
o Not visible to unrelated classes in other packages.
o Not applicable to top-level classes (only to members).
default (package-private) — no modifier
o Visible only within the same package (classes in same package).
o Top-level classes without modifier are package-private.
private
o Visible only within the same class.
o Not visible to subclasses or other classes, even in same package.
o Applicable to members; top-level classes cannot be private.
Summary for top-level classes: only public or package-private allowed.
Typical use-cases:
private to encapsulate internal state.
package-private for internal package APIs.
protected for controlled exposure to subclasses.
public for published APIs.
Q38) Java program — throw and catch ArrayIndexOutOfBoundsException and
NegativeArraySizeException
Answer (program + explanation):
Program:
public class ArrayExceptionsDemo {
public static void main(String[] args) {
// NegativeArraySizeException demonstration
try {
System.out.println("Attempting to create array with negative size...");
int[] a = new int[-5]; // throws NegativeArraySizeException
} catch (NegativeArraySizeException e) {
System.out.println("Caught NegativeArraySizeException: " + e);
}
// ArrayIndexOutOfBoundsException demonstration
try {
System.out.println("Attempting to access invalid index...");
int[] b = new int[3];
b[5] = 10; // throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e);
}
// Combined handling example
try {
int size = Integer.parseInt(args.length > 0 ? args[0] : "2");
int[] c = new int[size];
// purposely access out of bound to demonstrate
c[size + 1] = 100;
} catch (NumberFormatException e) {
System.out.println("Invalid input for size.");
} catch (NegativeArraySizeException | ArrayIndexOutOfBoundsException e) {
System.out.println("Handled array-related exception: " + e);
} finally {
System.out.println("Program finished (finally block).");
}
}
}
Explanation:
new int[-5] immediately throws NegativeArraySizeException.
Accessing b[5] when length is 3 throws ArrayIndexOutOfBoundsException.
Use separate or combined catch blocks to handle them.
Q39) Java program — reverse a number and check whether it is palindrome
Answer (steps + program):
Steps:
1. Read integer n. Save original orig = n. Work with absolute value for reverse if you want
to ignore sign.
2. Compute reverse by repeated % 10 and /= 10.
3. Compare reverse with orig (for negative numbers, you can decide policy; typical check
uses absolute values).
Program:
import java.util.Scanner;
public class ReverseAndPalindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = sc.nextInt();
sc.close();
int orig = n;
int num = Math.abs(n); // handle negative by absolute (optional)
int rev = 0;
while (num != 0) {
int digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
if (n < 0) rev = -rev; // if you want sign preserved
System.out.println("Reversed number: " + rev);
if (orig == rev) System.out.println(orig + " is a palindrome.");
else System.out.println(orig + " is not a palindrome.");
}
}
Example: input 121 → reversed 121 → palindrome. Input -121 → reversed -121 (with sign
preserved in code) → also palindrome if you treat sign.
Q40) Java program — print series 5 500 475 450 425 … (first n terms)
Answer (interpretation + program):
Observation & interpretation:
Given sample: 5 500 475 450 425 …
The sequence begins with 5.
The second term is 500.
From the second term onward the sequence decreases by 25 each time: 500, 475, 450,
425, …
We will implement this interpretation:
If n == 1 → print 5.
If n >= 2 → print 5 then start with 500 and repeatedly subtract 25 to produce remaining
n-1 terms.
Program:
import java.util.Scanner;
public class SeriesGenerator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of terms (n): ");
int n = sc.nextInt();
sc.close();
if (n <= 0) {
System.out.println("n must be positive.");
return;
}
// Print first term
System.out.print(5);
if (n == 1) {
System.out.println();
return;
}
// Second term starts at 500
int term = 500;
System.out.print(" " + term);
for (int i = 3; i <= n; i++) { // i=3 corresponds to third term
term = term - 25; // decrease by 25 each step
System.out.print(" " + term);
}
System.out.println();
}
}
Example runs:
n=1→5
n = 2 → 5 500
n = 5 → 5 500 475 450 425