BCA II SEM, JAVA MANUAL AND VIVA Q&As

 PROGRAMMING WITH JAVA

VIVA QUESTIONS AND ANSWERS

 

BASICS OF OOPS AND JAVA

1. What is Object-Oriented Programming (OOP)?

Answer:
Object-Oriented Programming is a programming paradigm that organizes software design around objects rather than functions and logic. An object represents a real-world entity and contains both data (variables) and behavior (methods). OOP helps in modularity, reusability, and maintainability of code.

2. What are the four main principles of OOP?

Answer:

  1. Encapsulation – Wrapping data and methods into a single unit (class).
  2. Inheritance – Acquiring properties of one class into another.
  3. Polymorphism – One interface, multiple forms (method overloading/overriding).
  4. Abstraction – Hiding implementation details and showing only essential features.

3. What is a Class?

Answer:
A class is a user-defined data type that acts as a blueprint for creating objects. It contains variables (data members) and methods (functions) that define the behavior of the object.

4. What is an Object?

Answer:
An object is an instance of a class. It represents a real-world entity and occupies memory. Objects can access the properties and methods defined in the class.

5. What is Encapsulation?

Answer:
Encapsulation is the process of binding data and methods together into a single unit. It is achieved using classes and access modifiers (private, public, protected). It improves data security by restricting direct access.

6. What is Inheritance?

Answer:
Inheritance is a mechanism where one class (child/subclass) acquires properties and behaviors of another class (parent/superclass). It promotes code reuse and hierarchical classification.

7. What is Polymorphism?

Answer:
Polymorphism means "many forms." It allows the same method name to perform different operations depending on the parameters (method overloading) or object type (method overriding).

8. What is Abstraction?

Answer:
Abstraction hides internal implementation details and exposes only necessary functionalities. It is achieved using abstract classes and interfaces.

9. What is a Constructor?

Answer:
A constructor is a special method used to initialize objects. It has the same name as the class and does not have a return type. It is automatically called when an object is created.

10. What is Method Overloading?

Answer:
Method overloading is the process of defining multiple methods with the same name but different parameters (type, number, or order). It is an example of compile-time polymorphism.

11. What is Java?

Answer:
Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems. It follows the principle “Write Once, Run Anywhere” (WORA).

12. Why is Java platform-independent?

Answer:
Java is platform-independent because it uses the Java Virtual Machine (JVM). The Java compiler converts source code into bytecode, which is executed by JVM on any system.

13. What is JVM?

Answer:
JVM (Java Virtual Machine) is responsible for executing Java bytecode. It provides platform independence and memory management.

14. What is JDK and JRE?

Answer:

  • JDK (Java Development Kit): Used for developing Java programs.
  • JRE (Java Runtime Environment): Provides runtime environment to execute Java programs.

 

15. What is Exception Handling?

Answer:
Exception handling is a mechanism to handle runtime errors using try, catch, finally, throw, and throws keywords. It prevents program termination.

 

PROGRAM-WISE DETAILED VIVA Q&As

 

LAB A1: Program to Find Positive, Negative or Zero

1. What is the objective of this program?
The objective of this program is to read an integer input from the user and determine whether it is positive, negative, or zero using conditional statements. It demonstrates basic decision-making in programming.

2. Which control structure is used in this program and why?
The program uses the if-else-if ladder. This structure is used because multiple mutually exclusive conditions need to be evaluated in sequence.

3. How does the program take input from the user?
The program uses the Scanner class from the
java.util package to read input from the keyboard using nextInt() method.

4. What is the role of relational operators in this program?
Relational operators such as
>, <, and == are used to compare the input number with zero and determine its category.

5. What happens if the user enters zero?
If the input number is zero, none of the first two conditions (
num > 0 or num < 0) are satisfied, so the control moves to the else block, which prints that the number is zero.

6. Why is the else block important here?
The else block acts as a default condition when all previous conditions fail, ensuring that all possible cases are handled.

7. Can this logic be implemented using switch statement? Why or why not?
No, because the switch statement works with discrete constant values, whereas this problem involves range-based conditions (greater than or less than zero).

8. What is the data type of the input variable and why?
The input variable is of type
int because the program deals with whole numbers.

