Java Interview Questions -46

Java Interview Questions -46

1. What is CLASSPATH variable? What is default classpath?

CLASSPATH is an environment variable that communicates JVM and other java applications for finding the java language class libraries, including the developer’s class library.

2. Explain how to convert any Java Object into byte array.

Create an object of ByteArrayOutputStream class. ByteArrayOutputStream bStream = new ByteArrayOutputStream()

3. Explain how to convert bytes[] into File object.

Create a File object. File file = new File(“path and file name here”);…

4. JavaSpaces technology vs. database

Java spaces is a technology with powerful high-level tool for the development of distributed and collaborative applications. A simple API is provided based on the network shared space for developing.

5. Explain the methods for accessing system properties about the Java virtual machine.

The system properties are accessed by the method System.getProperties(). This method returns a Properties object. By using the list() method of Properties, all the system properties can be viewed..

6. What is difference between add() and addElement() in Vector?

The add() methods inserts an element at a given position of the vector..

7. What is difference between sets and lists?

Sets can have unique values. Lists can have duplicate values..

8. Two String objects with same values not to be equal under the == operator. Explain How.

The == operator compares references and not contents. It compares two objects and if they are the same object in memory and present in the same memory location, the expression returns true else it returns false.

9. Explain static in java.

A static variable is attached with the class as a whole and not with specific instances of a class..

10. Explain Garbage collection mechanism in Java.

Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory.

11. Can Abstract Class have constructors?

Abstract class can have a constructor. But as we can’t instantiate abstract class, we can’t access it through the object.

12. Explain how Java addresses the issue of portability and security.

Addressing Portability: Many computers of different types with several operating systems are connected to network / internet..

13. Why does Java have different data types for integers and floating-point values?

The integer and floating-point types are different in terms of the consumption of the bits which represent them. There are certain data types which are rightly apt for speed.

14. Features of Java

Java omits rarely used, poorly understood features those are available in C++. These features include operator overloading, multiple inheritance, destructors, allocation and freeing of memory.

15. Explain why Java is called as Platform independent language. Explain how Java executable executes on any platform where JVM is available.

Java byte code can run on any OS with java installed. JVM takes care of executing of native byte code..

16. Explain Java architecture, i.e. typical Java environment.

Java programming language, Java class file format , Java Application Programming Interface, Java virtual machine..

17. Explain the features of Java class. Explain Fields, Methods, and Access Levels.

A Java class has attributes, static blocks, non-static blocks, constructors, methods and inner classes. Fields: Fields are referred to data members whom are to be accessed by the methods, constructors of the same class and methods of other classes.

18. What is a constructor? Explain the differences between methods and constructor.

A constructor is a block of code with the same name of its defining class without return type
Ex: Employee() {…} // The class name is Employee…………

19. What is instance members? Explain with an example

Instance members are the attributes and methods of a class. They share one copy each per object. Since an object is an instance of a class, memory has been set aside for each object to contain its own copies of instance members.

20. What are Java packages? Explain the importance of Java packages.

A package is a group of .class files.
The .class files are organized into namespaces. The java packages are compressed into files known as Java Archive files……..

21. Explain Java Garbage collector. Why garbage collection? Brief explanation of Garbage collection algorithms.

Garbage collection is the process of reclaiming heap memory space by removing orphan objects The objects that are no longer needed by the application are garbage collected
Garbage collection is done automatically…………..

22. Explain the importance of ‘super’ keyword in Java. Write code to depict the uses of ‘super’ keyword.

The keyword ‘super’ is used for referring parent class instance Same data members of super class hides the variables by the sub class Ex : super.number; //number of super class is accessed.

23. Define Method overloading. Explain its uses. Provide a code sample to explain the uses of Method overloading

Java supports to define two or more methods with same names within a class.All the methods should differ in either by the number or type of parameters.The method System.out.println() receives multiple parameters.

24. Describe Java string class. Explain methods of Java string class. Explain the characteristics of StringBuffer class

String Class:
The String class is immutable.
The contents of the String object can not be changed.
String class is final class. That implies it can not have sub classes.
String objects can be concatenated by using + and += operators.

