Вы находитесь на странице: 1из 14

Question

OOPS
Can we declare main methid as final?
What is the difference between instanceof operator and isInstance() method in
Java?

Can we declare class private ?

Polymorphism
Can we override a non-static method as static in Java?

Can we change the return type of overriding method from Number type to Integer
type?
How do compiler differentiate overloaded methods from duplicate methods?

In MyClass , there is a method called myMethod with four different overloaded


forms. All four different forms have different visibility ( private, protected, public
and default). Is myMethod properly overloaded?
If a method throws NullPointerException in super class, can we override it with a
method which throws RuntimeException?
Collections
Can we use any class as Map key?

How HashSet store elements?

What are differences between Collection and Collections in java?

How sort method of Collections class works internally?

Why doesn't Collection implement Cloneable and Serializable?

How to avoid ConcurrentModificationException while iterating a collection?

Inheritance
You know that all classes in java are inherited from java.lang.Object class. Are
interfaces also inherited from Object class.?

Java Garbage Collec


Can an unreachable object become reachable again?

Strings
What are wrapper classes? Is String a wrapper class ?

Which is the final class in these three classes String, StringBuffer and
StringBuilder?

Exception Handli
Is it necessary that each try block must be followed by a catch block?
Is there a case when finally will not be executed?
Java I/O
What is the difference between write(100) and print(100) of PrintWriter class?
Why does serialization NOT save the value of static class attributes? Why static
variables are not serialized?

How to Serialize a collection in java? How to serialize a ArrayList, Hashmap or


Hashset object in Java?

Java Enums

Design patterns
What are the rules for creating Sngleton class
Can you replace Singleton with Static Class in Java?
Packages
Static import

Can I import same package/class twice? Will the JVM load the package twice at
runtime?
Can you instantiate Math class?

Threads
When to use Runnable and Thread?

What happens when an exception occurs in Thread

How to share data between threads

int i=1;
float f =2.0f;
i += f; //ok, the cast is done automatically by the cpmpiler
I = I + f; //error

package com.instanceofjava;

public class B{

B b= new B();

public int show(){


return (true ? null : 0);
}

public static void main(String[] args) {

B b= new B();
b.show();
}

}
Output:
Exception in thread "main" java.lang.StackOverflowError
at com.instanceofjava.B.<init>(B.java:3)
at com.instanceofjava.B.<init>(B.java:5)
at com.instanceofjava.B.<init>(B.java:5)

package com.instanceofjava;
class A
{
void method(int i)
{
}
}
class B extends A
{
@Override
void method(Integer i)
{
}
}

What is the difference between volatile and Atomic variable ?

How can we transpose a table using SQL

How to generate row number in SQL Without ROWNUM

Write a program to find the missing number from the list of sorted numbers from
1N with less complexity

Answer
OOPS
Yes.

1. Both isInstance() method and instanceof operator (type comparison operator) are used to check
if an object is of a particular class or interface type
2. The right-hand-operand of instanceof operator must be evaluated to a type (class or interface),
which is known at compile time.
3. There may be chances when you don't know the type name at compile time and you want to
pass it as an argument that will be resolved at run time.
4. In those circumstances you won't be able to use instanceof operator because instanceof does
not work for types evaluated at run time.
5. The isInstance() method, which is dynamic equivalent of the Java language instanceof operator
does type checking at run time.
6. The public boolean isInstance(Object obj) method determines if the specified Object is
assignment-compatible with the object represented by this Class. This method returns true if the
specified Object argument is non-null and can be casted to the reference type represented by this
Class object without raising a ClassCastException. It returns false otherwise.
A class can be marked by the "private" access specifier only
if its a nested member of another class.
Top level classes cannot be marked as "private". Hence you
can have private classes in a java file but they must be
nested inside another class.

Polymorphism
No, its not possible to define a non-static method of same name as static method in parent class,
its compile time error in Java. See here to learn more about overriding static method in Java.
Yes. You can change as Integer is a sub class of Number type.

Compiler uses method signature to check whether the method is overloaded or duplicated.
Duplicate methods will have same method signatures i.e same name, same number of arguments
and same types of arguments. Overloaded methods will also have same name but differ in number
of arguments or else types of arguments.
Yes. Compiler checks only method signature for overloading of methods not the visibility of
methods.

