0% found this document useful (0 votes)
141 views10 pages

Viva Voice Questions and Answers

Uploaded by

sanjaygoud61065
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
141 views10 pages

Viva Voice Questions and Answers

Uploaded by

sanjaygoud61065
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Viva Voice Questions and Answers

Q1) Write a Java application to display Hello World message.

Questions and Answers

1. What is the syntax for printing "Hello, World!" in Java?

Answer:
System.out.println("Hello, World!");

2. What is the purpose of the main method in Java?

Answer:
The main method is the entry point of any Java application. The Java Virtual Machine (JVM) invokes this method
to execute the program.

3. Why do we use public static void main(String[] args)?

Answer:

 public: Makes the method accessible from anywhere.

 static: Allows the JVM to call the method without creating an instance of the class.

 void: The method does not return any value.

 String[] args: Accepts command-line arguments as an array of String.

4. What is System.out.println() mean?

Answer:
 System:

 It is a predefined class in the java.lang package.

 It provides access to system-related functionalities like standard input, output, and error streams.

 out:

 It is a static member of the System class.

 It represents the standard output stream (console) and is an instance of the PrintStream class.

 println:

 It is a method of the PrintStream class.

 It prints the provided argument to the standard output and adds a newline at the end.

5. Why is the class name the same as the file name in Java?
Answer:
In Java, the public class name must match the file name to avoid compilation errors. This ensures that the JVM
can correctly identify and execute the program.

6. What happens if we misspell main as Main?

Answer:
The program will not run because the JVM specifically looks for the method signature public static void
main(String[] args).

7. What is the significance of String[] args in the main method?


Answer:

It is used to pass command-line arguments to the program.

8. What is the role of String[] args in the main method?

Answer:
String[] args is used to pass command-line arguments to the program. Each argument is stored as a string in the
array.

9. Is it mandatory to have a main method in every Java program?

Answer:
Yes, for standalone Java applications. However, in Java frameworks (like servlets or Android), entry points may
differ.

10. What happens if we write System.out.println('Hello, World!'); instead of using double quotes?

Answer:
It will result in a compilation error. Single quotes (') are used for char literals, while double quotes (") are for
String literals.

Q2) Write a Java application to perform all arithmetic operations using Scanner class

Viva voice Q&A

1. What is the Scanner class used for?

Answer:
The Scanner class in Java is used to read input from various sources such as the keyboard, files, or input streams. It is
part of the java.util package and provides methods to parse input into primitive data types and strings.

2. What are some commonly used methods in the Scanner class?


Answer:

 nextInt(): Reads an integer.

 nextDouble(): Reads a double.

 nextLine(): Reads an entire line of text.

 next(): Reads a single word.

 hasNext(): Checks if there is more input available.

3. How do you handle invalid inputs with the Scanner class?

Answer:
You can use hasNextXxx() methods (e.g., hasNextInt(), hasNextDouble()) to validate the input type before reading it.
Example:

if (scanner.hasNextInt()) {

int num = scanner.nextInt();

} else {

System.out.println("Invalid input!");

4. What happens if you use nextInt() but the input is not an integer?

Answer:
If the input is not an integer, a java.util.InputMismatchException is thrown. This can be avoided using validation
methods like hasNextInt().

5. What is the difference between next() and nextLine()?

Answer:

 next(): Reads a single word (stops at space).

 nextLine(): Reads the entire line until a newline character.

6. What are Wrapper Classes in Java?

Answer:
Wrapper classes are used to convert primitive data types (e.g., int, double) into objects (Integer, Double). They provide
utility methods and allow primitives to be used in object-oriented features like collections.

7. What is Autoboxing and Unboxing?

Answer:
Autoboxing: Automatic conversion of a primitive type to its corresponding wrapper object.
Example:

 int num = 5;

 Integer obj = num; // Autoboxing

Unboxing: Automatic conversion of a wrapper object to its primitive type.


Example:

 Integer obj = 10;

 int num = obj; // Unboxing

8. List some commonly used methods in Wrapper Classes.

Answer:

 parseXxx(String): Converts a string to a primitive type.

 valueOf(String): Converts a string to a wrapper object.

 toString(): Converts an object to a string.

 compareTo(obj): Compares two wrapper objects.

9. Why are Wrapper Classes immutable?

Answer:
Wrapper classes are immutable to ensure their values remain consistent and thread-safe. Once a wrapper object is
created, its value cannot be changed.

10. What is the caching mechanism in Wrapper Classes?

Answer:
For performance optimization, some wrapper classes (e.g., Integer, Long) cache values in the range -128 to 127. This
means objects within this range are reused instead of creating new ones.

Q3) Write a Java application to perform all arithmetic operations using JOptionPane, class