25. What is Java inner class? Explain the types of inner classes, i.e. Static member classes, Member classes, Local classes, Anonymous classes

Inner Class : A class defined inside another class is called an ‘Inner Class’.
Types of inner classes:.

26. Explain about Java reflection class.

Classes, interfaces, methods, instance variables can be inspected at runtime by using reflection class To inspect he names of the classes, methods, fields etc. need not be known
Reflection in Java is powerful and useful, when objects are needed to be mapped into tables in a database at runtime……….

27. Write some important features of Swing.

Platform independent : Swing is platform independent in both expression and implementation Extensible : Allows plugging of custom implementations of specified framework interfaces.Users can provide custom component implementations by overriding the default implementations.

28. Explain different layout manager in Java.

A layout manager organizes the objects in a container Different layouts are used to organize or to arrange objects…

29. What is user defined Exception? Explain with an example.

A user defined exception is extended by Exception class. Unconventional actions are dealt with user defined exceptions Application demanded exceptions other than APIs are defined as user defined exceptions. Ex: When the balance of an account is below zero after withdrawl, an exception can be raised like ‘NegativeBalanceException’.

30. Explain how to use thread class for Multithreading in Java. Explain with an example.

Threads are used in java by a. extending the Thread class b. implementing the Runnable interface..

31. Difference between Stream classes and Reader writer classes

Stream Classes: They are byte-oriented, They never support Unicode characters, Supports 8-bit streams.

32. What is object Serialization? Explain the use of Persisting object.

Persisting the state of an object in a storage media is known as Object Serialization Saving and retrieving data is one of the critical tasks for developers
By persisting objects, applications can efficiently handle them, as only one object can be used at a given point of time…

33. Explain the characteristics of Java socket class.

The following are certain characteristics that socket share:
1. The socket is available as long as the network process maintains an open link to the socket 2. A socket can be named in order to communicate with other sockets in a network
3. Communication is performed by the sockets in network when the server receives the connections and requests from them…

34. State the functionalities of important classes in JDBC packages.

The important interfaces in JDBC are:
java.sql.DriverManager: Used to manage JDBC drivers, thus establishes a connection to the database server
java.sql.Connection; Used for establishing connection to a database. All SQL statements executes within the connection context.

35. What is endianness? Describe the ways an integer is stored in memory.

Endianness is the process of ordering the addressable sub units such as words, bytes or bits in a longer word that is to store in an external memory.

36. Explain why Java uses Unicode

To enable a computer system for storing text and numbers which is understandable by humans, there should be a code that transforms characters into numbers..

37. What are the different loops available in java? How do we choose the right loop for a specific job?

A loop is a set of statements that is supposed to repeat one or more times. Java supports 3 loops..

38. Explain why we don’t need to use new for variables of the primitive types, such as int or float

The key word ‘new’ is used for creation of objects. Primitive types are to use constants but not objects.

39. What is finalize()? Is finalize() similar to a destructor?

The finalize() method of java is invoked by JVM to reclaim the inaccessible memory location, When the ‘orphan’ object (without reference) is to be released, JVM invokes the finalize() method, when the next.

40. Why does String define the equals( ) method? Can’t I just use ==?

The equals() method is defined in String class in order to test whether two strings values are same sequence of characters. The method is for exclusively testing string objects, but not any other objects.

41. String objects are immutable in java. Explain how to create a string that can be changed.

A string object that is created using “String” class is immutable. The characters of the object can not be changed / modified. There are some methods, such as split(), substring(), beginsWith() etc.

42. Can we pass a primitive type by reference in java? How

Primitive types can be passed by reference. 1.By storing the primitive type value in an array of single element and passing it.

43. What do you mean by the term signature in java?

A signature in java is a combination of elements in a list such as constructor and methods thereby distinguishing them from other constructors and methods.

44. Static nested class vs. a non-static one.

A static nested class can not directly access non-static methods or fields of an instance of its enclosing class. They can be accessed by creating the object of the nested inner class. Where as non-static nested .

45. Explain when we should make an instance variable private.