you can very well throw super class of RuntimeException in overridden method but you can not do
same if its checked Exception.
Collections

You must know that HashMap store key-value pairs, with one condition i.e. keys will be unique.
HashSet uses Maps this feature to ensure uniqueness of elements. In HashSet class, a map
declaration is as below:
private transient HashMap<E,Object> map;
//This is added as value for each key
private static final Object PRESENT = new Object();
java.util.Collection is the root interface in the hierarchy of Java Collection framework.
The JDK does not provide any classes which directly implements java.util.Collection interface, but
it provides classes such as ArrayList, LinkedList, vector, HashSet, EnumSet, LinkedHashSet,
TreeSet, CopyOnWriteArrayList, CopyOnWriteArraySet, ConcurrentSkipListSet which implements
more specific subinterfaces like Set and List in java.
java.util.Collections is a utility class which consists of static methods that operate on or return
Collection in java.
java.util.Collections provides method like >
reverse method for reversing List in java.
shuffle method for shuffling elements of List in java.
unmodifiableCollection, unmodifiableSet, unmodifiableList, unmodifiableMap methods for making
List, Set and Map unmodifiable in java.
min method to return smallest element in Collection in java.
max method to return smallest element in Collection.
sort method for sorting List.
synchronizedCollection, synchronizedSet, synchronizedList, synchronizedMap methods for
synchronizing List, Set and Map respectively in java.

Collections.sort internally calls Arrays.sort,


Arrays.Sort() internally uses Merge Sort.
If number of elements is less than 7 then Insertion Sort is used rather than Merge Sort. (because in
case elements are less than 7 it offers better time complexity)
Collection is an interface that specifies a group of objects known as elements. The details of how
the group of elements is maintained is left up to the concrete implementations of Collection. For
example, some Collection implementations like List allow duplicate elements whereas other
implementations like Set don't. A lot of the Collection implementations have a public clone
method. However, it does't really make sense to include it in all implementations of Collection.
This is because Collection is an abstract representation. What matters is the implementation. The
semantics and the implications of either cloning or serializing come into play when dealing with
the actual implementation; that is, the concrete implementation should decide how it should be
cloned or serialized, or even if it can be cloned or serialized. In some cases, depending on what
the actual backing-implementation is, cloning and serialization may not make much sense. So
mandating cloning and serialization in all implementations is actually less flexible and more
restrictive. The specific implementation should make the decision as to whether it can be cloned
or serialized.

You should first try to find another alternative iterator which are fail-safe. For example if you are
using List and you can use ListIterator. If it is legacy collection, you can use enumeration.
If above options are not possible then you can use one of three changes:
If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList
classes. It is the recommended approach.
You can convert the list to an array and then iterate on the array.
You can lock the list while iterating by putting it in a synchronized block.

Inheritance
No, only classes in java are inherited from Object class. Interfaces in java are not inherited from
Object class. But, classes which implement interfaces are inherited from Object class.

Java Garbage Collection


Yes, an unreachable object may become reachable again.This
happens when the object's finalize() method is invoked and
the object performs an operation which causes it to become
accessible to reachable objects.

Strings
a (primitive) wrapper class in Java is one of those eight classes that wrap a (=one) primitive value.
String wraps a char[] so according to this it is not a (primitive) wrapper class.
String is not designed to wrap or decorate a character array. String has been designed to model a
string, a character sequence and the current implementation uses an internal char[]
All three are final

Exception Handling
It is not necessary that each try block must be followed by a catch block. It should be followed by
either a catch block or finally block. And whatever exceptions are likey to be thrown should be
declared
inexits
the throws
clause of
method.a fatal eror that causes the process to abort.
If program
System.exit()
or the
by causing
Java I/O
n the case of write(100) the corresponding character d will be written in to the file where as
print(100) is written int value 100.
The Java variables declared as static are not considered part of the state of an object since they
are shared by all instances of that class. Saving static variables with each serialized object would
have following problems
It will make redundant copy of same variable in multiple objects which makes it in-efficient.
The static variable can be modified by any object and a serialized copy would be stale or not in