Java Application to Perform All Arithmetic Operations Using JOptionPane

1. What is JOptionPane used for in Java?

Answer:
JOptionPane is part of the javax.swing package and is used to create standard dialog boxes to interact with the user in
graphical user interface (GUI) applications. It allows you to display messages, prompt users for input, and get user
selections.

2. What are the main methods of JOptionPane used in this program?

Answer:
 showInputDialog(String message): Displays a dialog box to get input from the user.

 showMessageDialog(Component parentComponent, String message, String title, int messageType): Displays a


message to the user in a dialog box. In this program, it is used to show the results of the arithmetic operations.

3. How does the program convert the input to a numeric value for calculations?

Answer:
The inputs received from JOptionPane.showInputDialog() are strings. These strings are then converted to double using
Double.parseDouble(input) to perform arithmetic operations.

4. How does the program handle division by zero?

Answer:
Before performing division or modulus, the program checks if the second number (num2) is zero. If num2 is zero, the
program displays "Undefined (division/modulus by zero)" to avoid errors like ArithmeticException.

5. What happens if the user enters a non-numeric value?

Answer:
If the user enters a non-numeric value, a NumberFormatException will be thrown when trying to parse the input with
Double.parseDouble(). To handle this, the program can be modified to catch this exception and display an appropriate
error message to the user.

6. Why is Double.parseDouble() used instead of Integer.parseInt() in this program?

Answer:
Double.parseDouble() is used because it allows handling both integer and floating-point values. This makes the program
more flexible in performing arithmetic operations on numbers with decimal points.

7. How can the program be extended to allow the user to select specific operations (e.g., addition, subtraction)?

Answer:
To allow the user to select specific operations, you could add a JOptionPane.showOptionDialog() to present a list of
operations to the user. Based on the selected option, the corresponding operation can be performed, and the result can
be displayed.

For example:

String[] options = {"Addition", "Subtraction", "Multiplication", "Division", "Modulus"};

int choice = JOptionPane.showOptionDialog(null, "Choose an operation:", "Arithmetic Operations",

JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);


Q4) Write a Java application for constructor overloading

1. What is Constructor Overloading? Type of constructors.

Answer:
Constructor overloading occurs when a class has multiple constructors with the same name but different parameter
lists. This allows objects to be initialized in different ways depending on the arguments passed to the constructor.

2. What is the difference between the default constructor and the parameterized constructor?

Answer:

 Default Constructor: A constructor that takes no parameters and assigns default values to the object fields. In
the Box class, the default constructor sets all dimensions to 1.

 Parameterized Constructor: A constructor that takes parameters to initialize object fields with specific values, as
seen in the constructors that accept double side or length, width, and height.

3. What is the purpose of the finalize() method in Java?

Answer:
The finalize() method is a method in Java's Object class, and it is used for cleanup before an object is garbage collected.
It is not a destructor in the traditional sense, but it is similar. It is called by the garbage collector just before the object is
destroyed.

Note: finalize() is rarely used in modern Java as it can lead to performance issues, and garbage collection is automatically
handled by the JVM.

4. Why is the finalize() method not recommended for resource cleanup in Java?

Answer:
The finalize() method is not reliable because the garbage collection process is not deterministic. You cannot predict
when or even if the finalize() method will be called. For managing resources such as files or database connections, it's
better to use try-with-resources or explicitly close resources in the finally block.

5. What will happen if you do not define a constructor in a class?

Answer:
If you do not define any constructor in a class, the Java compiler provides a default constructor (without parameters) for
you. However, if you define at least one constructor (either default or parameterized), the compiler will not provide the
default constructor.

6. Can we have more than one constructor in a class?

Answer:
Yes, we can have multiple constructors in a class as long as they have different parameter lists (either different number
of parameters or different types). This is called constructor overloading.

7. What is the significance of the System.gc() method?

Answer:
The System.gc() method is used to request the JVM to perform garbage collection. However, it is only a suggestion to
the JVM, and there is no guarantee that garbage collection will actually happen immediately. It's generally not
recommended to rely on this method for resource management.

Q5) Write a java application for method overloading

1. What is method overloading in Java?

Answer:
Method overloading in Java occurs when a class has multiple methods with the same name but different parameter lists
(either in the number or types of parameters). Overloading allows a single method name to perform different tasks
based on the arguments passed to it.

2. What is the use of the this keyword in Java?

Answer:
The this keyword in Java refers to the current instance of the class. It is used to:

 Access instance variables when there is a naming conflict between local variables and instance variables.

 Invoke the current class’s methods.

 Call other constructors of the same class.

