0% found this document useful (0 votes)
8 views11 pages

Viva Questions Java

The document consists of a series of viva questions and answers related to Java programming concepts, including copy constructors, constructor chaining, exception handling, race conditions, sockets, and deadlocks. It covers important topics such as inheritance, polymorphism, exception propagation, and database security practices in JSP. The content is structured as a Q&A format, providing concise explanations for each question.
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)
8 views11 pages

Viva Questions Java

The document consists of a series of viva questions and answers related to Java programming concepts, including copy constructors, constructor chaining, exception handling, race conditions, sockets, and deadlocks. It covers important topics such as inheritance, polymorphism, exception propagation, and database security practices in JSP. The content is structured as a Q&A format, providing concise explanations for each question.
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

VIVA QUESTIONS

Q1. Do we have Copy Constructor in Java?


Ans: No, Java does not have a built-in copy constructor like C++. However, you can achieve
similar functionality by creating a constructor that accepts an object of the same class and
initializes its fields with the values of the passed object.

Q2. What is Constructor Chaining?


Ans: Constructor chaining refers to the process of calling one constructor from another
constructor within the same class or from the constructor of its immediate superclass. This
allows for code reuse and helps in initializing objects efficiently.

Q3. How is a no-argument constructor different from a default Constructor?


Ans: In Java, a no-argument constructor is a constructor that takes no parameters, whereas a
default constructor is provided by the compiler if no constructor is explicitly defined in a
class. The default constructor takes no parameters and initializes instance variables to their
default values (0 for numeric types, null for objects, and false for boolean).

Q4. What are private constructors and where are they used?
Ans: Private constructors are constructors that are declared with the private access modifier.
They can only be accessed within the same class and are typically used to prevent the
instantiation of objects from outside the class. Private constructors are commonly used in
singleton design patterns and utility classes where instantiation is not desired.

Q5. Is there any method to call a sub-class constructor from a superclass constructor?
Ans: Yes, you can call a subclass constructor from a superclass constructor using the super
keyword followed by the appropriate arguments to the subclass constructor. This must be the
first statement in the superclass constructor and allows for initialization of subclass-specific
fields before completing the superclass initialization.
VIVA QUESTIONS
Q1. Can we override protected method of super class as public method in the sub class?
Ans: Yes, we can override a protected method of a superclass with a public method in the
subclass. However, the access level of the overriding method must be the same or more
permissive than that of the overridden method.

Q2. Can we override a super class method without throws clause as a method with throws
clause in the sub class?
Ans: No, we cannot override a superclass method without a throws clause with a method that
has a throws clause in the subclass. The overridden method in the subclass must either have
the same throws clause or a subset of the exceptions thrown by the superclass method.

Q3. How do you refer to the super class version of overridden method in the sub class?
Ans: To refer to the superclass version of an overridden method in the subclass, we can use
the super keyword followed by the method name and any required arguments. For example,
[Link](args);.

Q4. Can we change an exception of a method with throws clause from checked to unchecked
while overriding it?
Ans: No, we cannot change a checked exception to an unchecked exception or vice versa
while overriding a method. The overridden method must either declare the same checked
exceptions as the superclass method or a subclass of those exceptions.

Q5. Is it possible to override non-static methods as static?


Ans: No, it is not possible to override non-static methods as static methods. Static methods
belong to the class itself and are not associated with any instance of the class. Overriding,
however, is a concept applicable to instance methods, where a subclass provides a specific
implementation of a method defined in its superclass.
VIVA QUESTIONS
Q1. How is Inheritance useful to achieve Polymorphism in Java?
Ans: Inheritance allows a subclass to inherit properties and behaviors from its superclass.
Through inheritance, subclasses can override superclass methods to provide their own
implementation, enabling polymorphic behavior where the same method call can exhibit
different behaviors based on the actual object type at runtime.

Q2. Is it possible to implement runtime polymorphism by data members in Java?


Ans: No, runtime polymorphism is achieved through method overriding, not through data
members. Data members are not polymorphic; they are accessed based on the reference type,
not the actual object type at runtime.

Q3. What is Static binding in Java?


Ans: Static binding, also known as early binding, occurs when the compiler determines the
method to invoke based on the reference type at compile-time. It is used for methods that are
private, static, or final, as well as for overloaded methods.

