JAVA PROGRAMMING LABORATORY
VIVA VOCE QUESTION BANK
20 Lab Programs with Detailed Questions & Answers
Program 1: Display Hello World and show size of all data types
____________________________________________________________
Viva Questions and Answers
Q1. What is a class in Java?
A class is a blueprint or template from which objects are created. It defines the data (variables) and
behavior (methods) that the objects will have.
Q2. What is the main() method? Why is it needed?
The main() method is the entry point of any Java program. The JVM calls main() to start execution. Its
signature is: public static void main(String[] args).
Q3. Explain 'public static void main(String[] args)'. What does each keyword mean?
public — accessible from anywhere. static — called without creating an object. void — returns nothing.
main — method name. String[] args — command line arguments as string array.
Q4. What is [Link]() used for?
It prints the message to the standard output (console) and moves the cursor to a new line.
Q5. List all primitive data types in Java with their sizes.
byte (8 bits), short (16 bits), int (32 bits), long (64 bits), float (32 bits), double (64 bits), char (16 bits),
boolean (not precisely defined, JVM dependent).
Q6. Why is char 16 bits in Java?
Java uses Unicode (not ASCII) to support international characters. Unicode requires 16 bits to represent all
characters.
Q7. What is the default value of int, float, and boolean in Java?
int → 0, float → 0.0f, boolean → false. These defaults apply to instance variables, not local variables.
Q8. What is the difference between float and double?
float is 32-bit (precision ~7 decimal digits), double is 64-bit (precision ~15 digits). double is the default for
floating-point literals in Java.
Q9. Can we run a Java program without a main() method?
Before Java 7, it was possible using static blocks. From Java 7 onwards, main() is mandatory to run a
program.
Q10. What does the sizeof operator do in Java?
Java does NOT have a sizeof operator like C/C++. Sizes of primitive types are fixed by the language
specification and do not vary by platform.
Q11. What is the range of byte data type?
-128 to 127 (2^7 to 2^7 - 1).
Q12. What is the difference between println() and print()?
println() prints and moves to next line. print() prints and stays on the same line.
Q13. What is a Java keyword? Give examples.
A keyword is a reserved word with a predefined meaning in Java. Examples: class, public, static, void, int, if,
else, for, while.
Q14. Output-based: What is the output of [Link](10 + 20 + "Java" + 10 + 20)?
30Java1020. Explanation: 10+20=30 (integer addition), then string concatenation makes everything after a
string.
Q15. Common mistake: Why does the program not compile if we misspell 'String'?
String is a class in [Link] package. Misspelling it (e.g., 'string') will cause a compilation error because Java
is case-sensitive.
Program 2: Usage of static, local, and instance variables
____________________________________________________________
Q1. What is an instance variable?
A variable declared inside a class but outside any method. It is created when an object is created and
destroyed when the object is destroyed. Each object has its own copy.
Q2. What is a static variable?
A variable declared with the static keyword. It belongs to the class, not to any object. Only one copy exists,
shared by all objects.
Q3. What is a local variable?
A variable declared inside a method, constructor, or block. It is created when the method is called and
destroyed when it returns. Must be initialized before use.
Q4. What is the default value of an instance variable?
Depends on type: int→0, float→0.0, boolean→false, object→null. Local variables have NO default value.
Q5. Can we access a static variable using an object reference?
Yes, but it is not recommended. Static variables should be accessed using the class name:
[Link].
Q6. What is the difference between static and instance variables?
Static: one copy per class, loaded at class loading time, accessed via class name. Instance: one copy per
object, created with new, accessed via object reference.
Q7. What happens if we try to use a local variable without initializing?
Compilation error: 'variable might not have been initialized'. Local variables must be assigned a value
before use.
Q8. Can local variable names be the same as instance variable names?
Yes, but the local variable will shadow the instance variable within that method. Use 'this' keyword to refer
to the instance variable.
Q9. Output-based: What is output if static int count=0; is incremented in constructor and 3 objects created?
count = 3. All objects share the same static variable.
Q10. Where are static variables stored in memory?
In the Method Area (Metaspace in Java 8+), not on the heap. They are loaded when the class is loaded.
Q11. Can we declare a static variable inside a method?
No. Static variables must be class members (declared at class level). Variables inside methods are always
local.
Q12. What is a static method? Can it access instance variables?
A static method belongs to the class. It CANNOT directly access instance variables because no 'this'
reference exists in a static context.
Q13. Common mistake: What happens if we forget to initialize a local variable?
Compilation error. The compiler enforces definite assignment for local variables.
Q14. What is memory allocation for instance variables?
Instance variables are stored on the heap as part of the object. They get default values when the object is
created with new.
Q15. Can we use 'this' in a static method?
No. 'this' refers to the current object, and static methods have no current object context.
Program 3: String operations: Length, Concatenation, Substring
____________________________________________________________
Q1. What is a String in Java?
A String is an immutable sequence of characters. It is a class in the [Link] package. Once created, its
value cannot be changed.
Q2. How to find the length of a String in Java?
Using the length() method: [Link](). Returns the number of characters in the string.
Q3. How is String concatenation done in Java?
Using the + operator or the concat() method. Example: String s = "Hello" + " " + "World";
Q4. How to extract a substring?
Using substring() method: [Link](beginIndex) or [Link](beginIndex, endIndex). beginIndex is
inclusive, endIndex is exclusive.
Q5. What is the difference between String, StringBuilder, and StringBuffer?
String is immutable. StringBuilder is mutable and not thread-safe (faster). StringBuffer is mutable and
thread-safe (synchronized, slower).
Q6. Why are Strings immutable in Java?
For security (e.g., class names, network URLs), caching (String pool), thread-safety, and performance
(hashcode caching).
Q7. What is the String Pool?
A special memory area in the heap where String literals are stored. If the same literal appears again, the
JVM reuses the reference from the pool.
Q8. Output-based: What is the output of "Java".length()?
4
Q9. Output-based: What does "HelloWorld".substring(3,7) return?
loWo (characters from index 3 to 6 inclusive).
Q10. What is the difference between equals() and == for Strings?
equals() compares the actual content. == compares object references (whether they point to the same
memory location).
Q11. Can we modify a String after creation?
No. Any operation like concat(), replace(), substring() returns a NEW String. The original remains
unchanged.
Q12. Common mistake: What is wrong with String s = "Hello"; [Link](" World");?
The concat() returns a new String, but it is not assigned. The original s still contains "Hello". Correct: s =
[Link](" World");
Q13. What is the difference between length (array) and length() (String)?
length is a property of arrays. length() is a method of the String class.
Q14. What is the toCharArray() method?
Converts a String into a char array: char[] arr = [Link]();
Q15. Is String a primitive type or reference type?
String is a reference type (class) in Java, not a primitive type.
Q16. What is the charAt() method?
Returns the character at a specified index: [Link](index). Index starts from 0.
Program 4: Find maximum of three numbers
____________________________________________________________
Q1. What is the conditional operator (ternary operator) in Java?
It is a shorthand for if-else: condition ? value_if_true : value_if_false. Example: max = (a > b) ? a : b;
Q2. Write logic to find maximum of three numbers using if-else.
A: if(a>=b && a>=c) max=a; else if(b>=a && b>=c) max=b; else max=c;
Q3. Can we find max using nested ternary?
Yes: max = (a>b) ? ((a>c)?a:c) : ((b>c)?b:c);
Q4. What is the advantage of [Link]()?
It is a built-in method: [Link](a,b) returns the larger of two numbers. For three: [Link](a,
[Link](b,c)).
Q5. How does if-else work in Java?
if(condition) { block } else if(condition) { block } else { block }. The condition must evaluate to boolean.
Q6. Output-based: Find max of 10, 25, 7.
25
Q7. What is the difference between = and == in Java?
= is assignment operator. == is equality comparison operator. Confusing them is a common mistake.
Q8. Can we use switch-case for finding maximum?
Not practically. switch works only with discrete values (int, char, String), not with range comparisons.
Q9. What happens if all three numbers are equal?
The condition a>=b && a>=c is true, so a is returned as max. All equal means any number can be the max.
Q10. Common mistake: Why does if(a>b>c) not work?
Because comparison operators are binary. a>b returns boolean, and boolean cannot be compared with >.
Correct: (a>b && a>c).
Q11. Can we use Scanner class to read input?
Yes: Scanner sc = new Scanner([Link]); int a = [Link]();
Q12. What is the BufferedReader alternative?
BufferedReader br = new BufferedReader(new InputStreamReader([Link])); int a =
[Link]([Link]());
Q13. What package is Scanner in?
[Link]
Q14. What is the logic for min of three numbers?
Similarly: if(a<=b && a<=c) min=a; else if(b<=a && b<=c) min=b; else min=c;
Q15. What is an edge case for this program?
When numbers are negative, zero, floating-point, or very large (Integer.MAX_VALUE).
Program 5: Check whether a number is odd or even
____________________________________________________________
Q1. What is the modulus operator (%) in Java?
It returns the remainder of division. Example: 10 % 3 = 1.
Q2. How do you check if a number is even?
if(num % 2 == 0) → even. If the remainder when divided by 2 is 0, the number is even.
Q3. How do you check if a number is odd?
if(num % 2 != 0) or if(num % 2 == 1) → odd.
Q4. Does the modulus operator work with negative numbers?
Yes. In Java, -5 % 2 = -1 (preserves sign of dividend). So check != 0 instead of == 1 for odd detection.
Q5. Can we check odd/even without modulus?
Yes: using bitwise AND — if((num & 1) == 0) → even. The LSB (least significant bit) is 0 for even numbers.
Q6. What is the bitwise AND operator (&)?
It performs AND operation bit by bit. Example: 5 & 1 = 1 (101 & 001 = 001).
Q7. Output-based: Is 112 even or odd?
Even (112 % 2 = 0).
Q8. Output-based: Is -7 even or odd?
Odd (-7 % 2 = -1, not 0).
Q9. What is the difference between & and &&?
& is bitwise AND (works on integers) or logical AND (with boolean). && is short-circuit logical AND
(evaluates right side only if needed).
Q10. How to read an integer from the user?
Scanner sc = new Scanner([Link]); int n = [Link]();
Q11. Common mistake: Why does if(num % 2 == 1) fail for negative odd numbers?
Because -3 % 2 = -1, not 1. Use if(num % 2 != 0) to correctly detect odd numbers.
Q12. Can we use the conditional operator for this?
Yes: String result = (num%2==0) ? "Even" : "Odd";
Q13. What is the if-else syntax?
if(condition) { statements } else { statements }
Q14. What is a boolean expression?
An expression that evaluates to true or false. E.g., num%2==0 is a boolean expression.
Q15. What is the difference between = and == in this context?
Using if(num%2=0) is a compilation error because = is assignment, not comparison. Use == for equality
check.
Program 6: Default and Parameterized Constructors
____________________________________________________________
Q1. What is a constructor?
A constructor is a special method that initializes objects. It has the same name as the class and no return
type (not even void).
Q2. What is a default constructor?
A constructor with no parameters, provided automatically by Java if no constructor is defined. It initializes
instance variables to default values.
Q3. What is a parameterized constructor?
A constructor that accepts arguments to initialize an object with specific values.
Q4. Can we have multiple constructors in a class?
Yes. This is called constructor overloading. They must differ in parameter list.
Q5. What is constructor overloading?
Defining multiple constructors with different parameter lists. The correct one is called based on arguments
passed.
Q6. What happens if we define a parameterized constructor but no default constructor?
The default constructor is NOT automatically provided. Attempting new ClassName() will cause a
compilation error unless you explicitly define a no-arg constructor.
Q7. Does a constructor return any value?
No. Constructors do not have a return type, not even void. They initialize the object internally.
Q8. Can a constructor be private?
Yes. A private constructor prevents object creation from outside the class. Used in Singleton pattern.
Q9. What is 'this()' in a constructor?
this() calls another constructor of the same class. Must be the first statement in the constructor.
Q10. Output-based: If class A has A(int x){...} what is the output of new A()?
Compilation error — no default constructor exists.
Q11. What is the difference between constructor and method?
Constructor: same name as class, no return type, called automatically with new. Method: any name, has
return type, called explicitly.
Q12. Can constructors be inherited?
No. Constructors are not inherited by subclasses. But a subclass constructor can call superclass constructor
using super().
Q13. What is super() in constructors?
super() calls the parent class constructor. Must be the first statement in the child constructor.
Q14. Common mistake: Forgetting to provide a no-arg constructor when overloading.
If parameterized constructors exist and you write new ClassName(), it fails unless you explicitly define a
no-arg constructor.
Q15. What is a copy constructor? Does Java have it?
A copy constructor creates an object by copying another object. Java does not provide it automatically, but
you can define one manually: ClassName(ClassName obj) { this.x = obj.x; }
Q16. What is the purpose of a constructor?
To initialize the object's state (instance variables) when the object is created.
Program 7: Array of Objects
____________________________________________________________
Q1. What is an array of objects in Java?
An array that stores references to objects. Example: Student[] students = new Student[5]; creates an array
of 5 Student references (initially null).
Q2. How do you create objects in an array?
Each element must be individually instantiated: students[0] = new Student(); students[1] = new Student();
etc.
Q3. What is the default value in an object array?
null. Unlike primitive arrays, object arrays are initialized to null, not default objects.
Q4. How do you access a method of an object in an array?
students[0].getData() — first access the array element, then call the method.
Q5. Output-based: Student[] s = new Student[3]; [Link](s[0]);
null (array elements are null references).
Q6. What happens if we call a method on a null array element?
NullPointerException at runtime.
Q7. How to iterate through an array of objects?
for(int i=0; i<[Link]; i++) { arr[i].display(); } or using enhanced for: for(Student s : arr) { [Link](); }
Q8. What is the 'length' property of an array?
It is a public final field that gives the number of elements in the array. Not a method.
Q9. Can we have a 2D array of objects?
Yes: Student[][] matrix = new Student[3][4];
Q10. What is a NullPointerException?
An exception thrown when trying to access a method or field on a null reference.
Q11. What is the enhanced for loop (for-each) syntax?
for(ClassName var : arrayName) { }. Example: for(Student s : students) { [Link]([Link]); }
Q12. Common mistake: Creating array of objects without instantiating individual elements.
Student[] s = new Student[5]; s[0].display(); // NullPointerException — s[0] is null!
Q13. What is the difference between Object[] and primitive array?
Object[] stores references; primitive arrays store actual values.
Q14. Can an object array store different types of objects?
If declared as Object[] arr = new Object[5], it can store any object type (polymorphism).
Q15. How is memory allocated for an array of objects?
The array object itself is on the heap. Each element is a reference (4/8 bytes). The actual objects must be
created separately with new.
Program 8: Single Inheritance
____________________________________________________________
Q1. What is inheritance in Java?
A mechanism where one class (child/subclass) acquires properties and behaviors of another class
(parent/superclass). Promotes code reusability.
Q2. What is single inheritance?
A subclass inherits from exactly one superclass. Java supports only single inheritance through classes.
Q3. Which keyword is used for inheritance?
extends. Example: class Dog extends Animal { }
Q4. Can a subclass access private members of the superclass?
No. Private members are not inherited. They can only be accessed via public/protected methods of the
superclass.
Q5. What is the super keyword?
super refers to the immediate parent class object. Used to access parent methods/constructors that are
hidden by the child.
Q6. What is method overriding?
Defining a method in the child class that already exists in the parent class with the same signature. Used
for runtime polymorphism.
Q7. What is the @Override annotation?
It indicates that a method is overriding a superclass method. While optional, it helps catch errors (e.g.,
typo in method name).
Q8. Does Java support multiple inheritance through classes?
No. Java does not support multiple inheritance with classes to avoid the diamond problem. Interfaces are
used instead.
Q9. What is the diamond problem?
When a class inherits from two classes that have a method with the same name, causing ambiguity about
which method to call.
Q10. What is the Object class?
The root class of the Java class hierarchy. Every class implicitly extends Object.
Q11. Can we prevent a class from being inherited?
Yes, by declaring the class as final.
Q12. What is the difference between extends and implements?
extends is for class-to-class inheritance. implements is for class-to-interface contract implementation.
Q13. Output-based: If parent has method show() and child overrides show(), which is called?
The child's method is called (runtime polymorphism).
Q14. What is constructor chaining in inheritance?
When a child class constructor calls the parent class constructor using super(). If not written explicitly,
super() is added automatically by the compiler.
Q15. Can we override a static method?
No. Static methods are hidden, not overridden. Method resolution is done at compile-time based on
reference type.
Q16. Common mistake: Trying to override a final method.
Final methods cannot be overridden. Causes compilation error.
Program 9: Multiple Inheritance using Interface
____________________________________________________________
Q1. What is an interface in Java?
A reference type that contains only abstract methods (before Java 8) and constants. It defines a contract
that implementing classes must fulfill.
Q2. How does Java achieve multiple inheritance?
Through interfaces. A class can implement multiple interfaces: class A implements B, C { }
Q3. What is the syntax to declare an interface?
interface InterfaceName { void method(); }
Q4. Can an interface have variables?
Yes, but they are implicitly public static final (constants).
Q5. What is the difference between abstract class and interface?
Abstract class: can have constructors, instance variables, concrete methods. Interface: all methods
abstract (before Java 8), only constants. A class can extend only one abstract class but implement multiple
interfaces.
Q6. Can an interface extend another interface?
Yes: interface A extends B { }
Q7. What is a functional interface?
An interface with exactly one abstract method. Can be used with lambda expressions. Example: Runnable,
Comparator.
Q8. What is @FunctionalInterface annotation?
Used to mark an interface as functional. The compiler ensures it has only one abstract method.
Q9. What are default methods in interfaces (Java 8+)?
Methods with a body in interfaces, declared with the 'default' keyword. Implementing classes can inherit
or override them.
Q10. What are static methods in interfaces (Java 8+)?
Static methods with a body can be defined in interfaces. Called via [Link]().
Q11. Do interfaces support multiple inheritance?
Yes. A class can implement multiple interfaces, achieving multiple inheritance of behavior (not state).
Q12. Output-based: If two interfaces have a default method with same name, what happens?
The implementing class MUST override the method to resolve the conflict, or compilation error occurs.
Q13. What is the 'implements' keyword?
Used by a class to implement an interface: class MyClass implements MyInterface { }
Q14. Can we create an object of an interface?
No. Interfaces cannot be instantiated. However, a reference variable can be of interface type pointing to
an implementing class object.
Q15. What is a marker interface?
An interface with no methods (e.g., Serializable, Cloneable). It signals metadata to the JVM.
Q16. Common mistake: Forgetting to implement all methods of an interface.
If a class fails to implement all abstract methods of an interface, the class must be declared abstract.
Program 10: Life Cycle of an Applet
____________________________________________________________
Q1. What is an Applet?
A small Java program embedded in a web page. It runs in a browser using the JVM plugin. Applets are
deprecated since Java 9.
Q2. What are the stages of an Applet life cycle?
1. init() — initializes the applet (called once). 2. start() — starts execution (called after init and whenever
page is revisited). 3. paint() — draws output on the screen. 4. stop() — stops execution (called when page
is left). 5. destroy() — performs cleanup (called once before termination).
Q3. Which method is called first in an Applet?
init()
Q4. Which method is called only once in an Applet life cycle?
init() and destroy() are called once each.
Q5. Which method is called repeatedly?
paint() — called whenever the applet needs to be redrawn.
Q6. What class must an Applet extend?
[Link] (or [Link] for Swing).
Q7. Does an Applet have a main() method?
No. Applets do not require main(). The browser/AppletViewer controls the life cycle.
Q8. How is an Applet embedded in HTML?
Using <applet code="[Link]" width=300 height=200> </applet> (or <object> tag).
Q9. What is the Graphics class used for?
It provides methods for drawing shapes, text, and images in the paint() method.
Q10. What is the difference between init() and start()?
init() runs once during applet creation. start() runs after init and every time the page is revisited/refreshed.
Q11. Can an Applet read files from the local system?
By default, no (security restriction). Applets run in a sandbox for security.
Q12. What is AppletViewer?
A tool provided by JDK to test Applets without a browser.
Q13. Why are Applets deprecated?
Due to security concerns, browser plugin support removal, and the rise of modern web technologies
(HTML5, JavaScript).
Q14. What is the AWT package?
Abstract Window Toolkit — Java's original GUI toolkit. Used in Applets for UI components.
Q15. Common mistake: Trying to use [Link]() in an Applet.
It prints to console, not the browser. Use drawString() of Graphics class instead.
Program 11: Division by Zero Exception
____________________________________________________________
Q1. What is an exception in Java?
An abnormal event that disrupts the normal flow of program execution.
Q2. What happens when we divide an integer by zero in Java?
ArithmeticException is thrown at runtime (specifically, / by zero). The program terminates unless handled.
Q3. What happens when we divide a floating-point number by zero?
No exception. Float/Double division by zero yields Infinity (or -Infinity) or NaN.
Q4. Which exception class handles division by zero?
[Link]
Q5. How do you handle exceptions in Java?
Using try-catch-finally blocks: try { risky code } catch(ExceptionType e) { handling } finally { cleanup }
Q6. What is the try block?
Contains code that might throw an exception.
Q7. What is the catch block?
Catches and handles the exception. You can have multiple catch blocks for different exception types.
Q8. What is the finally block?
Executes always (whether exception occurs or not). Used for cleanup (closing files, connections).
Q9. Can we have try without catch?
Yes, but only if there is a finally block.
Q10. Output-based: What is the output of [Link](10/0)?
ArithmeticException: / by zero at runtime.
Q11. Output-based: What is the output of [Link](10.0/0)?
Infinity (no exception).
Q12. What is the difference between checked and unchecked exceptions?
Checked: checked at compile-time (IOException, SQLException). Unchecked: runtime exceptions
(ArithmeticException, NullPointerException).
Q13. Is ArithmeticException checked or unchecked?
Unchecked (extends RuntimeException).
Q14. What is the getMessage() method?
Returns the detail message string of an exception: [Link]() returns "/ by zero".
Q15. Common mistake: Catching Exception instead of specific type.
Bad practice. Always catch the most specific exception first (e.g., ArithmeticException before Exception).
Q16. What is printStackTrace()?
Prints the exception stack trace showing the sequence of method calls that led to the exception.
Program 12: Method Overloading — Add two int, two float, and default values
____________________________________________________________
Q1. What is method overloading?
Multiple methods with the same name but different parameters (different number, type, or order of
parameters). Also called compile-time polymorphism.
Q2. Can method overloading be achieved by changing only the return type?
No. The compiler cannot distinguish methods based on return type alone. Parameters must differ.
Q3. Write overloaded add() methods for int and float.
A: int add(int a, int b) { return a+b; } float add(float a, float b) { return a+b; }
Q4. How does Java decide which overloaded method to call?
At compile-time, based on the argument types and number of arguments.
Q5. What is default value in method overloading?
Providing fallback values using a no-arg method: int add() { return add(10, 20); } calls the parameterized
version with defaults.
Q6. Can we overload main() in Java?
Yes, but only public static void main(String[]) is the entry point called by JVM. Other overloaded versions
must be called explicitly.
Q7. What is the difference between method overloading and method overriding?
Overloading: compile-time, same class, different params. Overriding: runtime, parent-child class, same
signature.
Q8. Output-based: add(10,20) and add(10.5f, 20.5f) — which version is called?
First calls int version, second calls float version (based on argument types).
Q9. Can we overload by changing the order of parameters?
Yes: add(int a, float b) and add(float a, int b) are different overloads.
Q10. What is type promotion in method overloading?
When exact match is not found, Java promotes smaller types to larger
(byte→short→int→long→float→double).
Q11. What happens if there is ambiguity between overloaded methods?
Compilation error. Example: add(int, float) and add(float, int) with add(10, 20) creates ambiguity.
Q12. Is method overloading a form of polymorphism?
Yes — it is compile-time polymorphism (static binding).
Q13. Can we overload constructors?
Yes. Constructor overloading is very common.
Q14. What is the benefit of method overloading?
Increases code readability by using the same method name for similar operations with different data
types.
Q15. Common mistake: Expecting return type to differentiate overloaded methods.
Causes compilation error: 'method already defined'.
Program 13: Run-Time Polymorphism (Method Overriding)
____________________________________________________________
Q1. What is runtime polymorphism?
The ability of a reference variable to determine which method to call at runtime based on the actual object
type. Achieved through method overriding.
Q2. What is method overriding?
Redefining a superclass method in a subclass with the same signature (name, parameters, return type).
Q3. What is dynamic method dispatch?
The mechanism by which a call to an overridden method is resolved at runtime. JVM decides which version
to execute based on the object type.
Q4. Rules for method overriding?
Same method name, same parameter list, same return type (or covariant), cannot have weaker access
modifier, cannot override final/static/private methods.
Q5. What is a covariant return type?
A subclass can override a method with a more specific (subtype) return type. E.g., superclass returns
Object, subclass returns String.
Q6. Can we override private methods?
No. Private methods are not visible to subclasses, hence cannot be overridden.
Q7. Can we override static methods?
No. Static methods are hidden (not overridden). Method resolution happens at compile-time based on
reference type.
Q8. What is the difference between method hiding and overriding?
Method hiding: static methods, compile-time resolution, based on reference type. Overriding: instance
methods, runtime resolution, based on object type.
Q9. Output-based: Parent p = new Child(); [Link]();
Child's show() is called (runtime polymorphism).
Q10. What is the instanceof operator?
Checks if an object is an instance of a particular class: if(obj instanceof Child) { }
Q11. Can we override a method with a different access modifier?
Yes, but the overriding method cannot have a more restrictive access modifier. protected→public is okay;
public→protected is not.
Q12. What is the super keyword in overriding?
[Link]() calls the parent class's overridden method from the child class.
Q13. What happens if we forget @Override?
The method still overrides if the signature matches. @Override just helps catch errors if signature is wrong.
Q14. Common mistake: Changing parameter list in overriding.
Changing parameters creates an overloaded method, not an overridden one. Add @Override to catch this.
Q15. What is the benefit of runtime polymorphism?
Enables code extensibility — parent class reference can hold any child object, and the correct method is
called automatically.
Program 14: Catch NegativeArraySizeException
____________________________________________________________
Q1. What is NegativeArraySizeException?
An exception thrown when an array is created with a negative size. E.g., int[] arr = new int[-5];
Q2. Which package does NegativeArraySizeException belong to?
[Link]
Q3. Is it checked or unchecked?
Unchecked (extends RuntimeException).
Q4. What happens if we don't handle NegativeArraySizeException?
The program terminates abnormally with an exception message and stack trace.
Q5. Write the try-catch block to handle it.
A: try { int[] arr = new int[size]; } catch(NegativeArraySizeException e) { [Link]("Negative
size!"); }
Q6. Can we create an array of size zero?
Yes: int[] arr = new int[0]; creates an empty array. No exception.
Q7. Can we create an array with Integer.MAX_VALUE?
Possible but usually throws OutOfMemoryError because there is insufficient heap space.
Q8. Output-based: int[] a = new int[-1]; [Link]([Link]);
NegativeArraySizeException thrown at the array creation line. Program terminates if unhandled.
Q9. What is the difference between NegativeArraySizeException and ArrayIndexOutOfBoundsException?
NegativeArraySizeException: thrown when creating array with negative size.
ArrayIndexOutOfBoundsException: thrown when accessing an invalid index.
Q10. How do you read array size from user input safely?
Use try-catch: try { size = [Link]([Link]()); arr = new int[size]; }
catch(NegativeArraySizeException e) { ... } catch(NumberFormatException e) { ... }
Q11. Can we use a finally block with this exception?
Yes. finally runs regardless of exception, useful for cleanup.
Q12. What is the superclass of NegativeArraySizeException?
RuntimeException → Exception → Throwable → Object
Q13. What is the difference between error and exception?
Errors (OutOfMemoryError, StackOverflowError) are serious problems beyond program control. Exceptions
are conditions that a program can handle.
Q14. Can we throw NegativeArraySizeException explicitly?
Yes: throw new NegativeArraySizeException("Invalid size");
Q15. Common mistake: Checking size with if only but not handling exception.
User input can be negative even after validation. Exception handling provides a safety net.
Q16. What is multi-catch in Java 7+?
catch(IOException | SQLException e) — handling multiple exceptions in one catch block.
Program 15: Handle NullPointerException with finally block
____________________________________________________________
Q1. What is NullPointerException?
An exception thrown when trying to access a method or field on an object reference that is null.
Q2. What are common causes of NullPointerException?
Calling a method on null, accessing a field on null, accessing array length on null, unboxing a null wrapper
to primitive.
Q3. How do you prevent NullPointerException?
Check for null before access: if(obj != null) { [Link](); }
Q4. What is the finally block used for?
Used to execute important cleanup code that must run regardless of exception (closing files, database
connections, releasing resources).
Q5. Does finally execute if there is a return in try?
Yes. The finally block executes before the return statement completes.
Q6. What happens if both catch and finally have return statements?
The finally return overrides the catch return.
Q7. Output-based: String s = null; try { [Link](); } catch(NullPointerException e)
{ [Link]("Caught"); } finally { [Link]("Finally"); }
Output: Caught (followed by) Finally
Q8. Is NullPointerException checked or unchecked?
Unchecked — it extends RuntimeException.
Q9. Which package is NullPointerException in?
[Link]
Q10. Can we use try-with-resources for NullPointerException?
No. try-with-resources is for AutoCloseable resources. NullPointerException handling uses regular try-
catch.
Q11. What is Optional class (Java 8+)?
A container that may or may not contain a value. Helps avoid NullPointerException by explicitly handling
empty cases.
Q12. What is [Link]()?
Returns the object if non-null, otherwise throws NullPointerException with a custom message.
Q13. Does finally execute if [Link]() is called in try?
No. [Link]() terminates the JVM immediately, so finally does NOT execute.
Q14. Common mistake: Not checking parameters for null before use.
Always validate method parameters that may be null.
Q15. What is the difference between [Link]() and [Link]()?
getMessage() returns detail message only. toString() returns class name + detail message.
Program 16: Import and use User-Defined Packages
____________________________________________________________
Q1. What is a package in Java?
A package is a namespace that groups related classes and interfaces. It organizes code and prevents
naming conflicts.
Q2. How do you create a package?
Using the package keyword at the top of the source file: package mypackage;
Q3. How do you import a package?
Using the import keyword: import [Link]; or import mypackage.*;
Q4. What is the default package?
When no package is declared, classes go into the default (unnamed) package. Not recommended for real
projects.
Q5. What is the directory structure for packages?
The package name must match the directory structure. [Link] must be in
mypackage/[Link].
Q6. What is the difference between import and package?
package declares which package the class belongs to. import tells the compiler where to find classes from
other packages.
Q7. What is the [Link] package?
The default package imported automatically. Contains core classes like String, Math, System, Object.
Q8. Can we import classes from the default package?
No. Classes from the default package cannot be imported. They must be in the same directory.
Q9. What is a fully qualified name?
The complete name including the package: [Link]. Can be used without import.
Q10. What is the difference between import and #include (C/C++)?
import tells the compiler where to find class definitions at compile time. #include copies the entire header
file.
Q11. How does the CLASSPATH affect packages?
CLASSPATH tells the JVM where to look for package directories and JAR files.
Q12. What is a static import?
import static [Link]; — allows using static members without class name: sqrt(25) instead of
[Link](25).
Q13. Can two packages have classes with the same name?
Yes. Use fully qualified names to distinguish them: [Link] and [Link].
Q14. Common mistake: Forgetting that package declaration must be the first line.
package statement must be the first non-comment line. import comes after package.
Q15. How to compile a packaged class?
javac -d . [Link] (creates directory structure automatically).
Q16. How to run a packaged class?
java [Link]
Program 17: Check whether a number is Palindrome or not
____________________________________________________________
Q1. What is a palindrome number?
A number that reads the same forwards and backwards. E.g., 121, 12321, 4554.
Q2. Write the logic to check palindrome.
A: Reverse the number using a loop: while(n>0) { rev = rev*10 + n%10; n /= 10; } Then compare rev with
original.
Q3. How do you extract the last digit of a number?
Using modulus: n % 10 gives the last digit.
Q4. How do you remove the last digit?
n / 10 removes the last digit (integer division).
Q5. What is the algorithm for palindrome?
1. Store original number as temp. 2. Initialize rev=0. 3. While temp>0: digit=temp%10; rev=rev*10+digit;
temp/=10. 4. If rev == original → palindrome.
Q6. Output-based: Is 12321 a palindrome?
Yes. Reverse is also 12321.
Q7. Output-based: Is 123 a palindrome?
No. Reverse is 321, which is not equal to 123.
Q8. Can a single-digit number be a palindrome?
Yes. All single-digit numbers (0-9) are palindromes.
Q9. What is the while loop syntax?
while(condition) { statements; }
Q10. What is the difference between while and do-while?
while: condition checked before execution (may execute 0 times). do-while: condition checked after
(executes at least once).
Q11. What is the role of temp variable?
temp stores a copy of the original number so we can modify it during reversal without losing the original
value for comparison.
Q12. How do you check palindrome for a String?
Use StringBuilder: new StringBuilder(str).reverse().toString().equals(str)
Q13. Common mistake: Modifying the original number directly.
If you modify n directly, you lose the original value. Always use a temporary variable.
Q14. What is the time complexity of palindrome check?
O(d) where d is the number of digits.
Q15. Can negative numbers be palindromes?
Usually no, because the minus sign makes it asymmetric. Some implementations reject negative numbers.
Program 18: Factorial using Command Line Arguments
____________________________________________________________
Q1. What are command line arguments?
Arguments passed to the program when running from the command line. Accessed via String[] args
parameter of main().
Q2. How do you pass command line arguments?
java ClassName arg1 arg2 arg3. Each argument is separated by space.
Q3. How do you access command line arguments in Java?
Through the args array: args[0], args[1], etc. [Link] gives the count.
Q4. How do you convert a String argument to an integer?
int n = [Link](args[0]);
Q5. What exception can occur during parseInt()?
NumberFormatException if the string is not a valid integer.
Q6. Write the factorial logic.
A: int fact = 1; for(int i=1; i<=n; i++) { fact *= i; }
Q7. What is a factorial?
Factorial of n (n!) = n * (n-1) * (n-2) * ... * 1. Example: 5! = 120.
Q8. What is 0! ?
0! = 1 (by definition).
Q9. Output-based: java Factorial 5
120
Q10. Output-based: What happens for java Factorial? (no args)
ArrayIndexOutOfBoundsException because args[0] does not exist. Check [Link] first.
Q11. How do you handle insufficient arguments?
if([Link] == 0) { [Link]("Please provide a number"); return; }
Q12. What is the maximum factorial that int can hold?
12! = 479001600 fits in int. 13! overflows int (requires long). 21! overflows long (requires BigInteger).
Q13. How to handle large factorials?
Use BigInteger: BigInteger fact = [Link]; for(...) { fact = [Link]([Link](i)); }
Q14. What is the wrapper class for int?
Integer — provides methods like parseInt(), toString(), etc.
Q15. Common mistake: Not checking [Link] before accessing args[0].
Causes ArrayIndexOutOfBoundsException at runtime.
Q16. What is autoboxing and unboxing?
Automatic conversion between primitive types and their wrapper classes. E.g., Integer i = 10; (autoboxing),
int j = i; (unboxing).
Program 19: Display all Prime Numbers between two limits
____________________________________________________________
Q1. What is a prime number?
A number greater than 1 that is divisible only by 1 and itself. E.g., 2, 3, 5, 7, 11.
Q2. Is 1 a prime number?
No. 1 is neither prime nor composite.
Q3. Is 2 a prime number?
Yes. 2 is the smallest and only even prime number.
Q4. Write logic to check if a number is prime.
A: boolean isPrime = true; for(int i=2; i<=n/2; i++) { if(n%i==0) { isPrime=false; break; } }
Q5. What is the optimized condition for prime check?
Check up to sqrt(n): for(int i=2; i*i<=n; i++). Because if n has a divisor > sqrt(n), the complementary divisor
is < sqrt(n).
Q6. What are nested loops?
A loop inside another loop. Used here: outer loop iterates numbers, inner loop checks each for primality.
Q7. What is the break statement?
Terminates the innermost loop. Used in prime check to exit early when a divisor is found.
Q8. Output-based: Prime numbers between 10 and 20.
11, 13, 17, 19
Q9. Output-based: Prime numbers between 1 and 10.
2, 3, 5, 7
Q10. What is the time complexity of checking primes up to n?
O(n * sqrt(n)) for the naive approach.
Q11. What is the Sieve of Eratosthenes?
An efficient algorithm to find all primes up to n. O(n log log n) time. Uses a boolean array to mark multiples
of primes.
Q12. What is a flag variable?
A boolean variable used to track whether a condition is met (e.g., isPrime flag).
Q13. What is the continue statement?
Skips the current iteration and moves to the next iteration of the loop.
Q14. Common mistake: Forgetting that 1 is not prime.
The loop should skip numbers less than 2.
Q15. How to print primes between a and b?
for(int i=a; i<=b; i++) { if(isPrime(i)) [Link](i + " "); }
Q16. Can a negative number be prime?
No. By definition, prime numbers are positive integers greater than 1.
Program 20: Create a Thread using Runnable Interface
____________________________________________________________
Q1. What is a Thread in Java?
A thread is a lightweight process that runs concurrently with other threads. Java supports multithreading
for concurrent execution.
Q2. What are the two ways to create a thread in Java?
1. Implement the Runnable interface. 2. Extend the Thread class.
Q3. Which method must be implemented for Runnable?
The run() method: public void run() { }
Q4. How do you start a thread using Runnable?
Thread t = new Thread(new MyRunnable()); [Link]();
Q5. What is the difference between start() and run()?
start() creates a new thread and calls run() in that thread. run() executes in the current thread if called
directly (no new thread).
Q6. What is the advantage of Runnable over Thread class?
Java does not support multiple inheritance. If you extend Thread, you cannot extend another class.
Runnable allows extending another class.
Q7. What is the run() method?
Entry point of the thread. Contains the code that will be executed in the new thread.
Q8. What is the sleep() method?
[Link](milliseconds) pauses the current thread for the specified time. Throws InterruptedException.
Q9. What is the join() method?
[Link]() makes the current thread wait until thread t completes.
Q10. Output-based: If run() prints "Hello" and start() is called, what happens?
A new thread prints "Hello" (possibly interleaved with main thread output).
Q11. What is the thread life cycle?
New → Runnable → Running → Blocked/Waiting → Terminated/Dead.
Q12. What is the yield() method?
Suggests to the thread scheduler that the current thread is willing to pause and let other threads run.
Q13. What is the daemon thread?
A low-priority background thread (e.g., garbage collector). JVM exits when only daemon threads remain.
Q14. What is synchronization?
Mechanism to control access to shared resources by multiple threads. Use synchronized keyword.
Q15. What is thread priority?
Priority from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), default 5 (NORM_PRIORITY). Higher priority
threads get more CPU time.
Q16. Common mistake: Calling run() instead of start().
run() executes in the main thread sequentially, not creating a new thread.
Q17. What is the Runnable functional interface?
Runnable is a functional interface with a single abstract method run(). Can be used with lambda: Thread t =
new Thread(() -> { [Link]("Running"); });
Q18. What is the difference between concurrency and parallelism?
Concurrency: multiple threads making progress (interleaved). Parallelism: multiple threads executing
simultaneously (multi-core).
Quick Reference Summary
Program-wise Key Topics Covered
No Program Key Concepts
1 Hello World, Data Types Class, main(), primitives, sizes, [Link]
2 Variable Types Static, instance, local variables, memory,
scope
3 String Operations Immutability, String pool, length(),
concat(), substring()
4 Max of Three Numbers Ternary, if-else, Scanner, edge cases
5 Odd/Even Check Modulus %, bitwise &, negative numbers
6 Constructors Default, parameterized, overloading,
this(), super()
7 Array of Objects Null references, instantiation,
NullPointerException
8 Single Inheritance extends, super, overriding, final, Object
class
9 Multiple Inheritance (Interface) interface, implements, default methods,
functional interface
10 Applet Life Cycle init(), start(), paint(), stop(), destroy(),
deprecation
11 Division by Zero ArithmeticException, try-catch-finally,
Infinity
12 Method Overloading Compile-time polymorphism, type
promotion, default values
13 Run-Time Polymorphism Overriding, dynamic method dispatch,
instanceof
14 NegativeArraySizeException Array creation, unchecked exception,
handling
15 NullPointerException + finally Null check, Optional, finally execution
guarantee
16 User-Defined Packages package, import, directory structure,
CLASSPATH
17 Palindrome While loop, digit extraction, reversal
algorithm
18 Command Line Arguments args[], parseInt(), factorial, BigInteger
19 Prime Numbers Nested loops, break, sqrt optimization,
Sieve
20 Thread via Runnable Runnable, start() vs run(), sleep(),
synchronization