You are on page 1of 18

What is garbage collection? What is the process that is responsible for doing that in java?

- Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process What kind of thread is the Garbage collector thread? - It is a daemon thread. What is a daemon thread? - These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly. How will you invoke any external process in Java? Runtime.getRuntime().exec(.) What is the finalize method do? - Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected. What is mutable object and immutable object? - If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, ) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, ) What is the basic difference between string and stringbuffer object? - String is an immutable object. StringBuffer is a mutable object. What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void. What is reflection? - Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. What is the base class for Error and Exception? - Throwable What is the byte range? -128 to 127 What is the implementation of destroy method in java.. is it native or java code? - This method is not implemented. What is a package? - To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability. What are the approaches that you will follow for making a program very efficient? - By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more. What is a DatabaseMetaData? - Comprehensive information about the database as a whole. What is Locale? - A Locale object represents a specific geographical, political, or cultural region How will you load a specific locale? - Using ResourceBundle.getBundle(); What is JIT and its use? - Really, just a very fast compiler In this incarnation, pretty much a one-pass compiler no offline computations. So you cant look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, its an on-line problem. Is JVM a compiler or an interpreter? - Interpreter When you think about optimization, what is the best way to findout the time/memory consuming process? - Using profiler

What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing. How will you get the platform dependent values like line separator, path separator, etc., ? - Using Sytem.getProperty() (line.separator, path.separator, ) What is skeleton and stub? what is the purpose of those? - Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use it is deprecated long before in JDK. What is the final keyword denotes? - final keyword denotes that it is the final implementation for that method or variable or class. You cant override that method/variable/class any more. What is the significance of ListIterator? - You can iterate back and forth. What is the major difference between LinkedList and ArrayList? - LinkedList are meant for sequential accessing. ArrayList are meant for random accessing. What is nested class? - If all the methods of a inner class is static then it is a nested class. What is inner class? - If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class. What is composition? - Holding the reference of the other class within some other class is known as composition. What is aggregation? - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation. What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString Can you instantiate the Math class? - You cant instantiate the math class. All the methods in this class are static. And the constructor is not public. What is singleton? - It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods } What is DriverManager? - The basic service to manage set of JDBC drivers. What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( classinstance.newInstance() ). Inq adds a question: Expain the reason for each keyword of public static void main(String args[])

Java interview questions and answers for freshers and experienced

Java features

Simple, Object-Oriented, Robust, Distributed, Portable, Interpreted, Multithreaded, Platform Independent, Secure........... Read answer
Java program execution

What is JVM? Explain its roles and functions. Explain why Java is called as Platform independent language. Explain how Java executable executes on any platform where JVM is available................... Read answer
Java architecture

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

Explain the features of Java class. Explain Fields, Methods, and Access Levels. What are accessors and mutator methods in a Java class? Explain with example for each. Explain the importance of 'this' reference. Write a code to depicts the use of 'this' reference Explain static variables and static methods in Java. Provide an example to explain them.................. Read answer
Java constructors

What is a constructor? Explain the differences between methods and constructor. Differences between constructors and methods. Write code to depict the use of constructor..................... Read answer
Java class member

What is instance members? Explain with an example What is instance variable? Explain with an example What is instance method? Explain with an example What is static member? Explain with an example What is static variable? Explain with an example...................... Read answer
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............. Read answer
Java garbage collector

Explain Java Garbage collector. Why garbage collection? Brief explanation of Garbage collection algorithms. Explain the importance of finalizers in Java. Write code to depict the uses of finalizers in Java............... Read answer
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.................... Read answer
Java overloading & overriding

Define Method overloading. Explain its uses. Provide a code sample to explain the uses of Method overloading Define Method overriding. Explain its uses. Provide a code sample to explain the uses of Method overloading Difference between overloading and overriding....................... Read answer
Java string class

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...................... Read answer
Java inner classes

What is Java inner class? Explain the types of inner classes, i.e. Static member classes, Member classes, Local classes, Anonymous classes Need of inner class in context with adapter classes Explain few Wrapper Classes Methods............... Read answer
Java reflection class

Explain about Java reflection class. Write a code sample to depict the uses of Java reflection class......... Read answer
Java swing