Q4. Why Dynamic binding is also called late binding in Java?


Ans: Dynamic binding, also known as late binding, occurs when the method to invoke is
determined based on the actual object type at runtime. It allows for polymorphic behavior,
where the correct method implementation is chosen dynamically, making it "late" compared
to static binding, which occurs at compile-time.

Q5. Why binding of private, static, and final methods are always static binding in Java?
Ans: Private, static, and final methods are bound statically because their implementations
cannot be overridden by subclasses. Private methods are not visible outside their class, static
methods belong to the class itself, and final methods cannot be overridden. As a result, the
compiler can determine the method to invoke at compile-time, leading to static binding.
VIVA QUESTIONS
Q1. What are the important methods of Java Exception Class?
Ans: Some important methods of the Java Exception class include getMessage(), which
returns the detail message of this exception, toString(), which returns a short description of
this exception, printStackTrace(), which prints this exception's stack trace to the standard
error stream, and fillInStackTrace(), which fills in the execution stack trace.

Q2. Explain Java 7 ARM Feature and multi-catch block?


Ans: Java 7 introduced Automatic Resource Management (ARM) feature, also known as the
"try-with-resources" statement, which allows developers to declare resources within the try
block. These resources are automatically closed when the try block exits, eliminating the need
for explicit resource management and reducing the likelihood of resource leaks. The multi-
catch block allows handling multiple exceptions in a single catch block, reducing code
duplication and improving code readability.

Q3. What is the difference between Checked and Unchecked Exceptions in Java?
Ans: Checked exceptions are exceptions that are checked at compile-time, and the compiler
forces the developer to handle or declare them using the throws keyword. Examples include
IOException and SQLException. Unchecked exceptions, on the other hand, are not checked
at compile-time, and the compiler does not force the developer to handle or declare them.
Examples include RuntimeExceptions such as NullPointerException and
ArrayIndexOutOfBoundsException.

Q4. What is exception propagation in Java?


Ans: Exception propagation refers to the process of passing an exception from one method to
another within a program. When an exception occurs in a method and is not handled locally,
it is propagated up the call stack to the calling method. If the calling method does not handle
the exception, it continues to propagate up the call stack until it is either caught or reaches the
top-level of the program, resulting in termination.

Q5. What are runtime exceptions in Java?


Ans: Runtime exceptions, also known as unchecked exceptions, are exceptions that occur at
runtime and do not need to be explicitly handled or declared. They typically indicate
programming errors or unexpected conditions that could not be detected by the compiler.
Examples include NullPointerException, ArrayIndexOutOfBoundsException, and
ArithmeticException.
VIVA QUESTIONS
Q1. How do you handle checked exceptions?
Ans: Checked exceptions are handled using try-catch blocks or by declaring them in the
method signature using the throws keyword. In a try-catch block, the code that might throw a
checked exception is enclosed within the try block, and the catch block is used to handle the
exception. Alternatively, if a method throws a checked exception, the caller method must
either handle it using try-catch or propagate it using the throws keyword.

Q2. Can you catch and handle Multiple Exceptions in Java?


Ans: Yes, Java allows catching and handling multiple exceptions in a single catch block using
the multi-catch feature introduced in Java 7. This feature enables developers to catch different
types of exceptions in a single catch block, reducing code duplication and improving code
readability.

Q3. What is a stack trace and how is it related to an Exception?


Ans: A stack trace is a detailed report of the active stack frames at the point where an
exception occurs in a program. It provides information about the sequence of method calls
that led to the exception, including the class, method, and line number where each method
was invoked. The stack trace is printed to the standard error stream when an exception is
thrown and helps developers identify the cause of the exception.

Q4. How are the keywords final, finally, and finalize different from each other?
Ans: The keyword final is used to declare constants, prevent method overriding, and prevent
class inheritance. The finally block is used in exception handling to ensure that certain code is
executed regardless of whether an exception is thrown or not. It is typically used to release
resources or perform cleanup operations. The finalize() method is a special method provided
by the Object class that is called by the garbage collector before an object is reclaimed by the
memory management system. It can be overridden to perform cleanup actions on an object
before it is destroyed.

Q5. What do you understand by an unreachable catch block error?


