Download - Java Interview Questions 100
-
8/6/2019 Java Interview Questions 100
1/18
JAVA INTERVIEW QUESTIONS
1. How can you achieve Multiple Inheritance in Java?Java's interface mechanism can be used to implement multiple inheritance, with
one important differencefrom c++ way of doing MI: the inherited interfaces must be abstract. This
obviates the need to choosebetween different implementations, as with interfaces there are no
implementations.
2. Replacing Characters in a String
// Replace all occurrences of 'a' with 'o'
String newString = string.replace('a', 'o');Replacing Substrings in a Stringstatic String replace(String str,
String pattern, String replace) {
int s = 0;int e = 0;
StringBuffer result = new StringBuffer();while ((e = str.indexOf(pattern, s)) >= 0) {result.append(str.substring(s, e));
result.append(replace);
s = e+pattern.length();}result.append(str.substring(s));return result.toString();}Converting a String to Upper or Lower Case
// Convert to upper caseString upper = string.toUpperCase();
// Convert to lower caseString lower = string.toLowerCase();Converting a String to a Number
int i = Integer.parseInt("123");
long l = Long.parseLong("123");
float f = Float.parseFloat("123.4");double d = Double.parseDouble("123.4e10");Breaking a String into Words
String aString = "word1 word2 word3";StringTokenizer parser =
-
8/6/2019 Java Interview Questions 100
2/18
new StringTokenizer(aString);while (parser.hasMoreTokens()) {
processWord(parser.nextToken());
3. Searching a String
String string = "aString";// First occurrence.
int index = string.indexOf('S'); // 1// Last occurrence.
index = string.lastIndexOf('i'); // 4
// Not found.index = string.lastIndexOf('z'); // -1
4. Connecting to a Database and Strings Handling
Constructing a String
If you are constructing a string with several appends, it may be more efficient toconstruct it using a
StringBuffer and then convert it to an immutable String object.StringBuffer buf = new StringBuffer("Initial Text");
// Modifyint index = 1;
buf.insert(index, "abc");buf.append("def");
// Convert to string
String s = buf.toString();
Getting a Substring from a Stringint start = 1;int end = 4;
String substr = "aString".substring(start, end); // Str
5. What is a transient variable?
A transient variable is a variable that may not be serialized. If you don't wantsome field not to be serialized,
you can mark that field transient or static.
6. What is the difference between Serializalble and Externalizableinterface?When you use Serializable interface, your class is serialized automatically by
default. But you can overridewriteObject() and readObject()two methods to control more complex objectserailization process. When you
use Externalizable interface, you have a complete control over your class's
serialization process.
-
8/6/2019 Java Interview Questions 100
3/18
7. How many methods in the Externalizable interface?
There are two methods in the Externalizable interface. You have to implementthese two methods in order
to make your class externalizable. These two methods are readExternal() and
writeExternal().
8. How many methods in the Serializable interface?There is no method in the Serializable interface. The Serializable interface acts
as a marker, telling the
object serialization tools that your class is serializable.
9. How to make a class or a bean serializable?By implementing either the java.io.Serializable interface, or the
java.io.Externalizable interface. As long as
one class in a class's inheritance hierarchy implements Serializable orExternalizable, that class is
serializable.
10. What is the serialization?The serialization is a kind of mechanism that makes a class or a bean
persistence by having its propertiesor fields and state information saved and restored to and from storage.
11. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object.A thread only executes asynchronized method after it has acquired the lock for the method's object or
class. Synchronized
statements are similar to synchronized methods. A synchronized statement canonly be executed after a
thread has acquired the lock for the object or class referenced in thesynchronized statement.
12. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control theaccess of multiple threads toshared resources. Without synchronization, it is possible for one thread to
modify a shared object whileanother thread is in the process of using or updating that object's value. Thisoften causes dirty data and
leads to significant errors.
-
8/6/2019 Java Interview Questions 100
4/18
13. What is the purpose of finalization?The purpose of finalization is to give an unreachable object the opportunity to
perform any cleanupprocessing before the object is garbage collected.
14. What classes of exceptions may be caught by a catch clause?A catch clause can catch any exception that may be assigned to the Throwable
type. This includes theError and Exception types.
15. What is the difference between the Reader/Writer class hierarchy and
the InputStream/OutputStream
class hierarchy?The Reader/Writer class hierarchy is character-oriented, and the
InputStream/OutputStream class hierarchy
is byte-oriented.
16. What happens when a thread cannot acquire a lock on an object?If a thread attempts to execute a synchronized method or synchronized
statement and is unable to acquirean object's lock, it enters the waiting state until the lock becomes available.
17. What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type.
The overriding method may
not limit the access of the method it overrides. The overriding method may notthrow any exceptions thatmay not be thrown by the overridden method.
18. What restrictions are placed on method overloading?Two methods may not have the same name and argument list but different
return types.
19. How does multithreading take place on a computer with a single CPU?The operating system's task scheduler allocates execution time to multiple tasks.
By quickly switchingbetween executing tasks, it creates the impression that tasks executesequentially.
20. How is it possible for two String objects with identical values not to be
equal under the == operator?
The == operator compares two objects to determine if they are the same object
in memory. It is possible for
-
8/6/2019 Java Interview Questions 100
5/18
two String objects to have the same value, but located indifferent areas ofmemory.
21. How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke
a superclass constructor.
22. What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
23. What is the ResourceBundle class?The ResourceBundle class is used to store locale-specific resources that can beloaded by a program to
tailor the program's appearance to the particular locale in which it is being run.
24. What interface must an object implement before it can be written to a
stream as an object?An object must implement the Serializable or Externalizable interface before it
can be written to a stream asan object.
25. What is Serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream.
Deserialization is the process
of restoring these objects.
26. What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class hierarchy. The Class
class is used to representthe classes and interfaces that are loaded by a Java program.
27. Can you write Java code for declaration of multiple inheritance in Java
?Class C extends A implements B
{}
28. What do you mean by multiple inheritance in C++ ?
Multiple inheritance is a feature in C++ by which one class can be of different
types. Say class
teachingAssistant is inherited from two classes say teacher and Student.
-
8/6/2019 Java Interview Questions 100
6/18
29. Write the Java code to declare any constant (say gravitational constant)
and to get its value.
Class ABC
{
static final float GRAVITATIONAL_CONSTANT = 9.8;public void getConstant()
{system.out.println("Gravitational_Constant: " +
GRAVITATIONAL_CONSTANT);
}}
30. What are the disadvantages of using threads?
DeadLock.
31. Given two tables Student(SID, Name, Course) and Level(SID, level)
write the SQL statement to get the
name and SID of the student who are taking course = 3
and at freshman level.SELECT Student.name, Student.SID
FROM Student, LevelWHERE Student.SID = Level.SID
AND Level.Level = "freshman"
AND Student.Course = 3;
32. What do you mean by virtual methods?virtual methods are used to use the polymorhism feature in C++. Say class A is
inherited from class B. If we
declare say fuction f() as virtual in class B and override the same function inclass A then at runtime
appropriate method of the class will be called depending upon the type of theobject.
33. What do you mean by static methods?By using the static method there is no need creating an object of that class to use
that method. We candirectly call that method on that class. For example, say class A has staticfunction f(), then we can call f()
function as A.f(). There is no need of creating an object of class A.
-
8/6/2019 Java Interview Questions 100
7/18
34. What do mean by polymorphism, inheritance, encapsulation?Polymorhism: is a feature of OOPl that at run time depending upon the type of
object the appropriatemethod is called.
Inheritance: is a feature of OOPL that represents the "is a" relationship
between different objects(classes).Say in real life a manager is a employee. So in OOPL manger class is inherited
from the employee class.Encapsulation: is a feature of OOPL that is used to hide the information.
35. What are the advantages of OOPL?Object oriented programming languages directly represent the real life objects.
The features of OOPL asinhreitance, polymorphism, encapsulation makes it powerful.
36. How many methods do u implement if implement the SerializableInterface?
The Serializable interface is just a "marker" interface, with no methods of itsown to implement.
37. Are there any other 'marker' interfaces?
java.rmi.Remotejava.util.EventListener
38. What is the difference between instanceof and isInstance?instanceof is used to check to see if an object can be cast into a specified type
without throwing a cast class
exception. isInstance() determines if the specified object is assignment-compatible with the object
represented by this Class. This method is the dynamic equivalent of the Javalanguage instanceof operator.
The method returns true if the specified Object argument is nonnull and can becast to the reference type
represented by this Class object without raising a ClassCastException. It returnsfalse otherwise.
39. why do you create interfaces, and when MUST you use one?You would create interfaces when you have two or more functionalities talkingto each other. Doing it this
way help you in creating a protocol between the parties involved.
-
8/6/2019 Java Interview Questions 100
8/18
40. What's the difference between the == operator and the equals()
method? What test does Object.equals()
use, and why?
The == operator would be used, in an object sense, to see if the two objects
were actually the same object.
This operator looks at the actually memory address to see if it actually the sameobject. The equals()
method is used to compare the values of the object respectively. This is used ina higher level to see if the
object values are equal.
Of course the the equals() method would be overloaded in a meaningful way forwhatever object that you
were working with.
41. Discuss the differences between creating a new class, extending a class
and implementing an interface;
and when each would be appropriate.
* Creating a new class is simply creating a class with no extensions and noimplementations. The signature
is as follows
public class MyClass()
{}
* Extending a class is when you want to use the functionality of another class or
classes. The extendedclass inherits all of the functionality of the previous class. An example
of this when you create your own applet class and extend fromjava.applet.Applet. This gives you all of the
functionality of the java.applet.Applet class. The signature wouldlook like this
public class MyClass extends MyBaseClass{}
* Implementing an interface simply forces you to use the methods of theinterface implemented. This givesyou two advantages. This forces you to follow a standard(forces
you to use certain methods) and in doing so gives you a channel for
polymorphism. This isnt the only way
-
8/6/2019 Java Interview Questions 100
9/18
you can do polymorphism but this is one of the ways.public class Fish implements Animal
{}
42. Given a text file, input.txt, provide the statement required to open this
file with the appropriate I/O
stream to be able to read and process this file.
43. Name four methods every Java class will have.public String toString();
public Object clone();
public boolean equals();public int hashCode();
44. What does the "abstract" keyword mean in front of a method? A class?
Abstract keyword declares either a method or a class. If a method has a abstractkeyword in front of it, it is
called abstract method.Abstract method has no body. It has only arguments andreturn type. Abstract
methods act as placeholder methods that are implemented in the subclasses.
Abstract classes can't be
instantiated.If a class is declared as abstract,no objects of that class can becreated.If a class contains anyabstract method it must be declared as abstract.
45. Does Java have destructors?No garbage collector does the job working in the background
46. Are constructors inherited? Can a subclass call the parent's class
constructor? When?You cannot inherit a constructor. That is, you cannot create a instance of a
subclass using a constructor ofone of it's superclasses. One of the main reasons is because you probably don'twant to overide the
superclasses constructor, which would be possible if they were inherited. Bygiving the developer the abilityto override a superclasses constructor you would erode the encapsulation
abilities of the language.
-
8/6/2019 Java Interview Questions 100
10/18
47. what are checked & unchecked exceptions?
Java defines two kinds of exceptions :
Checked exceptions : Exceptions that inherit from the Exception class arechecked exceptions. Client code has to handle the checked exceptions thrown
by the API, either in a catch clause or by forwarding it outward with the throwsclause. Examples - SQLException, IOxception
Unchecked exceptions : RuntimeException also extends from Exception.However, all of the exceptions that inherit from RuntimeException get specialtreatment. There is no requirement for the client code to deal with them, and
hence they are called unchecked exceptions. Example Unchecked exceptions
are NullPointerException, OutOfMemoryError, DivideByZeroExceptiontypically, programming errors.
48. what is JAR file
JavaARchive files are a big glob of Java classes, images, audio, etc.,
compressed to make one simple, smaller file to ease Applet downloading.Normally when a browser encounters an applet, it goes and downloads all the
files, images, audio, used by the Applet separately. This can lead to slowerdownloads.
49. Does Java have "goto"?
No
50. What does the "final" keyword mean in front of a variable? A method?
A class?FINAL for a variable : value is constantFINAL for a method : cannot be overridden
FINAL for a class : cannot be derived
51.What is JNI ?
JNI is an acronym of Java Native Interface. Using JNI we can call functions
which are written in other languages from Java. Following are its advantagesand disadvantages.Advantages:* You want to use your existing library which was previously written in other
language.* You want to call Windows API function.
* For the sake of execution speed.
-
8/6/2019 Java Interview Questions 100
11/18
* You want to call API function of some server product which is in c or c++from java client.
Disadvantages:* You cant say write once run anywhere.
* Difficult to debug runtime error in native code.
* Potential security risk.* You cant call it from Applet.
52.What is serialization ?
Quite simply, object serialization provides a program the ability to read or write
a whole object to and from a raw byte stream. It allows Java objects and
primitives to be encoded into a byte stream suitable for streaming to some typeofnetworkor to a file-system, or more generally, to a transmission medium or
storage facility. A seralizable object must implement the Serilizable interface.
We use ObjectOutputStream to write this object to a stream andObjectInputStream to read it from the stream.
53.Why there are some null interface in java ? What does it mean ? Give
me some null interfaces in JAVA ?
Null interfaces act as markers..they just tell the compiler that the objects of thisclass need to be treated differently..some marker interfaces are : Serializable,Remote, Cloneable
54.Is synchronised a modifier?indentifier??what is it??
It's a modifier. Synchronized methods are methods that are used to controlaccess to an object. A thread only executes a synchronized method after it has
acquired the lock for the method's object or class. Synchronized statements aresimilar to synchronized methods. A synchronized statement can only be
executed after a thread has acquired the lock for the object or class referenced inthe synchronized statement.
55.What is similarities/difference between an Abstract class and Interface?
Differences are as follows:
Interfaces provide a form of multiple inheritance. A class can extend onlyone other class.
Interfaces are limited to public methods and constants with noimplementation. Abstract classes can have a partial implementation,protected parts, static methods, etc.
-
8/6/2019 Java Interview Questions 100
12/18
A Class may implement several interfaces. But in case of abstract class, aclass may extend only one abstract class.
Interfaces are slow as it requires extra indirection to to find correspondingmethod in in the actual class. Abstract classes are fast.
Similarities: Neither Abstract classes or Interface can be instantiated.
56.Is Iterator a Class or Interface? What is its use?
Iterator is an interface which is used to step through the elements of aCollection.
57.What is Collection API?
The Collection API is a set of classes and interfaces that support operation on
collections of objects. These classes and interfaces are more flexible, morepowerful, and more regular than the vectors, arrays, and hashtables if effectivelyreplaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and
TreeMap.Example of interfaces: Collection, Set, List and Map.
58.What is transient variable?
Transient variable can't be serialize. For example if a variable is declared astransient in a Serializable class and the class is written to an ObjectStream, thevalue of the variable can't be written to the stream instead when the class isretrieved from the ObjectStream the value of the variable becomes null.
59.What is a resource bundle?
In its simplest form, a resource bundle is represented by a text file containing
keys
and a text value for each key.
60.Why java is not a 100% oops?
Many people say this because Java uses primitive types such as int, char,
double. But then all the rest are objects. Confusing question..
-
8/6/2019 Java Interview Questions 100
13/18
61.Why java does not have multiple inheritance?
The Java design team strove to make Java:
Simple, object oriented, and familiar Robust and secure Architecture neutral and portable High performance Interpreted, threaded, and dynamic
The reasons for omitting multiple inheritance from the Java language mostlystem from the "simple, object oriented, and familiar" goal. As a simplelanguage, Java's creators wanted a language that most developers could grasp
without extensive training. To that end, they worked to make the language assimilar to C++ as possible (familiar) without carrying over C++'s unnecessarycomplexity (simple).
In the designers' opinion, multiple inheritance causes more problems and
confusion than it solves. So they cut multiple inheritance from the language(just as they cut operator overloading). The designers' extensive C++ experiencetaught them that multiple inheritance just wasn't worth the headache.
62.What is the List interface?The List interface provides support for ordered collections of objects.
63.Which characters may be used as the second character of an identifier,
but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier butthey maybe used after the first character of an identifier.
64. What state does a thread enter when it terminates its processing?When a thread terminates its processing, it enters the dead state.
65.What is the difference between preemptive scheduling and time slicing?Under preemptive scheduling, the highest priority task executes until it enters
the waitingor dead states or a higher priority task comes into existence. Under time slicing,
a taskexecutes for a predefined slice of time and then reenters the pool of ready tasks.
Thescheduler then determines which task should execute next, based on priority and
-
8/6/2019 Java Interview Questions 100
14/18
other factors.
66. What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface inits
implements clause.
67. What method is invoked to cause an object to begin executing as a
separate thread?
The start() method of the Thread class is invoked to cause an object to beginexecuting asa separate thread.
68. Name two subclasses of the TextComponent class.TextField and TextArea
69. What is the advantage of the event-delegation model over the earlier
eventinheritance
model?
The event-delegation model has two advantages over the event-inheritancemodel. First,
it enables event handling to be handled by objects other than the ones thatgenerate theevents (or their containers). This allows a clean separation between a
component's design
and its use. The other advantage of the event-delegation model is that itperforms muchbetter in applications where many events are generated. This performanceimprovement
is due to the fact that the event-delegation model does not have to repeatedly
processunhandled events, as is the case of the event-inheritance model.
70. Which containers may have a MenuBar?Frame
71.Is string a wrapper class?
String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for
each primitive type. They can be used to convert a primitive data value into anobject, and vice-versa.
-
8/6/2019 Java Interview Questions 100
15/18
72.What's new with the stop(), suspend() and resume() methods in JDK
1.2?The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
73. Is null a keyword?The null value is not a keyword.
74.Can an object's finalize() method be invoked while it is reachable?
An object's finalize() method cannot be invoked by the garbage collector while
the object
is still reachable. However, an object's finalize() method may be invoked by
other
objects.
75.What is the immediate superclass of the Applet class?Panel
76.. How are Java source code files named?
A Java source code file takes the name of a public class or interface that isdefined within
the file. A source code file may contain at most one public class or interface. If
a public
class or interface is defined within a source code file, then the source code file
must takethe name of the public class or interface. If no public class or interface is
defined within asource code file, then the file must take on a name that is different than its
classes andinterfaces. Source code files use the .java extension.
77. What is an abstract method?An abstract method is a method whose implementation is deferred to a subclass.
78.What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficientway for
threads to wait for a shared resource. When a thread executes an object's wait()
method, itenters the waiting state. It only enters the ready state after another thread
-
8/6/2019 Java Interview Questions 100
16/18
invokes theobject's notify() or notifyAll() methods..
79. How are commas used in the intialization and iteration parts of a for
statement?Commas are used to separate multiple statements within the initialization anditerationparts of a for statement.
80.. What is the relationship between the Canvas class and the Graphics
class?A Canvas object provides access to a Graphics object via its paint() method.
81.What value does readLine() return when it has reached the end of a file?
The readLine() method returns null when it has reached the end of a file.
82.Name three Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
83What is the difference between preemptive scheduling and time slicing?Under preemptive scheduling, the highest priority task executes until it enters
the waitingor dead states or a higher priority task comes into existence. Under time slicing,
a taskexecutes 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 andother factors.
84.What method is used to specify a container's layout?The setLayout() method is used to specify a container's layout
85.Which containers use a FlowLayout as their default layout?The Panel and Applet classes use the FlowLayout as their default layout
86.What is the preferred size of a component?
The preferred size of a component is the minimum component size that will
allow thecomponent to display normally.
-
8/6/2019 Java Interview Questions 100
17/18
87. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations oncollections of objects
.88.. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the typeallowed by
the operation.
89.What is synchronization and why is it important?With respect to multithreading, synchronization is the capability to control the
access ofmultiple threads to shared resources. Without synchronization, it is possible for
onethread to modify a shared object while another thread is in the process of usingorupdating that object's value. This often leads to significant errors.
90. What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits
that havebeen shifted out.
91. Which method of the Component class is used to set the position and
size of a component?setBounds()
92.What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When atask invokes
its sleep() method, it returns to the waiting state.
93. Which java.util classes and interfaces support event handling?The EventObject class and the EventListener interface support event processing.
94. How many bits are used to represent Unicode, ASCII, UTF-16, and
UTF-8
-
8/6/2019 Java Interview Questions 100
18/18
characters?Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII
character set usesonly 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using
8, 16,
and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
95.. What modifiers may be used with an inner class that is a member of an
outer class?A (non-local) inner class may be declared as public, protected, private, static,final, orabstract.
96.What is the Vector class?
The Vector class provides the capability to implement a growable array ofobjects
97.Is sizeof a keyword?The sizeof operator is not a keyword
98. Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Classobject..
99.What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control theaccess of
multiple threads to shared resources. Without synchronization, it is possible forone
thread to modify a shared object while another thread is in the process of usingorupdating that object's value. This often leads to significant errors.
100.What is a compilation unit?
The smallest unit of source code that can be compiled, i.e. a .java file.