Core java interview questions
1. How could Java classes direct program
messages to the system console, but error messages, say to a file?
Ans. By default, both System
console and err point at the system console.
The class System has a variable
out that represents the standard output.
The variable err that represents
the standard error device.
Stream st = new Stream (new
FileOutputStream ("withoutbook_com.txt"));
System.setErr(st);
System.setout (st);
2. What are the differences between an
interface and an abstract class?
Ans. An abstract class may
contain code in method bodies, which is not allowed in an interface. With
abstract classes, you have to inherit your class from it and Java does not
allow multiple inheritance. On the other hand, you can implement multiple
interfaces in your class.
Abstract class are used only when
there is a "IS-A" type of relationship between the classes.
Interfaces can be implemented by classes that are not related to one another
and there is "HAS-A" relationship.
You cannot extend more than one
abstract class. You can implement more than one interface.
Abstract class can implemented some
methods also. Interfaces cannot implement methods.
With abstract classes, you are
grabbing away each class’s individuality. With Interfaces, you are merely
extending each class’s functionality.
3. Why would you use a synchronized block vs.
synchronized method?
Ans. Synchronized blocks place
locks for shorter periods than synchronized methods.
If you go for synchronized block
it will lock a specific object.
If you go for synchronized method
it will lock all the objects.
In other way Both the
synchronized method and block are used to acquires the lock for an object. But
the context may vary. Suppose if we want to invoke a critical method which is
in a class whose access is not available then synchronized block is used.
Otherwise synchronized method can be used.
Synchronized methods are used
when we are sure all instance will work on the same set of data through the
same function Synchronized block is used when we use code which we cannot
modify ourselves like third party jars etc.
For a detail clarification see
the below code for example:
//Synchronized block
class A{
public void method1() {
//...
}
}
class B{
public static void main(String
s[]){
A objecta=new A();
A objectb=new A();
synchronized(objecta){
objecta.method1();
}
objectb.method1(); //not
synchronized
}
}
//synchronized method
class A{
public synchronized void method1()
{ ...}
}
class B{
public static void main(String
s[]){
A objecta=new A();
A objectb =new A();
objecta.method1();
objectb.method2();
}
}
4. Explain the usage of the keyword transient?
Ans. This keyword indicates that
the value of this member variable does not have to be serialized with the
object. When the class will be de-serialized, this variable will be initialized
with a default value of its data type (i.e. zero for integers).
For example:
class T {
transient int a; // will not
persist
int b; // will persist
}
5. How can you force garbage collection?
Ans. You can't force GC, but
could request it by calling System.gc(). JVM does not guarantee that GC will be
started immediately.
The following code of program
will help you in forcing the garbage collection. First of all we have created
an object for the garbage collector to perform some operation. Then we have
used the System.gc(); method to force the garbage collection on that object.
Then we have used the System.currentTimeMillis(); method to show the time take
by the garbage collector.
import java.util.Vector;
public class GarbageCollector{
public static void main(String[]
args) {
int SIZE = 200;
StringBuffer s;
for (int i = 0; i < SIZE; i++)
{
}
System.out.println("Garbage
Collection started explicitly.");
long time =
System.currentTimeMillis();
System.gc();
System.out.println("It took
" +(System.currentTimeMillis()-time) + " ms");
}
}
6. How do you know if an explicit object
casting is needed?
Ans. If you assign a superclass
object to a variable of a subclass's data type, you need to do explicit
casting. For example:
Object a; Customer b; b =
(Customer) a;
When you assign a subclass to a
variable having a superclass type, the casting is performed automatically.
7. What are the differences between the methods
sleep() and wait()?
Ans. The code sleep(1000); puts
thread aside for exactly one second. The code wait(1000), causes a wait of up
to one second. A thread could stop waiting earlier if it receives the notify()
or notifyAll() call.
The method wait() is defined in
the class Object and the method sleep() is defined in the class Thread.
8. Can you write a Java class that could be
used both as an applet as well as an application?
Ans. Yes. Add a main() method to
the applet.
import java.awt.*;
import java.applet.*;
import java.util.*;
public class AppApp extends
Applet {
public void init()
{
add(new TextArea("Welcome to
withoutbook.com"));
String ar[]=new String[2];
ar[0]="Welcome to
withoutbook.com";
main(ar);
}
public void main(String args[])
{
System.out.println(args[0]);
}
}
9. What is the difference between constructors
and other methods in core java?
Ans. Constructor will be
automatically invoked when an object is created whereas method has to be called
explicitly.
Constructor needs to have the
same name as that of the class whereas functions need not be the same.
There is no return type given in
a constructor signature (header). The value is this object itself so there is
no need to indicate a return value.
There is no return statement in
the body of the constructor.
The first line of a constructor
must either be a call on another constructor in the same class (using this), or
a call on the superclass constructor (using super). If the first line is
neither of these, the compiler automatically inserts a call to the
parameterless super class constructor.
10. Can you call one constructor from another
if a class has multiple constructors?
Ans. Yes. Use this( ) syntax.
Sometimes a method will need to
refer to the object that invoked it. To allow this, Java defines the this
keyword. this can be used inside any method to refer to the current object.
That is, this is always a reference to the object on which the method was
invoked. You can use this anywhere a reference to an object of the current
class type is permitted.
To better understand what this
refers to, consider the following version of Box( ):
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
11. Explain the usage of Java packages?
Ans. This is a way to organize
files when a project consists of multiple modules. It also helps resolve naming
conflicts when different packages have classes with the same names. Packages
access level also allows you to protect data from being used by the
non-authorized classes.
e.g.
java.lang— basic language
functionality and fundamental types
java.util — collection data structure classes
java.io— file operations
java.math— multiprecision
arithmetics
java.nio — the New I/O framework for Java
java.net — networking operations, sockets, DNS lookups
java.security— key generation,
encryption and decryption
java.sql — Java Database Connectivity (JDBC) to access databases
java.awt— basic hierarchy of
packages for native GUI components
javax.swing— hierarchy of
packages for platform-independent rich GUI components
java.applet— classes for creating
an applet
12. if a class is located in a package, what do
you need to change in the OS environment to be able to use it?
Ans. You need to add a directory
or a jar file that contains the package directories to the CLASSPATH
environment variable. Let’s say a class Employee belongs to a package
com.xyz.hr; and is located in the file c:/dev/com.xyz.hr.Employee.java. In this
case, you'd need to add c:/dev to the variable CLASSPATH. If this class
contains the method main(), you could test it from a command prompt window as
follows:
c:\>java com.xyz.hr.Employee
13. What's the difference between J2SDK 1.5 and
J2SDK 5.0?
Ans. There's no difference, Sun
Microsystems just re-branded this version.
14. What would you use to compare two String
variables - the operator == or the method equals()?
Ans. I would use the method
equals() to compare the values of the Strings and the == to check if two
variables point at the same instance of a String object.
15. Does it matter in what order catch
statements for FileNotFoundException and IOExceptipon are written?
Ans. Yes, it does. The
FileNoFoundException is inherited from the IOException. Exception's subclasses
have to be caught first.
16. Can an inner class declared inside of a
method access local variables of this method?
Ans. It is possible if these
variables are final.
17. What can go wrong if you replace &&
with & in the following code:
Ans. String a=null;
if (a!=null &&
a.length()>10){
...
}A single ampersand here would
lead to a NullPointerException.
18. What is the main difference between a
Vector and an ArrayList?
Ans. Sometimes Vector is better;
sometimes ArrayList is better; sometimes you don‘t want to use either. I hope
you weren‘t looking for an easy answer because the answer depends upon what you
are doing. There are four factors to consider: API
Synchronization
Data growth
Usage patterns
API: In The Java Programming Language Ken Arnold, James Gosling,
and David Holmes describe the Vector as an analog to the ArrayList. So, from an
API perspective, the two classes are very similar. However, there are still
some major differences between the two classes.
Synchronization: Vectors are synchronized. Any method that touches
the Vector‘s contents is thread safe. ArrayList, on the other hand, is
unsynchronized, making them, therefore, not thread safe. With that difference
in mind, using synchronization will incur a performance hit. So if you don‘t
need a thread-safe collection, use the ArrayList. Why pay the price of
synchronization unnecessarily?
Data growth: Internally, both the ArrayList and Vector hold onto
their contents using an Array. You need to keep this fact in mind while using
either in your programs. When you insert an element into an ArrayList or a
Vector, the object will need to expand its internal array if it runs out of
room. A Vector defaults to doubling the size of its array, while the ArrayList
increases its array size by 50 percent. Depending on how you use these classes,
you could end up taking a large performance hit while adding new elements. It‘s
always best to set the object‘s initial capacity to the largest capacity that
your program will need. By carefully setting the capacity, you can avoid paying
the penalty needed to resize the internal array later. If you don‘t know how
much data you‘ll have, but you do know the rate at which it grows, Vector does
possess a slight advantage since you can set the increment value.
Usage patterns: Both the ArrayList and Vector are good for
retrieving elements from a specific position in the container or for adding and
removing elements from the end of the container. All of these operations can be
performed in constant time -- O(1). However, adding and removing elements from
any other position proves more expensive -- linear to be exact: O(n-i), where n
is the number of elements and i is the index of the element added or removed.
These operations are more expensive because you have to shift all elements at
index i and higher over by one element. So what does this all mean? It means
that if you want to index elements or add and remove elements at the end of the
array, use either a Vector or an ArrayList. If you want to do anything else to
the contents, go find yourself another container class. For example, the
LinkedList can add or remove an element at any position in constant time --
O(1). However, indexing an element is a bit slower -- O(i) where i is the index
of the element. Traversing an ArrayList is also easier since you can simply use
an index instead of having to create an iterator. The LinkedList also creates
an internal object for each element inserted. So you have to be aware of the
extra garbage being created.
19. How can a subclass call a method or a
constructor defined in a superclass?
Ans. Use the following syntax:
super.myMethod(); To call a constructor of the superclass, just write super();
in the first line of the subclass‘s constructor.
20. What's the difference between a queue and a
stack?
Ans. Stacks works by
last-in-first-out rule (LIFO), while queues use the FIFO rule.
You can think of a queue like a
line at the bank. The first person to get there will get to the teller first.
If a bunch of people come while all the tellers are busy, they stand in line in
the order in which they arrived. That is to say, new people (items) are added
to the end of the line and the first person in line is the only one who is
called to a teller. In real life this is known as "first come, first
served." In programming terms it's known as first-in-first-out, or FIFO.
You can think of a stack like a
deck of cards. You can put down cards into a pile on your table one at a time,
but if you want to draw cards, you can only draw them from the top of the deck
one at a time. Unlike a queue, the first card to be put down is the last card
to be used. This is known as first-in-last-out, or FILO (also called LIFO for
last-in-first-out).
A queue is a first-in-first-out
data structure. When you add an element to the queue you are adding it to the
end, and when you remove an element you are removing it from the beginning.
A stack is a first-in-last-out
data structure. When you add an element to a stack you are adding it to the
end, and when you remove an element you are removing it from the end.
21. You can create an abstract class that
contains only abstract methods. On the other hand, you can create an interface
that declares the same methods. So can you use abstract classes instead of
interfaces?
Ans. Sometimes. But your class
may be a descendent of another class and in this case the interface is your
only option.
22. What comes to mind when you hear about a
young generation in Java?
Ans. Garbage collection.
In the J2SE platform version
1.4.1 two new garbage collectors were introduced to make a total of four
garbage collectors from which to choose.
Beginning with the J2SE platform,
version 1.2, the virtual machine incorporated a number of different garbage
collection algorithms that are combined using generational collection. While
naive garbage collection examines every live object in the heap, generational
collection exploits several empirically observed properties of most
applications to avoid extra work.
The default collector in HotSpot
has two generations: the young generation and the tenured generation. Most
allocations are done in the young generation. The young generation is optimized
for objects that have a short lifetime relative to the interval between
collections. Objects that survive several collections in the young generation
are moved to the tenured generation. The young generation is typically smaller
and is collected more often. The tenured generation is typically larger and
collected less often.
The young generation collector is
a copying collector. The young generation is divided into 3 spaces: Eden-space,
to-space, and from-space. Allocations are done from Eden-space and from-space.
When those are full a young generation is collection is done. The expectation
is that most of the objects are garbage and any surviving objects can be copied
to to-space. If there are more surviving objects than can fit into to-space,
the remaining objects are copied into the tenured generation. There is an
option to collect the young generation in parallel.
The tenured generation is
collected with a mark-sweep-compact collection. There is an option to collect
the tenured generation concurrently.
23. What comes to mind when someone mentions a
shallow copy and deep copy in Java?
Ans. Object cloning.
Java provides a mechanism for
creating copies of objects called cloning. There are two ways to make a copy of
an object called shallow copy and deep copy.
Shallow copy is a bit-wise copy
of an object. A new object is created that has an exact copy of the values in
the original object. If any of the fields of the object are references to other
objects, just the references are copied. Thus, if the object you are copying
contains references to yet other objects, a shallow copy refers to the same
subobjects.
Deep copy is a complete duplicate
copy of an object. If an object has references to other objects, complete new
copies of those objects are also made. A deep copy generates a copy not only of
the primitive values of the original object, but copies of all subobjects as
well, all the way to the bottom. If you need a true, complete copy of the
original object, then you will need to implement a full deep copy for the
object.
Java supports shallow and deep
copy with the Cloneable interface to create copies of objects. To make a clone
of a Java object, you declare that an object implements Cloneable, and then
provide an override of the clone method of the standard Java Object base class.
Implementing Cloneable tells the java compiler that your object is Cloneable.
The cloning is actually done by the clone method.
24. If you're overriding the method equals() of
an object, which other method you might also consider?
Ans. hashCode().
26. How would you make a copy of an entire Java
object with its state?
Ans. Have this class implement
Cloneable interface and call its method clone().
27. How can you minimize the need of garbage
collection and make the memory use more effective?
Ans. Use object pooling and weak
object references.
Pooling basically means utilizing
the resources efficiently, by limiting access of the objects to only the period
the client requires it.
Increasing utilization through
pooling usually increases system performance.
Object pooling is a way to manage
access to a finite set of objects among competing clients. in other words,
object pooling is nothing but
sharing of objects between different clients.
Since object pooling allows
sharing of objects, the other clients/processes need to re-instantiate the
object(which decreases the load time), instead they can use an existing object.
After the usage , the objects are returned to the pool.
28. There are two classes: A and B. The class B
need to inform a class A when some important event has happened. What Java
technique would you use to implement it?
Ans. If these classes are threads
I'd consider notify() or notifyAll(). For regular classes you can use the
Observer interface.
29. Describe what happens when an object is
created in Java?
Ans. Several things happen in a
particular order to ensure the object is constructed properly:
1. Memory is allocated from heap
to hold all instance variables and implementation-specific data of the object
and its superclasses. Implementation-specific data includes pointers to class
and method data.
2. The instance variables of the
objects are initialized to their default values.
3. The constructor for the most
derived class is invoked. The first thing a constructor does is call the
constructor for its uppercase. This process continues until the constructor for
java.lang.Object is called, as java.lang.Object is the base class for all
objects in java.
4. Before the body of the
constructor is executed, all instance variable initializers and initialization
blocks are executed. Then the body of the constructor is executed. Thus, the
constructor for the base class completes first and constructor for the most derived
class completes last.
30. In Java, you can create a String object as
below : String str = "abc"; & String str = new
String("abc"); Why can’t a
button object be created as : Button bt = "abc"? Why is it compulsory
to create a button object as: Button bt = new Button("abc"); Why this
is not compulsory in String's case?
Ans. Button bt1= "abc";
It is because "abc" is a literal string (something slightly different
than a String object, by-the-way) and bt1 is a Button object. That simple. The
only object in Java that can be assigned a literal String is java.lang.String.
Important to note that you are NOT calling a java.lang.String constuctor when
you type String s = "abc";
For example String x =
"abc"; String y = "abc"; refer to the same object. While
String x1 = new String("abc");
String x2 = new
String("abc"); refer to two different objects.
31. What is the advantage of OOP?
Ans. You will get varying answers
to this question depending on whom you ask. Major advantages of OOP are:
1. Simplicity: software objects model real world objects, so the
complexity is reduced and the program structure is very clear;
2. Modularity: each object forms a separate entity whose internal
workings are decoupled from other parts of the system;
3. Modifiability: it is easy to make minor changes in the data
representation or the procedures in an OO program. Changes inside a class do
not affect any other part of a program, since the only public interface that
the external world has to a class is through the use of methods;
4. Extensibility: adding new features or responding to changing
operating environments can be solved by introducing a few new objects and
modifying some existing ones;
5. Maintainability: objects can be maintained separately, making
locating and fixing problems easier;
6. Re-usability: objects can be reused in different programs
32. What are the main differences between Java
and C++?
Ans. Everything is an object in
Java( Single root hierarchy as everything gets derived from java.lang.Object).
Java does not have all the complicated aspects of C++ ( For ex: Pointers,
templates, unions, operator overloading, structures etc..) The Java language promoters initially said
"No pointers!", but when many programmers questioned how you can work
without pointers, the promoters began saying "Restricted pointers."
You can make up your mind whether it's really a pointer or not. In any event,
there's no pointer arithmetic.
There are no destructors in Java.
(automatic garbage collection),
Java does not support conditional
compile (#ifdef/#ifndef type).
Thread support is built into java
but not in C++.
Java does not support default
arguments.
There's no scope resolution
operator :: in Java. Java uses the dot for everything, but can get away with it
since you can define elements only within a class. Even the method definitions
must always occur within a class, so there is no need for scope resolution
there either.
There's no "goto"
statement in Java.
Java doesn't provide multiple
inheritance (MI), at least not in the same sense that C++ does.
Exception handling in Java is
different because there are no destructors.
Java has method overloading, but
no operator overloading.
The String class does use the +
and += operators to concatenate strings and String expressions use automatic
type conversion, but that's a special built-in case.
Java is interpreted for the most
part and hence platform independent.
33. What are interfaces?
Ans. Interfaces provide more
sophisticated ways to organize and control the objects in your system.
The interface keyword takes the
abstract concept one step further. You could think of it as a 'pure' abstract
class. It allows the creator to establish the form for a class: method names,
argument lists, and return types, but no method bodies. An interface can also
contain fields, but The interface keyword takes the abstract concept one step
further. You could think of it as a 'pure'?? abstract class. It allows the
creator to establish the form for a class: method names, argument lists, and
return types, but no method bodies. An interface can also contain fields, but
an interface says: 'This is what all classes that implement this particular
interface will look like.'?? Thus, any code that uses a particular interface
knows what methods might be called for that interface, and that'??s all. So the
interface is used to establish a 'protocol'?? between classes. (Some
object-oriented programming languages have a keyword called protocol to do the
same thing.) Typical example from
"Thinking in Java": import java.util.*;
interface Instrument {
int i = 5; // static & final
// Cannot have method
definitions:
void play(); // Automatically
public
String what();
void adjust();
}
class Wind implements Instrument
{
public void play() {
System.out.println("Wind.play()");
public String what() { return
"Wind"; }
public void adjust() {}
}
34. How can you achieve Multiple Inheritance in
Java?
Ans. interface CanFight {
void fight();
}
interface CanSwim {
void swim();
}
interface CanFly {
void fly();
}
class ActionCharacter {
public void fight() {}
}
class Hero extends
ActionCharacter implements CanFight, CanSwim, CanFly {
public void swim() {}
public void fly() {}
}
You can even achieve a form of
multiple inheritance where you can use the *functionality* of classes rather
than just the interface:
interface A {
void methodA();
}
class AImpl implements A {
void methodA() { //do stuff }
}
interface B {
void methodB();
}
class BImpl implements B {
void methodB() { //do stuff }
}
class Multiple implements A, B {
private A a = new A();
private B b = new B();
void methodA() { a.methodA(); }
void methodB() { b.methodB(); }
}
This completely solves the
traditional problems of multiple inheritance in C++ where name clashes occur
between multiple base classes. The coder of the derived class will have to
explicitly resolve any clashes. Don't you hate people who point out minor
typos? Everything in the previous example is correct, except you need to
instantiate an AImpl and BImpl. So class Multiple would look like this:
class Multiple implements A, B {
private A a = new AImpl();
private B b = new BImpl();
void methodA() { a.methodA(); }
void methodB() { b.methodB(); }
}
35. What is the difference between StringBuffer
and String class?
Ans. A string buffer implements a
mutable sequence of characters. A string buffer is like a String, but can be
modified. At any point in time it contains some particular sequence of
characters, but the length and content of the sequence can be changed through
certain method calls.
The String class represents
character strings. All string literals in Java programs, such as
"abc" are constant and implemented as instances of this class; their
values cannot be changed after they are created. Strings in Java are known to
be immutable.
Explanation: What it means is that every time you need to make a
change to a String variable, behind the scene, a "new" String is
actually being created by the JVM. For an example: if you change your String
variable 2 times, then you end up with 3 Strings: one current and 2 that are
ready for garbage collection. The garbage collection cycle is quite
unpredictable and these additional unwanted Strings will take up memory until
that cycle occurs. For better performance, use StringBuffers for string-type
data that will be reused or changed frequently. There is more overhead per
class than using String, but you will end up with less overall classes and
consequently consume less memory. Describe, in general, how java's garbage
collector works? The Java runtime environment deletes objects when it
determines that they are no longer being used. This process is known as garbage
collection. The Java runtime environment supports a garbage collector that
periodically frees the memory used by objects that are no longer needed. The
Java garbage collector is a mark-sweep garbage collector that scans Java's dynamic
memory areas for objects, marking those that are referenced. After all possible
paths to objects are investigated, those objects that are not marked (i.e. are
not referenced) are known to be garbage and are collected. (A more complete
description of our garbage collection algorithm might be "A compacting,
mark-sweep collector with some conservative scanning".) The garbage
collector runs synchronously when the system runs out of memory, or in response
to a request from a Java program. Your Java program can ask the garbage
collector to run at any time by calling System.gc(). The garbage collector
requires about 20 milliseconds to complete its task so, your program should
only run the garbage collector when there will be no performance impact and the
program anticipates an idle period long enough for the garbage collector to
finish its job. Note: Asking the garbage collection to run does not guarantee
that your objects will be garbage collected. The Java garbage collector runs
asynchronously when the system is idle on systems that allow the Java runtime
to note when a thread has begun and to interrupt another thread (such as
Windows 95). As soon as another thread becomes active, the garbage collector is
asked to get to a consistent state and then terminate.
36. What's the difference between == and equals
method?
Ans. equals checks for the
content of the string objects while == checks for the fact that the two String
objects point to same memory location ie they are same references.
37. What are abstract classes, abstract
methods?
Ans. simply speaking a class or a
method qualified with "abstract" keyword is an abstract class or
abstract method. You create an abstract class when you want to manipulate a set
of classes through a common interface. All derived-class methods that match the
signature of the base-class declaration will be called using the dynamic
binding mechanism. If you have an abstract class, objects of that class almost
always have no meaning. That is, abstract class is meant to express only the
interface and sometimes some default method implementations, and not a
particular implementation, so creating an abstract class object makes no sense
and are not allowed ( compile will give you an error message if you try to
create one). An abstract method is an incomplete method. It has only a
declaration and no method body. Here is the syntax for an abstract method
declaration: abstract void f(); If a class contains one or more abstract
methods, the class must be qualified an abstract. (Otherwise, the compiler
gives you an error message.). It's possible to create a class as abstract
without including any abstract methods. This is useful when you've got a class
in which it doesn't make sense to have any abstract methods, and yet you want
to prevent any instances of that class. Abstract classes and methods are
created because they make the abstractness of a class explicit, and tell both
the user and the compiler how it was intended to be used.
For example:
abstract class Instrument {
int i; // storage allocated for
each
public abstract void play();
public String what() {
return "Instrument";
public abstract void adjust();
}
class Wind extends Instrument {
public void play() {
System.out.println("Wind.play()");
}
public String what() { return
"Wind"; }
public void adjust() {}
Abstract classes are classes for
which there can be no instances at run time. i.e. the implementation of the
abstract classes are not complete. Abstract methods are methods which have no definition.
i.e. abstract methods have to be implemented in one of the sub classes or else
that class will also become Abstract.
38. Java says "write once, run
anywhere". What are some ways this isn't quite true?
Ans. As long as all implementations
of java are certified by sun as 100% pure java this promise of "Write
once, Run everywhere" will hold true. But as soon as various java core implementations
start digressing from each other, this won't be true anymore. A recent example
of a questionable business tactic is the surreptitious behavior and interface
modification of some of Java's core classes in their own implementation of
Java. Programmers who do not recognize these undocumented changes can build
their applications expecting them to run anywhere that Java can be found, only
to discover that their code works only on Microsoft's own Virtual Machine,
which is only available on Microsoft's own operating systems.
39. What is the difference between a Vector and
an Array. Discuss the advantages and disadvantages of both?
Ans. Vector can contain objects
of different types whereas array can contain objects only of a single type.
- Vector can expand at run-time,
while array length is fixed.
- Vector methods are synchronized
while Array methods are not.
40. What does the keyword
"synchronize" mean in java. When do you use it? What are the
disadvantages of synchronization?
Ans. Synchronize is used when you
want to make your methods thread safe. The disadvantage of synchronize is it
will end up in slowing down the program. Also if not handled properly it will
end up in dead lock.
41. What are java beans?
Ans. JavaBeans is a portable,
platform-independent component model written in the Java programming language,
developed in collaboration with industry leaders. It enables developers to
write reusable components once and run them anywhere ' benefiting from the
platform-independent power of Java technology. JavaBeans acts as a Bridge
between proprietary component models and provides a seamless and powerful means
for developers to build components that run in ActiveX container applications.
JavaBeans are usual Java classes which adhere to certain coding conventions:
1. Implements
java.io.Serializable interface
2. Provides no argument
constructor
3. Provides getter and setter
methods for accessing it'??s properties.
42. What gives java it's "write once and
run anywhere" nature?
Ans. Java is compiled to be a
byte code which is the intermediate language between source code and machine
code. This byte code is not platform specific and hence can be fed to any
platform. After being fed to the JVM, which is specific to a particular
operating system, the code platform specific machine code is generated thus
making java platform independent.
43. What are native methods? How do you use
them?
Ans. Native methods are methods
written in other languages like C, C++, or even assembly language. You can call
native methods from Java using JNI. Native methods are used when the
implementation of a particular method is present in language other than Java
say C, C++. To use the native methods in java we use the keyword native
public native method_a(). This
native keyword is signal to the java compiler that the implementation of this
method is in a language other than java. Native methods are used when we
realize that it would take up a lot of rework to write that piece of already
existing code in other language to Java.
44. Access specifiers: "public",
"protected", "private", nothing?
Ans. public : Public class is visible in other packages, field is
visible everywhere (class must be public too)
private : Private variables or methods may be used only by an
instance of the same class that declares the variable or method, A private
feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and
also available to all subclasses of the class that owns the protected
feature.This access is provided even to subclasses that reside in a different
package from the class that owns the protected feature.
default : What you get by default ie, without any access modifier
(ie, public private or protected).It means that it is visible to all within a
particular package.
45. What does the "final" keyword
mean in front of a variable? A method? A class?
Ans. FINAL for a variable : value
is constant
FINAL for a method : cannot be
overridden
FINAL for a class : cannot be
derived
A final variable cannot be
reassigned,
but it is not constant. For
instance,
final StringBuffer x = new
StringBuffer()
x.append("hello");
is valid. X cannot have a new
value in it,but nothing stops operations on the object
that it refers, including
destructive operations. Also, a final method cannot be overridden
or hidden by new access
specifications.This means that the compiler can choose
to in-line the invocation of such
a method.(I don't know if any compiler actually does
this, but it's true in theory.)
The best example of a final class is
String, which defines a class
that cannot be derived.
46. Does Java have "goto"?
Ans. No.
47. What synchronization constructs does Java
provide? How do they work?
Ans. The two common features that
are used are:
1. Synchronized keyword - Used to synchronize a method or a block
of code. When you synchronize a method, you are in effect synchronizing the
code within the method using the monitor of the current object for the lock.
The following have the same
effect.
synchronized void foo() {
}
and
void foo() {
synchronized(this) {
}
If you synchronize a static
method, then you are synchronizing across all objects of the same class, i.e.
the monitor you are using for the lock is one per class, not one per object.
2. wait/notify: wait() needs to be called from within a
synchronized block. It will first release the lock acquired from the
synchronization and then wait for a signal. In Posix C, this part is equivalent
to the pthread_cond_wait method, which waits for an OS signal to continue. When
somebody calls notify() on the object, this will signal the code which has been
waiting, and the code will continue from that point. If there are several
sections of code that are in the wait state, you can call notifyAll() which
will notify all threads that are waiting on the monitor for the current object.
Remember that both wait() and notify() have to be called from blocks of code
that are synchronized on the monitor for the current object.
48. Does Java have multiple inheritance?
Ans. Java does not support
multiple inheritence directly but it does thru the concept of interfaces.
We can make a class implement a
number of interfaces if we want to achieve multiple inheritence type of
functionality of C++.
49. How does exception handling work in Java?
Ans. 1.It separates the
working/functional code from the error-handling code by way of try-catch
clauses.
2.It allows a clean path for
error propagation. If the called method encounters a situation it can't manage,
it can throw an exception and let the calling method deal with it.
3.By enlisting the compiler to
ensure that "exceptional" situations are anticipated and accounted
for, it enforces powerful coding.
4.Exceptions are of two types:
Compiler-enforced exceptions, or checked exceptions. Runtime exceptions, or
unchecked exceptions. Compiler-enforced (checked) exceptions are instances of
the Exception class or one of its subclasses '?? excluding the RuntimeException
branch. The compiler expects all checked exceptions to be appropriately
handled. Checked exceptions must be declared in the throws clause of the method
throwing them '?? assuming, of course, they're not being caught within that
same method. The calling method must take care of these exceptions by either
catching or declaring them in its throws clause. Thus, making an exception
checked forces the us to pay heed to the possibility of it being thrown. An
example of a checked exception is java.io.IOException. As the name suggests, it
throws whenever an input/output operation is abnormally terminated.
50. Does Java have destructors?
Ans. Garbage collector does the
job working in the background
Java does not have destructors;
but it has finalizers that does a similar job.
the syntax is:
public void finalize(){
} if an object has a finalizer, the
method is invoked before the system garbage collects the object.
51. What does the "abstract" keyword
mean in front of a method? A class?
Ans. Abstract keyword declares
either a method or a class.
If a method has a abstract
keyword in front of it,it is called abstract method.Abstract method hs no
body.It has only arguments and return 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 be
created.If a class contains any abstract method it must be declared as abstract
Is it helpful? Yes No
Add Comment View Comments
Core Java Job interview questions
and answers Interview Question Databases Examination Email Spanish Language
52. Do I need to use synchronized on
setValue(int)?
Ans. It depends whether the
method affects method local variables, class static or instance variables. If
only method local variables are changed, the value is said to be confined by
the method and is not prone to threading issues.
53. What is the
SwingUtilities.invokeLater(Runnable) method for?
Ans. The static utility method
invokeLater(Runnable) is intended to execute a new runnable thread from a Swing
application without disturbing the normal sequence of event dispatching from
the Graphical User Interface (GUI). The method places the runnable object in
the queue of Abstract Windowing Toolkit (AWT) events that are due to be
processed and returns immediately. The runnable object run() method is only
called when it reaches the front of the queue. The deferred effect of the
invokeLater (Runnable) method ensures that any necessary updates to the user
interface can occur immediately, and the runnable work will begin as soon as
those high priority events are dealt with. The invoke later method might be
used to start work in response to a button click that also requires a
significant change to the user interface, perhaps to restrict other activities,
while the runnable thread executes.
54. What is the volatile modifier for?
Ans. The volatile modifier is
used to identify variables whose values should not be optimized by the Java
Virtual Machine, by caching the value for example. The volatile modifier is
typically used for variables that may be accessed or modified by numerous
independent threads and signifies that the value may change without
synchronization.
55. Which class is the wait() method defined
in?
Ans. The wait() method is defined
in the Object class, which is the ultimate superclass of all others. So the
Thread class and any Runnable implementation inherit this method from Object.
The wait() method is normally called on an object in a multi-threaded program
to allow other threads to run. The method should should only be called by a
thread that has ownership of the object monitor, which usually means it is in a
synchronized method or statement block.
56. Which class is the wait() method defined
in? I get incompatible return type for my thread getState( ) method!
Ans. It sounds like your
application was built for a Java software development kit before Java 1.5. The
Java API Thread class method getState() was introduced in version 1.5. Your
thread method has the same name but different return type. The compiler assumes
your application code is attempting to override the API method with a different
return type, which is not allowed, hence the compilation error.
57. What is a working thread?
Ans. A working thread, more
commonly known as a worker thread is the key part of a design pattern that
allocates one thread to execute one task. When the task is complete, the thread
may return to a thread pool for later use. In this scheme a thread may execute
arbitrary tasks, which are passed in the form of a Runnable method argument,
typically execute(Runnable). The runnable tasks are usually stored in a queue
until a thread host is available to run them. The worker thread design pattern
is usually used to handle many concurrent tasks where it is not important which
finishes first and no single task needs to be coordinated with another. The
task queue controls how many threads run concurrently to improve the overall
performance of the system. However, a worker thread framework requires
relatively complex programming to set up, so should not be used where simpler
threading techniques can achieve similar results.
58. What is a green thread?
Ans. A green thread refers to a
mode of operation for the Java Virtual Machine (JVM) in which all code is
executed in a single operating system thread. If the Java program has any concurrent
threads, the JVM manages multi-threading internally rather than using other
operating system threads. There is a significant processing overhead for the
JVM to keep track of thread states and swap between them, so green thread mode
has been deprecated and removed from more recent Java implementations. Current
JVM implementations make more efficient use of native operating system threads.
59. What interface do you implement to do the
sorting?
Ans. Comparable.
60. What is the eligibility for a object to get
cloned?
Ans. It must implement the
Cloneable interface.
61. What is the purpose of abstract class?
Ans. It is not an instantiable
class. It provides the concrete implementation for some/all the methods. So
that they can reuse the concrete functionality by inheriting the abstract
class.
62. What is the difference between interface
and abstract class?
Ans. Abstract class defined with
methods. Interface will declare only the methods. Abstract classes are very
much useful when there is a some functionality across various classes.
Interfaces are well suited for the classes which varies in functionality but
with the same method signatures.
63. What do you mean by RMI and how it is
useful?
Ans. RMI is a remote method
invocation. Using RMI, you can work with remote object. The function calls are
as though you are invoking a local variable. So it gives you a impression that
you are working really with a object that resides within your own JVM though it
is somewhere.
64. What is the protocol used by RMI?
Ans. RMI-IIOP
65. What is a hashCode?
Ans. hash code value for this
object which is unique for every object.
66. What is a thread?
Ans. Thread is a block of code
which can execute concurrently with other threads in the JVM.
67. What is the algorithm used in Thread
scheduling?
Ans. Fixed priority scheduling.
68. What is hash-collision in Hashtable and how
it is handled in Java?
Ans. Two different keys with the
same hash value. Two different entries will be kept in a single hash bucket to
avoid the collision.
69. What is the use of serializable?
Ans. To persist the state of an
object into any perminant storage device.
70. What is the use of transient?
Ans. It is an indicator to the
JVM that those variables should not be persisted. It is the users
responsibility to initialize the value when read back from the storage.
71. What are the different level lockings using
the synchronization keyword?
Ans. Class level lock Object
level lock Method level lock Block level lock
72. What is the use of preparedstatement?
Ans. Preparedstatements are
precompiled statements. It is mainly used to speed up the process of
inserting/updating/deleting especially when there is a bulk processing.
73. What is callable statement? Tell me the way
to get the callable statement?
Ans. Callablestatements are used
to invoke the stored procedures. You can obtain the callablestatement from
Connection using the following methods prepareCall(String sql)
prepareCall(String sql, int resultSetType, int resultSetConcurrency).
74. In a statement, I am executing a batch.
What is the result of the execution?
Ans. It returns the int array.
The array contains the affected row count in the corresponding index of the
SQL.
75. Can a abstract method have the static
qualifier?
Ans. No.
76. What are the different types of qualifier
and what is the default qualifier?
Ans. public, protected, private,
package (default)
77. What is the super class of Hashtable?
Ans. Dictionary.
78. What is a lightweight component?
Ans. Lightweight components are
the one which doesn't go with the native call to obtain the graphical units.
They share their parent component graphical units to render them. Example,
Swing components
79. What is a heavyweight component?
Ans. For every paint call, there
will be a native call to get the graphical units. Example, AWT.
80. What do you mean by a Classloader?
Ans. Classloader is the one which
loads the classes into the JVM.
81. What are the implicit packages that need
not get imported into a class file?
Ans. java.lang
82. What is the difference between lightweight
and heavyweight component?
Ans. Lightweight components
reuses its parents graphical units. Heavyweight components goes with the native
graphical unit for every component. Lightweight components are faster than the
heavyweight components.
83. What are the ways in which you can
instantiate a thread?
Ans. Using Thread class By
implementing the Runnable interface and giving that handle to the Thread class.
class RunnableThread implements
Runnable {
Thread runner;
public RunnableThread() {
}
public RunnableThread(String
threadName) {
runner = new Thread(this,
threadName); // (1) Create a new thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the
thread.
}
public void run() {
//Display info about this
particular thread
System.out.println(Thread.currentThread());
}
}
84. What are the states of a thread?
Ans. 1. New 2. Runnable 3. Not
Runnable 4. Dead
85. What is a socket?
Ans. A socket is an endpoint for
communication between two machines.
86. What are the threads will start, when you
start the java program?
Ans. Finalize, Main, Reference
Handler, Signal Dispatcher.
87. Can there be an abstract class with no
abstract methods in it?
Ans. Yes
88. Can an Interface be final?
Ans. No.
89. Can an Interface have an inner class?
Ans. Yes.
public interface abc
{
static int i=0;
void add();
class a1
{
a1()
{
int j;
System.out.println("inside");
};
public static void main(String
a1[])
{
System.out.println("in
interfia");
}
}
}
90. Can we define private and protected
modifiers for variables in interfaces?
Ans. No.
91. What is Externalizable?
Ans. Externalizable is an
Interface that extends Serializable Interface. And sends data into Streams in
Compressed Format. It has two methods, writeExternal(ObjectOuput out) and
readExternal(ObjectInput in).
92. What modifiers are allowed for methods in
an Interface?
Ans. Only public and abstract
modifiers are allowed for methods in interfaces.
93. What is a local, member and a class
variable?
Ans. Variables declared within a
method are 'local'?? variables. Variables declared within the class i.e not
within any methods are 'member'?? variables (global variables). Variables
declared within the class i.e not within any methods and are defined as 'static'??
are class variables
94. What are the different identifier states of
a Thread?
Ans. The different identifiers of
a Thread are: R - Running or runnable thread, S - Suspended thread, CW - Thread
waiting on a condition variable, MW - Thread waiting on a monitor lock, MS -
Thread suspended waiting on a monitor lock
95. What are some alternatives to inheritance?
Ans. Delegation is an alternative
to inheritance. Delegation means that you include an instance of another class
as an instance variable, and forward messages to the instance. It is often
safer than inheritance because it forces you to think about each message you
forward, because the instance is of a known class, rather than a new class, and
because it doesn't force you to accept all the methods of the super class: you can provide only the
methods that really make sense. On the other hand, it makes you write more
code, and it is harder to re-use (because it is not a subclass).
96. Why isn't there operator overloading?
Ans. Because C++ has proven by
example that operator overloading makes code almost impossible to maintain. In
fact there very nearly wasn't even method overloading in Java, but it was
thought that this was too useful for some very basic methods like print(). Note
that some of the classes like DataOutputStream have unoverloaded methods like
writeInt() and writeByte().
97. What does it mean that a method or field is
'static'???
Ans. Static variables and methods
are instantiated only once per class. In other words they are class variables,
not instance variables. If you change the value of a static variable in a
particular object, the value of that variable changes for all instances of that
class. Static methods can be referenced with the name of the class rather than
the name of a particular object of the class (though that works too). That's
how library methods like System.out.println() work. out is a static field in
the java.lang.System class.
98. How do I convert a numeric IP address like
192.18.97.39 into a hostname like java.sun.com?
Ans. String hostname =
InetAddress.getByName("192.18.97.39").getHostName();
99. Difference between JRE/JVM/JDK/OpenJDK?
Ans. A Java virtual machine (JVM)
is a virtual machine that can execute Java bytecode. It is the code execution
component of the Java software platform.
The Java Development Kit (JDK) is
an Oracle Corporation product aimed at Java developers. Since the introduction
of Java, it has been by far the most widely used Java Software Development Kit
(SDK).
Java Runtime Environment, is also
referred to as the Java Runtime, Runtime Environment.
OpenJDK (Open Java Development
Kit) is a free and open source implementation of the Java programming
language.[2] It is the result of an effort Sun Microsystems began in 2006. The
implementation is licensed under the GNU General Public License (GPL) with a
linking exception.
100. Why do threads block on I/O?
Ans. Threads block on i/o (that
is enters the waiting state) so that other threads may execute while the I/O
operation is performed.
101. What is synchronization and why is it
important?
Ans. With respect to
multithreading, synchronization is the capability to control the access of
multiple threads to shared resources. Without synchronization, it is possible
for one thread to modify a shared object while another thread is in the process
of using or updating that object's value. This often leads to significant
errors.
102. Is null a keyword?
Ans. The null value is not a
keyword.
103. Which characters may be used as the second
character of an identifier,but not as the first character of an identifier?
Ans. The digits 0 through 9 may
not be used as the first character of an identifier but they may be used after
the first character of an identifier.
104. What modifiers may be used with an inner
class that is a member of an outer class?
Ans. A (non-local) inner class
may be declared as public, protected, private, static, final, or abstract.
105. How many bits are used to represent
Unicode, ASCII, UTF-16, and UTF-8 characters?
Ans. Unicode requires 16 bits and
ASCII require 7 bits. Although the ASCII character set uses only 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.
106. What are wrapped classes?
Ans. Wrapped classes are classes
that allow primitive types to be accessed as objects.
107. What restrictions are placed on the
location of a package statement within a source code file?
Ans. A package statement must
appear as the first line in a source code file (excluding blank lines and
comments).
108. What is the difference between preemptive
scheduling and time slicing?
Ans. Under preemptive scheduling,
the highest priority task executes until it enters the waiting or dead states
or a higher priority task comes into existence. 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.
109. What is a native method?
Ans. A native method is a method
that is implemented in a language other than Java.
110. What are order of precedence and
associativity, and how are they used?
Ans. Order of precedence
determines the order in which operators are evaluated in expressions.
Associatity determines whether an expression is evaluated left-to-right or
right-to-left.
111. What is the catch or declare rule for
method declarations?
Ans. If a checked exception may
be thrown within the body of a method, the method must either catch the
exception or declare it in its throws clause.
112. Can an anonymous class be declared as
implementing an interface and extending a class?
Ans. An anonymous class may
implement an interface or extend a superclass, but may not be declared to do
both.
113. What is the range of the char type?
Ans. The range of the char type
is 0 to 2^16 - 1.
114. Is 'abc'?? a primitive value?
Ans. The String literal 'abc'??
is not a primitive value. It is a String object.
115. What restrictions are placed on the values
of each case of a switch statement?
Ans. During compilation, the
values of each case of a switch statement must evaluate to a value that can be
promoted to an int value.
116. What modifiers may be used with an
interface declaration?
Ans. An interface may be declared
as public or abstract.
117. Is a class a subclass of itself?
Ans. A class is a subclass of
itself.
118. What is the difference between a while
statement and a do statement?
Ans. A while statement checks at
the beginning of a loop to see whether the next loop iteration should occur. A
do statement checks at the end of a loop to see whether the next iteration of a
loop should occur. The do statement will always execute the body of a loop at
least once.
119. What modifiers can be used with a local inner
class?
Ans. A local inner class may be
final or abstract.
120. What is the purpose of the File class?
Ans. The File class is used to
create objects that provide access to the files and directories of a local file
system.
121. Can an exception be rethrown?
Ans. Yes, an exception can be
rethrown.
122. When does the compiler supply a default
constructor for a class?
Ans. The compiler supplies a
default constructor for a class if no other constructors are provided.
123. If a method is declared as protected,
where may the method be accessed?
Ans. A protected method may only
be accessed by classes or interfaces of the same package or by subclasses of
the class in which it is declared.
124. Which non-Unicode letter characters may be
used as the first character of an identifier?
Ans. The non-Unicode letter
characters $ and _ may appear as the first character of an identifier
125. What restrictions are placed on method
overloading?
Ans. Two methods may not have the
same name and argument list but different return types.
126. What is casting?
Ans. There are two types of
casting, casting between primitive numeric types and casting between object
references. Casting between numeric types is used to convert larger values,
such as double values, to smaller values, such as byte values. Casting between
object references is used to refer to an object by a compatible class,
interface, or array type reference.
127. What is the return type of a program's
main() method?
Ans. A program's main() method
has a void return type.
public static void main(String
args[])
{
System.out.println("WithoutBook");
}
128. What class of exceptions are generated by
the Java run-time system?
Ans. The Java runtime system
generates RuntimeException and Error exceptions.
129. What class allows you to read objects
directly from a stream?
Ans. The ObjectInputStream class
supports the reading of objects from input streams.
130. What is the difference between a field
variable and a local variable?
Ans. A field variable is a
variable that is declared as a member of a class. A local variable is a
variable that is declared local to a method.
131. How are this() and super() used with
constructors?
Ans. this() is used to invoke a
constructor of the same class. super() is used to invoke a superclass
constructor.
132. What is the relationship between a
method's throws clause and the exceptions that can be thrown during the
method's execution?
Ans. A method's throws clause
must declare any checked exceptions that are not caught within the body of the
method.
133. Why are the methods of the Math class
static?
Ans. So they can be invoked as if
they are a mathematical code library.
134. What are the legal operands of the
instanceof operator?
Ans. The left operand is an
object reference or null value and the right operand is a class, interface, or
array type.
135. What an I/O filter?
Ans. An I/O filter is an object
that reads from one stream and writes to another, usually altering the data in
some way as it is passed from one stream to another.
136. If an object is garbage collected, can it
become reachable again?
Ans. Once an object is garbage
collected, it ceases to exist. It can no longer become reachable again.
137. What are E and PI?
Ans. E is the base of the natural
logarithm and PI is mathematical value pi.
138. Are true and false keywords?
Ans. The values true and false
are not keywords.
139. What is the difference between the File
and RandomAccessFile classes?
Ans. The File class encapsulates
the files and directories of the local file system. The RandomAccessFile class
provides the methods needed to directly access data contained in any part of a
file.
140. What happens when you add a double value
to a String?
Ans. The result is a String
object.
141. What is your platform's default character
encoding?
Ans. If you are running Java on
English Windows platforms, it is probably Cp1252. If you are running Java on
English Solaris platforms, it is most likely 8859_1.
142. Which package is always imported by
default?
Ans. The java.lang package is
always imported by default.
143. What interface must an object implement
before it can be written to a stream as an object?
Ans. An object must implement the
Serializable or Externalizable interface before it can be written to a stream
as an object.
144. How can my application get to know when a
HttpSession is removed?
Ans. Define a Class
HttpSessionNotifier which implements HttpSessionBindingListener and implement
the functionality what you need in valueUnbound() method. Create an instance of
that class and put that instance in HttpSession.
145. What’s the difference between notify() and
notifyAll()?
Ans. notify() is used to unblock
one waiting thread; notifyAll() is used to unblock all of them. Using notify()
is preferable (for efficiency) when only one blocked thread can benefit from
the change (for example, when freeing a buffer back into a pool). notifyAll()
is necessary (for correctness) if multiple threads should resume (for example,
when releasing a 'writer'?? lock on a file might permit all 'readers'?? to resume).
146. Why can't I say just abs() or sin()
instead of Math.abs() and Math.sin()?
Ans. The import statement does
not bring methods into your local name space. It lets you abbreviate class
names, but not get rid of them altogether. That's just the way it works, you'll
get used to it. It's really a lot safer this way.
However, there is actually a
little trick you can use in some cases that gets you what you want. If you’re
top-level class doesn't need to inherit from anything else, make it inherit
from java.lang.Math. That *does* bring all the methods into your local name
space. But you can't use this trick in an applet, because you have to inherit
from java.awt.Applet. And actually, you can't use it on java.lang.Math at all,
because Math is a '??final'?? class which means it can't be extended.
147. Why are there no global variables in Java?
Ans. Global variables are
considered bad form for a variety of reasons: Adding state variables breaks
referential transparency (you no longer can understand a statement or
expression on its own: you need to understand it in the context of the settings
of the global variables), State variables lessen the cohesion of a program: you
need to know more to understand how something works. A major point of
Object-Oriented programming is to break up global state into more easily
understood collections of local state, When you add one variable, you limit the
use of your program to one instance. What you thought was global, someone else
might think of as local: they may want to run two copies of your program at
once. For these reasons, Java decided to ban global variables.
148. What does it mean that a class or member
is final?
Ans. A final class can no longer
be subclasses. Mostly this is done for security reasons with basic classes like
String and Integer. It also allows the compiler to make some optimizations, and
makes thread safety a little easier to achieve. Methods may be declared final
as well. This means they may not be overridden in a subclass. Fields can be
declared final, too. However, this has a completely different meaning. A final
field cannot be changed after it's initialized, and it must include an initialize
statement where it's declared. For example, public final double c = 2.998; It's
also possible to make a static field final to get the effect of C++'s const
statement or some uses of C's #define, e.g. public static final double c =
2.998;
149. What does it mean that a method or class
is abstract?
Ans. An abstract class cannot be
instantiated. Only its subclasses can be instantiated. You indicate that a
class is abstract with the abstract keyword like this:
public abstract
class Container extends Component {
Abstract classes may contain
abstract methods. A method declared abstract is not actually implemented in the
current class. It exists only to be overridden in subclasses. It has no body.
For example,
public
abstract float price();
Abstract methods may only be
included in abstract classes. However, an abstract class is not required to
have any abstract methods, though most of them do. Each subclass of an abstract
class must override the abstract methods of its superclasses or itself be
declared abstract.
150. What is a transient variable?
Ans. transient variable is a
variable that may not be serialized.
151. How are Observer and Observable used?
Ans. Objects that subclass the
Observable class maintain a list of observers. When an Observable object is
updated it invokes the update() method of each of its observers to notify the
observers that it has changed state. The Observer interface is implemented by
objects that observe Observable objects.
152. Can a lock be acquired on a class?
Ans. Yes, a lock can be acquired
on a class. This lock is acquired on the class's Class object.
153. What state does a thread enter when it
terminates its processing?
Ans. When a thread terminates its
processing, it enters the dead state.
154. How does Java handle integer overflows and
underflows?
Ans. It uses those low order
bytes of the result that can fit into the size of the type allowed by the
operation.
155. What is the difference between the
>> and >>> operators?
Ans. The >> operator
carries the sign bit when shifting right. The >>> zero-fills bits that
have been shifted out.
156. Is sizeof a keyword?
Ans. The sizeof operator is not a
keyword.
157. Does garbage collection guarantee that a program will not run out
of memory?
Ans. Garbage collection does not
guarantee that a program will not run out of memory. It is possible for
programs to use up memory resources faster than they are garbage collected. It
is also possible for programs to create objects that are not subject to garbage
collection
158. Can an object's finalize() method be
invoked while it is reachable?
Ans. 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.
159. What value does readLine() return when it
has reached the end of a file?
Ans. The readLine() method
returns null when it has reached the end of a file.
160. Can a for statement loop indefinitely?
Ans. Yes, a for statement can
loop indefinitely. For example, consider the following: for(;;) ;
161. To what value is a variable of the String
type automatically initialized?
Ans. The default value of an
String type is null.
162. What is a task's priority and how is it
used in scheduling?
Ans. A task's priority is an
integer value that identifies the relative order in which it should be executed
with respect to other tasks. The scheduler attempts to schedule higher priority
tasks before lower priority tasks.
163. What is the range of the short type?
Ans. The range of the short type
is -(2^15) to 2^15 - 1.
164. What is the purpose of garbage collection?
Ans. The purpose of garbage
collection is to identify and discard objects that are no longer needed by a
program so that their resources may be reclaimed and reused.
165. What do you understand by private,
protected and public?
Ans. These are accessibility
modifiers. Private is the most restrictive, while public is the least
restrictive. There is no real difference between protected and the default type
(also known as package protected) within the context of the same package,
however the protected keyword allows visibility to a derived class in a
different package.
166. What is Downcasting ?
Ans. Downcasting is the casting
from a general to a more specific type, i.e. casting down the hierarchy
167. Can a method be overloaded based on
different return type but same argument type ?
Ans. No, because the methods can
be called without using their return type in which case there is ambiguity for
the compiler.
168. What happens to a static var that is
defined within a method of a class ?
Ans. Can't do it. You'll get a
compilation error
169. How many static init can you have ?
Ans. As many as you want, but the
static initializers and class variable initializers are executed in textual
order and may not refer to class variables declared in the class whose
declarations appear textually after the use, even though these class variables
are in scope.
170. What is the difference amongst JVM Spec,
JVM Implementation, JVM Runtime ?
Ans. The JVM spec is the
blueprint for the JVM generated and owned by Sun. The JVM implementation is the
actual implementation of the spec by a vendor and the JVM runtime is the actual
running instance of a JVM implementation.
171. What does the 'final'?? keyword mean in
front of a variable? A method? A class?
Ans. FINAL for a variable: value
is constant. FINAL for a method: cannot be overridden. FINAL for a class:
cannot be derived
172. What is the difference between instanceof
and isInstance?
Ans. 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 Java language instanceof operator. The method
returns true if the specified Object argument is non-null and can be cast to
the reference type represented by this Class object without raising a
ClassCastException. It returns false otherwise.
173. What is garbage collection? What is the
process that is responsible for doing that in java?
Ans. Reclaiming the unused memory
by the invalid objects. Garbage collector is responsible for this process
174. What kind of thread is the Garbage
collector thread?
Ans. It is a daemon thread.
175. What is a daemon thread?
Ans. These are the threads which
can run without user intervention. The JVM can exit when there are daemon
thread by killing them abruptly.
176. How will you invoke any external process
in Java?
Ans.
Runtime.getRuntime().exec('.)
177. What is the finalize method do?
Ans. Before the invalid objects
get garbage collected, the JVM give the user a chance to clean up some
resources before it got garbage collected.
178. What is mutable object and immutable
object?
Ans. 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, ')
179. What is the basic difference between
string and stringbuffer object?
Ans. String is an immutable
object. StringBuffer is a mutable object.
180. What is the purpose of Void class?
Ans. The Void class is an
uninstantiable placeholder class to hold a reference to the Class object
representing the primitive Java type void.
181. What is reflection?
Ans. 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.
182. What is the base class for Error and Exception?
Ans. Throwable.
183. What is the byte range?
Ans. 128 to 127
184. What is the implementation of destroy
method in java.. is it native or java code?
Ans. This method is not
implemented.
185. What is a package?
Ans. To group set of classes into
a single unit is known as packaging. Packages provides wide namespace ability.
186. What are the approaches that you will
follow for making a program very efficient?
Ans. 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.
187. What is a DatabaseMetaData?
Ans. Comprehensive information
about the database as a whole.
188. What is Locale?
Ans. A Locale object represents a
specific geographical, political, or cultural region
189. How will you load a specific locale?
Ans. Using
ResourceBundle.getBundle(');
190. What is JIT and its use?
Ans. Really, just a very fast
compiler' In this incarnation, pretty much a one-pass compiler '?? no offline
computations. So you can'??t look at the whole method, rank the expressions
according to which ones are re-used the most, and then generate code. In theory
terms, it'??s an on-line problem.
191. Is JVM a compiler or an interpreter?
Ans. Interpreter.
192. When you think about optimization, what is
the best way to findout the time/memory consuming process?
Ans. Using profiler.
193. What is the purpose of assert keyword used
in JDK1.4.x?
Ans. 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.
194. How will you get the platform dependent
values like line separator, path separator, etc., ?
Ans. Using Sytem.getProperty(')
(line.separator, path.separator, ')
195. What is skeleton and stub? what is the
purpose of those?
Ans. 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.
196. What is the final keyword denotes?
Ans. final keyword denotes that
it is the final implementation for that method or variable or class. You can't
override that method/variable/class any more.
197. What is the significance of ListIterator?
Ans. You can iterate back and
forth.
198. What is the major difference between
LinkedList and ArrayList?
Ans. LinkedList are meant for
sequential accessing. ArrayList are meant for random accessing.
199. What is nested class?
Ans. If all the methods of a
inner class is static then it is a nested class.
200. What is inner class?
Ans. If the methods of the inner
class can only be accessed via the instance of the inner class, then it is called
inner class.
201. What is composition?
Ans. Holding the reference of the
other class within some other class is known as composition.
202. What is aggregation?
Ans. 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.
203. What are the methods in Object?
Ans. clone, equals, wait,
finalize, getClass, hashCode, notify, notifyAll, toString
204. Can you instantiate the Math class?
Ans. You can't instantiate the
math class. All the methods in this class are static. And the constructor is
not public.
205. What is singleton?
Ans. 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 e.g., public class Singleton { private
static final Singleton s = new Singleton(); private Singleton() { } public
static Singleton getInstance() { return s; } // all non static methods ' }.
206. What is DriverManager?
Ans. The basic service to manage
set of JDBC drivers.
207. What is Class.forName() does and how it is
useful?
Ans. It loads the class into the
ClassLoader. It returns the Class. Using that you can get the instance (
'class-instance'??.newInstance() ).
208. What is the purpose of finalization?
Ans. The purpose of finalization
is to give an unreachable object the opportunity to perform any cleanup
processing before the object is garbage collected.
209. What is the difference between the Boolean
& operator and the && operator?
Ans. If an expression involving
the Boolean & operator is evaluated, both operands are evaluated. Then the
& operator is applied to the operand. When an expression involving the
&& operator is evaluated, the first operand is evaluated. If the first
operand returns a value of true then the second operand is evaluated. The
&& operator is then applied to the first and second operands. If the first
operand evaluates to false, the evaluation of the second operand is skipped.
210. How many times may an object's finalize()
method be invoked by the garbage collector?
Ans. An object's finalize()
method may only be invoked once by the garbage collector.
211. What is the purpose of the finally clause
of a try-catch-finally statement?
Ans. The finally clause is used
to provide the capability to execute code no matter whether or not an exception
is thrown or caught.
212. What is the argument type of a program's
main() method?
Ans. A program's main() method
takes an argument of the String[] type.
public static void main(String
args[])
{
System.out.println("WithoutBook");
}
213. Which Java operator is right associative?
Ans. The = operator is right
associative.
214. Can a double value be cast to a byte?
Ans. Yes, a double value can be
cast to a byte.
215. What is the difference between a break
statement and a continue statement?
Ans. A break statement results in
the termination of the statement to which it applies (switch, for, do, or
while). A continue statement is used to end the current loop iteration and
return control to the loop statement.
216. What must a class do to implement an
interface?
Ans. It must provide all of the
methods in the interface and identify the interface in its implements clause.
217. What is the advantage of the
event-delegation model over the earlier event-inheritance model?
Ans. The event-delegation model
has two advantages over the event-inheritance model. First, it enables event
handling to be handled by objects other than the ones that generate the events
(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
it performs much better in applications where many events are generated. This
performance improvement is due to the fact that the event-delegation model does
not have to repeatedly process unhandled events, as is the case of the
event-inheritance model.
218. How are commas used in the intialization
and iteration parts of a for statement?
Ans. Commas are used to separate
multiple statements within the initialization and iteration parts of a for
statement.
219. What is an abstract method?
Ans. An abstract method is a
method whose implementation is deferred to a subclass.
220. What value does read() return when it has
reached the end of a file?
Ans. The read() method returns -1
when it has reached the end of a file.
221. Can a Byte object be cast to a double
value?
Ans. No, an object cannot be cast
to a primitive value.
222. What is the difference between a static
and a non-static inner class?
Ans. A non-static inner class may
have object instances that are associated with instances of the class's outer
class. A static inner class does not have any object instances.
223. If a variable is declared as private,
where may the variable be accessed?
Ans. A private variable may only
be accessed within the class in which it is declared.
224. What is an object's lock and which
object's have locks?
Ans. An object's lock is a
mechanism that is used by multiple threads to obtain synchronized access to the
object. A thread may execute a synchronized method of an object only after it
has acquired the object's lock. All objects and classes have locks. A class's
lock is acquired on the class's Class object.
225. What is the % operator?
Ans. It is referred to as the
modulo or remainder operator. It returns the remainder of dividing the first
operand by the second operand.
226. When can an object reference be cast to an
interface reference?
Ans. An object reference be cast
to an interface reference when the object implements the referenced interface.
227. Which class is extended by all other
classes?
Ans. The Object class is extended
by all other classes.
228. Can an object be garbage collected while
it is still reachable?
Ans. A reachable object cannot be
garbage collected. Only unreachable objects may be garbage collected.
229. Is the ternary operator written x : y ? z
or x ? y : z ?
Ans. It is written x ? y : z.
230. How is rounding performed under integer
division?
Ans. The fractional part of the
result is truncated. This is known as rounding toward zero.
231. What is the difference between the
Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
Ans. The Reader/Writer class
hierarchy is character-oriented, and the InputStream/OutputStream class
hierarchy is byte-oriented.
232. What classes of exceptions may be caught
by a catch clause?
Ans. A catch clause can catch any
exception that may be assigned to the Throwable type. This includes the Error
and Exception types.
233. If a class is declared without any access
modifiers, where may the class be accessed?
Ans. A class that is declared
without any access modifiers is said to have package access. This means that
the class can only be accessed by other classes and interfaces that are defined
within the same package.
234. Does a class inherit the constructors of
its superclass?
Ans. A class does not inherit
constructors from any of its superclasses.
235. What is the purpose of the System class?
Ans. The purpose of the System
class is to provide access to system resources.
public static void main(String
args[])
{
System.out.println("WithoutBook");
}
236. Name the eight primitive Java types.
Ans. The eight primitive types
are byte, char, short, int, long, float, double, and boolean.
237. Which class should you use to obtain
design information about an object?
Ans. The Class class is used to
obtain information about an object's design.
238. What is Collection API ?
Ans. The Collection API is a set
of classes and interfaces that support operation on collections of objects.
These classes and interfaces are more flexible, more powerful, and more regular
than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet,
HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces:
Collection, Set, List and Map.
239. Is Iterator a Class or Interface? What is
its use?
Ans. Answer: Iterator is an
interface which is used to step through the elements of a Collection.
240. What is similarities/difference between an
Abstract class and Interface?
Ans. Differences are as follows:
Interfaces provide a form of
multiple inheritance. A class can extend only one other class. Interfaces are
limited to public methods and constants with no implementation. Abstract
classes can have a partial implementation, protected parts, static methods,
etc.
A Class may implement several
interfaces. But in case of abstract class, a class may extend only one abstract
class. Interfaces are slow as it requires extra indirection to to find
corresponding method in in the actual class. Abstract classes are fast.
Similarities:
Neither Abstract classes or
Interface can be instantiated.
241. How to define an Abstract class?
Ans. A class containing abstract
method is called Abstract class. An Abstract class can't be instantiated.
Example of Abstract class:
abstract class testAbstractClass
{
protected String myString;
public String getMyString() {
return myString;
}
public abstract string
anyAbstractFunction();
}
242. How to define an Interface in Java ?
Ans. In Java Interface defines
the methods but does not implement them. Interface can include constants. A
class that implements the interfaces is bound to implement all the methods
defined in Interface.
Emaple of Interface:
public interface sampleInterface
{
public void functionOne();
public long CONSTANT_ONE = 1000;
}
243. If a class is located in a package, what
do you need to change in the OS environment to be able to use it?
Ans. You need to add a directory
or a jar file that contains the package directories to the CLASSPATH
environment variable. Let's say a class Employee belongs to a package
com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this
case, you'd need to add c:\dev to the variable CLASSPATH. If this class
contains the method main(), you could test it from a command prompt window as
follows:
c:\>java com.xyz.hr.Employee
244. How many methods in the Serializable
interface?
Ans. 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.
245. How many methods in the Externalizable
interface?
Ans. There are two methods in the
Externalizable interface. You have to implement these two methods in order to
make your class externalizable. These two methods are readExternal() and
writeExternal().
246. What is the difference between
Serializalble and Externalizable interface?
Ans. 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.
247. Which containers use a border layout as
their default layout?
Ans. The Window, Frame and Dialog
classes use a border layout as their default layout.
248. When should I use abstract methods?
Ans. Abstract methods are usually
declared where two or more subclasses are expected to fulfil a similar role in
different ways. Often the subclasses are required to the fulfil an interface,
so the abstract superclass might provide several of the interface methods, but
leave the subclasses to implement their own variations of the abstract methods.
Abstract classes can be thought of as part-complete templates that make it
easier to write a series of subclasses.
For example, if you were
developing an application for working with different types of documents, you
might have a Document interface that each document must fulfil. You might then
create an AbstractDocument that provides concrete openFile() and closeFile()
methods, but declares an abstract displayDocument(JPanel) method. Then separate
LetterDocument, StatementDocument or InvoiceDocument types would only have to
implement their own version of displayDocument(JPanel) to fulfil the Document
interface.
249. Why use an abstract class instead of an
interface?
Ans. The main reason to use an
abstract class rather than an interface is because abstract classes can carry a
functional "payload" that numerous subclasses can inherit and use
directly. Interfaces can define the same abstract methods as an abstract class
but cannot include any concrete methods.
In a real program it is not a
question of whether abstract classes or interfaces are better, because both
have features that are useful. It is common to use a mixture of interface and
abstract classes to create a flexible and efficient class hierarchy that
introduces concrete methods in layers. In practical terms it is more a question
of the appropriate point in the hierarchy to define "empty" abstract
methods, concrete methods and combine them through the extends and implements
keywords.
The example below compares a
"Spectrum" type defined by an interface and an abstract class and
shows how the abstract class can provide protected methods that minimise the
implementation requirements in its subclasses.
250. In which case, do we need abstract classes
with no abstract methods?
Ans. An abstract class without
any abstract methods should be a rare thing and you should always question your
application design if this case arises. Normally you should refactor to use a
concrete superclass in this scenario.
One specific case where abstract
class may justifiably have no abstract methods is where it partially implements
an interface, with the intention that its subclasses must complete the
interface.
Example: To take a slightly
contrived motoring analogy, a Chassis class may partially implement a Vehicle
interface and provide a set of core methods from which a range of concrete
Vehicle types are extended. Chassis is not a viable implementation of a Vehicle
in its own right, so a concrete Car subclass would have to implement interface
methods for functional wheels, engine and bodywork.
251. What's the use of concrete methods in
abstract classes?
Ans. One of the design principles
of Java inheritance is to create superclass methods that can be used by one or
more subclasses, this avoids duplication of code and makes it easier to amend.
The same principle holds with abstract classes that are fulfilled by numerous
subclasses.
One useful technique with
abstract classes is that a concrete method may be defined in anticipation of
abstract methods being fulfilled in its subclasses. In the example below the
AbstractShape class has a concrete printArea() method that calls the abstract
getArea() method. Subclasses inherit the printArea() method and must implement
the getArea() method to stand as concrete classes.
252. If an object is garbage collected, can it
become reachable again?
Ans. Once an object is garbage
collected, It can no longer become reachable again.
253. What is the purpose of finalization?
Ans. The purpose of finalization
is to give an unreachable object the opportunity to perform any cleanup, before
the object gets garbage collected. For example, closing an opened database
Connection.
254. Does garbage collection guarantee that a
program will not run out of memory?
Ans. Garbage collection does not
guarantee that a program will not run out of memory. It is possible for
programs to use up memory resources faster than they are garbage collected. It
is also possible for programs to create objects that are not subject to garbage
collection.
255. an object's finalize() method be invoked
while it is reachable?
Ans. 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..
256. What kind of thread is the Garbage
collector thread?
Ans. It is a daemon thread.
257. Explain Garbage collection mechanism in
Java?
Ans. Garbage collection is one of
the most important features of Java. The purpose of garbage collection is to
identify and discard objects that are no longer needed by a program so that
their resources can be reclaimed and reused. A Java object is subject to
garbage collection when it becomes unreachable to the program in which it is
used. Garbage collection is also called automatic memory management as JVM
automatically removes the unused variables/objects (value is null) from the
memory. Every class inherits finalize() method from java.lang.Object, the
finalize() method is called by garbage collector when it determines no more
references to the object exists. In Java, it is good idea to explicitly assign
null into a variable when no more in use.
In Java on calling System.gc()
and Runtime.gc(), JVM tries to recycle the unused objects, but there is no
guarantee when all the objects will garbage collected. Garbage collection is an
automatic process and can't be forced. There is no guarantee that Garbage
collection will start immediately upon request of System.gc().
258. What is difference between String and
StringTokenizer?
Ans. A StringTokenizer is utility
class used to break up string.
Example:
StringTokenizer st = new
StringTokenizer("Hello World");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Output: Hello World
259. Can a method be static and synchronized?
Ans. A static method can be
synchronized. If you do so, the JVM will obtain a lock on the java.lang. Class
instance associated with the object. It is similar to saying:
synchronized(XYZ.class) {
}
260. What is phantom memory?
Ans. Phantom memory is false
memory. Memory that does not exist in reality.
261. Does JVM maintain a cache by itself? Does
the JVM allocate objects in heap? Is this the OS heap or the heap maintained by
the JVM? Why?
Ans. Yes, the JVM maintains a
cache by itself. It creates the Objects on the HEAP, but references to those
objects are on the STACK.
262. What is reflection API? How are they
implemented?
Ans. What is reflection API? How
are they implemented?
Reflection is the process of
introspecting the features and state of a class at runtime and dynamically
manipulate at run time. This is supported using Reflection API with built-in
classes like Class, Method, Fields, Constructors etc. Example: Using Java
Reflection API we can get the class name, by using the getName method.
263. What is data encapsulation?
Ans. Encapsulation may be used by
creating 'get' and 'set' methods in a class (JAVABEAN) which are used to access
the fields of the object. Typically the fields are made private while the get
and set methods are public. Encapsulation can be used to validate the data that
is to be stored, to do calculations on data that is stored in a field or
fields, or for use in introspection (often the case when using javabeans in
Struts, for instance). Wrapping of data and function into a single unit is
called as data encapsulation. Encapsulation is nothing but wrapping up the data
and associated methods into a single unit in such a way that data can be accessed
with the help of associated methods. Encapsulation provides data security. It
is nothing but data hiding.
264. How can I swap two variables without using
a third variable?
Ans. Add two variables and assign
the value into First variable. Subtract the Second value with the result Value.
and assign to Second variable. Subtract the Result of First Variable With
Result of Second Variable and Assign to First Variable.
Example:
int a=5,b=10;a=a+b; b=a-b; a=a-b;
265. Explain working of Java Virtual Machine (JVM)?
Ans. JVM is an abstract computing
machine like any other real computing machine which first converts .java file
into .class file by using Compiler (.class is nothing but byte code file.) and
Interpreter reads byte codes.
266. When is static variable loaded? Is it at
compile time or runtime? When exactly a static block is loaded in Java?
Ans. Static variable are loaded
when classloader brings the class to the JVM. It is not necessary that an
object has to be created. Static variables will be allocated memory space when
they have been loaded. The code in a static block is loaded/executed only once
i.e. when the class is first initialized. A class can have any number of static
blocks. Static block is not member of a class, they do not have a return statement
and they cannot be called directly. Cannot contain this or super. They are
primarily used to initialize static fields.
267. What is reason of NoClassDefFoundError in
Java?
Ans. NoClassDefFoundError in Java
comes when Java Virtual Machine is not able to find a particular class at
runtime which was available during compile time. for example if we have a
method call from a class or accessing any static member of a Class and that
class is not available during run-time then JVM will throw NoClassDefFoundError.
It’s important to understand that this is different than ClassNotFoundException
which comes while trying to load a class at run-time only and name was provided
during runtime not on compile time. Most of the java developer mingle this two
Error and gets confused.
268. How to resolve NoClassDefFoundError?
Ans. Obvious reason of
NoClassDefFoundError is that a particular class is not available in Classpath,
so we need to add that into Classpath or we need to check why it’s not
available in Classpath if we are expecting it to be. There could be multiple
reasons like:
1) Class is not available in Java
Classpath.
2) You might be running your
program using jar command and class was not defined in manifest file's
ClassPath attribute.
3) Any startup script is overriding
Classpath environment variable.
269. Difference between ClassNotFoundException
and NoClassDefFoundError in Java?
Ans. Many a times we confused
ourselves with ClassNotFoundException and NoClassDefFoundError, though both of
them related to Java Classpath they are completely different to each other.
ClassNotFoundException comes when JVM tries to load a class at runtime
dynamically means you give the name of class at runtime and then JVM tries to
load it and if that class is not found in classpath it throws
ClassNotFoundException. While in case of NoClassDefFoundError the problematic
class was present during Compile time and that's why program was successfully
compile but not available during runtime by any reason. NoClassDefFoundError is
easier to solve than ClassNotFoundException in my opinion because here we know
that Class was present during build time.
Let me know how exactly you are
facing NoClassDefFoundError and I will guide you how to troubleshoot it, if you
are facing with something new way than I listed above we will probably document
if for benefit of others and again don’t afraid with Exception in thread
"main" java.lang.NoClassDefFoundError.
270. What is java.lang.OutOfMemoryError in
Java?
Ans. OutOfMemoryError in Java is
a subclass of java.lang.VirtualMachineError and JVM throws
java.lang.OutOfMemoryError when it ran out of memory in heap. OutOfMemoryError
in Java can come any time in heap mostly while you try to create an object and
there is not enough space in heap to allocate that object. javavdoc of
OutOfMemoryError is not very informative about this though.
271. Types of OutOfMemoryError in Java.
Ans. I have seen mainly two types
of OutOfMemoryError in Java:
1) Java.lang.OutOfMemoryError:
Java heap space
2) Java.lang.OutOfMemoryError:
PermGen space
Though both of them occur because
JVM ran out of memory they are quite different to each other and there
solutions are independent to each other.
272. Difference between
"java.lang.OutOfMemoryError: Java heap space" and
"java.lang.OutOfMemoryError: PermGen space"
Ans. If you are familiar with
different generations on heap and How garbage collection works in java and
aware of new, old and permanent generation of heap space then you would have
easily figured out this OutOfMemoryError in Java. Permanent generation of heap
is used to store String pool and various Meta data required by JVM related to
Class, method and other java primitives. Since in most of JVM default size of
Perm Space is around "64MB" you can easily ran out of memory if you
have too many classes or huge number of Strings in your project. Important
point to remember is that it doesn't depends on –Xmx value so no matter how big
your total heap size you can ran OutOfMemory in perm space. Good think is you can
specify size of permanent generation using JVM options "-XX:PermSize"
and "-XX:MaxPermSize" based on your project need.
One small thing to remember is
that "=" is used to separate parameter and value while specifying
size of perm space in heap while "=" is not required while setting
maximum heap size in java, as shown in below example.
export JVM_ARGS="-Xmx1024m
-XX:MaxPermSize=256m"
Another reason of
"java.lang.OutOfMemoryError: PermGen" is memory leak through
Classloaders and it’s very often surfaced in WebServer and application server
like tomcat, webshere, glassfish or weblogic. In Application server different
classloaders are used to load different web application so that you can deploy
and undeploy one application without affecting other application on same
server, but while undeploying if container somehow keeps reference of any class
loaded by application class loader than that class and all other related class
will not be garbage collected and can quickly fill the PermGen space if you
deploy and undeploy your application many times.
"java.lang.OutOfMemoryError: PermGen” has been observed many times in
tomcat in our last project but solution of this problem are really tricky
because first you need to know which class is causing memory leak and then you
need to fix that. Another reason of OutOfMemoryError in PermGen space is if any
thread started by application doesn't exist when you undeploy your application.
These are just some example of
infamous classloader leaks, anybody who is writing code for loading and
unloading classes have to be very careful to avoid this. You can also use
visualgc for monitoring PermGen space, this tool will show graph of PermGen
space and you can see how and when Permanent space getting increased. I suggest
using this tool before reaching to any conclusion.
Another rather unknown but
interesting cause of "java.lang.OutOfMemoryError: PermGen" we found
is introduction of JVM options "-Xnoclassgc". This option sometime
used to avoid loading and unloading of classes when there is no further live
references of it just to avoid performance hit due to frequent loading and
unloading, but using this option is J2EE environment can be very dangerous
because many framework e.g. Struts, spring etc uses reflection to create
classes and with frequent deployment and undeployment you can easily ran out of
space in PermGen if earlier references was not cleaned up. This instance also
points out that some time bad JVM arguments or configuration can cause
OutOfMemoryError in Java.
273. How HashMap works in Java?
Ans. "How does get () method
of HashMap works in Java"
And then you get answers like I
don't bother its standard Java API, you better look code on java; I can find it
out in Google at any time etc.
But some interviewee definitely
answer this and will say "HashMap works on principle of hashing, we have
put () and get () method for storing and retrieving data from hashMap. When we
pass an object to put () method to store it on hashMap, hashMap implementation
calls
hashcode() method hashMap key
object and by applying that hashcode on its own hashing funtion it identifies a
bucket location for storing value object , important part here is HashMap
stores both key+value in bucket which is essential to understand the retrieving
logic. if people fails to recognize this and say it only stores Value in the
bucket they will fail to explain the retrieving logic of any object stored in
HashMap . This answer is very much acceptable and does make sense that
interviewee has fair bit of knowledge how hashing works and how HashMap works
in Java.
But this is just start of story
and going forward when depth increases a little bit and when you put
interviewee on scenarios every java developers faced day by day basis. So next
question would be more likely about collision detection and collision
resolution in Java HashMap ->
"What will happen if two
different objects have same hashcode?"
Now from here confusion starts
some time interviewer will say that since Hashcode is equal objects are equal
and HashMap will throw exception or not store it again etc. then you might want
to remind them about equals and hashCode() contract that two unequal object in
Java very much can have equal hashcode. Some will give up at this point and
some will move ahead and say "Since hashcode () is same, bucket location
would be same and collision occurs in hashMap, Since HashMap use a linked list
to store in bucket, value object will be stored in next node of linked
list." great this answer make sense to me though there could be some other
collision resolution methods available this is simplest and HashMap does follow
this.
"How will you retreive if
two different objects have same hashcode?"
Interviewee will say we will call
get() method and then HashMap uses keys hashcode to find out bucket location
and retrieves object but then you need to remind him that there are two objects
are stored in same bucket , so they will say about traversal in linked list
until we find the value object , then you ask how do you identify value object
because you don't value object to compare ,So until they know that HashMap
stores both Key and Value in linked list node they won't be able to resolve
this issue and will try and fail.
But those bunch of people who
remember this key information will say that after finding bucket location , we
will call keys.equals() method to identify correct node in linked list and
return associated value object for that key in Java HashMap. Perfect this is
the correct answer.
In many cases interviewee fails
at this stage because they get confused between hashcode () and equals () and
keys and values object in hashMap which is pretty obvious because they are
dealing with the hashcode () in all previous questions and equals () come in
picture only in case of retrieving value object from HashMap.
Some good developer point out
here that using immutable, final object with proper equals () and hashcode ()
implementation would act as perfect Java HashMap keys and improve performance
of Java hashMap by reducing collision. Immutability also allows caching there
hashcode of different keys which makes overall retrieval process very fast and
suggest that String and various wrapper classes e.g Integer provided by Java
Collection API are very good HashMap keys.
Now if you clear all this java
hashmap interview question you will be surprised by this very interesting
question "What happens On HashMap in Java if the size of the Hashmap
exceeds a given threshold defined by load factor ?". Until you know how
hashmap works exactly you won't be able to answer this question.
if the size of the map exceeds a
given threshold defined by load-factor e.g. if load factor is .75 it will act
to re-size the map once it filled 75%. Java Hashmap does that by creating
another new bucket array of size twice of previous size of hashmap, and then
start putting every old element into that new bucket array and this process is
called rehashing because it also applies hash function to find new bucket
location.
If you manage to answer this
question on hashmap in java you will be greeted by "do you see any problem
with resizing of hashmap in Java" , you might not be able to pick the
context and then he will try to give you hint about multiple thread accessing
the java hashmap and potentially looking for race condition on HashMap in Java.
So the answer is Yes there is
potential race condition exists while resizing hashmap in Java, if two thread
at the same time found that now Java Hashmap needs resizing and they both try
to resizing. on the process of resizing of hashmap in Java , the element in
bucket which is stored in linked list get reversed in order during there
migration to new bucket because java hashmap doesn't append the new element at
tail instead it append new element at head to avoid tail traversing. if race
condition happens then you will end up with an infinite loop. though this point
you can potentially argue that what the hell makes you think to use HashMap in
multi-threaded environment to interviewer.
274. What is the difference between
Synchronized Collection classes and Concurrent Collection Classes ? When to use
what ?
Ans. The synchronized collections
classes, Hashtable and Vector, and the synchronized wrapper classes,
Collections.synchronizedMap and Collections.synchronizedList, provide a basic
conditionally thread-safe implementation of Map and List.
However, several factors make
them unsuitable for use in highly concurrent applications -- their single
collection-wide lock is an impediment to scalability and it often becomes
necessary to lock a collection for a considerable time during iteration to
prevent ConcurrentModificationExceptions.
The ConcurrentHashMap and
CopyOnWriteArrayList implementations provide much higher concurrency while
preserving thread safety, with some minor compromises in their promises to
callers. ConcurrentHashMap and CopyOnWriteArrayList are not necessarily useful
everywhere you might use HashMap or ArrayList, but are designed to optimize
specific common situations. Many concurrent applications will benefit from
their use.
So what is the difference between
hashtable and ConcurrentHashMap , both can be used in multithreaded environment
but once the size of hashtable becomes considerable large performance degrade
because for iteration it has to be locked for longer duration.
Since ConcurrentHashMap
indroduced concept of segmentation , how large it becomes only certain part of
it get locked to provide thread safety so many other readers can still access
map without waiting for iteration to complete.
In Summary ConcurrentHashMap only
locked certain portion of Map while Hashtable lock full map while doing
iteration.
275. How to use Comparator and Comparable in
Java? With example.
Ans. Comparators and comparable
in Java are two of fundamental interface of Java API which is very important to
understand to implement sorting in Java. It’s often required to sort objects
stored in any collection class or in Array and that time we need to use compare
() and compare To () method defined in java.util.Comparator and
java.lang.Comparable class. Let’s see some important points about both
Comparable and Comparator in Java before moving ahead
Difference
between Comparator and Comparable in Java
1) Comparator in Java is defined
in java.util package while Comparable interface in Java is defined in java.lang
package.
2) Comparator interface in Java
has method public int compare (Object o1, Object o2) which returns a negative
integer, zero, or a positive integer as the first argument is less than, equal
to, or greater than the second. While Comparable interface has method public
int compareTo(Object o) which returns a negative integer, zero, or a positive
integer as this object is less than, equal to, or greater than the specified
object.
3) If you see then logical
difference between these two is Comparator in Java compare two objects provided
to him, while Comparable interface compares "this" reference with the
object specified.
4) Comparable in Java is used to
implement natural ordering of object. In Java API String, Date and wrapper
classes implement Comparable interface.
5) If any class implement
Comparable interface in Java then collection of that object either List or
Array can be sorted automatically by using Collections.sort() or Arrays.sort()
method and object will be sorted based on there natural order defined by
CompareTo method.
6)Objects which implement
Comparable in Java can be used as keys in a sorted map or elements in a sorted
set for example TreeSet, without specifying any Comparator.
276. What is polymorphism in Java? Method
overloading or overriding?
Ans. What is polymorphism in Java
Polymorphism is an Oops concept
which advice use of common interface instead of concrete implementation while
writing code. When we program for interface our code is capable of handling any
new requirement or enhancement arise in near future due to new implementation
of our common interface. If we don't use common interface and rely on concrete
implementation, we always need to change and duplicate most of our code to
support new implementation. Its not only java but other object oriented
language like C++ also supports polymorphism and it comes as fundamental along
with encapsulation , abstraction and inheritance.
Method overloading and method
overriding in Java
Method is overloading and method
overriding uses concept of polymorphism in java where method name remains same
in two classes but actual method called by JVM depends upon object. Java
supports both overloading and overriding of methods. In case of overloading
method signature changes while in case of overriding method signature remains
same and binding and invocation of method is decided on runtime based on actual
object. This facility allows java programmer to write very flexibly and
maintainable code using interfaces without worrying about concrete implementation.
One disadvantage of using polymorphism in code is that while reading code you
don't know the actual type which annoys while you are looking to find bugs or
trying to debug program. But if you do java debugging in IDE you will
definitely be able to see the actual object and the method call and variable
associated with it.
277. What is abstraction?
Ans. something which is not
concrete , something which is imcomplete.
java has concept of abstract
classes , abstract method but a variable can not be abstract.
an abstract class is something
which is incomplete and you can not create instance of it for using it.if you
want to use it you need to make it complete by extending it.
an abstract method in java
doesn't have body , its just a declaration.
so when do you use abstraction ?
( most important in my view )
when I know something needs to be
there but I am not sure how exactly it should look like.
e.g. when I am creating a class
called Vehicle, I know there should be methods like start() and Stop() but
don't know start and stop mechanism of every vehicle since they could have
different start and stop mechanism e..g some can be started by kick or some can
be by pressing buttons .
the same concept apply to
interface also , which we will discuss in some other post.
so implementation of those
start() and stop() methods should be left to there concrete implementation e.g.
Scooter , MotorBike , Car etc.
In Java Interface is an another
way of providing abstraction, Interfaces are by default abstract and only
contains public static final constant or abstract methods. Its very common
interview question is that where should we use abstract class and where should
we use Java Interfaces in my view this is important to understand to design
better java application, you can go for java interface if you only know the
name of methods your class should have e.g. for Server it should have start()
and stop() method but we don't know how exactly these start and stop method
will work. if you know some of the behavior while designing class and that
would remain common across all subclasses add that into abstract class.
in Summary
1) Use abstraction if you know
something needs to be in class but implementation of that varies.
2) In Java you cannot create
instance of abstract class , its compiler error.
3) abstract is a keyword in java.
4) a class automatically becomes
abstract class when any of its method declared as abstract.
5) abstract method doesn't have
method body.
6) variable cannot be made
abstract , its only behavior or methods which would be abstract.
278. String vs StringBuffer vs StringBuilder in
Java
Ans. String in Java
1) String is immutable in Java:
String is by design immutable in java you can check this post for reason.
Immutability offers lot of benefit to the String class e.g. his hash code value
can be cached which makes it a faster hashmap key; it can be safely shared
between multithreaded applications without any extra synchronization. To know
why strings are immutable in java see the link
2)when we represent string in
double quotes like "abcd" they are referred as String literal and
String literals are created in String pools.
3) "+" operator is
overloaded for String and used to concatenated two string. Internally
"+" operation is implemented using either StringBuffer or
StringBuilder.
4) Strings are backed up by
Character Array and represented in UTF-16 format.
5) String class overrides
equals() and hashcode() method and two Strings are considered to be equal if
they contain exactly same character in same order and in same case. If you want
ignore case comparison of two strings consider using equalsIgnoreCase() method.
To learn how to correctly override equals method in Java see the link.
7) toString() method provides
string representation of any object and its declared in Object class and its
recommended for other class to implement this and provide string
representation.
8) String is represented using
UTF-16 format in Java.
9) In Java you can create String
from byte array, char array, another string, from StringBuffer or from
StringBuilder. Java String class provides constructor for all of these.
Problem
with String in Java
One of its biggest strength
"immutability" is a biggest problem of Java String if not used
correctly. many a times we create a String and then perform a lot of operation
on them e.g. converting string into uppercase, lowercase , getting substring
out of it , concatenating with other string etc. Since String is an immutable
class every time a new String is created and older one is discarded which creates
lots of temporary garbage in heap. If String are created using String literal
they remain in String pool. To resolve this problem Java provides us two
Classes StringBuffer and StringBuilder. String Buffer is an older class but
StringBuilder is relatively new and added in JDK 5.
Differences
between String and StringBuffer in Java
Main difference between String
and StringBuffer is String is immutable while StringBuffer is mutable means you
can modify a StringBuffer object once you created it without creating any new
object. This mutable property makes StringBuffer an ideal choice for dealing
with Strings in Java. You can convert a StringBuffer into String by its
toString() method. String vs StringBuffer or what is difference between
StringBuffer and String is one of the popular interview questions for either
phone interview or first round. Now days they also include StringBuilder and
ask String vs StringBuffer vs StringBuilder. So be preparing for that. In the
next section we will see difference between StringBuffer and StringBuilder in
Java.
Difference
between StringBuilder and StringBuffer in Java
StringBuffer is very good with
mutable String but it has one disadvantage all its public methods are
synchronized which makes it thread-safe but same time slow. In JDK 5 they
provided similar class called StringBuilder in Java which is a copy of
StringBuffer but without synchronization. Try to use StringBuilder whenever
possible it performs better in most of cases than StringBuffer class. You can
also use "+" for concatenating two string because "+"
operation is internal implemented using either StringBuffer or StringBuilder in
Java. If you see StringBuilder vs StringBuffer you will find that they are
exactly similar and all API methods applicable to StringBuffer are also
applicable to StringBuilder in Java. On the other hand String vs StringBuffer
is completely different and there API is also completely different, same is
true for StringBuilders vs String.
Summary
1) String is immutable while
StringBuffer and StringBuilder is mutable object.
2) StringBuffer is synchronized
while StringBuilder is not which makes StringBuilder faster than StringBuffer.
3) Concatenation operator
"+" is internal implemented using either StringBuffer or
StringBuilder.
4) Use String if you require
immutability, use Stringbuffer in java if you need mutable + threadsafety and
use StringBuilder in Java if you require mutable + without thread-safety.
279. Why String is immutable or final in Java?
Ans. 1)Imagine StringPool
facility without making string immutable , its not possible at all because in
case of string pool one string object/literal e.g. "Test" has
referenced by many reference variables , so if any one of them change the value
others will be automatically gets affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called
"Test".toUpperCase() which change the same object into
"TEST" , so A will also be "TEST" which is not desirable.
2)String has been widely used as
parameter for many java classes e.g. for opening network connection you can
pass hostname and port number as stirng , you can pass database URL as string
for opening database connection, you can open any file by passing name of file
as argument to File I/O classes.
In case if String is not
immutable , this would lead serious security threat , I mean some one can
access to any file for which he has authorization and then can change the file
name either deliberately or accidentally and gain access of those file.
3)Since String is immutable it
can safely shared between many threads ,which is very important for
multithreaded programming and to avoid any synchronization issues in Java.
4) Another reason of Why String
is immutable in Java is to allow String to cache its hashcode , being immutable
String in Java caches its hashcode and do not calculate every time we call
hashcode method of String, which makes it very fast as hashmap key to be used
in hashmap in Java. This one is also suggested by Jaroslav Sedlacek in comments
below.
5) Another good reason of Why String
is immutable in Java suggested by Dan Bergh Johnsson on comments is: The
absolutely most important reason that String is immutable is that it is used by
the class loading mechanism, and thus have profound and fundamental security
aspects.
280. What is Encapsulation in Java and OOPS
with Example?
Ans. Encapsulation is nothing but
protecting anything which is prone to change. rational behind encapsulation is
that if any functionality which is well encapsulated in code i.e maintained in
just one place and not scattered around code is easy to change. this can be
better explained with a simple example of encapsulation in Java. we all know
that constructor is used to create object in Java and constructor can accept
argument.
Advantage of Encapsulation in Java and OOPS
Here are few advantages of using
Encapsulation while writing code in Java or any Object oriented programming
language:
1. Encapsulated Code is more
flexible and easy to change with new requirements.
2. Encapsulation in Java makes
unit testing easy.
3. Encapsulation in Java allows
you to control who can access what.
4. Encapsulation also helps to
write immutable class in Java which are a good choice in multi-threading
environment.
5. Encapsulation reduce coupling
of modules and increase cohesion inside a module because all piece of one thing
are encapsulated in one place.
6. Encapsulation allows you to
change one part of code without affecting other part of code.
What should you encapsulate in
code Anythign which can be change and more likely to change in near future is
candidate of Encapsulation. This also helps to write more specific and cohesive
code. Example of this is object creation code, code which can be improved in
future like sorting and searching logic.
Design Pattern based on Encapsulation in Java
Many design pattern in Java uses
encapsulation concept, one of them is Factory pattern which is used to create
objects. Factory pattern is better choice than new operator for creating object
of those classes whose creation logic can vary and also for creating different
implementation of same interface. BorderFactory class of JDK is a good example
of encapsulation in Java which creates different types of Border and
encapsulate creation logic of Border. Singleton pattern in Java also encpasulate
how you create instance by providing getInstance() method. since object is
created inside one class and not from any other place in code you can easily
change how you create object without affect other part of code.
281. Difference between Thread and Runnable
interface in Java?
Ans. Here are some of my thoughts
on whether I should use Thread or Runnable for implementing task in Java,
though you have another choice as "Callable" for implementing thread
which we will discuss later.
1) Java doesn't support multiple
inheritance, which means you can only extend one class in Java so once you
extended Thread class you lost your chance and can not extend or inherit
another class in Java.
2) In Object oriented programming
extending a class generally means adding new functionality, modifying or
improving behaviors. If we are not making any modification on Thread than use
Runnable interface instead.
3) Runnable interface represent a
Task which can be executed by either plain Thread or Executors or any other means.
so logical separation of Task as Runnable than Thread is good design decision.
4) Separating task as Runnable
means we can reuse the task and also has liberty to execute it from different
means. since you can not restart a Thread once it completes. again Runnable vs
Thread for task, Runnable is winner.
5) Java designer recognizes this
and that's why Executors accept Runnable as Task and they have worker thread
which executes those task.
6) Inheriting all Thread methods
are additional overhead just for representing a Task which can can be done
easily with Runnable.
282. Difference between Wait and Sleep , Yield
in Java
Ans. Difference between Wait and
Sleep in Java
Main difference between wait and
sleep is that wait() method release the acquired monitor when thread is waiting
while Thread.sleep() method keeps the lock or monitor even if thread is
waiting. Also wait method in java should be called from synchronized method or
block while there is no such requirement for sleep() method. Another difference
is Thread.sleep() method is a static method and applies on current thread,
while wait() is an instance specific method and only got wake up if some other
thread calls notify method on same object. also in case of sleep, sleeping
thread immediately goes to Runnable state after waking up while in case of
wait, waiting thread first acquires the lock and then goes into Runnable state.
So based upon your need if you require a specified second of pause use sleep()
method or if you want to implement inter-thread communication use wait method.
here is list of difference
between wait and sleep in Java :
1) wait is called from
synchronized context only while sleep can be called without synchronized block.
see Why wait and notify needs to call from synchronized method for more detail.
2) wait is called on Object while
sleep is called on Thread. see Why wait and notify are defined in object class
instead of Thread.
3) waiting thread can be awake by
calling notify and notifyAll while sleeping thread can not be awaken by calling
notify method.
4) wait is normally done on
condition, Thread wait until a condition is true while sleep is just to put
your thread on sleep.
5) wait release lock on object
while waiting while sleep doesn’t release lock while waiting.
Difference between yield and sleep in java
Major difference between yield
and sleep in Java is that yield() method pauses the currently executing thread
temporarily for giving a chance to the remaining waiting threads of the same
priority to execute. If there is no waiting thread or all the waiting threads
have a lower priority then the same thread will continue its execution. The
yielded thread when it will get the chance for execution is decided by the
thread scheduler whose behavior is vendor dependent. Yield method doesn’t
guarantee that current thread will pause or stop but it guarantee that CPU will
be relinquish by current Thread as a result of call to Thread.yield() method in
java.
Sleep method in Java has two
variants one which takes millisecond as sleeping time while other which takes
both mill and nano second for sleeping duration.
sleep(long millis)
or
sleep(long millis,int nanos)
Cause the currently executing
thread to sleep for the specified number of milliseconds plus the specified
number of nanoseconds.
10 points about Thread sleep() method in Java
I have listed down some important
and worth to remember points about Sleep() method of Thread Class in Java:
1) Thread.sleep() method is used
to pause the execution, relinquish the CPU and return it to thread scheduler.
2) Thread.sleep() method is a
static method and always puts current thread on sleep.
3) Java has two variants of sleep
method in Thread class one with one argument which takes milliseconds as
duration for sleep and other method with two arguments one is millisecond and
other is nanosecond.
4) Unlike wait() method in Java,
sleep() method of Thread class doesn't relinquish the lock it has acquired.
5) sleep() method throws
Interrupted Exception if another thread interrupt a sleeping thread in java.
6) With sleep() in Java its not
guaranteed that when sleeping thread woke up it will definitely get CPU,
instead it will go to Runnable state and fight for CPU with other thread.
7) There is a misconception about
sleep method in Java that calling t.sleep() will put Thread "t" into
sleeping state, that's not true because Thread.sleep method is a static method
it always put current thread into Sleeping state and not thread "t".
That’s all on Sleep method in
Java. We have seen difference between sleep and wait along with sleep and yield
in Java. In Summary just keep in mind that both sleep() and yield() operate on
current thread.
283. Difference between Vector and ArrayList in
Java
Ans. 1) Vector and ArrayList are
index based and backed up by an array internally.
2) Both ArrayList and Vector
maintains the insertion order of element. Means you can assume that you will
get the object in the order you have inserted if you iterate over ArrayList or
Vector.
3) Both iterator and ListIterator
returned by ArrayList and Vector are fail-fast.
Key Differences between Vector and ArrayList in
Java
1) First and foremost difference
is Vector is synchronized and ArrayList is not, what it means is that all the
method which structurally modifies Vector e.g. add () or remove () are
synchronized which makes it thread-safe and allows it to be used safely in a
multi-threaded environment. On the other hand ArrayList methods are not
synchronized thus not suitable for use in multi-threaded environment.
2) ArrayList is faster than
Vector. Since Vector is synchronized it pays price of synchronization which
makes it little slow. On the other hand ArrayList is not synchronized and fast
which makes it obvious choice in a single-threaded access environment. You can
also use ArrayList in a multi-threaded environment if multiple threads are only
reading values from ArrayList.
3) Whenever Vector crossed the
threshold specified it increases itself by value specified in capacityIncrement
field while you can increase size of arrayList by calling ensureCapacity ()
method.
4) Vector can return enumeration
of items it hold by calling elements () method which is not fail-fast as
opposed to iterator and ListIterator returned by ArrayList.
5) Another point worth to
remember is Vector is one of those classes which comes with JDK 1.0 and
initially not part of Collection framework but in later version it's been
re-factored to implement List interface so that it could become part of
collection framework
Conclusion is use ArrayList
wherever possible and avoids use of Vector until you have no choice.
284. What is FileOutputStream in java?
Ans. Java.io.FileOutputStream is
an output stream for writing data to a File or to a FileDescriptor. Following
are the important points about FileOutputStream:
This class is meant for writing
streams of raw bytes such as image data.
For writing streams of
characters, use FileWriter
public class FileOutputStream
extends OutputStream
Constructors:
1 FileOutputStream(File
file)
This creates a file output stream
to write to the file represented by the specified File object.
2 FileOutputStream(File
file, boolean append)
This creates a file output stream
to write to the file represented by the specified File object.
3 FileOutputStream(FileDescriptor
fdObj)
This creates an output file stream
to write to the specified file descriptor, which represents an existing
connection to an actual file in the file system.
4 FileOutputStream(String
name)
This creates an output file
stream to write to the file with the specified name.
5 FileOutputStream(String
name, boolean append)
This creates an output file
stream to write to the file with the specified name.
Example:
file = new
File("c:/newfile.txt");
fop = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes =
content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
285. What is Constructor in Java?
Ans. Constructor is a block of
code which is executed at the time of Object creation. It is entirely different
than methods. It has same name of class name and it cannot have any return
type.
286. What is this() keyword in core java and
when should we use this() in core java?
Ans. The this keyword is
primarily used in three situations. The first and most common is in setter
methods to disambiguate variable references. The second is when there is a need
to pass the current class instance as an argument to a method of another
object. The third is as a way to call alternate constructors from within a
constructor.
Example of Case 1: Using this to disambiguate variable references.
In Java setter methods, we commonly pass in an argument with the same name as
the private member variable we are attempting to set. We then assign the
argument x to this.x.
public class Foo {
private String name;
// ...
public void setName(String name) {
// This makes it clear that you are
assigning
// the value of the parameter
"name" to the
// instance variable "name".
this.name = name;
}
// ...
}
Example of Case 2: Using this we
can pass current class object through method argument to another object.
Class Foo{
void
callMethod(){
Toy
toy = new Toy();
toy.insertValue(this);
//Here this means Foo current object
}
}
Example of Case 3: Using this to
call alternate constructors. In the comments, trinithis correctly pointed out
another common use of this. When you have multiple constructors for a single
class, you can use this(arg0, arg1, ...) to call another constructor of your
choosing, provided you do so in the first line of your constructor.
class Foo {
public Foo() {
this("Some default value for
bar");
// Additional code here will be
executed
// after the other constructor is done.
}
public Foo(String bar) {
// Do something with bar
}
// ...
}
287. What is java.lang package in Core java?
Ans. For writing any java
program, the most commonly required classes & interfaces are defined in a
separate package called java.lang package. This package is by default available
for every java program, no import statement is required to include this
package.
Few Examples: java.lang.Object
java.lang.Class
java.lang.String
288. What is java.util package in Core Java?
Ans. Java.util package contains
the collections framework, legacy collection classes, event model, date and
time facilities, internationalization, and miscellaneous utility classes.
E.g. java.util.List
java.util.Set
java.util.Date
289. What is java.io package in Core Java?
Ans. Java.io package provides
classes for system input and output through data streams, serialization and the
file system.
E.g. java.io.BufferedReader
java.io.FileReader
290. What is java.math package in Core Java?
Ans. Java.math package provides
classes for performing arbitrary-precision integer arithmetic (BigInteger) and
arbitrary-precision decimal arithmetic (BigDecimal).
E.g. java.math.BigDecimal
java.math.BigInteger.
291. What is Cloneable Interface in Core Java?
Ans. A clone of an object is an object with distinct
identity and equal contents. To define clone, a class must implement Cloneable
interface and must override Object’s clone method with a public modifier. At
this point, it is worth nothing that Cloneable interface does not contain the
clone method, and Object’s clone method is protected.
When the Object class finds that
the object to be cloned isn’t an instance of a class that implements Cloneable
interface, it throws CloneNotSupportedException.
If a class wants to allow clients
to clone it’s instances, it must override Object’s clone method with a public
modifier.
292. What is dead lock in thread?
Ans. A special type of error that
you need to avoid that relates specifically to multitasking is deadlock, which
occurs when two threads have a circular dependency on a pair of synchronized
objects.
For example, suppose one thread
enters the monitor on object X and another thread enters the monitor on object
Y. If the thread in X tries to call any synchronized method on Y, it will block
as expected. However, if the thread in Y, in turn, tries to call any
synchronized method on X, the thread waits forever, because to access X, it
would have to release its own lock on Y so that the first thread could
complete.
293. Difference between wait, notify and
notifyAll in Core Java.
Ans. Methods - wait, notify, and
notifyAll are used for inter thread communication in Java. wait() allows a
thread to check for a condition, and wait if condition doesn't met, while
notify() and notifyAll() method informs waiting thread for rechecking
condition, after changing state of shared variable.
Though Both notify() and
notifyAll() are used to notify waiting
threads, waiting on shared queue object, but there are some subtle difference
between notify and notifyAll in Java. Well, when we use notify(), only one of
the sleeping thread will get notification, while in case of notifyAll(), all
sleeping thread on that object will get notified.
294. What is thread pool in java?
Ans. A thread pool is a group of
threads initially created that waits for jobs and executes them. The idea is to
have the threads always existing, so that we won't have to pay overhead time
for creating them every time. They are appropriate when we know there's a
stream of jobs to process, even though there could be some time when there are
no jobs.
295. What is concurrency in java?
Ans. Concurrency is the ability
to run several programs or several parts of a program in parallel. If a time
consuming task can be performed asynchronously or in parallel, this improve the
throughput and the interactivity of the program.
A modern computer has several
CPU's or several cores within one CPU. The ability to leverage these
multi-cores can be the key for a successful high-volume application.
Concurrency Issues: Threads
have their own call stack, but can also access shared data. Therefore you have
two basic problems, visibility and access problems.
A visibility problem occurs if
thread A reads shared data which is later changed by thread B and thread A is
unaware of this change.
An access problem can occur if
several thread access and change the same shared data at the same time.
Visibility and access problem can
lead to
·
Liveness
failure: The program does not react anymore due to problems in the
concurrent access of data, e.g. deadlocks.
·
Safety
failure: The program creates incorrect data.
No comments:
Post a Comment