Ans: An unreachable catch block error occurs when a catch block is declared for an exception
that cannot be thrown by the try block. This typically happens when the catch block is
declared for a superclass of an exception type that is never thrown, or when the exception
type is already caught by an earlier catch block. This error is detected by the compiler during
compilation, and it indicates a logical error in the code that needs to be corrected.
VIVA QUESTIONS
Q1. How does race condition occur?
Ans: Race condition occurs in a concurrent program when the outcome of the program
depends on the sequence or timing of uncontrollable events. It typically happens when
multiple threads or processes access shared resources concurrently, and the final result
depends on the order of execution of these threads or processes. Race conditions can lead to
unexpected behavior, such as incorrect results, deadlocks, or data corruption.

Q2. What does a socket consist of?


Ans: A socket consists of an IP address and a port number. In networking, a socket represents
an endpoint for communication between two hosts over a network. It is identified by a
combination of an IP address, which identifies the host, and a port number, which identifies a
specific application or service running on that host.

Q3. Explain echo server.


Ans: An echo server is a network service or application that listens for incoming network
requests and echoes back the same data that it receives from the client. When a client sends
data to an echo server, the server reads the data from the client's request and sends it back to
the client without any modification. Echo servers are commonly used for testing network
connectivity and troubleshooting network-related issues.

Q4. What does socketpair() do?


Ans: The socketpair() function in Unix-like operating systems creates a pair of connected
sockets that can be used for inter-process communication (IPC) within the same host. It
creates two connected sockets, one for reading and one for writing, and returns file
descriptors for both sockets. The sockets in the pair are bidirectional, meaning data written to
one socket can be read from the other socket, and vice versa.

Q5. How to dispose of a socket?


Ans: In Java, sockets are automatically closed and disposed of by the garbage collector when
they are no longer referenced by any part of the program. However, it is good practice to
explicitly close sockets when they are no longer needed to release system resources and avoid
resource leaks. This can be done by calling the close() method on the socket object, which
releases the underlying network resources associated with the socket and closes the socket
connection.
VIVA QUESTIONS
Q1. How does race condition occur?
A1. Race condition occurs when multiple threads or processes access shared data or resources
concurrently, resulting in unpredictable behavior due to the non-deterministic order of
execution.

Q2. What does a socket consist of?


A2. A socket consists of an IP address and a port number, which together uniquely identify
the communication endpoints in a network.

Q3. Explain echo server.


A3. An echo server is a server program that echoes back any data it receives from a client,
essentially mirroring the input back to the sender. It is commonly used for testing network
connectivity and debugging.

Q4. What does the socketpair() function do?


A4. The socketpair() function creates a pair of connected sockets that are bidirectionally
linked, allowing communication between two processes running on the same host.

Q5. How to dispose of a socket?


A5. To dispose of a socket, you can close it using the close() function in C or C++, or by
calling the close() method in Java. This releases the socket and its associated resources,
allowing them to be reused or reclaimed by the operating system.
VIVA QUESTIONS
Q1. What is a Java Bean?
A1. A Java Bean is a reusable software component in Java that follows specific conventions,
including having private properties with public getter and setter methods, being serializable,
and having a no-argument constructor.

Q2. How to create an input stream?


A2. To create an input stream in Java, you can use classes such as FileInputStream,
FileReader, or InputStreamReader, depending on the source of the data you want to read.

Q3. What will happen if you have too many socket connections in TIME_WAIT state on
Server?
A3. If a server has too many socket connections in the TIME_WAIT state, it can exhaust the
available ports and lead to resource starvation or denial of service for new connection
attempts.

Q4. What is TIME_WAIT state in TCP protocol? When does a socket connection goes to
TIME_WAIT state?
A4. TIME_WAIT state in the TCP protocol is a transitional state where a socket remains
active to handle any delayed packets and ensure proper termination of the connection. A
socket connection enters the TIME_WAIT state after it is closed by either the client or the
server.

Q5. What is multicasting or multicast transmission? Which Protocol is generally used for
multicast? TCP or UDP?
A5. Multicasting or multicast transmission is a method of sending data to multiple recipients
simultaneously. It is generally used with the UDP (User Datagram Protocol) because UDP
supports broadcast and multicast.