What is Swing? Explain the need of Swing. Write some important features of Swing. Describe Java Swing class hierarchy. Explain the need of Layout manager........... Read answer
Java layout manager

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............. Read answer
Java exception handling

Explain the need of Exception handling. Explain the Exceptions categories, i.e. checked and unchecked exceptions. Provide the general form of Exception handling constructs with explanation What is user defined Exception? Explain with an example............ Read answer
Java multithreading

What is Multithreading? Explain the life cycle of a thread. Explain how to use thread class for Multithreading in Java. Explain with an example. What is Runnable interface? Explain how to use Runnable interface for Multithreading. What are the methods of thread class in java? Explain them Can your explain thread priorities?.............. Read answer
Java file handling

Explain the use of Streams. Difference between Stream classes and Reader writer classes Explain and demonstrate the use of File, RandomAccessFile classes. Explain the use of Reader and Writer classes.............. Read answer
Java utility classes

What is object Serialization? Explain the use of Persisting object. Depict the step of using object Deserialization..................... Read answer
Java socket programming

What is socket? Explain the features of socket. Explain the characteristics of Java socket class. Explain ServerSocket class with an example Explain InetAddress class with an example Explain DatagramSocket class with an example Explain DatagramPacket class with an example............. Read answer
JDBC

Purposes of JDBC API Describe 4 types of JDBC drivers and their characteristics with usages. State the functionalities of important classes in JDBC packages. Explain how to use JDBC statement to execute SQL queries. Show in an example Explain how to use Prepared Statement to execute parameterized queries. Show in an example What is JDBC Callable Statement? What is batch updates in JDBC? Explain with an example...................... Read answer

Java interview questions and answers - April 18, 2011


What is an abstract method?
An abstract method is a method which doesnt have a body, just declared with modifier abstract.

Explain the use of the finally block.


Finally block is a block which always executes. The block executes even when an exception is occurred. The block won't execute only when the user calls System.exit()

What is the initial state of a thread?


It is in a ready state.

What is time slicing?


In time slicing, the task continues its execution for a predefined period of time and reenters the pool of ready tasks.

What are Wrapper Classes?


Wrapper Classes allow to access primitives as objects.

What is List interface?


List is an ordered collection of objects.

Can you explain transient variables in java?


They are the variables that cannot be serialized.

What is synchronization?
Synchronization ensures only one thread to access a shared resource, thus controls the access of multiple threads to shared resources.

What is serialization?
Serialization helps to convert the state of an object into a byte stream.

What is HashMap and Map?


Map is Interface and Hashmap is class that implements that.

Java interview questions and answers - April 18, 2011


Explain the usage of serialization.
Objects are serialized when need to be sent over network. They are serialized when the state of an object is to be saved.

How are Observer and Observable used?


The observable class represents an observable object. The object to be observed can be represented by sub-classing observable class. When there is a change in an observable instance, an application calling the Observable's notifyObservers method causes all of its observers to be notified of the change by a call to their update method.

Difference between Swing and Awt.

AWT are heavy-weight components. Swings are light-weight components. Thus, swing works faster than AWT.

Define inner class in Java


Class that is nested within a class is called as inner class. The inner class can access private members of the outer class. It is mainly used to implement data structure and some time called as a helper class.

Differences between constructors and methods.


A constructor is used to create objects of a class. A method is an ordinary member in a class. Constructor does not have a return type. A method should have a return type. Constructor name is the name of the class. A method name should not be the name of the class Constructor is invoked at the time of creation of the class. Method needs to be invoked in another method by using the dot operator. Constructor can not have return statement. All methods that return non-void return type should have return statement.

Define Method overriding. Explain its uses.


Method overriding is the process of writing functionality for methods with same signature and return type, both in super class and subclass The uses of method overriding: Time to invest method signature is reduced Different functionality in both super class and sub class by sharing same signature The functionality can be enhanced The behavior can be replaced in the sub class

What is the purpose of the File class?


The File class provides access to the files and directories of a local file system.

Java interview questions and answers - April 20, 2011


What is StringBuffer class?
StringBuffer class is same as String class with the exception that it is mutable. It allows change and doesnt create a new instance on change of value.

How can you force garbage collection?

It is not possible to force GC. We can just request it by calling System.gc().

Is it possible an exception to be rethrown?


Yes, an exception can be rethrown.