9. What will happen if invalid input (like a string) is entered?
The program will throw an InputMismatchException, since
nextInt() expects an integer input.

10. What is the time complexity of this program?
The time complexity is O(1) because the program executes a constant number of operations.

 

LAB A2: Program to Find Factorial of Numbers 1 to 10

1. What is factorial and how is it mathematically defined?
Factorial of a number
n is defined as:
n! = n × (n-1) × (n-2) × ... × 1
Special case: 0! = 1

2. Why are two loops used in this program?

  • The outer loop iterates from 1 to 10.
  • The inner loop calculates the factorial of each number.

3. Why is the factorial variable initialized to 1?
Because factorial involves multiplication, and 1 is the identity element for multiplication.

4. Why is long data type used instead of int?
Factorial values grow rapidly and may exceed the range of int. Using
long prevents overflow for larger values.

5. What is the time complexity of this program?
The time complexity is O(n²) due to nested loops.

6. Can factorial be calculated using recursion?
Yes. A recursive approach calls the same function repeatedly until the base condition is reached.

7. What is the space complexity?
O(1), since no extra memory is used apart from variables.

8. What is the difference between iterative and recursive factorial?

  • Iterative uses loops
  • Recursive uses function calls and stack memory

9. What happens if factorial is calculated for a very large number?
It may cause overflow even in long datatype or stack overflow in recursion.

10. Why is this program important?
It helps understand loops, nested loops, and mathematical computation in programming.

 

LAB A3: Program to Demonstrate Class and Object

1. What is demonstrated in this program?
This program demonstrates the creation of a class and objects, along with accessing data members and methods.

2. What is a class in this program?
StudentA3 is a class that defines attributes (name, age) and behavior (display method).

3. What is an object and how is it created?
An object is an instance of a class. It is created using the
new keyword: StudentA3 s1 = new StudentA3();

4. Where are objects stored in memory?
Objects are stored in heap memory, and reference variables are stored in stack memory.

5. What is the purpose of the display() method?
It is used to print the values of the object's attributes.

6. What is a reference variable?
It stores the memory address of the object.

7. Can multiple objects be created from a class?
Yes, a class can have multiple objects.

8. What is the advantage of using classes and objects?
They help in modular programming, code reuse, and better data organization.

9. What is default initialization?
If values are not assigned, Java assigns default values like 0, null, etc.

10. What is the difference between class and object?
Class is a blueprint, object is an instance.

 

LAB A4: Method Overloading

1. What is method overloading?
Defining multiple methods with the same name but different parameter lists.

2. On what basis does Java differentiate overloaded methods?
Based on number, type, and order of parameters.

3. Does return type play a role in overloading?
No, return type alone cannot differentiate methods.

4. Is method overloading compile-time or runtime polymorphism?
Compile-time polymorphism.

5. What is the advantage of method overloading?
Improves readability and reduces code duplication.

6. Can constructors be overloaded?
Yes.

7. What happens if parameters are same?
Compiler error occurs.

8. Can different data types be used?
Yes, like int, double.

9. What is static binding?
Binding done at compile time (method overloading).

10. Example use case?
Calculator methods with different inputs.

LAB A5: Inheritance

1. What is inheritance?
Mechanism of acquiring properties of another class.

2. Which keyword is used?
extends

3. What is base class and derived class?

  • Base class: SimpleCalculator
  • Derived class: AdvancedCalculator

4. What is the benefit of inheritance?
Code reuse and hierarchical structure.

5. What types of inheritance exist in Java?
Single, Multilevel, Hierarchical (Multiple via interfaces).

6. Can private members be inherited?
No, they cannot be accessed directly.

7. What is method overriding?
Redefining parent method in child class.

8. What is super keyword?
Used to access parent class members.

9. What is IS-A relationship?
Represents inheritance relationship.

10. Why is inheritance important?
Reduces redundancy and improves maintainability.

 

LAB A6: Array Max and Min

1. What is an array?
A collection of elements of the same data type stored in contiguous memory.

2. How is maximum element found?
By comparing each element with current maximum.

3. Why initialize max and min with first element?
To have a valid reference for comparison.

4. What loop is used?
For loop.

5. What is arr.length?
It gives the size of the array.

6. Can arrays store different data types?
No, only same data type.

7. What is time complexity?
O(n)