Q6. What is Network Byte Order? How do two host communicate if they have different byte-
ordering?
A6. Network Byte Order refers to the standard byte order used in networking protocols,
where the most significant byte (MSB) is transmitted first. Hosts with different byte-ordering
communicate by converting data to and from network byte order using functions like htons()
and ntohs().
VIVA QUESTIONS
1. What is a deadlock in Java?
 Answer: A deadlock in Java occurs when two or more threads are blocked
forever, each waiting for a resource that the other thread holds. In other
words, they are stuck in a cyclic waiting state.
2. What are the necessary conditions for a deadlock to occur?
 Answer: Deadlock can occur if the following four conditions hold
simultaneously:
1. Mutual Exclusion: At least one resource must be held in a non-
sharable mode.
2. Hold and Wait: A process holding at least one resource is waiting to
acquire additional resources held by other processes.
3. No Preemption: Resources cannot be forcibly taken away from a
process holding them; they must be released voluntarily.
4. Circular Wait: A circular chain of two or more processes exists, where
each process is waiting for a resource held by the next process in the
chain.
3. How can we detect a deadlock in Java?
 Answer: Deadlocks can be detected using various methods such as thread
dump analysis, monitoring tools, or implementing deadlock detection
algorithms.
4. What are some strategies to prevent deadlock?
 Answer: Several strategies can prevent deadlocks, including:
 Avoidance: Ensuring that the system never enters a deadlock-prone
state by carefully managing the allocation of resources.
 Detection and Recovery: Periodically check for deadlocks and recover
by releasing resources or aborting processes.
5. How can we resolve a deadlock once it occurs?
 Answer: Deadlocks can be resolved using various techniques such as:
 Resource Preemption: Introduce the capability to forcibly remove
resources from processes to break the circular wait condition.
 Process Termination: Identify and terminate one or more processes
involved in the deadlock.
VIVA QUESTIONS
1. How do you ensure security when inserting data into a database using JSP?
 Short Answer: Use parameterized queries or prepared statements to prevent
SQL injection attacks. Validate user input to ensure it meets expected criteria
before inserting into the database.
2. What are the advantages and disadvantages of directly inserting data into a
database from JSP?
 Short Answer: Advantages include simplicity and rapid development.
Disadvantages include reduced maintainability, lack of separation of
concerns, and security risks such as SQL injection.
3. Can you explain the role of prepared statements in inserting data into a database
from JSP?
 Short Answer: Prepared statements precompile SQL queries, allowing
parameters to be set dynamically. They help prevent SQL injection attacks by
automatically escaping user input, making database operations safer.
4. How would you handle exceptions or errors that may occur during the data
insertion process in a JSP program?
 Short Answer: Use try-catch blocks to handle exceptions gracefully. Display
meaningful error messages to the user and log detailed error information for
debugging purposes.
5. What are the best practices to follow when designing a JSP program for inserting
data into a database table?
 Short Answer: Separate business logic from presentation logic by using
servlets or controllers to handle database operations. Validate user input,
sanitize data, and use prepared statements to prevent security vulnerabilities.
Implement error handling to ensure robustness.
VIVA QUESTIONS
1. What is Regular Expression validation in JSP?
 Answer: Regular Expression validation in JSP involves using pattern matching
to verify user input against predefined rules, ensuring it conforms to specific
formats (e.g., email addresses, phone numbers).
2. How do you implement Regular Expression validation in JSP?
 Answer: In JSP, Regular Expression validation can be implemented using
JavaScript or server-side scripting languages like Java. JavaScript can be used
for client-side validation, while Java can handle server-side validation.
3. What are the advantages of using Regular Expressions for validation in JSP?
 Answer: Regular Expressions offer a concise and powerful method for
defining validation rules. They enable developers to enforce complex patterns
easily, enhancing data integrity and security in web applications.
4. How can you handle errors when Regular Expression validation fails in JSP?
 Answer: When Regular Expression validation fails in JSP, developers can
display informative error messages to users, guiding them on correct input
formats. Additionally, highlighting invalid fields can improve user experience.
5. Are Regular Expressions suitable for all types of data validation in JSP?
 Answer: Regular Expressions are ideal for validating string-based input, such
as email addresses, phone numbers, and passwords. However, for more
complex validations or non-string data types, other validation techniques may
be necessary.

You might also like