What is the return type of a programs main() method?


A programs main() method has a void return type.

Which package is always imported by default?


The java.lang package is always imported by default.

What is a Class?
A class implements the behavior of member objects by describing all the attributes of objects and the methods.

What is an Object?
An object is the members of a class. It is the basic unit of a system. It has attributes, behavior and identity.

Explain the use of "instanceOf" keyword.


"instanceOf" keyword is used to check the type of object.

How do you refer to a current instance of object?


You can refer the current instance of object using "this" keyword.

What is the use of JAVAP tool?


JAVAP is used to disassemble compiled Java files. This option is useful when original source code is not available.

In which package is the applet class located?


Applet classes are located in "java.applet" package.

Java array vs. ArrayList class.


ArrayList is a dynamic array that can grow depending on demand whereas Java arrays are fixed length.

Explain Enumeration Interface.


It defines the methods using which we can enumerate the elements in a collection of objects.

What are access modifiers?


Access modifiers determine if a method or a data variable can be accessed by another method in another class.

Explain the impact of private constructor.


Private constructor prevents a class from being explicitly instantiated by callers.

What is an exception?
An exception is an abnormal condition that arises in a code sequence at run time

Java interview questions and answers - April 21, 2011


What are ways to create threads?
There are two ways to create a thread: extend the java.lang.Thread class implement the java.lang.Runnable interface

How can we stop a thread programmatically?


thread.stop;

What are daemon threads?


Daemon threads are designed to run in background. An example of such thread is garbage collector thread.

What are the different types of locks in JDBC?


There are four types of major locks in JDBC: Exclusive locks Shared locks

Read locks Update locks

What are Servlets?


Servlets are program that run under web server environments.

What are the different ways to maintain state between requests?


There are four different ways: URL rewriting Cookies Hidden fields Sessions

What are wrapper classes?


In Java we have classes for each primitive data types. These classes are called as wrapper class. For example, Integer, Character, Double etc.

What are checked exceptions?


There are exceptions that are forced to catch by Java compiler, e.g IOException. Those exceptions are called checked exceptions.

What is the Locale class?


Locale class is a class that converts the program output to a particular geographic, political, or cultural region

Is main a keyword in Java?


No, main is not a keyword in Java.

What is the most important feature of Java?


Platform independency makes Java a premium language.

What is a JVM?
JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

Does Java support multiple inheritances?

No, Java doesn't support multiple inheritances.

What is the base class of all classes?


java.lang.Object

Can a class be declared as protected?


A class can't be declared as protected. Only methods can be declared as protected.

Can an abstract class be declared final?


No, since it is obvious that an abstract class without being inherited is of no use.

Java interview questions and answers - April 22, 2011


Can we declare a variable as abstract?
Variables can't be declared as abstract. Only classes and methods can be declared as abstract.

Define Marker Interface.


An Interface which doesn't have any declaration inside but still enforces a mechanism.

What is an abstract method?


An abstract method is a method whose implementation is deferred to a subclass.

When can an object reference be cast to an interface reference?


An object reference is cast to an interface reference when the object implements the referenced interface.

Which class is extended by all other classes?


The Object class is extended by all other classes.

What is the return type of a program's main() method?


void.

What are the eight primitive Java types?


The eight primitive types are byte, char, short, int, long, float, double, and boolean.

Difference between a public and a non-public class.


A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.

Which Java operator is right associative?


The = operator is right associative.

What is a transient variable?


Transient variable is a variable that may not be serialized.

Java interview questions - July 07, 2011


Can you explain Native methods in Java?

The Java native method is used to merge the power of C or C++ programming into Java. To enhance to high performance language, when efficient native Java compilers are not fully implemented, use of native method boosts the performance to at least the speed of C compiled code.

Java applications can call code written in C, C++, or assembler. This is sometimes done for performance and sometimes to access the underlying host operating system or GUI API using the JNI.

Explain class loaders in Java with an example.


The class loader describes the behavior of converting a named class into the bits responsible for implementing that class. Class loaders eradicate the JREs need to know anything about files and file systems when running Java programs. A class loader creates a flat name space of class bodies that are referenced by a string name and are written as: Class r = loadClass(String className, boolean resolveIt);

What is Reflection API in Java?


