Core Java
1)is-a and has-a relationship implementation in Core Java
Ans:About inheritance and composition.
2)How polymorphism is achieved in Core Java
Ans:Static binding and dynamic binding
3)If 2 different threads hit 2 different synchronized methods in an object at the same time will they both continue?
Ans:No. Only one method can acquire the lock.
4)Given a Collection of Objects(ex: Employees), how can we sort them based on various properties of that object?
Ans: Comparator
What are the methods that a class should override if that class object is used as a key in a HashMap? and Why?
Ans:Equals and hashCode for hashing technique
5)What will be the output for String “B”, “C”, “A”, “F”, “D” if we use hashset, linkedset, treeset?
6)There are 2 interfaces:
I1
{
A=10;
}
I2
{
A=10;
}
Class C implements I1, I2
{
System out.println(“” +A);
}
What will be the output of A?
Ans: It will not compile.
7)About exception hierarchy? What are the different ways?
Ans:Refer the link below:
http://www.tutorialspoint.com/java/java_exceptions.htm
8)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.
9)What’s the difference between an interface and an abstract class?
Ans:Interface is similar to a class which may contain method’s signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a) Declaring methods that one or more classes are expected to implement b) Capturing similarities between unrelated classes without forcing a class relationship. c) Determining an object’s programming interface without revealing the actual body of the class.
An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.
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 inheritances. On the other hand, you can implement multiple interfaces in your class.
10)When should I use abstract classes and when should I use interfaces?
Ans:
Use Interfaces when…
11)What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
Ans:You do not need to specify any access level, and Java will use a default package access level.
12)What is a reflection package?-
Ans:java. lang. reflect package has the ability to analyze itself in runtime. Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipluate at run time.This is supported using Reflection API with built-in classes like Class,Method,Fields,Constructors,etc.,
13)What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?
Ans:Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
14)What is synchronization?
Ans:Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.
15)When you will synchronize a piece of your code?
Ans:When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
16)What is the difference between set and list?
Ans:Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.
17)What is serialization and deserialization?
Ans:Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
18)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.
19)What is the difference between checked and Unchecked Exceptions in Java ?
Ans: All predefined exceptions in Java are either a checked exception or an unchecked exception. Checked exceptions must be caught using try .. catch() block or we should throw the exception using throws clause. If you dont, compilation of program will fail.
Java Exception Hierarchy +--------+ | Object | +--------+ | | +-----------+ | Throwable | +-----------+ / \ / \ +-------+ +-----------+ | Error | | Exception | +-------+ +-----------+ / | \ / | \ \________/ \______/ \ +------------------+ unchecked checked | RuntimeException | +------------------+ / | | \ \_________________/ unchecked
20) What are the static fields & static Methods ?
Ans: If a field or method defined as a static, there is only one copy for entire class, rather than one copy for each instance of class. static method cannot accecss non-static field or call non-static method
Example Java Code
static int counter = 0;
A public static field or method can be accessed from outside the class using either the usual notation:
Java-class-object.field-or-method-name
or using the class name instead of the name of the class object:
Java- class-name.field-or-method-name
21)What is the difference b/w Iterator & ListIterator...
Iterator :--- Iterator takes the place of Enumeration in the Java collections framework. One can traverse throughr the the collection with the help of iterator in forward direction only and Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics
ListIterator:--An iterator for lists that allows one to traverse the list in either direction.modify the list during iteration and obtain the iterator's current position in the list. A ListIterator has no current element. its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). In a list of length n there are n+1 valid index values from 0 to n inclusive.
22)What is the difference between Enumeration and Iterator?
Ans:
Enumeration:
Enumeration doesn't have a remove() method
Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects
Iterator
Iterator has a remove() method
Can be abstract, final, native, static, or synchronized
Note: So Enumeration is used whenever we want to make Collection objects as Read-only.
23)Why are Iterators returned by ArrayList called Fail Fast ?
Ans:Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
24) Given a Collection of Objects(ex: Employees), how can we sort them based on various properties of that object? Comparator
What are the methods that a class should override if that class object is used as a key in a HashMap? and Why? equals and hashCode for hasing technique
Answer : Java Comparators and Comparables? What are they? How do we use them? This is a question we received from one of our readers. This article will discuss the java.util.Comparator and java.lang.Comparable in details with a set of sample codes for further clarifications.
What are Java Comparators and Comparables? As both names suggest (and you may have guessed), these are used for comparing objects in Java. Using these concepts; Java objects can be
sorted according to a predefined order.
Two of these concepts can be explained as follows.
Comparable : A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
Comparator : A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.
Do we need to compare objects? The simplest answer is yes. When there is a list of objects, ordering these objects into different orders becomes a must in some situations. For example; think of displaying a list of employee objects in a web page. Generally employees may be displayed by sorting them using the employee id. Also there will be requirements to sort them according to the name or age as well. In these situations both these (above defined) concepts will become handy.
How to use these? There are two interfaces in Java to support these concepts, and each of these has one method to be implemented by user.
Those are;
java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.
The above explained Employee example is a good candidate for explaining these two concepts. First we’ll write a simple Java bean to represent the Employee.
public class Employee {
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
// set values on attributes
}
// getters & setters
}
Next we’ll create a list of Employees for using in different sorting requirements. Employees are added to a List without any specific order in the following class.
import java.util.*;
public class Util {
public static List<Employee> getEmployees() {
List<Employee> col = new ArrayList<Employee>();
col.add(new Employee(5, "Frank", 28));
col.add(new Employee(1, "Jorge", 19));
col.add(new Employee(6, "Bill", 34));
col.add(new Employee(3, "Michel", 10));
col.add(new Employee(7, "Simpson", 8));
col.add(new Employee(4, "Clerk",16 ));
col.add(new Employee(8, "Lee", 40));
col.add(new Employee(2, "Mark", 30));
return col;
}
}
Sorting in natural ordering Employee’s natural ordering would be done according to the employee id. For that, above Employee class must be altered to add the comparing ability as follows.
public class Employee implements Comparable<Employee> {
private int empId;
private String name;
private int age;
/**
* Compare a given Employee with this object.
* If employee id of this object is
* greater than the received object,
* then this object is greater than the other.
*/
public int compareTo(Employee o) {
return this.empId - o.empId ;
}
….
}
The new compareTo() method does the trick of implementing the natural ordering of the instances. So if a collection of Employee objects is sorted using Collections.sort(List) method; sorting happens according to the ordering done inside this method.
We’ll write a class to test this natural ordering mechanism. Following class use the Collections.sort(List) method to sort the given list in natural order.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
Collections.sort(coll); // sort method
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
Run the above class and examine the output. It will be as follows. As you can see, the list is sorted correctly using the employee id. As empId is an int value, the employee instances are ordered so that the int values ordered from 1 to 8.
EmpId Name Age
1 Jorge 19
2 Mark 30
3 Michel 10
4 Clerk 16
5 Frank 28
6 Bill 34
7 Simp 8
8 Lee 40
Sorting by other fields If we need to sort using other fields of the employee, we’ll have to change the Employee class’s compareTo() method to use those fields. But then we’ll loose this empId based sorting mechanism. This is not a good alternative if we need to sort using different fields at different occasions. But no need to worry; Comparator is there to save us.
By writing a class that implements the java.util.Comparator interface, you can sort Employees using any field as you wish even without touching the Employee class itself; Employee class does not need to implement java.lang.Comparable or java.util.Comparator interface.
Sorting by name field Following EmpSortByName class is used to sort Employee instances according to the name field. In this class, inside the compare() method sorting mechanism is implemented. In compare() method we get two Employee instances and we have to return which object is greater.
public class EmpSortByName implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}
Watch out: Here, String class’s compareTo() method is used in comparing the name fields (which are Strings).
Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how the EmpSortByName comparator is used inside sort method.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll, new EmpSortByName());
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
Now the result would be as follows. Check whether the employees are sorted correctly by the name String field. You’ll see that these are sorted alphabetically.
EmpId Name Age
6 Bill 34
4 Clerk 16
5 Frank 28
1 Jorge 19
8 Lee 40
2 Mark 30
3 Michel 10
7 Simp 8
Sorting by empId field Even the ordering by empId (previously done using Comparable) can be implemented using Comparator; following class
does that.
public class EmpSortByEmpId implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getEmpId() - o2.getEmpId();
}
}
25) How do you decide when to use HashMap and when to use TreeMap ?
Ans: For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
26)Difference between HashSet and TreeSet
HashSet
HashSet is under set interface i.e. it does not guarantee for either sorted order or sequence order.
We can add any type of elements to hash set.
TreeSet
TreeSet is under set i.e. it provides elements in a sorted order (acceding order).
We can add only similar types of elements to tree set.
27)What are the differences between method overloading and method overriding?
Ans:
Overloaded Method Overridden Method
Arguments Must change Must not change
Return type Can change Can’t change except for covariant returns
Exceptions Can change Can reduce or eliminate. Must not throw new or broader checked exceptions
Access Can change Must not make more restrictive (can be less restrictive)
Invocation Reference type determines which Object type determines which method is selected. overloaded version is selected. Happens at runtime.
Happens at compile time.
28)What is the basic difference between the 2 approaches to exception handling.
1> try catch block and
2> specifying the candidate exceptions in the throws clause?
When should you use which approach?
Ans: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.
29)How do I create a read-only collection?
Ans: The Collections class has six methods to help out here:
• unmodifiableCollection(Collection c)
• unmodifiableList(List list)
• unmodifiableMap(Map m)
• unmodifiableSet(Set s)
• unmodifiableSortedMap(SortedMap m)
• unmodifiableSortedSet(SortedSet s)
If you then get an Iterator from one of these unmodifiable collections, when you call remove() it will throw an UnsupportedOperationException.
30)Which is faster, synchronizing a HashMap or using a Hashtable for thread-safe access?
Ans: Because a synchronized HashMap requires an extra method call, a Hashtable is faster for synchronized access.
31)How to implement collection ordering?
Ans: SortedSet and SortedMap interfaces maintain sorted order. The classes, which implement the Comparable interface, impose natural order. For classes that don’t implement comparable interface, or when one needs even more control over ordering based on multiple attributes, a Comparator interface should be used.
32) How do I properly alphabetize (sort) a list of strings in a language-sensitive manner?
Ans: This is actually outside the scope of the Collections Framework. Instead, it is part of the java.text package with the Collator and CollationKey classes.
The following example demonstrates this capability:
import java.text.*;
import java.util.*;
public class CollatorTest {
public static void main(String args[]) {
Collator collator =
Collator.getInstance();
CollationKey key1 =
collator.getCollationKey("Tom");
CollationKey key2 =
collator.getCollationKey("tom");
CollationKey key3 =
collator.getCollationKey("thom");
CollationKey key4 =
collator.getCollationKey("Thom");
CollationKey key5 =
collator.getCollationKey("Thomas");
Set set = new TreeSet();
set.add(key1);
set.add(key2);
set.add(key3);
set.add(key4);
set.add(key5);
printCollection(set);
}
static private void printCollection(
Collection collection) {
boolean first = true;
Iterator iterator = collection.iterator();
System.out.print("[");
while (iterator.hasNext()) {
if (first) {
first = false;
} else {
System.out.print(", ");
}
CollationKey key =
(CollationKey)iterator.next();
System.out.print(key.getSourceString());
}
System.out.println("]");
}
}
33)In Java, if we insert a return statement inside the try block of a try-catch-finally, will the finally block still get executed?
Ans: Yes. The finally block will be executed even if there is a return statement in the try block.
yes, it will be executed, but if we use System.exit(0) in try block it will never go to finally block.
34) What is Garbage Collection and how to call it explicitly?-
Ans: When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.
35)What are Transient and Volatile Modifiers?-
Ans:
Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized.
Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program
36)What is the difference between String and String Buffer?
Ans: String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.
37)What are three ways in which a thread can enter the waiting state?
Ans: A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
38)Write the Java code to declare any constant (say gravitational constant) and to get its value.
Ans:
Class ABC
{
static final float GRAVITATIONAL_CONSTANT = 9.8;
public void getConstant()
{
system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT);
}
}
39)What's the difference between the == operator and the equals() method? What test does Object.equals() use, and why?
Ans: The == operator would be used, in an object sense, to see if the two objects were actually the same object.
This operator looks at the actually memory address to see if it actually the same object. The equals()
method is used to compare the values of the object respectively. This is used in a higher level to see if the
object values are equal.
Of course the the equals() method would be overloaded in a meaningful way for whatever object that you
were working with.
40)Name four methods every Java class will have.
Ans:
clone()
equals() & hashcode()
getClass()
finalize()
wait() & notify()
toString()
41)What is NullPointerException and how to handle it?
Ans: When an object is not initialized, the default value is null. When the following things happen, the NullPointerException is thrown:
--Calling the instance method of a null object.
--Accessing or modifying the field of a null object.
--Taking the length of a null as if it were an array.
--Accessing or modifying the slots of null as if it were an array.
--Throwing null as if it were a Throwable value.
The NullPointerException is a runtime exception. The best practice is to catch such exception even if it is not required by language design.
42) What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
Ans: The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.
43)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
44)Can there be an abstract class with no abstract methods in it?
Ans: Yes, A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
45)How to convert String to Number in java program?
Ans: The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = “1000″;
int id=Integer.valueOf(numString).intValue();
46)In what different forms Polymorphism exists in Java?
Ans:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
47)Advantages of using string builder compared to String buffer?
Ans: A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
For example, if z refers to a string builder object whose current contents are "start", then the method call z.append("le") would cause the string builder to contain "startle", whereas z.insert(4, "le") would alter the string builder to contain "starlet".
In general, if sb refers to an instance of a StringBuilder, then sb.append(x) has the same effect as sb.insert(sb.length(), x). Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.
Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
48) What's New in Java 1.5?
Generics provide a way to create and use typesafe data structures. This means that no longer do you have to create a List of the basic Objects then typecast every time you pull stuff out! You can declare your list to automatically typecast the stuff inside:
List things = createListOfBorkObjects();
for(Iterator i = things.iterator() ; i.hasNext() ; ) {
Bork item = (Bork)i.next();
//do something useful
}
Simply becomes...
List<Bork> things = createListOfBorkObjects();
for(Iterator<String> i = things.iterator() ; i.hasNext() ; ) {
Bork item = i.next();
//do something useful
}
The Java compiler also protects things from having non-Bork objects inside. If you try to put a String or anything else in, you'll get an error. This essentially means that you can create a list with specific types now instead of just objects. These exist in other classes such as Map which uses two:
Map<String, Bork> myMap = new HashMap<String, Bork>();
That creates a map that uses a String key and a Bork value. This implementation kind of looks like something using templates in C++...
Be careful though! You can create a string iterator that iterates over a list of non-strings that will only become an error at runtime. The compiler doesn't catch this.
Also, sometimes when using a type that can be parameterized, but not specifying the parameter type (in angle brackets) you can get lint warnings. This just means that you haven't provided a specific type, and the current definition of the type is "fuzzy" -- like lint, get it?
2. For/in loop
This is probably one of the coolest new features. I personally hate using iterators--it seems redundant and annoying sometimes. Well, lucky for me there's a way around them now!
So now you can do this:
for(Iterator lineup = list.iterator() ; lineup.hasNext() ; ) {
Object thatThing = lineup.next();
myMonster.eat(thatThing);
}
In a shortened:
for(Object thatThing : list) {
myMonster.eat(thatThing);
}
Much prettier, no? This works with arrays too.
int[] nums = { 1, 2, 3, 4, 5, 6 };
for(int n : nums) {
System.out.println(n);
}
Say you want to get your class to work with this nifty loop. Then, you have to implement Iterable (or extend something that does). This involves telling Iterable what type of things you iterate over. You can define a custom iterator to do something more robust, but for this illustration, I'm just going to grab one out of the list. public class MailBox implements Iterable<MailMessage> {
/** structure storing the messages */
private ArrayList<MailMessage> messages;
//...
/**
* Implemented for Iterable.
*/
public Iterator<MailMessage>() {
return messages.iterator();
}
//...
}
For more detailed information, see Java 1.5 Tiger: A Developer's Notebook[4] or the information on Sun's J2SE 5.0 language documentation.
3 Autoboxing/Unboxing
Integer i = new Integer(4);
int j = i.intValue();
Number n = new Float(3.14159);
Boolean stuff = new Boolean(false);
// stuff before ? must be a boolean (lower case)
System.out.println( stuff.booleanValue() ? "Yep" : "Nope" );
Sick of this? Me too. Do this instead:
Integer i = 4;
int j = i;
Number n = 3.14159f;
Boolean stuff = false;
System.out.println( stuff ? "Yep" : "Nope" );
This is pretty nice. Especially since you can use ++ and other similar operators with the wrapper types now too.
4 Typesafe Enums
Enums are just magic classes to help prevent the methodless-interface antipattern. They let you make classes that will enumerate values, but also keep the types specific. Before, we could simulate enums with a bunch of static final int variables or something. The problem with those is that you could confuse any int with one of the constants. With enumerations, only the values in the enum are valid. For example:
public enum JettStaff {
ADRIAN,
ARIJIT,
BETH,
ERIC,
KATIE,
KATY,
RAJA,
RICH,
SUZANNE
};
JettStaff x = JettStaff.SUZANNE;
Now, it gets even cooler. I don't have to keep track of separate information to store, say the peoples' full names. I can associate them directly, just like in a class! Each of the values of JettStaff are instances of the JettStaff enumeration, so we can define a constructor and a toString() method.
public enum JettStaff {
ADRIAN("Adrian German"),
ARIJIT("Arijit Sengupta"),
BETH("Beth Plale"),
ERIC("Eric Wernert"),
KATIE("Katie A. Siek"),
KATY("Katy Borner"),
RAJA("Raja Sooriamurthi"),
RICH("Rich Kick"),
SUZANNE("Suzanne Menzel");
private String name;
public JettStaff(String n) { this.name = n; }
public String toString() { return this.name; }
}
JettStaff x = JettStaff.SUZANNE;
System.out.println(x);
But wait, it gets cooler! Now you can also give each enumerated value a custom body. Since they're each instances, you could design a toString() method for each:
public enum JettStaff {
ADRIAN("Adrian German") {
public String toString() {
return name + " ([email protected])";
}
},
ARJIT("Arjit Sengupta") {
public String toString() {
return name + " ([email protected])";
}
},
// and on for the rest...
private String name;
public JettStaff(String n) { this.name = n; }
}
JettStaff x = JettStaff.SUZANNE;
System.out.println(x);
Last but not least, enums can extend each other. Imagine that!
5 Varargs
What is your impression of "..."? It's a nice little note that might come in handy. Notice how when you pass arguments from the command line ...
C:/> java MyProg a b c
You gave me 3 args! Yay.
...
... you don't have to pass an array of stuff. The runtime automatically converts the arguments into an array of strings. You can do that now in all of your methods! For example, instead of doing this:
public class VarArgs {
public static void main(String[] args) {
String[] newArgs = {"a", "b", "c"};
vaMethod(newArgs);
}
public void vaMethod(String[] args) {
System.out.println("You gave me " + args.length + " args! Yay.");
}
}
You can declare it more easily, and not have to construct the array ahead of time:
public class VarArgs {
public static void main(String[] args) {
vaMethod("a", "b", "c");
}
public void vaMethod(String... args) {
System.out.println("You gave me " + args.length + " args! Yay.");
}
}
Notice that when you use the ... syntax, it automatically treats that parameter as an array but you don't have to pass it in that way. Nifty. Let's add one of those for/in loops:
public class VarArgs {
public static void main(String[] args) {
vaMethod("a", "b", "c");
}
public void vaMethod(String... args) {
for(String s : args)
System.out.println(s);
}
}
6 Static Import
Remember making all those interfaces that just have constants in them?
import java.awt.*;
public interface BouncingBallConstants {
public static final Color BACK_COLOR = Color.WHITE;
public static final Color BALL_COLOR = Color.BLUE;
public static final int BALL_SIZE = 50;
}
Scrap that. Put these into a REAL class and then just import the static members from all the other ones using import static <Package or Class>;. This addition is pretty straightforward, and it helps prevent bloat and the "methodless interface" design antipattern.
7 Annotations (Metadata) Now for the weirdest part. Annotations are not really something that will affect how you program in Java, unless you need to associate some sort of metadata or annotations with classes, methods, variables, etc.
So what are annotations anyway? That's a good question. They provide a little extra information about the classes you write, and a class can use the Reflection package later to read the annotations. These are useful because you can attach extra information to your code that may determine how it is used or maybe if it is used at all.
For example, in J2SE 5, you can declare your intent to override a method like toString() in one of your classes:
public class MyClass extends Object {
@Override
public String toString() {
return "My overridden method!";
}
}
In the above example, we declare that we will override the immediately following toString() method. So the compiler looks in our superclass (Object) for the same metho and makes sure it exists. If for some reason we had overloaded toString() by declaring it with different parameters and maybe return type, then the compiler would throw an error saying we didn't override correctly. This is really useful if you want to make sure you override a method as opposed to simply overloading it.
Of course you can define your own annotations. They're basically like interfaces, but they can contain values. An example annotation looks like:
public @interface Conference {
String what();
String when();
String location();
}
This annotation declares three members: what, when, location and sets them up to have "getters" and "setters" automatically! That means each @Conference annotation has those three fields associated with it, and I don't have to define the accessor and mutator methods to set them up (see the next code listing). If I define this annotation like this, I can use it to mark code that I use for the Jett conference:
@Conference(what="JETT",
when="November 2004",
location="IUB")
public class MyMagicJettClass {
//...
}
And now the @Conference type of data is associated with my class. Later on, I could write an analyzer that goes through all of my code and lets me know which classes were used at conferences as well as which conferences they were used at and when. This specific example doesn't have any effect on the way MyMagicJettClass operates.
So the annotations require two-fold cooperation: the programmer must properly annotate her code to provide adequate metadata needed and other developers who will want to know this metadata must know how to extract it using the Java Reflection package. That's a whole hours-long session on how to extract them, so I'm not going to go into depth here.
Where are they useful? Say you are working with RMI (Remote Method Invocation) and you don't want all of your methods available remotely. You could annotate the remotable ones with a @Remote annotation, then whatever serves up the remote access can only allow those to be remotely accessed. There are a ton of great uses for these, and they are fully extendable (you can annotate annotations)!
49)How to schedule a job in Java?
Ans: When there is a need for schedule an event to occur at a certain time, or the event needs to be executed repeated at a certain interval, the TimerTask and TImer class are designed for this.
A TimerTask is “A task that can be scheduled for one-time or repeated execution by a Timer.” A TimerTask is similar to a Thread. Both classes implement the Runable interface. Thus both classes need to implement the public void run() method. The code inside the run() method is will be executed by a thread. The TimerTask has two more methods besides the run() method. They are the public boolean cancel() and the public long scheduledExecutionTime(). The cancel() method cancels the not yet executed task. The scheduledExecautionTime() returns the most recent actual execution time of this task.
A Timer is facility to schedule TimerTasks. "Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. Timer tasks should complete quickly." The constructor of the Timer class starts the background thread.
An simple example here:
public class SimpleTimer {
class Checker extends TimerTask {
public static final int DELAY = 60 * 1000;
public void run() {
doCheck();
}
private void doCheck() {
System.out.println("Current time is: " + System.currentTimeMillis());
}
}
pubic static void main (String … argv) {
Timer timer = new Timer(); // start the timer thread
timer.schedule(Checker(), Checker.DELAY,
Checker.DELAY); // calls the Checker's run() method after one minute and repeat every one minute.
}
}
For a gracefully shutdown, the Timer's cancel() method should be called. The cancel() method "Terminates this timer, discarding any currently scheduled tasks".
50) About NoClassDefFoundException and ClassNotFoundException difference?
Ans: NoClassDefFoundException is thrown if a class is referenced with Java’s “new” operator (i.e. static loading)
but the runtime system cannot find the referenced class.
Ex: Classes are statically loaded with Java’s “new” operator.
class MyClass {
public static void main(String args[]) {
Car c = new Car();
}
}
A ClassNotFoundException is thrown when an application tries to load in a class through its string name using the following methods but no definition for the class with the specified name could be found:
The forName(..) method in class - Class.
The findSystemClass(..) method in class - ClassLoader.
The loadClass(..) method in class - ClassLoader.
Ex: Class.forName (String className);
51)How do you sort an ArrayList (or any list) of user-defined objects ?
Ans: Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).
52)What is the Comparable interface ?
Ans: The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
interface Comparable<T>
where T is the name of the type parameter.
All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be negative.
If object1 > object2: The value of i returned will be positive.
If object1 = object2: The value of i returned will be zero.
53)With Java, deleting non numeric characters (letters, symbols etc) from a string to produce a numbers-only String is a common requirement in web applications, as application users are used to insert numeric values with non-numeric characters.
For example a phone number will be entered with (-) characters like;
650-212-5710.
A price value may be entered with (,) characters like;
12,500.00
In Java, java.lang.Character class has a method; isDigit() which can be used to identify whether a character is a digit or not. Following method can be used for extracting a numbers-only string.
public static String getOnlyNumerics(String str) {
if (str == null) {
return null;
}
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < str.length() ; i++) {
c = str.charAt(i);
if (Character.isDigit(c)) {
strBuff.append(c);
}
}
return strBuff.toString();
}
Calling above method with any String will return a numbers-only string.
54) Is emp.setName("XYZ") valid when emp is a final variable with declaration : final Employee emp=new Employee()?
Ans:Valid as we are not making emp to point to some other object.
55) What is ConcurrentModificationException and explain.
Ans:Removal of an item through Iterator when the list is accessed by a different iterator.
56)Certain Customers buy kindle on day one and certain customers buy kindle on day two. Design an algorithm(optimum) to find customers who bought on both days. Each customer has a unique ID (Integer). (I forgot to consider case of duplicates,until she reminded), You need to write complete code(NOT just pseudo code within given time and read it out)”
Or
In an array 1-100 many numbers are duplicates, how do you find it?
Ans:We need a little more information about the data. Are there two lists of customers (one list with people that bought a kindle on day one, and another that bought a kindle on day two, for example)? Or are we given a list of customers, from which we can determine which days they bought kindles?
If we are given two lists of customer IDs, each representing customers that bought kindles on each day, we can put all of the customers in the first list into a hashtable using the customer ID as a key and setting the value to null, and then iterate through the second list, and check if the customer ID already exists in the hash table. If it does, then we can update the value of the respective key in the hash table to a non-null value, and return the list of those keys. This is O(n) time.
57)Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.
Ans:Here is a quick tip to solve this programming question: put the elements of the second array in the hash table and for every element of the first array, check whether it’s present in the hash or not, O/P all those elements from the first array that are not present in the hash table
58) "What is deadlock ?"
Ans:answer is simple , when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multithreading.
59)How do you detect deadlock ?
Ans:though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful.
other way is to find it when you actually get locked while running the application , try to take thread dump , in linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object.
other way is to use jconsole , jconsole will show you exactly which threads are get locked and on which object.
once you answer this , they may ask you to write code which will result in deadlock ?
here is one of my version
public void method1(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
}
}
}
public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock becuase if thead 1 aquires lock on Sting object while executing method1() and thread 2 aquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen.
now interviewer comes to final part , one of the most important in my view , How to fix deadlock ?
if you have looked above code carefully you may have figured out that real reason for deadlock is not multiple threads but the way they access lock , if you provide an ordered access then problem will be resolved , here is
the fixed version.
public void method1(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
Now there would not be any deadlock because both method is accessing lock on Integer and String object in same order . so if thead A aquires lock on Integer object , thread B will not proceed until thread A releases Integer lock , same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further.
60)What is immutable object? Can you write immutable object?
Ans: You need to make class final and all its member final so that once objects gets created no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.
61) What is the difference between creating String as new () and literal?
Ans:When we create string with new () it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.
62)How to identify a given positive decimal number as even/odd without using % or / operator ?
Ans:A plain trap, even for those experienced people. You may be very good at coding,but if you questioning how on earth you could solve this problem.Then here is a solution. If you remember the good old days of our primary school then the solution is easy,"division is a matter of iterative subtraction".
public class TestEvenOdd {
02.
03. public static void main(String arg[]){
04.
05. int num=6;
06.
07. int result=num;
08.
09. while(result>=2){
10.
11. result=result-2;
12.
13. }
14.
15. if(result==1){
16.
17. System.out.println("The number is odd");
18.
19. }else{
20.
21. System.out.print("The number is even");
22.
23. }
24.
25. }
26.
27. }
63) About assertions in Java
64) What is the Java heap, and what is the stack? (Hint: dynamic, program thread execution.)
65) Why does garbage collection occur and when can it occur? (Hint: To recover memory, as heap gets full.)
66) If I have a circular reference of objects, but I no longer reference any of them from any executing thread, will these cause garbage collection problems? (Hint: no)
67) What language features are available to allow shared access to data in a multi-threading environment? (Hint: Synchronized block,Synchronized method,wait, notify)
68) What is the difference between synchronized method and synchronized block? (Hint:Block on subset of data. Smaller code segment).
69) What Java language features would you use to implement a producer (one thread) and a consumer (another thread) passing data via a stack? (Hint: wait, notify)
1)is-a and has-a relationship implementation in Core Java
Ans:About inheritance and composition.
2)How polymorphism is achieved in Core Java
Ans:Static binding and dynamic binding
3)If 2 different threads hit 2 different synchronized methods in an object at the same time will they both continue?
Ans:No. Only one method can acquire the lock.
4)Given a Collection of Objects(ex: Employees), how can we sort them based on various properties of that object?
Ans: Comparator
What are the methods that a class should override if that class object is used as a key in a HashMap? and Why?
Ans:Equals and hashCode for hashing technique
5)What will be the output for String “B”, “C”, “A”, “F”, “D” if we use hashset, linkedset, treeset?
6)There are 2 interfaces:
I1
{
A=10;
}
I2
{
A=10;
}
Class C implements I1, I2
{
System out.println(“” +A);
}
What will be the output of A?
Ans: It will not compile.
7)About exception hierarchy? What are the different ways?
Ans:Refer the link below:
http://www.tutorialspoint.com/java/java_exceptions.htm
8)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.
9)What’s the difference between an interface and an abstract class?
Ans:Interface is similar to a class which may contain method’s signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a) Declaring methods that one or more classes are expected to implement b) Capturing similarities between unrelated classes without forcing a class relationship. c) Determining an object’s programming interface without revealing the actual body of the class.
An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.
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 inheritances. On the other hand, you can implement multiple interfaces in your class.
10)When should I use abstract classes and when should I use interfaces?
Ans:
Use Interfaces when…
- You see that something in your design will change frequently.
- If various implementations only share method signatures then it is better to use Interfaces.
- you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
- If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
- When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
- Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
11)What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
Ans:You do not need to specify any access level, and Java will use a default package access level.
12)What is a reflection package?-
Ans:java. lang. reflect package has the ability to analyze itself in runtime. Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipluate at run time.This is supported using Reflection API with built-in classes like Class,Method,Fields,Constructors,etc.,
13)What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?
Ans:Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
14)What is synchronization?
Ans:Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.
15)When you will synchronize a piece of your code?
Ans:When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
16)What is the difference between set and list?
Ans:Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.
17)What is serialization and deserialization?
Ans:Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
18)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.
19)What is the difference between checked and Unchecked Exceptions in Java ?
Ans: All predefined exceptions in Java are either a checked exception or an unchecked exception. Checked exceptions must be caught using try .. catch() block or we should throw the exception using throws clause. If you dont, compilation of program will fail.
Java Exception Hierarchy +--------+ | Object | +--------+ | | +-----------+ | Throwable | +-----------+ / \ / \ +-------+ +-----------+ | Error | | Exception | +-------+ +-----------+ / | \ / | \ \________/ \______/ \ +------------------+ unchecked checked | RuntimeException | +------------------+ / | | \ \_________________/ unchecked
20) What are the static fields & static Methods ?
Ans: If a field or method defined as a static, there is only one copy for entire class, rather than one copy for each instance of class. static method cannot accecss non-static field or call non-static method
Example Java Code
static int counter = 0;
A public static field or method can be accessed from outside the class using either the usual notation:
Java-class-object.field-or-method-name
or using the class name instead of the name of the class object:
Java- class-name.field-or-method-name
21)What is the difference b/w Iterator & ListIterator...
Iterator :--- Iterator takes the place of Enumeration in the Java collections framework. One can traverse throughr the the collection with the help of iterator in forward direction only and Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics
ListIterator:--An iterator for lists that allows one to traverse the list in either direction.modify the list during iteration and obtain the iterator's current position in the list. A ListIterator has no current element. its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). In a list of length n there are n+1 valid index values from 0 to n inclusive.
22)What is the difference between Enumeration and Iterator?
Ans:
Enumeration:
Enumeration doesn't have a remove() method
Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects
Iterator
Iterator has a remove() method
Can be abstract, final, native, static, or synchronized
Note: So Enumeration is used whenever we want to make Collection objects as Read-only.
23)Why are Iterators returned by ArrayList called Fail Fast ?
Ans:Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
24) Given a Collection of Objects(ex: Employees), how can we sort them based on various properties of that object? Comparator
What are the methods that a class should override if that class object is used as a key in a HashMap? and Why? equals and hashCode for hasing technique
Answer : Java Comparators and Comparables? What are they? How do we use them? This is a question we received from one of our readers. This article will discuss the java.util.Comparator and java.lang.Comparable in details with a set of sample codes for further clarifications.
What are Java Comparators and Comparables? As both names suggest (and you may have guessed), these are used for comparing objects in Java. Using these concepts; Java objects can be
sorted according to a predefined order.
Two of these concepts can be explained as follows.
Comparable : A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
Comparator : A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.
Do we need to compare objects? The simplest answer is yes. When there is a list of objects, ordering these objects into different orders becomes a must in some situations. For example; think of displaying a list of employee objects in a web page. Generally employees may be displayed by sorting them using the employee id. Also there will be requirements to sort them according to the name or age as well. In these situations both these (above defined) concepts will become handy.
How to use these? There are two interfaces in Java to support these concepts, and each of these has one method to be implemented by user.
Those are;
java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.
The above explained Employee example is a good candidate for explaining these two concepts. First we’ll write a simple Java bean to represent the Employee.
public class Employee {
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
// set values on attributes
}
// getters & setters
}
Next we’ll create a list of Employees for using in different sorting requirements. Employees are added to a List without any specific order in the following class.
import java.util.*;
public class Util {
public static List<Employee> getEmployees() {
List<Employee> col = new ArrayList<Employee>();
col.add(new Employee(5, "Frank", 28));
col.add(new Employee(1, "Jorge", 19));
col.add(new Employee(6, "Bill", 34));
col.add(new Employee(3, "Michel", 10));
col.add(new Employee(7, "Simpson", 8));
col.add(new Employee(4, "Clerk",16 ));
col.add(new Employee(8, "Lee", 40));
col.add(new Employee(2, "Mark", 30));
return col;
}
}
Sorting in natural ordering Employee’s natural ordering would be done according to the employee id. For that, above Employee class must be altered to add the comparing ability as follows.
public class Employee implements Comparable<Employee> {
private int empId;
private String name;
private int age;
/**
* Compare a given Employee with this object.
* If employee id of this object is
* greater than the received object,
* then this object is greater than the other.
*/
public int compareTo(Employee o) {
return this.empId - o.empId ;
}
….
}
The new compareTo() method does the trick of implementing the natural ordering of the instances. So if a collection of Employee objects is sorted using Collections.sort(List) method; sorting happens according to the ordering done inside this method.
We’ll write a class to test this natural ordering mechanism. Following class use the Collections.sort(List) method to sort the given list in natural order.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
Collections.sort(coll); // sort method
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
Run the above class and examine the output. It will be as follows. As you can see, the list is sorted correctly using the employee id. As empId is an int value, the employee instances are ordered so that the int values ordered from 1 to 8.
EmpId Name Age
1 Jorge 19
2 Mark 30
3 Michel 10
4 Clerk 16
5 Frank 28
6 Bill 34
7 Simp 8
8 Lee 40
Sorting by other fields If we need to sort using other fields of the employee, we’ll have to change the Employee class’s compareTo() method to use those fields. But then we’ll loose this empId based sorting mechanism. This is not a good alternative if we need to sort using different fields at different occasions. But no need to worry; Comparator is there to save us.
By writing a class that implements the java.util.Comparator interface, you can sort Employees using any field as you wish even without touching the Employee class itself; Employee class does not need to implement java.lang.Comparable or java.util.Comparator interface.
Sorting by name field Following EmpSortByName class is used to sort Employee instances according to the name field. In this class, inside the compare() method sorting mechanism is implemented. In compare() method we get two Employee instances and we have to return which object is greater.
public class EmpSortByName implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}
Watch out: Here, String class’s compareTo() method is used in comparing the name fields (which are Strings).
Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how the EmpSortByName comparator is used inside sort method.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll, new EmpSortByName());
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
Now the result would be as follows. Check whether the employees are sorted correctly by the name String field. You’ll see that these are sorted alphabetically.
EmpId Name Age
6 Bill 34
4 Clerk 16
5 Frank 28
1 Jorge 19
8 Lee 40
2 Mark 30
3 Michel 10
7 Simp 8
Sorting by empId field Even the ordering by empId (previously done using Comparable) can be implemented using Comparator; following class
does that.
public class EmpSortByEmpId implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getEmpId() - o2.getEmpId();
}
}
25) How do you decide when to use HashMap and when to use TreeMap ?
Ans: For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
26)Difference between HashSet and TreeSet
HashSet
HashSet is under set interface i.e. it does not guarantee for either sorted order or sequence order.
We can add any type of elements to hash set.
TreeSet
TreeSet is under set i.e. it provides elements in a sorted order (acceding order).
We can add only similar types of elements to tree set.
27)What are the differences between method overloading and method overriding?
Ans:
Overloaded Method Overridden Method
Arguments Must change Must not change
Return type Can change Can’t change except for covariant returns
Exceptions Can change Can reduce or eliminate. Must not throw new or broader checked exceptions
Access Can change Must not make more restrictive (can be less restrictive)
Invocation Reference type determines which Object type determines which method is selected. overloaded version is selected. Happens at runtime.
Happens at compile time.
28)What is the basic difference between the 2 approaches to exception handling.
1> try catch block and
2> specifying the candidate exceptions in the throws clause?
When should you use which approach?
Ans: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.
29)How do I create a read-only collection?
Ans: The Collections class has six methods to help out here:
• unmodifiableCollection(Collection c)
• unmodifiableList(List list)
• unmodifiableMap(Map m)
• unmodifiableSet(Set s)
• unmodifiableSortedMap(SortedMap m)
• unmodifiableSortedSet(SortedSet s)
If you then get an Iterator from one of these unmodifiable collections, when you call remove() it will throw an UnsupportedOperationException.
30)Which is faster, synchronizing a HashMap or using a Hashtable for thread-safe access?
Ans: Because a synchronized HashMap requires an extra method call, a Hashtable is faster for synchronized access.
31)How to implement collection ordering?
Ans: SortedSet and SortedMap interfaces maintain sorted order. The classes, which implement the Comparable interface, impose natural order. For classes that don’t implement comparable interface, or when one needs even more control over ordering based on multiple attributes, a Comparator interface should be used.
32) How do I properly alphabetize (sort) a list of strings in a language-sensitive manner?
Ans: This is actually outside the scope of the Collections Framework. Instead, it is part of the java.text package with the Collator and CollationKey classes.
The following example demonstrates this capability:
import java.text.*;
import java.util.*;
public class CollatorTest {
public static void main(String args[]) {
Collator collator =
Collator.getInstance();
CollationKey key1 =
collator.getCollationKey("Tom");
CollationKey key2 =
collator.getCollationKey("tom");
CollationKey key3 =
collator.getCollationKey("thom");
CollationKey key4 =
collator.getCollationKey("Thom");
CollationKey key5 =
collator.getCollationKey("Thomas");
Set set = new TreeSet();
set.add(key1);
set.add(key2);
set.add(key3);
set.add(key4);
set.add(key5);
printCollection(set);
}
static private void printCollection(
Collection collection) {
boolean first = true;
Iterator iterator = collection.iterator();
System.out.print("[");
while (iterator.hasNext()) {
if (first) {
first = false;
} else {
System.out.print(", ");
}
CollationKey key =
(CollationKey)iterator.next();
System.out.print(key.getSourceString());
}
System.out.println("]");
}
}
33)In Java, if we insert a return statement inside the try block of a try-catch-finally, will the finally block still get executed?
Ans: Yes. The finally block will be executed even if there is a return statement in the try block.
yes, it will be executed, but if we use System.exit(0) in try block it will never go to finally block.
34) What is Garbage Collection and how to call it explicitly?-
Ans: When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.
35)What are Transient and Volatile Modifiers?-
Ans:
Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized.
Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program
36)What is the difference between String and String Buffer?
Ans: String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.
37)What are three ways in which a thread can enter the waiting state?
Ans: A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
38)Write the Java code to declare any constant (say gravitational constant) and to get its value.
Ans:
Class ABC
{
static final float GRAVITATIONAL_CONSTANT = 9.8;
public void getConstant()
{
system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT);
}
}
39)What's the difference between the == operator and the equals() method? What test does Object.equals() use, and why?
Ans: The == operator would be used, in an object sense, to see if the two objects were actually the same object.
This operator looks at the actually memory address to see if it actually the same object. The equals()
method is used to compare the values of the object respectively. This is used in a higher level to see if the
object values are equal.
Of course the the equals() method would be overloaded in a meaningful way for whatever object that you
were working with.
40)Name four methods every Java class will have.
Ans:
clone()
equals() & hashcode()
getClass()
finalize()
wait() & notify()
toString()
41)What is NullPointerException and how to handle it?
Ans: When an object is not initialized, the default value is null. When the following things happen, the NullPointerException is thrown:
--Calling the instance method of a null object.
--Accessing or modifying the field of a null object.
--Taking the length of a null as if it were an array.
--Accessing or modifying the slots of null as if it were an array.
--Throwing null as if it were a Throwable value.
The NullPointerException is a runtime exception. The best practice is to catch such exception even if it is not required by language design.
42) What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
Ans: The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.
43)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
44)Can there be an abstract class with no abstract methods in it?
Ans: Yes, A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
45)How to convert String to Number in java program?
Ans: The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = “1000″;
int id=Integer.valueOf(numString).intValue();
46)In what different forms Polymorphism exists in Java?
Ans:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
47)Advantages of using string builder compared to String buffer?
Ans: A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
For example, if z refers to a string builder object whose current contents are "start", then the method call z.append("le") would cause the string builder to contain "startle", whereas z.insert(4, "le") would alter the string builder to contain "starlet".
In general, if sb refers to an instance of a StringBuilder, then sb.append(x) has the same effect as sb.insert(sb.length(), x). Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.
Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
48) What's New in Java 1.5?
Generics provide a way to create and use typesafe data structures. This means that no longer do you have to create a List of the basic Objects then typecast every time you pull stuff out! You can declare your list to automatically typecast the stuff inside:
List things = createListOfBorkObjects();
for(Iterator i = things.iterator() ; i.hasNext() ; ) {
Bork item = (Bork)i.next();
//do something useful
}
Simply becomes...
List<Bork> things = createListOfBorkObjects();
for(Iterator<String> i = things.iterator() ; i.hasNext() ; ) {
Bork item = i.next();
//do something useful
}
The Java compiler also protects things from having non-Bork objects inside. If you try to put a String or anything else in, you'll get an error. This essentially means that you can create a list with specific types now instead of just objects. These exist in other classes such as Map which uses two:
Map<String, Bork> myMap = new HashMap<String, Bork>();
That creates a map that uses a String key and a Bork value. This implementation kind of looks like something using templates in C++...
Be careful though! You can create a string iterator that iterates over a list of non-strings that will only become an error at runtime. The compiler doesn't catch this.
Also, sometimes when using a type that can be parameterized, but not specifying the parameter type (in angle brackets) you can get lint warnings. This just means that you haven't provided a specific type, and the current definition of the type is "fuzzy" -- like lint, get it?
2. For/in loop
This is probably one of the coolest new features. I personally hate using iterators--it seems redundant and annoying sometimes. Well, lucky for me there's a way around them now!
So now you can do this:
for(Iterator lineup = list.iterator() ; lineup.hasNext() ; ) {
Object thatThing = lineup.next();
myMonster.eat(thatThing);
}
In a shortened:
for(Object thatThing : list) {
myMonster.eat(thatThing);
}
Much prettier, no? This works with arrays too.
int[] nums = { 1, 2, 3, 4, 5, 6 };
for(int n : nums) {
System.out.println(n);
}
Say you want to get your class to work with this nifty loop. Then, you have to implement Iterable (or extend something that does). This involves telling Iterable what type of things you iterate over. You can define a custom iterator to do something more robust, but for this illustration, I'm just going to grab one out of the list. public class MailBox implements Iterable<MailMessage> {
/** structure storing the messages */
private ArrayList<MailMessage> messages;
//...
/**
* Implemented for Iterable.
*/
public Iterator<MailMessage>() {
return messages.iterator();
}
//...
}
For more detailed information, see Java 1.5 Tiger: A Developer's Notebook[4] or the information on Sun's J2SE 5.0 language documentation.
3 Autoboxing/Unboxing
Integer i = new Integer(4);
int j = i.intValue();
Number n = new Float(3.14159);
Boolean stuff = new Boolean(false);
// stuff before ? must be a boolean (lower case)
System.out.println( stuff.booleanValue() ? "Yep" : "Nope" );
Sick of this? Me too. Do this instead:
Integer i = 4;
int j = i;
Number n = 3.14159f;
Boolean stuff = false;
System.out.println( stuff ? "Yep" : "Nope" );
This is pretty nice. Especially since you can use ++ and other similar operators with the wrapper types now too.
4 Typesafe Enums
Enums are just magic classes to help prevent the methodless-interface antipattern. They let you make classes that will enumerate values, but also keep the types specific. Before, we could simulate enums with a bunch of static final int variables or something. The problem with those is that you could confuse any int with one of the constants. With enumerations, only the values in the enum are valid. For example:
public enum JettStaff {
ADRIAN,
ARIJIT,
BETH,
ERIC,
KATIE,
KATY,
RAJA,
RICH,
SUZANNE
};
JettStaff x = JettStaff.SUZANNE;
Now, it gets even cooler. I don't have to keep track of separate information to store, say the peoples' full names. I can associate them directly, just like in a class! Each of the values of JettStaff are instances of the JettStaff enumeration, so we can define a constructor and a toString() method.
public enum JettStaff {
ADRIAN("Adrian German"),
ARIJIT("Arijit Sengupta"),
BETH("Beth Plale"),
ERIC("Eric Wernert"),
KATIE("Katie A. Siek"),
KATY("Katy Borner"),
RAJA("Raja Sooriamurthi"),
RICH("Rich Kick"),
SUZANNE("Suzanne Menzel");
private String name;
public JettStaff(String n) { this.name = n; }
public String toString() { return this.name; }
}
JettStaff x = JettStaff.SUZANNE;
System.out.println(x);
But wait, it gets cooler! Now you can also give each enumerated value a custom body. Since they're each instances, you could design a toString() method for each:
public enum JettStaff {
ADRIAN("Adrian German") {
public String toString() {
return name + " ([email protected])";
}
},
ARJIT("Arjit Sengupta") {
public String toString() {
return name + " ([email protected])";
}
},
// and on for the rest...
private String name;
public JettStaff(String n) { this.name = n; }
}
JettStaff x = JettStaff.SUZANNE;
System.out.println(x);
Last but not least, enums can extend each other. Imagine that!
5 Varargs
What is your impression of "..."? It's a nice little note that might come in handy. Notice how when you pass arguments from the command line ...
C:/> java MyProg a b c
You gave me 3 args! Yay.
...
... you don't have to pass an array of stuff. The runtime automatically converts the arguments into an array of strings. You can do that now in all of your methods! For example, instead of doing this:
public class VarArgs {
public static void main(String[] args) {
String[] newArgs = {"a", "b", "c"};
vaMethod(newArgs);
}
public void vaMethod(String[] args) {
System.out.println("You gave me " + args.length + " args! Yay.");
}
}
You can declare it more easily, and not have to construct the array ahead of time:
public class VarArgs {
public static void main(String[] args) {
vaMethod("a", "b", "c");
}
public void vaMethod(String... args) {
System.out.println("You gave me " + args.length + " args! Yay.");
}
}
Notice that when you use the ... syntax, it automatically treats that parameter as an array but you don't have to pass it in that way. Nifty. Let's add one of those for/in loops:
public class VarArgs {
public static void main(String[] args) {
vaMethod("a", "b", "c");
}
public void vaMethod(String... args) {
for(String s : args)
System.out.println(s);
}
}
6 Static Import
Remember making all those interfaces that just have constants in them?
import java.awt.*;
public interface BouncingBallConstants {
public static final Color BACK_COLOR = Color.WHITE;
public static final Color BALL_COLOR = Color.BLUE;
public static final int BALL_SIZE = 50;
}
Scrap that. Put these into a REAL class and then just import the static members from all the other ones using import static <Package or Class>;. This addition is pretty straightforward, and it helps prevent bloat and the "methodless interface" design antipattern.
7 Annotations (Metadata) Now for the weirdest part. Annotations are not really something that will affect how you program in Java, unless you need to associate some sort of metadata or annotations with classes, methods, variables, etc.
So what are annotations anyway? That's a good question. They provide a little extra information about the classes you write, and a class can use the Reflection package later to read the annotations. These are useful because you can attach extra information to your code that may determine how it is used or maybe if it is used at all.
For example, in J2SE 5, you can declare your intent to override a method like toString() in one of your classes:
public class MyClass extends Object {
@Override
public String toString() {
return "My overridden method!";
}
}
In the above example, we declare that we will override the immediately following toString() method. So the compiler looks in our superclass (Object) for the same metho and makes sure it exists. If for some reason we had overloaded toString() by declaring it with different parameters and maybe return type, then the compiler would throw an error saying we didn't override correctly. This is really useful if you want to make sure you override a method as opposed to simply overloading it.
Of course you can define your own annotations. They're basically like interfaces, but they can contain values. An example annotation looks like:
public @interface Conference {
String what();
String when();
String location();
}
This annotation declares three members: what, when, location and sets them up to have "getters" and "setters" automatically! That means each @Conference annotation has those three fields associated with it, and I don't have to define the accessor and mutator methods to set them up (see the next code listing). If I define this annotation like this, I can use it to mark code that I use for the Jett conference:
@Conference(what="JETT",
when="November 2004",
location="IUB")
public class MyMagicJettClass {
//...
}
And now the @Conference type of data is associated with my class. Later on, I could write an analyzer that goes through all of my code and lets me know which classes were used at conferences as well as which conferences they were used at and when. This specific example doesn't have any effect on the way MyMagicJettClass operates.
So the annotations require two-fold cooperation: the programmer must properly annotate her code to provide adequate metadata needed and other developers who will want to know this metadata must know how to extract it using the Java Reflection package. That's a whole hours-long session on how to extract them, so I'm not going to go into depth here.
Where are they useful? Say you are working with RMI (Remote Method Invocation) and you don't want all of your methods available remotely. You could annotate the remotable ones with a @Remote annotation, then whatever serves up the remote access can only allow those to be remotely accessed. There are a ton of great uses for these, and they are fully extendable (you can annotate annotations)!
49)How to schedule a job in Java?
Ans: When there is a need for schedule an event to occur at a certain time, or the event needs to be executed repeated at a certain interval, the TimerTask and TImer class are designed for this.
A TimerTask is “A task that can be scheduled for one-time or repeated execution by a Timer.” A TimerTask is similar to a Thread. Both classes implement the Runable interface. Thus both classes need to implement the public void run() method. The code inside the run() method is will be executed by a thread. The TimerTask has two more methods besides the run() method. They are the public boolean cancel() and the public long scheduledExecutionTime(). The cancel() method cancels the not yet executed task. The scheduledExecautionTime() returns the most recent actual execution time of this task.
A Timer is facility to schedule TimerTasks. "Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. Timer tasks should complete quickly." The constructor of the Timer class starts the background thread.
An simple example here:
public class SimpleTimer {
class Checker extends TimerTask {
public static final int DELAY = 60 * 1000;
public void run() {
doCheck();
}
private void doCheck() {
System.out.println("Current time is: " + System.currentTimeMillis());
}
}
pubic static void main (String … argv) {
Timer timer = new Timer(); // start the timer thread
timer.schedule(Checker(), Checker.DELAY,
Checker.DELAY); // calls the Checker's run() method after one minute and repeat every one minute.
}
}
For a gracefully shutdown, the Timer's cancel() method should be called. The cancel() method "Terminates this timer, discarding any currently scheduled tasks".
50) About NoClassDefFoundException and ClassNotFoundException difference?
Ans: NoClassDefFoundException is thrown if a class is referenced with Java’s “new” operator (i.e. static loading)
but the runtime system cannot find the referenced class.
Ex: Classes are statically loaded with Java’s “new” operator.
class MyClass {
public static void main(String args[]) {
Car c = new Car();
}
}
A ClassNotFoundException is thrown when an application tries to load in a class through its string name using the following methods but no definition for the class with the specified name could be found:
The forName(..) method in class - Class.
The findSystemClass(..) method in class - ClassLoader.
The loadClass(..) method in class - ClassLoader.
Ex: Class.forName (String className);
51)How do you sort an ArrayList (or any list) of user-defined objects ?
Ans: Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).
52)What is the Comparable interface ?
Ans: The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
interface Comparable<T>
where T is the name of the type parameter.
All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be negative.
If object1 > object2: The value of i returned will be positive.
If object1 = object2: The value of i returned will be zero.
53)With Java, deleting non numeric characters (letters, symbols etc) from a string to produce a numbers-only String is a common requirement in web applications, as application users are used to insert numeric values with non-numeric characters.
For example a phone number will be entered with (-) characters like;
650-212-5710.
A price value may be entered with (,) characters like;
12,500.00
In Java, java.lang.Character class has a method; isDigit() which can be used to identify whether a character is a digit or not. Following method can be used for extracting a numbers-only string.
public static String getOnlyNumerics(String str) {
if (str == null) {
return null;
}
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < str.length() ; i++) {
c = str.charAt(i);
if (Character.isDigit(c)) {
strBuff.append(c);
}
}
return strBuff.toString();
}
Calling above method with any String will return a numbers-only string.
54) Is emp.setName("XYZ") valid when emp is a final variable with declaration : final Employee emp=new Employee()?
Ans:Valid as we are not making emp to point to some other object.
55) What is ConcurrentModificationException and explain.
Ans:Removal of an item through Iterator when the list is accessed by a different iterator.
56)Certain Customers buy kindle on day one and certain customers buy kindle on day two. Design an algorithm(optimum) to find customers who bought on both days. Each customer has a unique ID (Integer). (I forgot to consider case of duplicates,until she reminded), You need to write complete code(NOT just pseudo code within given time and read it out)”
Or
In an array 1-100 many numbers are duplicates, how do you find it?
Ans:We need a little more information about the data. Are there two lists of customers (one list with people that bought a kindle on day one, and another that bought a kindle on day two, for example)? Or are we given a list of customers, from which we can determine which days they bought kindles?
If we are given two lists of customer IDs, each representing customers that bought kindles on each day, we can put all of the customers in the first list into a hashtable using the customer ID as a key and setting the value to null, and then iterate through the second list, and check if the customer ID already exists in the hash table. If it does, then we can update the value of the respective key in the hash table to a non-null value, and return the list of those keys. This is O(n) time.
57)Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.
Ans:Here is a quick tip to solve this programming question: put the elements of the second array in the hash table and for every element of the first array, check whether it’s present in the hash or not, O/P all those elements from the first array that are not present in the hash table
58) "What is deadlock ?"
Ans:answer is simple , when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multithreading.
59)How do you detect deadlock ?
Ans:though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful.
other way is to find it when you actually get locked while running the application , try to take thread dump , in linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object.
other way is to use jconsole , jconsole will show you exactly which threads are get locked and on which object.
once you answer this , they may ask you to write code which will result in deadlock ?
here is one of my version
public void method1(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
}
}
}
public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock becuase if thead 1 aquires lock on Sting object while executing method1() and thread 2 aquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen.
now interviewer comes to final part , one of the most important in my view , How to fix deadlock ?
if you have looked above code carefully you may have figured out that real reason for deadlock is not multiple threads but the way they access lock , if you provide an ordered access then problem will be resolved , here is
the fixed version.
public void method1(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
Now there would not be any deadlock because both method is accessing lock on Integer and String object in same order . so if thead A aquires lock on Integer object , thread B will not proceed until thread A releases Integer lock , same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further.
60)What is immutable object? Can you write immutable object?
Ans: You need to make class final and all its member final so that once objects gets created no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.
61) What is the difference between creating String as new () and literal?
Ans:When we create string with new () it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.
62)How to identify a given positive decimal number as even/odd without using % or / operator ?
Ans:A plain trap, even for those experienced people. You may be very good at coding,but if you questioning how on earth you could solve this problem.Then here is a solution. If you remember the good old days of our primary school then the solution is easy,"division is a matter of iterative subtraction".
public class TestEvenOdd {
02.
03. public static void main(String arg[]){
04.
05. int num=6;
06.
07. int result=num;
08.
09. while(result>=2){
10.
11. result=result-2;
12.
13. }
14.
15. if(result==1){
16.
17. System.out.println("The number is odd");
18.
19. }else{
20.
21. System.out.print("The number is even");
22.
23. }
24.
25. }
26.
27. }
63) About assertions in Java
64) What is the Java heap, and what is the stack? (Hint: dynamic, program thread execution.)
65) Why does garbage collection occur and when can it occur? (Hint: To recover memory, as heap gets full.)
66) If I have a circular reference of objects, but I no longer reference any of them from any executing thread, will these cause garbage collection problems? (Hint: no)
67) What language features are available to allow shared access to data in a multi-threading environment? (Hint: Synchronized block,Synchronized method,wait, notify)
68) What is the difference between synchronized method and synchronized block? (Hint:Block on subset of data. Smaller code segment).
69) What Java language features would you use to implement a producer (one thread) and a consumer (another thread) passing data via a stack? (Hint: wait, notify)