Sei sulla pagina 1di 13

INTERVIEW QUESTIONS FOR -CORE JAVA

Q1.Core Java - What is the purpose of the Runtime class?


Runtime class provides access to the Java runtime system.
Some of the other purposes provided are by this class are:
Writing to console output
Reading from the keyboard as input
Interaction with JVM process
Reading/writing system properties/environment variables
Executing other programs from within java apps

Q2.What is the difference between a static and a non-static inner class?
Like static methods and static members are defined in a class, a class can also be static. To specify the static class,
prefix the keyword static before the keyword class.
Example: public static class InnerClass { }
A static inner class is like other regular classes. They need to be referred by the class name being it is static, e.g.
OuterClass.InnerClass. A static inner class can have access even to the private members of the outer class.
The non-static inner class has the reference that is not visible in the outer class. To utilize the non-static inner class
attributes and methods, its instance is to be created in the outer class.

Q3.What is the difference between the String and StringBuffer classes?
The StringBuffer is class to manipulate the string objects. This class has similar functionalities that of String class.
The StringBuffer class is mutable, which means, the strings can be altered. For example, new strings can be
appended, inserted. Characters from the string can be deleted. Where as the String class is immutable, which can
not make changes to the existing objects.
String class provides the concatenation facility with concat() method. But it creates a new String object and returns it.
Where as the StringBuffer just appends / adds the new string to the existing StringBuffer object. This process is pretty
quicker than concatenation using + or concat() method of String class.