The Reflection API allows Java code to examine classes and objects at run time. The new reflection classes allow you to call another class's methods dynamically at run time. With the reflection classes, you can also examine an instance's fields and change the fields' contents. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method, Constructor, Array, and Modifier.

Java interview questions - July 9, 2011


Static class loading vs. dynamic class loading.

The static class loading is done through the new operator. Dynamic class loading is achieved through Run time type identification. Also called as reflection

This is done with the help of the following methods: getClass(); getName(); getDeclaredFields(); Instance can also be created using forName() method. It loads the class into the current class memory.

Can you explain shallow cloning and deep cloning?


Cloning of objects can be very useful if you use the prototype pattern or if you want to store an internal copy of an object inside an aggregation class for example.

Deep cloning - You clone the object and their constituent parts. It should be used when it is inappropriate to separate the parts; the object is formed of, from it. Shallow cloning - You clone only the object, not their parts. You add references to their parts. It should be used when it is adequate to have the references added to the cloned object

Explain the purpose of Comparator Interface.

Comparators can be used to control the order of certain data structures and collection of objects too.

The interface can be found in java.util.Comparator A Comparator must define a compare function which takes two Objects and returns a -1, 0, or 1 Sorting can be done implicitly by using data structures of by implementing sort methods explicitly.

Java interview questions - July 11, 2011


What is the impact of private constructor?

Private Constructors can't be access from any derived classes neither from another class. So you have to provide a public function that calls the private constructor if the object has not been initialized, or you have to return an instance to the object, if it was initialized.

This can be useful for objects that can't be instantiated.

Can you explain static Initializers in Java?


A static initializer block resembles a method with no name, no arguments, and no return type. There is no need to refer to it from outside the class definition. Syntax: static { //CODE } The code in a static initializer block is executed by the virtual machine when the class is loaded. Because it is executed automatically when the class is loaded, parameters don't make any sense, so a static initializer block doesn't have an argument list.

Java interview questions - July 12, 2011


Define Externalizable Interface and explain its purpose.

The Externizable interface extends the serializable interface.

When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process. The two methods to be implemented are : void readExternal(ObjectInput) The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays. void writeExternal(ObjectOutput) The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.

Explain in brief transient modifiers and volatile modifiers.


When serializable interface is declared, the compiler knows that the object has to be handled so as so be able to serialize it. However, if you declare a variable in an object as transient, then it doesnt get serialized. Volatile - Specifying a variable as volatile tells the JVM that any threads using that variable are not allowed to cache that value at all. Volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

Java interview questions - July 13, 2011


Define daemon threads and explain its purposes.
Threads that work in the background to support the runtime environment are called daemon threads. Eg garbage collector threads. When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service. You cannot create a daemon method but you can use public final void setDaemon(boolean isDaemon) method to turn it into one.

Can you explain JAVAdoc utility.

Javadoc utility enables you to keep the code and the documentation in sync easily. The javadoc utility lets you put your comments right next to your code, inside your ".java" source files. All you need to do after completing your code is to run the Javadoc utility to create your HTML documentation automatically.

StringBuilder class vs. StringBuffer class.


StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Java interview questions - July 14, 2011


Can you explain semaphore and monitors in java threading?
A semaphore is a flag variable used to check whether a resource is currently being used by another thread or process. The drawback of semaphores is that there is no control or guarantee of proper usage. A Monitor defines a lock and condition variables for managing concurrent access to shared data. The monitor uses the lock to ensure that only a single thread is active in the monitor code at any time. A semaphore is a generalization of a monitor. A monitor allows only one thread to lock an object at once.

Describe synchronization in respect to multithreading.


Multithreading occurs asynchronously, meaning one thread executes independently of the other threads. In this way, threads dont depend on each others execution. In contrast, processes that run synchronously depend on each other. That is, one process waits until the other process terminates before it can execute

Java interview questions - July 15, 2011


What are Checked and UnChecked Exception?

The java.lang.Throwable class has two subclasses Error and Exception. There are two types of exceptions non runtime exceptions and runtime exceptions. Non runtime exceptions are called checked exceptions and the unchecked exceptions are runtime exceptions. Runtime Exceptions occur when the code is not robust and non runtime exceptions occur due to the problems is environment, settings, etc.

You might also like