JAVA Important Questions and Answers
JAVA Important Questions and Answers
1. What is the difference between Object Oriented Programming language and object based
programming language.
2. What are Access Specifiers available in Java?
3. What is the difference between abstraction and encapsulation?
4. How do you prevent a method from being overridden?
5. What is garbage collection?
6. Why java does not support pointers?
7. Explain the usage of Java packages. Why do we need to use package in Java? How to create a
package in Java?
8. Differentiate between method overloading and method overriding. Write a program to implement
the Fibonacci series using for loop control structure.
9. What is an Interface? How can you achieve multiple inheritances in java? Explain with a
suitable example.
10. What is the difference between static and non-static variables? What is this keyword?
Explain with example.
11. Can I import same package/class twice? Justify. Will the JVM load the package twice at runtime?
12. Differentiate between Interface and abstract class.
13. Explain Casting in Java and its types.
14. Illustrate the use cases of final keyword.
15. When you declare a method as abstract, can other nonabstract methods access it? Justify.
16. Can we have a method with the same name as class and how it is different from constructor?
17. Differentiate between checked and unchecked exceptions in Java.
18. Explain CRUD operations in Java.
19. Define Autoboxing and Unboxing.
20. Define the output of the following Java code
21. class multithreaded_programing
{
public static void main(String args[])
{
}
Thread t= Thread.currentThread ();
System.out.println (t);
}
22. Distinguish between == and equals () method.
23. State object cloning and its need.
24. Explain the thread synchronization in Java. Why is it necessary, and how is it achieved?
25. Write the difference between static variable and final variable in Java.
26. Explain indexOf() and lastIndexOf() with a suitable example.
27. Briefly discuss various features of Object-Oriented Programming. Write a Java program to find
factorial of a Number.
28. Derive the advantages of ArrayList over Arrays. Design an ArrayList called CGU_Subjects: [Java,
Machine Learning, Database], add the elements DAA, DL to the ArrayList and display the final
ArrayList as CGU_Subjects: [Java, Machine Learning, DAA, DL, Database].
29. Define Super Keyword and its need. Illustrate the implementation of multilevel Inheritance using
Super keyword with a suitable example.
30. Explain the different stages of the thread life cycle in Java. Explain the concept of thread priorities
in Java.
31. Write short notes on-
i. Callable Statement in JDBC
ii. Clone ()
iii. Thin Driver
32. Write a program to demonstrate the knowledge of students in advanced concepts of Java string
handling. Eg., (Bioinformatics: finding genes) Biologists use a sequence of letters A, C, T, and G to
model a genome. A gene is a substring of a genome that starts after a triplet ATG and ends before
a triplet TAG, TAA, or TGA. Furthermore, the length of a gene string is a multiple of 3 and the gene
does not contain any of the triplets ATG, TAG, TAA, and TGA. Prompt the user to enter a genome
and displays all genes in the genome. If no gene is found in the input sequence, displays no gene.
Here are the sample runs: Enter a genome string: TTATGTTTTAAGGATGGGGCGTTAGTT
O/P: TTT GGGCGT.
33. Differentiate between constructor and method. Explain constructor overloading with a
suitable example.
34. Write a Java program to solve the given problem statement of CGU_Banking_System.
35. The CGU_Banking_System contains a Bank class with two methods, transfer() and
credit(). The transfer() method transfers money from one account to another, and the
credit() method adds money to an account. Both methods use synchronized blocks to
ensure thread safety. Now, suppose we have two threads, Thread A and Thread B, each
trying to transfer money between two accounts in the bank. Thread A calls the transfer ()
method with account A and account B as arguments, and Thread B calls the transfer ()
method with account B and account A as arguments. If Thread A acquires the lock on
account A and Thread B acquires the lock on account B, both threads will be blocked,
waiting for the lock on the other account to be released.
36. Suppose we have two classes named "Engine" and "Wheels". The Engine class contains
methods to start, stop and maintain the engine, while the Wheels class contains methods to
rotate the wheels, change the tire pressure, and control the brakes. Now, let's assume that
we have a class named "Car" that we want to create by inheriting properties and methods
from both the Engine and Wheels classes.
37. Suppose we have a class named "CGU_Match" which contains the following methods:
getMatch Details(): This method will return the match details such as the team names,
venue, date, and time of the match.
getMatch Details(team1: String, team2: String): This method will return the match details
for a specific match between two teams.
getMatch Details (team: String, venue: String): This method will return the match details
for a specific match played at a particular venue.
getMatch Details(team: String, date: String): This method will return the match details for
a specific match played on a particular date.
getMatch Details (team: String, time: String): This method will return the match details for
a specific match played at a particular time.
For instance, if we call the method getMatch Details() without any arguments, it will return
the details of the most recent match played. However, if we pass the team names as
arguments to the method, it will return the details of the match between those two teams.
Similarly, if we pass the venue, date, or time as an argument, the method will return the
details of the match played at that particular venue, on that particular date or at that
particular time.
38. Describe character stream in Java. Assume in Drive D: two text files are
there(D:\javaprg.txt, D:\javaout.txt). The "javaprg.txt" contains pre-existing test as 4 java
program is best among all". WAP in Java to copy the content of "javaprg.txt" to
"javaout.txt" using FileInputStream and FileOutputStream.
39. Explain the concept of JDBC in Java. Differentiate between Statement and
PreparedStatement interfaces. How can you connect to a database using JDBC?
40. Write a program to create a user defined Package named Engineering which has one class
Student. Accept student detail (Reg.no, Name, Branch, Marks of 5 subject (Data Structure,
Math, Computer networking, Computer Architecture, Operating System) through
parameterized constructor. Write display () method to display details. Create a main class
which will use package and calculate total marks and percentage.
Answers
Do not support all OOP features: Specifically, they do not support inheritance and
polymorphism.
Examples: JavaScript (though modern versions now support a form of inheritance),
Visual Basic.
Limited in creating hierarchical classifications: Since there's no inheritance, objects
can be created but without the advantage of reusing the common logic.
2. Access Specifiers available in Java
private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
default (no modifier): If no access specifier is defined, Java assumes a default access
level, which means it is accessible within the same package.
protected: The protected access level provides access to the class itself, its package, and
its subclasses.
public: The public access level means that the class, method, or field is accessible from
any other class.
Abstraction:
Hides the complex implementation details and shows only the necessary features of
the object.
It focuses on what the object does.
Achieved using abstract classes and interfaces.
Encapsulation:
Binds (encapsulates) the data and the code that manipulates the data into a single
unit called class.
It focuses on keeping the data safe from outside interference and misuse.
Achieved using access modifiers (private, public, protected).
In Java, you can prevent a method from being overridden by using the final keyword in the
method declaration. For example:
java
Copy code
class SuperClass {
public final void show() {
System.out.println("This method cannot be overridden.");
}
}
Garbage collection is the process of automatically freeing memory on the heap by deleting
objects that are no longer reachable in your program. In Java, garbage collection is managed by
the Java Virtual Machine (JVM), which removes objects from memory when they are no longer
in use, thus preventing memory leaks and inefficient use of resources.
Java does not support pointers (in the sense of memory addresses that can be manipulated as in
languages like C or C++) for several reasons:
Security: Direct access to memory can lead to vulnerabilities where malicious code
could manipulate memory addresses, leading to unauthorized access or corruption of
data.
Simplicity: By abstracting away the complexity of pointers, Java simplifies
programming and reduces errors related to memory management.
Garbage Collection: Java's garbage collection relies on being able to know exactly
which objects are still in use. Pointers would complicate this process, potentially leading
to memory leaks or other issues.
7. Java Packages
Creating a Package in Java: To create a package in Java, use the package keyword followed
by the package name at the top of your Java source file. For example:
java
Copy code
package com.example.myapp;
To compile: javac -d . MyClass.java (This will place the compiled class in the correct
directory structure)
8. Method Overloading vs Method Overriding
Method Overloading:
Method Overriding:
java
Copy code
public class FibonacciSeries {
public static void main(String[] args) {
int n = 10, firstTerm = 0, secondTerm = 1;
System.out.println("Fibonacci Series till " + n + " terms:");
An interface in Java is a reference type that can contain only constants, method signatures,
default methods, static methods, and nested types. Interfaces cannot contain instance fields. The
methods in interfaces are abstract by default.
Java does not support multiple inheritances with classes to avoid the "Diamond Problem."
However, it supports multiple inheritances through interfaces. A class can implement multiple
interfaces, thereby inheriting the abstract methods of multiple interfaces.
Example:
java
Copy code
interface InterfaceA {
void methodA();
}
interface InterfaceB {
void methodB();
}
Static Variables:
this Keyword:
java
Copy code
public class ExampleClass {
int instanceVar;
ExampleClass(int instanceVar) {
this.instanceVar = instanceVar; // Using 'this' to refer to the
instance variable
}
}
Let's continue with the detailed responses to your questions:
11. Can I Import the Same Package/Class Twice? Will the JVM Load the
Package Twice at Runtime?
You can technically import the same package or class more than once in your Java source file,
but the Java compiler and JVM are smart enough to recognize and ignore redundant imports.
This means that the JVM will not load the package or class twice at runtime. Import statements
are primarily for the compiler to locate and reference the classes you're using in your code. Once
compiled, the bytecode contains fully qualified class names, and the import statements have
served their purpose.
Interface:
Cannot have any concrete methods (Java 8 and earlier). Java 8 onwards, interfaces can
have default and static concrete methods.
All fields are public, static, and final by default.
A class can implement multiple interfaces, supporting multiple inheritance.
Used to define a contract for what a class can do, without saying anything about how the
class will do it.
Abstract Class:
Casting in Java is the process of converting a value from one data type to another. There are two
types of casting:
java
Copy code
int myInt = 9;
long myLong = myInt; // Implicit casting
Explicit Casting (Narrowing Conversion):
java
Copy code
double myDouble = 9.78;
int myInt = (int) myDouble; // Explicit casting
Final Variables: When applied to variables, final makes the variable unchangeable
after it's initialized.
java
Copy code
final int MY_CONSTANT = 100;
java
Copy code
public final void myFinalMethod() {}
java
Copy code
public final class MyFinalClass {}
Yes, non-abstract methods in an abstract class can access abstract methods. Abstract methods act
as placeholders for methods that must be implemented in non-abstract subclasses. Non-abstract
methods can invoke abstract methods, expecting that the subclass will provide the concrete
implementation.
java
Copy code
abstract class MyAbstractClass {
abstract void myAbstractMethod();
void myConcreteMethod() {
myAbstractMethod(); // Calling an abstract method
}
}
16. Can We Have a Method With the Same Name as the Class? How Is It
Different From a Constructor?
Yes, you can have a method with the same name as the class, but it's generally not recommended
due to readability and convention reasons. However, this method must have a return type,
distinguishing it from a constructor, which does not have a return type.
java
Copy code
public class MyClass {
void MyClass() { // This is a method, not a constructor
System.out.println("This is a method, not a constructor.");
}
}
Constructor:
java
Copy code
public class MyClass {
MyClass() { // This is a constructor
System.out.println("This is a constructor.");
}
}
Constructors are special methods used to initialize new objects. They are called when an instance
of the class is created, and they have the same name as the class but no return type, not even
void.
In Java, exceptions are divided into two main categories: checked and unchecked exceptions.
Checked Exceptions:
java
Copy code
import java.io.*;
Unchecked Exceptions:
java
Copy code
public class UncheckedExample {
public static void main(String[] args) {
int[] arr = new int[5];
System.out.println(arr[5]); // Throws ArrayIndexOutOfBoundsException
}
}
CRUD stands for Create, Read, Update, and Delete. These are the four basic functions of
persistent storage (e.g., databases).
In Java, CRUD operations are typically performed using JDBC (Java Database Connectivity) for
relational databases or through libraries/frameworks like JPA (Java Persistence API), Hibernate
for both SQL and NoSQL databases.
Autoboxing is the automatic conversion that the Java compiler makes between the primitive
types and their corresponding object wrapper classes. For example, converting an int to an
Integer, a double to a Double, etc.
java
Copy code
Integer myInteger = 25; // Autoboxing from int to Integer
Unboxing is the reverse process of converting an object of a wrapper type to its corresponding
primitive type.
java
Copy code
int myInt = myInteger; // Unboxing from Integer to int
This code snippet will print details about the current thread executing the main method. The
output will include the name of the thread (typically "main"), its priority, and the thread group it
belongs to, in a format similar to:
Copy code
Thread[main,5,main]
This indicates that the thread's name is "main", its priority is 5, and it belongs to the "main"
thread group.
== is a reference comparison operator. It checks if two references point to the same object
in the memory. It is used for primitive data types and reference comparisons.
java
Copy code
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1 == str2); // false, because two different String
objects are created.
equals() method is defined in Object class in Java and it is used for checking logical
equality of two objects. Classes can override equals() method to check if two instances
are logically equal.
java
Copy code
System.out.println(str1.equals(str2)); // true, because `equals()` checks the
content equality.
22. State Object Cloning and Its Need
Object cloning in Java is the process of creating an exact copy of an object. It is achieved using
the clone() method of the Object class. Cloning is needed when you want to duplicate an
existing object to modify the original or the copy without affecting the other.
To use cloning, a class must implement the Cloneable interface and override the clone()
method from the Object class.
java
Copy code
class Example implements Cloneable {
int a;
Cloning can be shallow (default) or deep, depending on whether the object references inside are
copied or also cloned.
23. Explain the Thread Synchronization in Java. Why Is It Necessary, and How
Is It Achieved?
Necessity:
How It Is Achieved:
java
Copy code
public synchronized void method() {
// critical section
}
Synchronized Blocks: More fine-grained than synchronized methods. They allow
locking for any object, providing flexibility in the choice of the lock.
java
Copy code
public void method() {
synchronized(this) {
// code block
}
}
Static Synchronization: When you synchronize a static method, you lock the class, not
the object.
24. Write the Difference Between Static Variable and Final Variable in Java
Static Variable:
Belongs to the class rather than any instance of the class (object).
Initialized only once, at the start of the execution and will be destroyed at the end of the
execution.
A static variable can be changed by the user.
Final Variable:
The indexOf() method in Java is used to return the index within the calling String object of the
first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is
not found.
The lastIndexOf() method returns the index within the calling String object of the last
occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value
is not found.
java
Copy code
String example = "This is a test string";
int index = example.indexOf('i'); // Returns 2, the first occurrence of 'i'
int lastIndex = example.lastIndexOf('i'); // Returns 13, the last occurrence
of 'i'
26. Briefly Discuss Various Features of Object-Oriented Programming. Write a
Java Program to Find Factorial of a Number
Encapsulation: The bundling of data, along with the methods that operate on that data,
into a single unit or class.
Inheritance: The mechanism wherein a new class is derived from an existing class.
Polymorphism: The ability of a single function or method to work in different ways
based on the input.
Abstraction: The concept of hiding complex implementation details and showing only
the necessary features of an object.
java
Copy code
public class Factorial {
public static void main(String[] args) {
int number = 5; // Example number
int factorial = 1;
for(int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println("Factorial of " + number + " is: " + factorial);
}
}
Dynamic Sizing: ArrayList can dynamically grow and shrink after addition and
removal of elements. In contrast, arrays are fixed in size.
API Methods: ArrayList offers more methods and features, such as add(), remove(),
indexOf(), etc., making it easier to work with.
Type Safety: ArrayList can be made type-safe using generics, providing compile-time
type checking and reducing runtime errors.
java
Copy code
import java.util.ArrayList;
28. Define Super Keyword and Its Need. Illustrate the Implementation of
Multilevel Inheritance Using Super Keyword with a Suitable Example
Super Keyword: The super keyword in Java is a reference variable that is used to refer to the
immediate parent class object. It is used to access:
java
Copy code
class Grandparent {
void display() {
System.out.println("Grandparent class.");
}
}
29. Explain the Different Stages of the Thread Life Cycle in Java. Explain the
Concept of Thread Priorities in Java.
1. New: When a thread is created, it is in the new state. It remains in this state until the program
starts the thread.
2. Runnable: A thread enters the runnable state either after being started with the start()
method or when it is reactivated from a paused state. In this state, a thread might be running or
ready to run at any instant of time.
3. Blocked: A thread can enter this state because it is waiting for a monitor lock to enter a
synchronized block/method or reenter a synchronized block/method after calling wait().
4. Waiting: A thread transitions to this state because of calling wait() (without timeout), join()
(without timeout), or LockSupport.park(). It will remain in this state until some other thread
calls notify() or notifyAll() on the object.
5. Timed Waiting: A thread is in this state when it calls a method with a time-out parameter like
sleep(long millis), wait(long timeout), join(long millis), or
LockSupport.parkNanos().
6. Terminated: A thread enters this state when it completes its execution or due to an unexpected
exception.
Thread priorities in Java help the scheduler determine when each thread should run. Java
provides a default priority of 5 (defined by Thread.NORM_PRIORITY) and allows for a range of
priorities from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10). Threads with higher
priority are generally executed in preference to threads with lower priority. However, thread
scheduling is not guaranteed and is dependent on the JVM and underlying operating system.
A CallableStatement is used in JDBC to call stored procedures from the database. Unlike
Statement and PreparedStatement, which execute regular SQL queries, CallableStatement
can execute stored procedures, which can return results and accept parameters both as input ( IN),
output (OUT), and both (INOUT).
ii. Clone ()
The clone() method creates and returns a copy of the object. The default implementation in the
Object class is a shallow copy. To use clone(), a class must implement the Cloneable
interface, otherwise, it throws CloneNotSupportedException. For a deep copy, you must
override clone() and manually copy the deeply nested objects.
A thin driver is a type of JDBC driver that provides a direct connection to a database server by
converting JDBC calls directly into the vendor-specific database protocol. This means that,
unlike thick drivers, thin drivers do not require additional software on the client side. Thin
drivers are fully written in Java and are platform-independent, making them a popular choice for
web applications.
int start = 0;
while ((start = genome.indexOf("ATG", start)) != -1) {
int end = genome.indexOf("TAG", start + 3);
if (end == -1) end = genome.indexOf("TAA", start + 3);
if (end == -1) end = genome.indexOf("TGA", start + 3);
if (end != -1 && (end - start) % 3 == 0) {
String gene = genome.substring(start + 3, end);
System.out.println(gene);
geneFound = true;
start = end + 3;
} else {
start += 3;
}
}
if (!geneFound) {
System.out.println("No gene found.");
}
}
}
This program prompts the user to enter a genome sequence and displays all genes based on the
specified criteria. If no gene is found, it displays "No gene found."
32. Differentiate Between Constructor and Method. Explain Constructor
Overloading with a Suitable Example
Constructor:
o Used to initialize the state of an object.
o Has no return type, not even void.
o Automatically called when an instance of the class is created.
o Must have the same name as the class itself.
Method:
o Used to expose the behavior of an object.
o Must have a return type.
o Needs to be called explicitly.
o Can have any name.
java
Copy code
public class Rectangle {
private int length;
private int breadth;
Constructor overloading allows a class to have more than one constructor that differs in
parameter lists. It enables the class to be initialized in different ways.
Certainly! Here are the answers with proper numbering as per the questions:
Constructor:
Method:
Example:
java
Copy code
class Box {
double width, height, depth;
To solve the deadlock, we can ensure that locks on accounts are acquired in a consistent order,
thus avoiding the circular wait condition.
Java does not support multiple inheritance directly due to the Diamond Problem. However, you
can achieve this using interfaces or composition.
Character streams in Java are used to perform input and output of characters. They use Unicode
and are thus text-based.
Copy Content Example:
java
Copy code
import java.io.*;
try {
in = new FileReader("D:\\javaprg.txt");
out = new FileWriter("D:\\javaout.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
JDBC (Java Database Connectivity) is an API that enables Java programs to execute SQL
statements. This allows Java applications to interact with a database.
Statement is used for executing a simple SQL query. It is not precompiled, and the query
is compiled every time it is executed.
PreparedStatement is used for executing precompiled SQL queries. This improves
performance, especially for queries executed multiple times. It also provides features to
prevent SQL injection through parameterized queries.
java
Copy code
import java.sql.*;
// Establish connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "password");
// Create statement
Statement stmt = con.createStatement();
// Execute query
ResultSet rs = stmt.executeQuery("select * from emp");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2));
// Close connection
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Engineering Package:
Student Class:
java
Copy code
package Engineering;
Main Class:
java
Copy code
import Engineering.Student;