Java Practical Viva Questions Answers
Java Practical Viva Questions Answers
1. Control Structures
Control structures are used to dictate the flow of execution in a program. They help in
making decisions, repeating actions, or branching the control flow.
The difference is that 'if' statements check conditions, 'switch' executes code based on the
value of a variable, and loops repeat actions.
Constructors are special methods that are called when an object is created. They often
initialize the object’s attributes.
The 'this' keyword refers to the current object. It helps to differentiate between class
attributes and parameters.
3. Method Overloading
Method overloading allows multiple methods to have the same name but different
parameters.
Example of method overloading:
Java determines which method to call based on the method signature (method name and
parameter types).
4. Single Inheritance
Inheritance allows a class to inherit properties and methods from another class. Single
inheritance means a class inherits from one superclass.
class Animal {}
class Dog extends Animal {}
The 'super' keyword is used to refer to the superclass's methods and constructors.
5. Polymorphism
Polymorphism allows methods to do different things based on the object that it is acting
upon.
6. Arrays
An array is a collection of elements of the same type, while an ArrayList can grow and
shrink in size.
7. Packages
Packages are used to group related classes and interfaces. They help in organizing code.
You create a package using the 'package' keyword at the top of your Java file:
package myPackage;
8. Interfaces
An interface is a reference type in Java that can contain only constants, method signatures,
default methods, static methods, and nested types. It is different from an abstract class
because it cannot have instance fields.
Example:
9. Exception Handling
Exception handling in Java is a mechanism to handle runtime errors, allowing the normal
flow of the program to be maintained.
Syntax:
try {
// code that may throw an exception
} catch (ExceptionType e) {
// handle exception
} finally {
// cleanup code
}
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}