Java Viva Questions and Answers with
Syntax
1. What is a Class in Java?
A class is a blueprint for creating objects. It defines variables and methods that describe object
behavior.
<b>Syntax</b> <font face='Courier'>class ClassName {
int x;
void display() {
[Link]('Hello');
}
}</font>
2. What is an Object?
An object is an instance of a class created using the new keyword.
<b>Syntax</b> <font face='Courier'>ClassName obj = new ClassName();</font>
3. Difference between Constructor and Method
Constructor initializes an object, has same name as class, no return type. Method performs
operations, has return type, must be called explicitly.
<b>Syntax</b> <font face='Courier'>class Sample {
Sample() {} // Constructor
void show() {} // Method
}</font>
4. What is the use of new Keyword?
Used to create objects dynamically and allocate memory.
<b>Syntax</b> <font face='Courier'>ClassName obj = new ClassName();</font>
5. Can we have multiple classes in one .java file?
Yes, but only one class can be public and it must match the filename.
<b>Syntax</b> <font face='Courier'>public class Main {}
class Helper {}</font>
6. What if filename doesn’t match public class name?
It results in a compile-time error.
<b>Syntax</b> <font face='Courier'>Filename: [Link]
public class Teacher {} // Error</font>
7. Role of main() Method in Java
It acts as the entry point for Java program execution.
<b>Syntax</b> <font face='Courier'>public static void main(String[] args) {
[Link]('Program starts');
}</font>
8. Difference between POP and OOP
POP focuses on functions; OOP focuses on objects, encapsulation, and inheritance.
<b>Syntax</b> <font face='Courier'>POP: void sum() {}
OOP: class Calculator { void sum(){} }</font>
9. What is Method Overloading?
Multiple methods with same name but different parameters.
<b>Syntax</b> <font face='Courier'>void show(int a){}
void show(String s){}</font>
10. What is Constructor Overloading?
Multiple constructors in a class with different parameters.
<b>Syntax</b> <font face='Courier'>Student(){}
Student(String name){}</font>
11. What is Inheritance?
Process where one class acquires properties and behavior of another using extends keyword.
<b>Syntax</b> <font face='Courier'>class Parent {}
class Child extends Parent {}</font>
12. What is Interface in Java?
Interface is a collection of abstract methods used to achieve abstraction and multiple inheritance.
<b>Syntax</b> <font face='Courier'>interface A { void show(); }
class B implements A { public void show(){} }</font>
13. Interface in Multiple Inheritance
Java uses interfaces to achieve multiple inheritance.
<b>Syntax</b> <font face='Courier'>interface A{}
interface B{}
class C implements A, B{}</font>
14. What is Method Overriding?
Subclass provides new definition for a method defined in parent class.
<b>Syntax</b> <font face='Courier'>class Parent{ void show(){} }
class Child extends Parent{ void show(){} }</font>