3. Can the this keyword be used in a static context?

Answer:
No, the this keyword cannot be used in a static context because this refers to an instance of the class, and static
methods do not belong to any specific instance. Static methods belong to the class itself, not an object.

4. Can a method be overloaded based on the return type alone?

Answer:
No, method overloading is determined by the method's parameter list, not the return type. Overloading is not possible if
methods have the same parameters but only differ in return type.

5. What happens if a method is called without sufficient arguments for an overloaded method?

Answer:
If a method is called with insufficient arguments that do not match any overloaded method, the compiler will throw a
compile-time error. The method call must match one of the overloaded methods in terms of the number or types of
arguments.

Q6) Write a java application for method overriding

1. What is method overriding in Java?

Answer:
Method overriding in Java is when a subclass provides its own specific implementation of a method that is already
defined in the superclass. The overriding method must have the same name, return type, and parameter list as the
method in the superclass. The goal is to provide a specialized behavior for the subclass.
2. What is the difference between method overloading and method overriding?

Answer:

 Method Overloading: It occurs when two or more methods in the same class have the same name but different
parameters (either in number, type, or both). Overloading is resolved at compile time.

 Method Overriding: It occurs when a subclass provides a specific implementation of a method that is already
defined in the superclass. Overriding is resolved at runtime and is part of polymorphism.

3. Can a method be overridden in a final class?

Answer:
No, a method cannot be overridden in a final class. A final class cannot be subclassed, so there is no way to override its
methods. If you attempt to override a method in a final class, the compiler will generate an error.

4. What happens if you don't use the @Override annotation in method overriding?

Answer:
If you do not use the @Override annotation, the code will still compile and run correctly, as long as the method
signature in the subclass matches the method in the superclass. However, using @Override helps the compiler catch
errors like misspelling the method name or incorrect parameter lists, making the code more robust and easier to
maintain.

5. Can a subclass call the overridden method from the superclass?

Answer:
Yes, a subclass can call the overridden method from the superclass using the super keyword. For example,
super.methodName() can be used within the subclass method to call the parent class's version of the method.

Q7) Inheritance Viva voice questions and answers

1. What is inheritance in Java?

Answer:
Inheritance in Java is a mechanism in which one class acquires the properties and behaviors (fields and methods) of
another class. It promotes code reusability and establishes a relationship between the parent (superclass) and child
(subclass) classes. The child class inherits all the non-private members of the parent class and can add its own features
or override existing ones.

Syntax:

class ChildClass extends ParentClass {

// Additional members or methods

2. What is the difference between the extends and implements keywords in Java?

Answer:

 extends: Used when a class is inheriting from another class. It is used for implementing inheritance.
class ChildClass extends ParentClass { }

 implements: Used when a class is implementing an interface. It is used for implementing interfaces and is part
of Java's interface-based inheritance mechanism.

class ClassName implements InterfaceName { }

3. Can a class in Java inherit from more than one class?

Answer:
No, Java does not support multiple inheritance through classes. A class can inherit from only one superclass. However,
Java supports multiple inheritance through interfaces, meaning a class can implement multiple interfaces.

4. What is method overriding and how does it work in inheritance?

Answer:
Method overriding is the process where a subclass provides its own implementation of a method that is already defined
in the superclass. The method in the subclass must have the same signature (name, return type, and parameters) as the
method in the superclass. Method overriding is used to achieve runtime polymorphism.

5. What is the difference between super and this in inheritance?

Answer:

 this: Refers to the current instance of the class. It is used to access the instance variables and methods of the
current class. It can also be used to call the current class's constructor.

 super: Refers to the superclass (parent class). It is used to access superclass methods and constructors. It is also
used to differentiate between instance variables in the superclass and subclass when they have the same name.

6. What is the difference between final, finally, and finalize in Java?

Answer:

 final: Used to define constants, prevent method overriding, or prevent inheritance.

o final class cannot be subclassed.

o final method cannot be overridden.

o final variable cannot be reassigned after initialization.

 finally: A block that follows a try-catch block, used for code that must execute regardless of whether an
exception is thrown or not.

 finalize: A method in the Object class that is called by the garbage collector before an object is destroyed. It
allows an object to clean up resources before it is reclaimed by the garbage collector.

7. What is constructor inheritance in Java?

Answer:
In Java, constructors are not inherited by subclasses. However, a subclass can call the constructor of its superclass using
the super() keyword. If a subclass does not explicitly call a superclass constructor, the default no-argument constructor
of the superclass is called automatically.

8. Why Java cant implement multiple inheritance using classes

9. How to implement multiple inheritance in java

10. What is diamond problem in inheritance

You might also like