Java Questions
Java Questions
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.The confusing
and ambiguous concepts of C++ are either left out in Java or they have been re-implemented in
a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important part of C++
2) Object Oriented
In java everything is Object which has some data and behaviour. Java can be easily extended
as it is based on Object Model.
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time
error checking and runtime checking. But the main areas which Java improved were Memory
Management and mishandled Exceptions by introducing automatic Garbage
Collector and Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into platform
specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent
and can be run on any machine, plus this bytecode format also provide security. Any machine
with Java Runtime Environment can run Java Programs.
5) Secure
When it comes to security, Java is always the first choice. With java secure features it enable us
to develop virus free, temper free system. Java program always runs in Java runtime
environment with almost null interaction with system OS, hence it is more secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to
execute multiple threads at the same time, like While typing, grammatical errors are checked
along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or
C++. But, Java enables high performance with the use of just-in-time compiler.
2.Why java is named as java only? Elaborate (Expected details from History)?
Java, initially, was called OAK but they couldn't use the name as it was already a trademark by
OAK technologies. Then they started brainstorming sessions. People were suggesting different
names. The end result was that about ten possible names were chosen. They were then
submitted to the legal department. Three of them came back clean: Java, DNA, and Silk. No
one remembers who first came up with the name 'Java. Java coffee, said to be consumed in
large quantities by the language's creators.
class Simple{
System.out.println(a);
main(10);
}
7. Who will load .class file in JVM?
The classloader subsystem is an essential core of the Java Virtual machine and is used for
loading/reading the .class files and saving the bytecode in the JVM method area.
8. We have default constructor in sub class and super class. When we create sub class object
in single inheritance. Which constructor is called? Why?
Base class constructors are always called in the derived class constructors. Whenever you
create derived class object, first the base class default constructor is executed and then the
derived class's constructor finishes execution.
It happens due to the super(); call in the constructor.
13. Which data structure is used by JVM to deal with methods (example calling) in java?
JVM uses stack for invoking and returning from methods.
14. What is difference between JRE JDK and JVM?
JDK
Java Development Kit is the core component of Java Environment and provides all the tools,
executables and binaries required to compile, debug and execute a Java Program. JDK is a
platform specific software and thats why we have separate installers for Windows, Mac and
Unix systems. We can say that JDK is superset of JRE since it contains JRE with Java
compiler, debugger and core classes. Current version of JDK is 1.7 also known as Java 7.
JVM
JVM is the heart of java programming language. When we run a program, JVM is responsible to
converting Byte code to the machine specific code. JVM is also platform dependent and
provides core java functions like memory management, garbage collection, security etc. JVM is
customizable and we can use java options to customize it, for example allocating minimum and
maximum memory to JVM. JVM is called virtual because it provides a interface that does not
depend on the underlying operating system and machine hardware. This independence from
hardware and operating system is what makes java program write-once run-anywhere.
JRE
JRE is the implementation of JVM, it provides platform to execute java programs. JRE consists
of JVM and java binaries and other classes to execute any program successfully. JRE doesn’t
contain any development tools like java compiler, debugger etc. If you want to execute any java
program, you should have JRE installed but we don’t need JDK for running any java program.
Let’s look at some of the important difference between JDK, JRE and JVM.
1. JDK is for development purpose whereas JRE is for running the java programs.
2. JDK and JRE both contains JVM so that we can run our java program.
3. JVM is the heart of java programming language and provides platform independence.
Sometimes we heard this term and being it a part of JVM it confuses us. JIT is part of JVM that
optimise byte code to machine specific language compilation by compiling similar byte codes at
same time, hence reducing overall time taken for compilation of byte code to machine specific
language.
16. What is native interface?
The Java Native Interface (JNI) is a programming framework that enables Java code running in
a Java Virtual Machine (JVM) to call and be called bynative applications (programs specific to a
hardware and operating system platform) and libraries written in other languages such as C,
C++ and assembly.
17. When to select interface and abstract class for implementation? Explain with real time
example of your choices?
Abstract Class
Consider using abstract classes if any of these statements apply to your situation:
Interface
An interface is just the declaration of methods of an Object, it’s not the implementation. In
interface, we define what kind of operation an object can perform. These operations are defined
by the classes that implement interface. Interfaces form a contract between the class and the
outside world, and this contract is enforced at build time by the compiler.
Consider using interfaces if any of these statements apply to your situation:
1. You expect that unrelated classes would implement your interface. For example, the
interfaces Comparable and Cloneable are implemented by many unrelated classes.
2. You want to specify the behavior of a particular data type, but not concerned about who
implements its behavior.
3. You want to take advantage of multiple inheritances.
Duplicate Objects
The main difference between List and Set interface in Java is that List allows
duplicates while Set doesn't allow duplicates. All implementation of Set honor this contract.
While a Map holds two objects per Entry e.g. a key and a value and It may contain duplicate
values but keys are always unique. See here for more difference between List and Set data
structure in Java.
Order
Another key difference between List and Set is that List is an ordered collection, List's contract
maintains insertion order or element. Set is an unordered collection, you get no guarantee on
which order element will be stored.
Null elements
The list allows null elements and you can have many null objects in a List because it also
allowed duplicates. Set just allow one null element as there is no duplicate permitted while in
Map you can have null values and at most one null key.
23. What is difference between concurrent collection and simple collection?
We all know about about Traditional Collections ( i.e. List, Set, Queue and its implemented
Classes) and Concurrent Collection (i.e. ConcurrentMap interface, ConcurrentHashMap class,
CopyOnWriteArrayList class etc). In these two Collections, there are few differences like:
Most of the Classes which are present in Traditional Collections
(i.e ArrayList, LinkedList, HashMap etc)are non-synchronized in nature and Hence there
is no thread-safety. But All the classes present in Concurrent Collections are synchronized
in nature. Therefore In Concurrent classes, we dont have to take care about Thread-safety.
While Traditional Collections also have some classes (like Vector, Stack etc) which are
synchronized in nature and Traditional Collections also have SynchronizedSet,
SynchronizedList, SynchronizedMapmethods through which we can get Synchronized
version of non-synchronized objects. But these above Synchronized classes are not good
in terms of performance because of wide-locking mechanism .Whereas Concurrent
Collections classes performance are relatively high than Traditional Collections classes.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the behavior/state that
the object of its type support.
Differences
Vectors are synchronized, ArrayLists are not.
Data Growth Methods
Use ArrayLists if there is no specific requirement to use Vectors.
Synchronization
If multiple threads access an ArrayList concurrently then we must externally synchronize the
block of code which modifies the list either structurally or simply modifies an element. Structural
modification means addition or deletion of element(s) from the list. Setting the value of an
existing element is not a structural modification.
Collections.synchronizedList is normally used at the time of creation of the list to avoid any
accidental unsynchronized access to the list.
Reference
Data growth
Internally, both the ArrayList and Vector hold onto their contents using an Array. When an
element is inserted into an ArrayList or a Vector, the object will need to expand its internal array
if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList
increases its array size by 50 percent
ArrayList LinkedList
3) ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List
and Deque interfaces.
Enumeration Iterator
Enumeration is used to traverse the Iterator is used to iterate most of the classes in
legacy classes the collection framework
like Vector, Stackand HashTable. like ArrayList, HashSet, HashMap, LinkedList etc.
Methods
: hasMoreElements() and nextElement() Methods : hasNext(), next() and remove()
List
1. Is an Ordered grouping of elements.
2. List is used to collection of elements with duplicates.
3. New methods are defined inside List interface.
Set
1. Is an Unordered grouping of elements.
2. Set is used to collection of elements without duplicates.
3. No new methods are defined inside Set interface, so we have to use Collection interface
methods only with Set subclasses.
32. What is the difference between Collection and Collections?
The differences between the Collection and Collections are given below.
Reduces programming effort: By providing useful data structures and algorithms, the
Collections Framework frees you to concentrate on the important parts of your program
rather than on the low-level "plumbing" required to make it work. By facilitating
interoperability among unrelated APIs, the Java Collections Framework frees you from
writing adapter objects or conversion code to connect APIs.
Increases program speed and quality: This Collections Framework provides high-
performance, high-quality implementations of useful data structures and algorithms. The
various implementations of each interface are interchangeable, so programs can be
easily tuned by switching collection implementations. Because you're freed from the
drudgery of writing your own data structures, you'll have more time to devote to
improving programs' quality and performance.
Allows interoperability among unrelated APIs: The collection interfaces are the
vernacular by which APIs pass collections back and forth. If my network administration
API furnishes a collection of node names and if your GUI toolkit expects a collection of
column headings, our APIs will interoperate seamlessly, even though they were written
independently.
Reduces effort to learn and to use new APIs: Many APIs naturally take collections on
input and furnish them as output. In the past, each such API had a small sub-API
devoted to manipulating its collections. There was little consistency among these ad hoc
collections sub-APIs, so you had to learn each one from scratch, and it was easy to
make mistakes when using them. With the advent of standard collection interfaces, the
problem went away.
Reduces effort to design new APIs: This is the flip side of the previous advantage.
Designers and implementers don't have to reinvent the wheel each time they create an
API that relies on collections; instead, they can use standard collection interfaces.
Fosters software reuse: New data structures that conform to the standard collection
interfaces are by nature reusable. The same goes for new algorithms that operate on
objects that implement these interfaces.
34. What is the advantage of generic collection?
1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store
other objects.
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.
SN Array ArrayList
1 The Array is of fixed size, means we ArrayList is not of the fixed size we can
cannot resize the array as per need. change the size dynamically.
3 Arrays can store primitive data types ArrayList cannot store the primitive data
as well as objects. types it can only store the objects.
36. What is the difference between length of Array and size of ArrayList?
The length of an array can be obtained using the property of length whereas ArrayList does not
support length property, but we can use size() method to get the number of objects in the list.
37. What is the difference between Comparable and Comparator?
No. Comparable Comparator
The hashCode() method returns a hash code value (an integer number).
The hashCode() method returns the same integer number if two keys (by calling equals()
method) are identical.
However, it is possible that two hash code numbers can have different or the same keys.
If two objects do not produce an equal result by using the equals() method, then the hashcode()
method will provide the different integer result for both the objects.
39. Why we override equals() method?
The equals method is used to check whether two objects are the same or not. It needs to be
overridden if we want to check the objects based on the property.
For example, Employee is a class that has 3 data members: id, name, and salary. However, we
want to check the equality of employee object by the salary. Then, we need to override the
equals() method.
JDBC is a Java API that is used to connect and execute the query to the database. JDBC API
uses JDBC drivers to connect to the database. JDBC API can be used to access tabular data
stored into any relational database.
JDBC Driver is a software component that enables Java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver: The JDBC-ODBC bridge driver uses the ODBC driver to
connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls
into the ODBC function calls. This is now discouraged because of the thin driver. It is
easy to use and can be easily connected to any database.
2. Native-API driver (partially java driver): The Native API driver uses the client-side
libraries of the database. The driver converts JDBC method calls into native calls of the
database API. It is not written entirely in Java. Its performance is better than JDBC-
ODBC bridge driver. However, the native driver must be installed on each client
machine.
3. Network Protocol driver (fully java driver): The Network Protocol driver uses
middleware (application server) that converts JDBC calls directly or indirectly into the
vendor-specific database protocol. It is entirely written in Java. There is no requirement
of the client-side library because of the application server that can perform many tasks
like auditing, load balancing, logging, etc.
4. Thin driver (fully java driver): The thin driver converts JDBC calls directly into the
vendor-specific database protocol. That is why it is known as the thin driver. It is entirely
written in Java language. Its performance is better than all other drivers however these
drivers depend upon the database.
42.What are the steps to connect to the database in java?
//2.Creating Connection
String url="jdbc:mysql://localhost:3306/mysdb?useSSL=false";
String user="root";
String password="xyz";
//1.Loading Driver
try
Class.forName("com.mysql.jdbc.Driver");
catch (ClassNotFoundException e)
e.printStackTrace();
catch (SQLException e)
{
e.printStackTrace();
System.out.println("Database Connected...");
}
43.What are the JDBC API components?
The java.sql package contains following interfaces and classes for JDBC API.
Interfaces:
o DriverManager: The DriverManager class acts as an interface between the user and
drivers. It keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver. It contains several methods
to keep the interaction between the user and drivers.
o Blob: Blob stands for the binary large object. It represents a collection of binary data
stored as a single entity in the database management system.
o Clob: Clob stands for Character large object. It is a data type that is used by various
database management systems to store character files. It is similar to Blob except for
the difference that BLOB represent binary data such as images, audio and video files,
etc. whereas Clob represents character stream data such as character files, etc.
In JDBC, Statements are used to send SQL commands to the database and receive data from
the database. There are various methods provided by JDBC statements such as execute(),
executeUpdate(), executeQuery, etc. which helps you to interact with the database.
Statements Explanation
Statement PreparedStatement
he DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().
The Connection interface maintains a session with the database. It can be used for
transaction management. It provides factory methods that return the instance of Statement,
PreparedStatement, CallableStatement, and DatabaseMetaData.
The ResultSet object represents a row of a table. It can be used to change the cursor pointer
and get the information from the database. By default, ResultSet object can move in the forward
direction only and is not updatable. However, we can make this object to move the forward and
backward direction by passing either TYPE_SCROLL_INSENSITIVE or
TYPE_SCROLL_SENSITIVE in createStatement(int, int) method.
49. What are the benefits of PreparedStatement over Statement?
51. What are the differences between execute, executeQuery, and executeUpdate?
execute executeQuery executeUpdate