8. Alternative approach?
Sorting the array.

9. Why sorting is less efficient?
Sorting takes O(n log n) time.

10. What is index of array?
Position of element starting from 0.

 

LAB A7: Palindrome String

1. What is a palindrome string?
A string that reads the same forward and backward.

2. Why convert to lowercase?
To avoid case sensitivity issues.

3. Why remove spaces?
To ensure correct comparison.

4. What is the logic used?
Reverse the string and compare with original.

5. What is the correct comparison method?
cleanStr.equals(rev)

6. Why equals() instead of ==?
equals() compares content, == compares reference.

7. What is string immutability?
Strings cannot be changed after creation.

8. What is time complexity?
O(n)

9. Alternative method?
Using StringBuilder reverse().

10. Common error in this program?
Wrong comparison and incorrect string handling.

LAB A8: Student Class

1. What is object array?
Array that stores objects.

2. Why use class here?
To group student data and behavior.

3. What is calculateTotal()?
Method to compute total marks.

4. What is enhanced for loop?
Simplified loop to iterate objects.

5. Why use multiple objects?
To store multiple student records.

6. What is encapsulation here?
Combining data and methods in class.

7. What is constructor?
Used to initialize objects (not used here but important).

8. Can we use ArrayList instead?
Yes, dynamic size.

9. What is advantage of object array?
Better data organization.

10. Real-world example?
Student management system.

 

PART - B

LAB B1: NegativeArraySizeException

1. What is NegativeArraySizeException?
NegativeArraySizeException is a runtime exception that occurs when a program tries to create an array with a negative size. Since array size must always be zero or positive, Java throws this exception to prevent invalid memory allocation.

2. Why does this exception occur?
It occurs when a negative value is passed as the size while declaring an array, for example:
int[] arr = new int[-5];
This is logically incorrect because memory cannot be allocated for a negative number of elements.

3. At what stage does this exception occur?
It occurs at runtime, not at compile time, because the size may depend on user input or variable values evaluated during execution.

4. How is this exception handled?
It is handled using a try-catch block, where the risky code is placed inside the try block and the exception is caught in the catch block to prevent program termination.

 

5. Is NegativeArraySizeException checked or unchecked? Why?
It is an unchecked exception because it occurs during runtime and is not checked by the compiler. It belongs to the RuntimeException class.

6. How can this exception be prevented?
By validating the array size before creating it:

  • Ensure the size is greater than or equal to zero
  • Use conditional checks before allocation

7. What is the importance of handling this exception?
Handling this exception prevents abrupt program termination and allows the program to continue execution safely.

8. What happens if this exception is not handled?
The program will terminate abnormally and display an error message.

 

LAB B2: NullPointerException

1. What is NullPointerException?
NullPointerException occurs when a program attempts to use an object reference that has not been initialized (i.e., it is null).

2. When exactly does this exception occur?
It occurs when:

  • Calling a method on a null object
  • Accessing or modifying a null object’s field
  • Taking the length of a null array

3. Give an example of NullPointerException.

String str = null;
System.out.println(str.length());

This will throw NullPointerException because str is null.

4. Why is this exception dangerous?
Because it causes program crashes and indicates improper handling of object references.

5. How can this exception be handled?
Using try-catch block:

try {
   // code
} catch (NullPointerException e) {
   // handling
}

6. How can it be prevented?

  • Always initialize objects before use
  • Perform null checks:
    if (str != null)
  • Use defensive programming techniques

7. Is it checked or unchecked?
Unchecked exception (RuntimeException).

8. What is the best practice to avoid NullPointerException?
Always ensure proper object initialization and validation before accessing methods or properties.

 

LAB B3: NumberFormatException

1. What is NumberFormatException?
It is a runtime exception that occurs when a string is converted into a numeric type (like int or double), but the string does not contain a valid number.

2. When does this exception occur?
When invalid input such as letters or special characters is passed to methods like:

  • Integer.parseInt()
  • Double.parseDouble()

3. Give an example.

int num = Integer.parseInt("ABC");

This will throw NumberFormatException.

4. What method is commonly used in this program?
Integer.parseInt()

5. How is this exception handled?
Using try-catch block to catch invalid input and display an appropriate error message.