An instance variable can be declared as private to promote information hiding..

46. Overridden methods in Java

Overridden methods of super class in subclass allow a class to inherit and behave close enough. To avoid naming conflict and signature and type and number of parameters.

47. Is C++ access specifier called protected is similar to Java’s?

The java access specifier ‘protected’ is placed proceeding the member of the class and the access control is applicable only for that particular definition.

48. Why should we catch super class exceptions?

Every exception is represented by the instance of Throwable or its subclasses. An object can carry the information for the exception raising point to the exception handler which catches it.

49. Why would we manually throw an exception?

When an exception is to be handled which are not java class library, a user defined exception can be thrown. An exception can be thrown explicitly, when a condition is met. In other words, in a situation.

50. What is chained exceptions in java?

Once an application finds an exception, responds an exception by throwing another exception. It causes another exception. Knowing an exception that causes another exception is very useful.

51. When should we create our own custom exception classes?

The term exception lets the programmer to know that there is something exceptional has occurred in the program. Apart from Java exception class library, a custom..

52. What are primitive type wrappers classes? Explain the purpose of primitive type wrapper classes.

Primitive type wrapper classes or simply wrapper classes are available in java.lang package for providing object methods for all the eight primitive types. All the wrapper class objects are immutable.

53. Why do you recommend that the main thread be the last to finish?

In an application, a program continues to run until all of the threads have ended. Hence, the main thread to finish at last is not a requirement. It is a good programming practice to make it to run last to finish.

54. Why does Java have two ways to create child threads? Which way is better?

Java threads can be created graciously in two ways: implementing the Runnable interface and extending Thread class…

55. Tips on effectively using Multithreading to improve the efficiency of my programs.

In multiple processor systems, a large algorithm will split the process into threads. So that different processors can handle different threads.

54. Enumerations vs final variables in java.

Enumeration is type safe. Where as final variables are not. Enumeration supports to have a blend of various values.

55. Is it possible for a method other than paint() or update() to output to an applet’s window? Explain how.

Yes I is possible for a method other than paint() or update() to output an applet’s window. It is mandatory to obtain a graphics context by invoking getGraphics() method..

56. What is byte code and why is it important to Java’s use for Internet programming?

The compiled Java source code is known as byte code. Java compiler generates the byte code. The byte code can run on any platform / machine regardless of the system’s architecture.

57. Why does Java strictly specify the range and behavior of its primitive types?

Java strictly specifies the ranges for primitive values. The selection of values in integer or floating point types differs based on the requirement of an application.

58. What is Java’s character type, and how does it differ from the character type used by many other programming languages?

The char data type in Java is a single 16-bit Unicode character. It represents a character that could be any one of the world languages.

59. Explain the difference between the prefix and postfix forms of the increment operator.

The prefix operator ++ adds one to its operand / variable and returns the value before it is assigned to the variable. In other words, the increment takes place first and the assignment next.

60. What is the difference between the String methods indexOf( ) and lastIndexOf( )?

The method indexOf() returns the first occurrence (index) of a given character or a combination as parameter in a given string.

61. Explain the difference between protected and default access.

The default access specifier is one which is not specified with a key word. If no access specifier (any one of private, protected, public) is mentioned it is known as the default access specifier.

62.What is a meant by light object mapping?

The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns.
This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known
to all.

63. What is a meant by medium object mapping?

The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex
transactions. Used when the mapping exceeds 25 different database products at a time.

64. What is meant by full object mapping?

Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent
persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are
implemented transparently to the application.

65. What are the benefits of ORM and Hibernate?

There are many benefits from these. Out of which the following are the most important one.
Productivity : Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.Maintainability :As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational
persistence it even reduces the LOC. Performance : Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more
optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance.
Vendor independence : Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

66. What the Core interfaces are of hibernate framework?

There are many benefits from these. Out of which the following are the most important one. Session Interface : This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and
destroy. Hibernate sessions are not thread safe. SessionFactory Interface : This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads. Configuration Interface : This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the
location of hibernate specific mapping documents. Transaction Interface : This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.Query and Criteria Interface : This interface allows the user to perform queries and also control the flow of the query execution.