Q4.What is the Dictionary class?
The Dictionary class is an abstract class. The class maps keys to values. The classes such as HashTable are the sub
classes of the abstract class Dictionary. The key and values are objects. The key and value are non-null objects.
Q5.What is the ResourceBundle class?
A ResourceBundle is a group of related sub classes which are sharing the same base name. For example,
ButtonLabel is the base name. All the characters following the base name indicates the following elements
respectively.
language code, country code,platform code.
Ex : Locale.ButtonLabel_en_GB_Unix - It matches the Locale specifies the code for English language(en) and the
country code for Great Britain(GB) and the UNIX platform
Q6. What is the Vector class?
The capability of implementing a growable array of objects is provided by the class Vector.
A Vector class implements the dynamic array that can grow and shrink at run time (dynamically). It resembles the
implementation of ArrayList with a difference that Vector is synchronized.
Q7. What is the SimpleTimeZone class?
SimpleTimeZone is a concrete subclass of TimeZone class. The TimeZone class represents a time zone, that is to be
used with Gregorian calendar.
The SimpleTimeZone is created by using the base time zone offset from GMT time zone ID and rules, for starting and
ending the time of daylight.
Q8. What is the purpose of the System class?
System class is provided with useful fields (static members) that are pertaining to the environment.
Standard input,output and error output streams are provided with System class. These are used to access the
externally defined properties and environment variables.
Ex. : System.in - external property for input device.
System.out external property for output device
Other useful methods that interact with external system / environment are:
currentTimeMillis() returns the current time in millieconds
exit() - terminates currently running JVM
gc() - invokes the garbage collector
getProperties() - returns the system properties.
The System class can not be instantiated.
Q9. How are this() and super() used with constructors?
this() constructor is invoked within a method of a class, if the execution of the constructor is to be done before the
functionality of that method.
Ex :
void getValue() {
this();

}
super() constructor is used within the constructor of the sub class, as the very first statement. This process is used
when the super class constructor is to be invoked first, when the sub class object is instantiated everytime.
Ex : class SubClass {
SubClass() {
super();
..
}
Q10. What is the purpose of finalization?
Finalization is the facility to invoke finalized() method. The purpose of finalization is to perform some action before the
objects get cleaned up. This method performs the required cleanup before the garbage collection, which means the
elimination of the orphan objects
Q11. What is the difference between the File and RandomAccessFile classes?
The File class is used to perform the operations on files and directories of the file system of an operating system. This
operating system is the platform for the java application that uses the File class objects. The contents of the files
cannot be read or write.
The RandomAccessFile class has methods that perform the direct access to data of any part of the file.
RandomAccessFile class also provides the facilities to read and write data from a single file without closing the
streams for each read or write. It provides the facilities to write primitive data to the files
Q12. What is the difference between StringBuilder and StringBuffer?
StringBuffer is thread safe, where as StringBuilder is not. In other words, StringBuffer class is synchronized and
StringBuilder class is not synchronized.
When an application is to run a single thread using some changes for strings, it is advisable to use StringBuilder. If an
application uses multiple threads which are used to perform changes to the strings, it is advisable to use StringBuffer
Q13. Explain how to implement shallow cloning and deep cloning.
Cloning is a process to create copies of objects.
Implementing Shallow cloning:
In shallow cloning, a new object is created which is an exact copy of the original object. It is a bit-wise copy of an
object. In case any field of the object is referred to other objects, only the references are copied but not the objects.
For example, an application is using a class by name Car, Person which implements Cloneable interface and another
class with public static void main(String args[]) creates object of Person like
Person per1 = new Person(.); Person per2 = (Person) per1.clone();
The following code snippet in Person in the lower level class Person implements the Shallow cloning:
public Object clone() {
//shallow copy
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
Implementing Deep cloning:
In deep cloning, a duplicate of an object is created, and it is complete. In case any fields of the object is referred to
other objects, the fields of duplicate object are copied. It copies not only primitive values of the original object, but
also copies the subobjects, all way to the bottom.
Implementing is done by the method clone() method of Object class and implemented by Cloneable interface.
The following code snippet implements deep cloning using the Person class described in the above Implementing
Shallow cloning section:
public Object clone() {
//Deep copy
Person p = new Person(name, car.getName());
return p;
}
Q14. What is an abstract class?
Answer
An abstract class defines an abstract concept which cant be instantiated. We cant create object of abstract class, it
can only be inherited. Abstract class normally represents concept with general actions associated with it
Q15. What is an interface?
Answer
An interface is a set of method definition without implementation. It is a protocol of behavior for a class.
Example
Lets create an interface for a simple mathematical calculation application. In the interface, we will keep all
required vocabulary so that we will not miss anything. Preparing an interface is one time exercise. We can
use same interface and implement it
Q16.J VM (J ava virtual machine) and J IT (J ust in compilation) - posted by Vidya Sagar
JVM
Java Virtual Machine is acting as a machine for interpreting the byte code into a machine independent native code.
The byte code is a portable binary form file, which can execute on various OS. It has a stack-based architecture. The
byte code that is generated in Windows OS can run on Linux system. The corresponding JVM (or OS dependent
JVM) converts the basic byte code instructions into executable form.
JIT Compiler
JIT compiler coverts a byte code of one operating system to the current operating systems executable code. This
instruction is given by JVM of the current system. The byte is compiled into native platform code. The execution
speed is greatly improved by this process, because the platform is directly executing the native byte code.
as required whenever we require similar functionality.
Q17. Explain how to implement polymorphism in JAVA.
Answer
Capacity of a method to do different things based on the object that it is acting upon is called as polymorphism. Poly
means multiple and morph means change which means a method that provides multiple outputs with different input is
said to follow polymorphism principle.
Types of polymorphism
Polymorphism through overloading
Polymorphism through inheritance or interfaces
Q18. How can you achieve Multiple Inheritance in Java?
The feature of multiple inheritance in java is eliminated. To inherit a class is to be extended by another class to reuse
the class elements and extend itself. A class can implement multiple interfaces, in which all the methods of interfaces
must be overridden. Where as in inheritance concept, all the methods, if needed, can be invoked directly and need
not be overridden. This is the reason why java eliminates the multiple inheritance feature. Of course, the static final
members can be reused.
Q19. What are Native methods in Java?
Answer
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.
The steps for doing that are:
First write the Java code and compile it
Then create a C header file
Create C stubs file
Write the C code
Create shared code library (or DLL)
Run application
Q20. What are class loaders?
Answer
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);
Q21. What is Reflection API in Java?
Answer
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.
The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method,
Constructor, Array, and Modifier.
Q22. Explain the difference between static and dynamic class loading.
Answer
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.
Q23. Explain Shallow and deep cloning.
Answer
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
Q25. What is the purpose of Comparator Interface?
Answer
Comparators can be used to control the order of certain data structures and collection of objets 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 datastructures of by implementing sort methods explicitly.
Q26. Explain the impact of private constructor.
Answer
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 initailized, 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
Q27. What are Static Initializers?
Answer
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.
Q28. Explain autoboxing and unboxing.
Answer
To add any primitive to a collection, you need to explicitly box (or cast) it into an appropriate wrapper class.It is
not possible to put any primitive values, such as int or char, into a collection. Collections can hold only object
references.
While taking out an object out of the collection, it needs to be unboxed. Hence the autoboxing and unboxing features
of Java 5 can be used to avoid these steps.
All that needs to be done in a code is declaring class autoboxunbox
Q29. Explain the concepts of Map and SortedMap interface.
Keys will be mapped to their values using Map object. Map allows no duplicate values. The keys in a map objects
must be unique. Java collection framework allows implementing Map interface in three classes namely, HashMap,
TreeMap and LinkedHashMap.
SortedMap is a special interface for maintaining all the elements in a sorted order. This interface extends Map
interface. It maintains all the elements in ascending order. The sorting process is performed on the map keys. It has
two additional methods than Map interface. They are firstKey() and lastKey(). Method firstKey() returns the first value
available currently in the map, where as the lastKey() returns the last value available currently in the map.
Q30. Explain the concepts of Externalizable Interface.
Serialization is the process of persistence the state of objects to the storage media for future retrieval. The classes for
persistence are to implement the Serializable interface.
The Externalizable interface has two methods namely writeExternal() and readExternal() which are to be overridden
for the purpose of object serialization process. Using Externalizable interface , the developers have the complete
control over object serialization.
The writeExternal() method is used save the contents of an object by invoking writeObject() method of OutputStream
class or the contents of primitive types by invoking the appropriate methods of DataOutput. For deserialization, the
readObject() method of InutStream class or contents of primitive types by invoking appropriate methods of DataInput
Q31. What are transient and volatile modifiers?
Volatile is a access modifier that informs to the compiler that the variable with this modifier can be changed
unexpectedly by other elements of the program. In multithreading environment, one or more threads can share the
same instance variables. Each thread can have its own copy of volatile variable. The real copy or the master copy of
the variable is updated at times.
The transient access modifier is used at the time of object serialization in order not to serialize the instance variable
value.
In the following code snippet, the content of the variable nopersist would not be saved. The content of the variable
number would be saved.
class SampleSerialize {
transient int nopersist; // will not persist
int number; // will persist


}
Q32. What are daemon threads?
The thread that provides continuous services for other threads is known as a daemon thread. For example an infinite
loop in a run() method is a daemon thread. Garbage collector in java is a daemon thread which is always keeps track
about orphan objects. When only daemon thread remains in the process the interpreter exits, because there are no
threads to serve. We can explicitly set a thread as daemon thread by using the method setDaemon().
Q33. What is JAVAdoc utility and Javadoc doclets?
Javadoc is java tool, used to parse the declaration comments and documentation comments available in a set of java
source files. Javadoc produces a group of HTML pages with information about classes, interfaces, constructors,
methods and fields.
Javadoc doclets are programs that use Doclet API and used to customize the output generated by Javadoc.
The content and format of the output to be generated by the Javadoc tool is specified by the Doclet API.
Doclet supports to generate various text-file outputs such as HTML, XML, RTF, MIF, SGML etc. The standard
doclet generates HTML format API documentation


Q34.What is the difference between StringBuffer and String class?
String class objects are immutable. They can not be changed and read only.
The StringBuffer class objects are mutable. They can be changed.
The difference between these two classes is StringBuffer is faster than String at the time of concatenating strings. To
concatenate a string to another string object, + sign is used. In this process, an intermediately string object is created
and to be stored in one string object. Where as using StringBuffer, it just joins / concatenates the new string to the
existing string.
Q35.
Explain the concepts of semaphore and monitors in Java threading.
Semaphore:
A semaphore is a construct in multithreading. It is a construct that can be used to send signals between synchronized
threads in order to avoid missing signals. It can also be used to guard critical operations such as dead locks.
Monitor:
Thread monitor supports the threads which are synchronized and mutual exclusion and co-operation. Multiple threads
will work independently on shared data without interfering each other with the help of object locks concept.
Cooperation between threads is performed with the usage of wait() and notify() methods of Object class. Cooperation
is enabling threads work together for a common goal.
Synchronization allows the threads to execute one after another without interrupting the thread that is running.
Monitor contains special memory location which allows storing a threads data and handles one at a time.
Q36. What is checked and unchecked exception?
The exceptions that are not the sub classes of RuntimeException and its sub classes are called checked exceptions.
A checked exception forces the developer to handle it. For example, IOException is a checked exception.
The exceptions that are the exceptions of RuntimeException and its sub classes are called unchecked exceptions.
The class Error and its subclasses also are unchecked exceptions. An unchecked exception does not force the
developer to handle it, either by catch block or by throws clauses. The developer may not predict these exceptions to
handle.
For example, ArrayIndexOutOfBoundsException is an unchecked exception
Q37 Explain the different types of inner classes.
A class within a class is called as inner class. Sometimes it is also known as nested class.
There are 4 types of inner classes.
1. Member Inner Class : A class that is a member ( like methods, attributes ) is called as a member inner class.
2. Local Inner Class: A class which is defined in a block( without name) is known as local inner class.
3. Static Inner Class: A class with static modifier in its definition is known as static inner class. Like other static
members, a static inner class member is to be referred by its class name.
4. Anonymous Inner Class: A class that has no name and exactly implements only one interface or extends one
abstract class is known as anonymous inner class. AWT and Swings uses inner classes to handle various events.
Q38. What is wrapper classes in Java.
Wrapper classes allow primitive data types to be accessed as objects. They are one per primitive type: Boolean,
Byte, Character, Double, Float, Integer, Long and Short. Wrapper classes make the primitive type data to act as
objects.
Q39.Why do we need wrapper classes in Java?
Dealing with primitives as objects is easier at times. Most of the objects collection store objects and not primitive
types. Many utility methods are provided by wrapper classes. To get these advantages we need to use wrapper
classes. As they are objects, they can be stored in any of the collection and pass this collection as parameters to the
methods.
Q40.Features of the Java wrapper Classes.
Wrapper classes convert numeric strings into numeric values.
The way to store primitive data in an object.
The valueOf() method is available in all wrapper classes except Character
All wrapper classes have typeValue() method. This method returns the value of the object as its primitive
type.
Q41.How to use wrapper classes in java? Explain with an example.
Java uses primitive types and are part of any object hierarchy. These values are passed to methods by values.
Character class methods:
isDigit() to determine whether the character is digit.
isLower() to determine whether the character is lower case alphabet.
is Letter() to determine whether the character is an alphabet.
Ex:
if(Character.isDigit(a[i]))
System.out.println(a[i] + "is a digit ");
if(Character.isLetter(a[i]))
System.out.println(a[i] + "is a letter ");

Byte class methods:
byteValue() returns the Byte value as byte value
Ex : byte bvalue = Byte.byteValue();
parseByte() returns byte value from a byte string
Ex: byte bvaue = Byte.parseByte(93);
Integer class methods:
intValue() returns the Integer value as int value
Ex: int bvalue = Integer.intValue();
parseInt() returns int value from a int string
Ex: int bvaue = Integer.parseInt(73);
Q42.List out the primitive types and the corresponding wrapper classes in java
Primitive Data Types Wrapper class
byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
boolean Boolean
Q43.There are some of the methods of the Wrapper class which are used to manipulate the
data. Explain them
Some of the data manipulation methods from Byte and Integer classes are:
Byte Class
static Byte decode(String nm): A string is decoded into Byte
double doubleValue(): Returns the value of Byte as double value
byte parseByte(String str): Returns byte value of the given byte string
static String toString(byte b): Returns String object representing the byte type
byte byteValue(): Returns byte value of the Byte object
Integer Class
byte byteValue(): Returns byte value of the Integer object
int intValue(): Returns int value of the Integer object
static int reverse(int ivalue): Returns the value after reversing the order of bits specified in twos complement for an int
value.
static String toBinaryString(int inum): Returns the String representation of int as an unsigned integer in base 2.
static String toHexString(int inum): Returns the String representation of int as an unsigned integer in base 16.
String toString(): Returns a string object that represents this Integers value
Q44. What is the difference between error and an exception?
Answer
Errors are abnormal conditions that should never occur. Not to be confused with the compile time errors.
A method is not required to declare in its throws clause any subclasses of Error that might be thrown during
the execution of the method but not caught.
An exception is a condition that a programmer has already predicted. These can be caught unlike errors.
They occur due to bad input, etc
Q45.. What is the difference between preemptive scheduling and time slicing?
Answer
Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The
scheduler then determines which task should execute next, based on priority and other factors.
However, in preemptive scheduling a task with a higher priority interrupts a task with a lower priority and
executes itself

Q46. What is serializable Interface?
Answer
If we want to transfer data over a network then it needs to be serialized. Objects cannot be transferred as they
are. Hence, we need to declare that a class implements serializable so that a compiler knows that the data needs
to be serialized.
Q47. How does thread synchronization occurs inside a monitor?
Answer
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 inactive in the monitor code at any time.
A monitor allows only one thread to lock an object at once.
Q48.What are the three typs of priority?
Answer
MAX_PRIORITY (10)
MIN_ PRIORITY (1)
NORM_PRIORITY (5)
Q49. What is the difference between AWT and Swing?
Answer
Classes in swing are not OS dependent. They dont create peer components, so they are light weight unlike
AWT.
They dont take the look and feel of the target platform so they have a consistent appearance
Q50.What are all the components used in Swing ?
Answer
JButton, JCheckBox, JChoice, JMenu, JTextComponent, JScrollbar, JCanvas, JLabel, etc
Q51. What is meant by Stream Tokenizer?
Answer
The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one
at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The
stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.
Q52. What is meant by getCodeBase and getDocumentBase method?
Answer
The getCodebase() method is also commonly used to establish a path to other files or folders that are in the same
location as the class being run.
URL getCodeBase()
Gets the base URL.
URL getDocumentBase()
Gets the URL of the document in which the applet is embedded.

Potrebbero piacerti anche