All standard implementations of collections List, Set and Map interface already implement
java.io.Serializable. All the commonly used collection classes like java.util.ArrayList,
java.util.Vector, java.util.Hashmap, java.util.Hashtable, java.util.HashSet, java.util.TreeSet do
implement Serializable. This means you do not really need to write anything specific to serialize
collection objects. However you should keep following things in mind before you serialize a
collection object - Make sure all the objects added in collection are Serializable. - Serializing the
collection can be costly therefore make sure you serialize only required data isntead of serializing

Java Enums

Design patterns

Packages
By using static imports, we can import the static members from a class rather than the classes
from a given package. For example, Thread class has static sleep method, below example gives an
idea: import static java.lang.Thread; public class MyStaticImportTest { public static void
main(String[] a) { try{ sleep(100); } catch(Exception ex){ } } } - See more at:
http://www.java2novice.com/java_interview_questions/java-static-import/#sthash.1ECg7rjl.dpuf
One can import the same package or same class multiple times. Neither compiler nor JVM
complains anything about it. And the JVM will internally load the class only once no matter how
many
times you
import the same
class.
No. It cannot
be instantited.
The class
is final and its constructor is private. But all the methods are
static, so we can use them without instantiating the Math class.
Threads
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.
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.
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.
by extending Thread, each of your threads has a unique object associated with it, whereas
implementing Runnable, many threads can share the same object instance.
A class that implements Runnable is not a thread and just a class.For a Runnable to become a
Thread, You need to create an instance of Thread and passing itself in as the target.

When an uncaught exception occurs, the JVM does the following:


it calls a special private method, dispatchUncaughtException(), on the Thread class in which the
exception occurs;
it then terminates the thread in which the exception occurred1.
We are talking about unchecked exceptions thrown from Thread.run method. By default, you will
get sth like this in system error:
Exception in thread "Thread-0" java.lang.RuntimeException
at Main$1.run(Main.java:11)
at java.lang.Thread.run(Thread.java:619)
This is the result of printStackTrace for unhandled exceptions. To handle it, you can add your own
UncaughtExceptionHandler:
Thread t = new Thread(new Runnable(){
public void run() {
throw new RuntimeException();
}
});
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("exception " + e + " from thread " + t);
}
});
t.start();
To set handler for all threads use a static method Thread.setDefaultUncaughtExceptionHandler.

use a BlockingQueue for this. You define a single BlockingQueue such as the
LinkedBlockingQueue. Your listener class then calls queue.take() which will wait for your server to
call queue.put(). It leaves all of the synchronization, waits, notifies, etc. to the Java class instead of
your own code.

The compound assognment operators automatically include cast operations in their behaviors.

Exaplanation:
Whenever we create the object of any class constructor will be called first and memory allocated
for all non static variables
Here B b= new B(); variable is object and assigned to new object of same class
B b= new B(); statement leads to recursive execution of constructor will create infinite objects so
at run time an exception will be raised
Exception in thread "main" java.lang.StackOverflowError
The common cause for a stack overflow exception is a bad recursive call. Typically this is caused
when your recursive functions doesn't have the correct termination condition
Pasted from <http://www.instanceofjava.com/2015/05/10-tricky-core-java-interview-coding.html>

1. Compile time Error:The method method(Integer) of type B must override or implement a


supertype method
Pasted from <http://www.instanceofjava.com/2015/05/10-tricky-core-java-interview-coding.html>

Method 1 -> Using DECODE function


Method 2 -> Using CASE statement
Method 3 -> Using PIVOT Operator
Method 4 -> Using WITH clause and PIVOT Operator
Method 5 -> Using WITH clause and Sub-query
Method 6 -> Using Multiple Joins
http://www.aliencoders.org/content/convert-rows-columns-or-transpose-rows-columns-oracle-sql/
SELECT name, sal, (SELECT COUNT(*) FROM EMPLOYEE i WHERE o.name >= i.name) row_num
FROM EMPLOYEE o
order by row_num
https://dwbi.org/database/sql/72-top-20-sql-interview-questions-with-answers

n (n+1)/2

Вам также может понравиться