67. What are Callback interfaces?

These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need
to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality

68. What is a SessionFactory? Is it a thread-safe object?

SessionFactory is Hibernates concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton
so that it can be easily accessed in an application code.

69. What are the benefits of detached objects?

Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

70. What is the difference between the session.get() method and the session.load() method?

Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null

71. How would you reatach detached objects to a session when the same object has already been loaded into the session?

You can use the session.merge() method call.

72. What are the important tags of hibernate.cfg.xml?

An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest.

73. What is object/relational mapping metadata?

ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys,Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and
relationship representations.

74. What is HQL?

HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL

75. What are Callback interfaces?

These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality.

76. Define collable collections in java.

A callable collection is an interface whose implementers define a single method with no arguments. The Callable interface resembles Runnable

77. Purpose of making a method thread safe. How to make a method thread safe without using synchronized keyword?

Java supports threads natively without using additional libraries. Using ‘synchronized’ key word makes the methods thread safe.

78. Can you explain why a constructor doesn’t have return type?

The primary goal of a constructor is to create an object. Though the constructor resembles a method, its explicit purpose is to initialize the instance variables.

79. Explain how to add a button in applet.

The following are the steps to add a button in applet: 1. Declare and create the object of Button class – Button clickMe;.

80. Explain the purpose of jar file. Can you explain how to create a jar file in java.

A Jar file contains mostly .class files and optionally other files like sound files, image files for Java applications, gathered into a single file in the compressed format.

81. Difference between String s=”hello”; and String s=new String(“hello”); in Java

The statement String s = “hello” is initialized to s and creates a single interned object.

82. Java vs. Javascript.

The differences of Java and Java Script are: – Java can stand on its own where as Java Script mandatorily be placed within an HTML document.

83. Explain upcasting and downcasting in Java. Give an example

Upcasting: Java permits an object of a sub class can be referred by its super class. It is done automatically.

84. Can you explain benefits of classpath?

Classpath is the path in which JVM searches for class libraries at the time of compiling the Java Application. By setting the CLASSPATH environment variable.

85. Explain the reason of Out of Memory exception in Java.

The OutOfMemoryException can occur either the JVM may have a limit of memory to access to, or the system may have run out of physical memory.

86. What will happen when ResultSet is not closed?

In a pooled database connection, it is returned to the pool and could close only after expiring its life time..

87. Explain the use of Clonable,and serializable interface.

The similarity of Clonable and Serializable interfaces is that they both are marker interfaces.

88. Java architecture

Java programming language, Java class file format, Java Application Programming Interface, Java virtual machine.

89. Java super keyword

Explain the importance of ‘super’ keyword in Java. Write code to depict the uses of ‘super’ keyword – The keyword ‘super’ is used for referring parent class instance.

90. Java packages

What are Java packages? Explain the importance of Java packages.Steps for creating a package in Java Explain the packages access specifier, i.e. private, protected, public, default.

91. What are the two types of multitasking?

Process-based and Thread-based

92. Name the ways to create the thread.

Implementing Runnable and Extending Thread

93. What is timeslicing?

Timeslicing is the method of allocating CPU time to individual threads in a priority schedule.

94. Name the methods available in the Runnable Interface.


95. Name the methods available in the Thread class.

isAlive(), join(), resume(), suspend(), stop(), start(), sleep(), destroy()

96. Write the signature of the constructor of a thread class.

Thread(Runnable threadobject,String threadName)

97. Name the methods used for Inter Thread communication.

wait(),notify() & notifyall()

98. Name the mechanism defined by java for the Resources to be used by only one Thread at a time.


99. Data type for the parameter of the sleep() method is


100. Provide the values for max-priority, min-priority and normal-priority level.


101. Name the method for setting the priority.


102. Name the default thread at the time of starting the program.

main thread

103. How many threads at a time can access a monitor?


104. Name the four states associated in the thread.

new, runnable, blocked, dead

105. What is the priority for Garbage collector thread?




This site uses Akismet to reduce spam. Learn how your comment data is processed.