6. How can this exception be prevented?

  • Validate input before conversion
  • Use exception handling
  • Use regular expressions for input validation

7. Why is input validation important?
To ensure the program receives correct data and avoids runtime errors.

8. Is this exception checked or unchecked?
Unchecked exception.

 

LAB B4: AWT Buttons Program

1. What is AWT?
AWT (Abstract Window Toolkit) is a Java library used to create graphical user interfaces (GUI). It provides components like buttons, labels, frames, etc.

2. What is a Frame?
A Frame is a top-level window in AWT that acts as a container for other GUI components.

3. What is a Button?
A Button is a GUI component that triggers an action when clicked.

4. What is ActionListener?
ActionListener is an interface used to handle button click events. It contains the method
actionPerformed().

5. What is event-driven programming?
A programming paradigm where program execution is controlled by events such as user actions (clicks, typing).

6. What is FlowLayout?
A layout manager that arranges components in a left-to-right flow.

7. What happens when a button is clicked?
An event is generated and handled by the
actionPerformed() method.

8. What is the role of setVisible(true)?
It makes the frame visible on the screen.

9. What is WindowListener?
It handles window events like closing the window.

10. Why is GUI important?
It improves user interaction and makes applications user-friendly.

LAB B5: Mouse Events Program

1. What is MouseListener?
MouseListener is an interface used to handle mouse-related events such as clicks, presses, and movement.

2. What are the methods in MouseListener?

  • mouseClicked()
  • mousePressed()
  • mouseReleased()
  • mouseEntered()
  • mouseExited()

3. Which method is used in this program?
mouseClicked() is used to detect mouse click events.

4. What is MouseEvent?
It is an event class that contains information about mouse actions.

5. What happens when the mouse is clicked?
The label text is updated to display a message.

6. What is the role of addMouseListener()?
It registers the mouse listener with the component.

7. Difference between mousePressed and mouseClicked?

  • mousePressed: triggered when button is pressed
  • mouseClicked: triggered after press and release

8. What is event handling?
Responding to user interactions like mouse clicks.

 

LAB B6: Binary File Read/Write

1. What is a binary file?
A binary file stores data in raw byte format rather than human-readable text.

2. What is FileOutputStream?
It is used to write data to a file in binary format.

3. What is FileInputStream?
It is used to read data from a binary file.

4. How does writing occur?
Using
write() method which writes bytes to file.

5. How does reading occur?
Using
read() method which reads one byte at a time.

6. What is EOF (End of File)?
Indicated by -1 when no more data is available.

7. What are advantages of binary files?

  • Faster processing
  • Efficient storage
  • Compact format

8. Difference between binary and text file?

  • Binary: machine-readable
  • Text: human-readable

9. What happens if file is not found?
Throws FileNotFoundException.

10. Why exception handling is used here?
To handle file-related errors safely.

 

LAB B7: Family AWT Program

1. What is the purpose of this program?
To display family details using buttons in a GUI.

2. What is getSource()?
It identifies which button generated the event.

3. What is Label?
A component used to display text.

4. What is layout manager?
Controls arrangement of components.

5. What is ActionListener used for?
Handling button click events.

6. How is close button implemented?
Using
System.exit(0).

7. What is event handling?
Responding to user actions dynamically.

8. What is GUI advantage?
User-friendly interaction.

LAB B8: Menu Bar Program

1. What is MenuBar?
A container that holds menus in a GUI application.

2. What is a Menu?
A dropdown list that contains menu items.

3. What is MenuItem?
An individual selectable option within a menu.

4. What is a pull-down menu?
A menu that appears when clicked and shows options.

5. How is MenuBar added to frame?
Using
setMenuBar() method.

6. What is hierarchy in menu?
MenuBar → Menu → MenuItem

7. What is purpose of menu?
To provide organized options to user.

8. Can menu items have events?
Yes, using ActionListener.

9. What is GUI usability?
Ease of use for users.

Programming with Java Viva Questions and Answers

Click here to Download (Google Drive)


📚 STUDY WITH YASHVANTH
More notes, explanations & exam-oriented content coming soon!

Comments

Popular posts from this blog

ABOUT : STUDY WITH YASHVANTH

ABOUT AUTHOR

BCA III SEM, DBMS SYLLABUS & NOTES