You are on page 1of 64

Can transient variables be declared as 'final' or 'static'?

Java's serialization provides an elegant, and easy to use mechanism for making an object's state persistent. While controlling object serialization, we might have a particular object data member that we do not want the serialization mechanism to save. The modifier transient can be applied to field members of a class to turn off serialization on these field members. Every field marked as transient will not be serialized. You use the transient keyword to indicate to the Java virtual machine that the transient variable is not part of the persistent state of an object. The transient modifier applies to variables only. Surprisingly, the java compiler does not complaint if you declare a static member field as transient or a final member field as transient in your classes. These should be compiletime errors. Because a "transient" part of an object's state is assumed to be changing within each instance, it can not be static or final. Similarly, a "volatile" variable cannot be final (constant). This restriction matters only in the future, though, when transient and volatile are actually used by Java. Question: Which of the following is true? A. transient methods must be static B. native methods violate Java's platform independence. C. static methods cannot be protected D. transient variables may not be final or static Answer: A is incorrect as the modifier transient applies to variables only. B is correct because native methods execute code which lies entirely outside the Java Virtual Machine, this code is compiled for a specific targeted machine and hence makes the application platform independent thereby violating Java's platform independence. C is incorrect as there is nothing wrong in static methods being protected. D is correct, as transient variables may not be final or static. Can static methods be overridden?

The static methods can not be overridden! If a subclass defines a static method with the same signature as a static method in the superclass, the method in the subclass hides the one in the superclass. The distinction between hiding and overriding has important implications.

Are parameters passed by reference or passed by value in method invocation? All primitives are pass-by-value, period. When a primitive value is passed into a method, a copy of the primitive is made. The copy is what is actually manipulated in the method. So, the value of the copy can be changed within the method, but the original value remains unchanged. Objects, however, work a bit differently. When you pass a Java object or array as a parameter, an object reference or array reference is passed into a method. The method can manipulate the attributes of the object that is referenced by the reference (formal parameter). Why it's only proper to call the start() method to start the thread instead of calling the run() method directly?

In both the above examples, the run() method is the most important method in the thread classes, it is also the only method that we need to implement in both cases. Why it's only proper to call the start() method to start the thread instead of calling the run() method directly? Because the run() method is not a regular class method. It should only be called by the JVM. Writing thread classes is not about a single sequential thread, it's about the use of multiple threads running at the same time and performing different tasks in a single program. The JVM needs to work closely with the underneath operating system for the actual implementation of concurrent operations. This is how the performance can be improved, and all other benefits mentioned above can be achieved. You should not invoke the run() method directly. If you call the run() method directly, it will simply execute in the caller's thread instead of as its own thread. Instead, you need to call the start() method, which schedules the thread with the JVM. The JVM will call the corresponding run() method when the resources and CPU is ready. The JVM is not guaranteed to call the run() method right way when the start() method is called, or in the order that the start() methods are called. Especially for the computers have a single processor, it is impossible to run all running threads at the same time. The JVM must implement a scheduling scheme that shares the processor among all running threads. This is why when you call the start() methods from more than one thread, the sequence of execution of the corresponding run() methods is random, controlled only by the JVM. What are the valid signatures of the main() function of a class? The Java literature frequently refers to the Signature of a method. A method signature is a collection of information about the method, and that includes the name, type (e.g., static or non-static), visibility (e.g., public, private, etc.), arguments (e.g., formal parameters), and return type. The main method is the entry point of the JVM when the class in launched. The JVM launchs the Java program by invoking the main method of the class identified in the

command to start the program. The method main must be declared public, static, and void. It must accept a single argument that is an array of strings. The main method can be declared as either: public static void main(String[] args) or public static void main(String args[]) A compile-time error will occurs, if more than one main methods exist in your code with the signatures described in the above. For example, you will get compile-time error when you try to compile the following code. public class Program{ public static void main(String[] args) { } public static void main(String args[]){ } } You can have more than one methods with name "main" but have different other signatures. The JVM only looks for the main method described in the above at starting time. For example, the following code compiles and output "calling from public static void main(String[] args)". public class Program{ public static void main(String[] args) { main("calling from public static void main(String[] args)"); } public static void main(String arg){ System.out.println(arg); } } Is it allowed to declare the main method private? Former JVM versions (pre-1.4) allowed the main method to have any accessibility (private, protected, etc). This incompatibility with the Section 12.1.4 of the Java Language Specification has been fixed as of version 1.4. In order to invoke a main method from the command-line, it is now mandatory to declare the main method as the above. If the main method has any access level other than public, it will no longer run from the command-line. String Literal Pool

String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code creates a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption. Can the remainder/modulus operator be used with floating point operands? The % operator, called the modulus or remainder operator, returns the remainder of two numbers. In C and C++, the remainder operator accepts only integral operands, but in the Java programming language, it also accepts floating-point operands. Remeber that the evaluation of a floating-point remainder operator % never throws a run-time exception, even if the right-hand operand is zero. Overflow, underflow, or loss of precision cannot occur. Examples: 5.0%3.0 produces 2.0 5.0%(-3.0) produces 2.0 (-5.0)%3.0 produces -2.0 (-5.0)%(-3.0) produces -2.0 5.0/0.0 produces NaN Can a Java application have memory leak? Yes, there could be memory leak in Java applications. Wait a minute, doesn't Java virtual machine have a garbage collector that will collect and free all unreferenced memory automatically? Let's find out in general what memory leaks are, and how they occur in applications. If an application fails to return the not-in-use memory back to the heap, the "lost" memory is called memory leak. Memory leaks occur when the application doesn't free the memory allocated, usually are the objects no longer in use, but the object references are lost. If an object is no longer accessible, there is no way to free its memory. Each time such a leak is re-created, additional memory is used and not freed. Eventually, the process that runs the application will run out of memory and crash. It's true that for other programming languages, such as C/C++, there is not such a thing called garbage collector. The programmer is responsible for freeing the memory when the object is no longer in use. In Java, all unreferenced objects are indeed automatically freed by the garbage collector. The garbage collector looks for objects that are no longer needed and to remove them when they can no longer be accessed or referenced. The garbage collector starts at the root nodes, classes that persist throughout the life of a Java application, and sweeps though all of the nodes that are referenced. As it traverses the nodes, it keeps track of

which objects are actively being referenced. Any classes that are no longer being referenced are then eligible to be garbage collected. The memory resources used by these objects can be returned to the Java virtual machine (JVM) when the objects are deleted. But in some situations, when the object is no longer in use, but some references to that object has not been removed. This kind of objects will not be collected by the garbage collector. That means there is a memory leak. Sometimes memory leaks in Java is also referred to as "dangling references". What are the symptoms of a memory leak?

When the application has a memory leak, basically, you will notice: 1. Memory usage consistently increases during the application life span. Sooner or later the application will crash because out of memory. 2. Performance consistently decreases. This is because more and more un collectable objects are in the heap, which will trigger the garbage collector to work more frequently and work longer, on the other hand, the application will run slower.

Typical Leaks

Now that we know it is indeed possible to create memory leaks in Java, let's have a look at some typical leaks and what causes them. Global collections It is quite common in larger applications to have some kind of global data repository, a JNDI-tree for example, or a session table. In these cases care has to be taken to manage the size of the repository. There has to be some mechanism in place to remove data that is no longer needed from the repository. Caches A cache is a data structure used for fast lookup of results for already-executed operations. Therefore, if an operation is slow to execute, you can cache the result of the operation for common input data and use that cached data the next time the operation is invoked. Usually, the application keeps adding new data that was not in the cache, but not controlling the size of the cache. Depends on what data is kept in the cache, the cache will potentially increase to too big for the application to handle. When designing the cache, the program has to make sure the cache has an upper bound on the amount of memory it will use. What is variable hiding and shadowing?

In Java, there are three kinds of variables: local variables, instance variables, and class variables. Variables have their scopes. Different kinds of variables have different scopes. A variable is shadowed if there is another variable with the same name that is closer in scope. In other words, referring to the variable by name will use the one closest in scope , the one in the outer scope is shadowed. What is runtime polymorphism in Java? Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementation. This is one of the basic principles of object oriented programming. The method overriding is an example of runtime polymorphism. You can have a method in subclass overrides the method in its super classes with the same name and signature. Java virtual machine determines the proper method to call at the runtime, not at the compile time. Let's take a look at the following example: class Animal { void whoAmI() { System.out.println("I am } } class Dog extends Animal { void whoAmI() { System.out.println("I am } } class Cow extends Animal { void whoAmI() { System.out.println("I am } } class Snake extends Animal { void whoAmI() { System.out.println("I am } }

a generic Animal.");

a Dog.");

a Cow.");

a Snake.");

class RuntimePolymorphismDemo { public static void main(String[] args) { Animal ref1 = new Animal(); Animal ref2 = new Dog(); Animal ref3 = new Cow(); Animal ref4 = new Snake(); ref1.whoAmI(); ref2.whoAmI();

ref3.whoAmI(); ref4.whoAmI(); } } The output is I I I I am am am am a a a a generic Animal. Dog. Cow. Snake.

In the example, there are four variables of type Animal (e.g., ref1, ref2, ref3, and ref4). Only ref1 refers to an instance of Animal class, all others refer to an instance of the subclasses of Animal. From the output results, you can confirm that version of a method is invoked based on the actually object's type. In Java, a variable declared type of class A can hold a reference to an object of class A or an object belonging to any subclasses of class A. The program is able to resolve the correct method related to the subclass object at runtime. This is called the runtime polymorphism in Java. This provides the ability to override functionality already available in the class hierarchy tree. At runtime, which version of the method will be invoked is based on the type of actual object stored in that reference variable and not on the type of the reference variable. What does Class.forname method do? A call to Class.forName("X") causes the class named X to be dynamically loaded (at runtime). A call to forName("X") causes the class named X to be initialized (i.e., JVM executes all its static block after class loading). Class.forName("X") returns the Class object associated with the "X" class. The returned Class object is not an instance of the "x" class itself. Class.forName("X") loads the class if it not already loaded. The JVM keeps track of all the classes that have been previously loaded. This method uses the classloader of the class that invokes it. The "X" is the fully qualified name of the desired class. For example, package com.xyzws; class AClass { static { System.out.println("static block in AClass"); } } public class Program { public static void main(String[] args) { try { Class c = Class.forName("com.xyzws.AClass");

} catch (ClassNotFoundException e) { } } } The output is static block in AClass Here is one example that uses returned Class to create an instance of AClass: package com.xyzws; class AClass { public AClass() { System.out.println("AClass's Constructor"); } static { System.out.println("static block in AClass"); } } public class Program { public static void main(String[] args) { try { System.out.println("The first time calls forName:"); Class c = Class.forName("com.xyzws.AClass"); AClass a = (AClass)c.newInstance(); System.out.println("The second time calls forName:"); Class c1 = Class.forName("com.xyzws.AClass"); } catch (ClassNotFoundException e) { ... } catch (InstantiationException e) { ... } catch (IllegalAccessException e) { ... } } } The output is The first time calls forName: static block in AClass AClass's Constructor The second time calls forName:

//Calss has been loaded so there is not "static block in AClass" printing out JDBC Driver Is a Good Example You may have experience working with JDBC Drivers. For example, the classloader attempts to load and link the Driver class in the "org.gjt.mm.mysql" package. If successful, the static initializer is called. Class.forName("org.gjt.mm.mysql.Driver"); Connection con = DriverManager.getConnection(url,?myLogin", "myPassword"); Let's see why you need Class.forName() to load a driver into memory. All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static an initializer only. The MySQL JDBC Driver has a static initializer looks like this: static { try { java.sql.DriverManager.registerDriver(new Driver()); } catch (SQLException E) { throw new RuntimeException("Can't register driver!"); } } JVM executes the static block and the Driver registers itself with the DriverManager. You need a database connection to manipulate the database. In order to create the connection to the database, the DriverManager class has to know which database driver you want to use. It does that by iterating over the array (internally a Vector) of drivers that have registered with it and calls the acceptsURL(url) method on each driver in the array, effectively asking the driver to tell it whether or not it can handle the JDBC URL. Why does TreeSet.add throw ClassCastException? The following code throws ClassCastException, why? class MyObject { int i; MyObject(int i) { this.i = i; } } public class Program { public static void main(String[] args) { Set s = new TreeSet();

s.add(new MyObject(1)); s.add(new MyObject(2)); //Runtime exception: ClassCastException .... } } The TreeSet() Constructor said: Constructs a new, empty set, sorted according to the elements' natural order. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If an element is added to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the add(Object) call will throw a ClassCastException; or if the to be added object cannot be compared with the elements currently in the set, the add(Object) call will throw a ClassCastException. In the above code, the MyObject class does not implement the Comparable interface. Therefore, when the second object is added to the TreeSet, the second object can't be compared with the first element already in the set, the code throws a ClassCastException. What is the advantage of using an Iterator compared to the get(index) method? You can navigate or access a List by using the get (index) method or an Iterator. Sometimes the get (index) method is your only option, and sometimes it's slightly faster than an Iterator. Other times, however, it can be much, much slower than an Iterator. For example, a LinkedList is a classic example. This class has a get (index) method but it is very slow. Well, it's not that bad if the list is short, or if you're looking for an item that is close to the beginning or end. But if you need to access the List frequently, you will see a big difference. Let's take a look at the following example: public class TestClass { public static void main (String[] args) { int len = 100000; LinkedList linkedLst = new LinkedList(); ArrayList arrayLst = new ArrayList(); for (int m =0; m!= len; m++) { int x = (int)Math.random(); linkedLst.add(x); arrayLst.add(x); } long t = System.currentTimeMillis(); for (int i = 0; i!=len; i++) {

linkedLst.get(i); } t = System.currentTimeMillis() - t; System.out.println("LinkedList -- get(index) takes "+t +"(ms)"); t = System.currentTimeMillis(); for (Iterator itr = linkedLst.iterator(); itr.hasNext();) { itr.next(); } t = System.currentTimeMillis() - t; System.out.println("LinkedList -- Iterator takes "+t +"(ms)"); t = System.currentTimeMillis(); for (int i = 0; i!=len; i++) { arrayLst.get(i); } t = System.currentTimeMillis() - t; System.out.println("ArrayList -- get(index) takes "+t +"(ms)"); t = System.currentTimeMillis(); for (Iterator itr = arrayLst.iterator(); itr.hasNext();) { itr.next(); } t = System.currentTimeMillis() - t; System.out.println("ArrayList -- Iterator takes "+t +"(ms)"); } } The output is LinkedList -- get (index) takes 25777(ms) LinkedList -- Iterator takes 0(ms) ArrayList -- get (index) takes 10(ms) ArrayList -- Iterator takes 10(ms) And in many cases, you don't know for sure whether you want a LinkedList or an ArrayList or some other List implementation. If you use get(index), you will get the fastest possible response from an ArrayList, but you will get a very poor response from a LinkedList. If you use an Iterator, you will get something fairly close to the fastest possible response from an ArrayList, and you will get the fastest possible response from a LinkedList, too. So in general, an Iterator is a more reliable choice. It's not always the fastest possible choice, but it's always close. And it protects you from the extremely slow behavior you would get if you mistakenly used a get(index) on a LinkedList.

Also, the enhanced for loop will automatically use a hidden Iterator any time you try to loop over any Collection (or more generally, any Iterable) in JDK 5. Using an Iterator is directly supported by the language so that it's the most convenient thing for you to do - as well as being fastest, or close to fastest. ... for (Integer i:linkedLst) { System.out.println(i); } ... for (Integer i:arrayLst) { System.out.println(i); } If more than one thread can access a Collection (or Map or array or other group-ofthings), you need to synchronize. (Or use something like java.util.concurrent.locks classes from JDK 5+). No matter what you use a get(index) or an Iterator, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. The main difference is that:

Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw ConcurrentModificationException exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future. The get(index) method will return bad data that makes very difficult to identify the real problem.

A ConcurrentModificationException is a nice signal making us easy to find the problem and to handle the problem. This is another good reason to use an Iterator. Note that fail-fast behavior cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast operations throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.

Why always override hashcode ( ) if overriding equals ( )? In Java, every object has access to the equals () method because it is inherited from the Object class. However, this default implementation just simply compares the memory addresses of the objects. You can override the default implementation of the equals () method defined in java.lang.Object. If you override the equals (), you MUST also override hashCode (). Otherwise a violation of the general contract for Object.hashCode

will occur, which can have unexpected repercussions when your class is in conjunction with all hash-based collections. Here is the contract, copied from the java.lang.Object specialization: public int hashCode () Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable. The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals (Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals (java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects might improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.) The default implementation of equals () method checks to see if the two objects have the same identity. Similarly, the default implementation of the hashCode() method returns an integer based on the object's identity and is not based on the values of instance (and class) variables of the object. No matter how many times the values of its instance variables (data fields) change, the hash code calculated by the default hashCode implementation does not change during the life of the object. Consider the following code, we have overridden equals() method to check if two objects are equal based on the values of their instance variables. Two objects may be stored at different memory addresses but may still be equal base on their instance variable. public class CustomerID { private long crmID; private int nameSpace; public CustomerID(long crmID, int nameSpace) {

super(); this.crmID = crmID; this.nameSpace = nameSpace; } public boolean equals(Object obj) { //null instanceof Object will always return false if (!(obj instanceof CustomerID)) return false; if (obj == this) return true; return this.crmID == ((CustomerID) obj).crmID && this.nameSpace == ((CustomerID) obj).nameSpace; } public static void main(String[] args) { Map m = new HashMap(); m.put(new CustomerID(2345891234L,0),"Jeff Smith"); System.out.println(m.get(new CustomerID(2345891234L,0))); } } Compile and run the above code, the output result is null What is wrong? The two instances of CustomerID are logically equal according to the class's equals method. Because the hashCode() method is not overridden, these two instances' identities are not in common to the default hashCode implementation. Therefore, the Object.hashCode returns two seemingly random numbers instead of two equal numbers. Such behavior violates "Equal objects must have equal hash codes" rule defined in the hashCode contract. Let's provide a simple hashCode() method to fix this problem: public class CustomerID { private long crmID; private int nameSpace; public CustomerID(long crmID, int nameSpace) { super(); this.crmID = crmID; this.nameSpace = nameSpace; } public boolean equals(Object obj) { //null instanceof Object will always return false if (!(obj instanceof CustomerID))

return false; if (obj == this) return true; return this.crmID == ((CustomerID) obj).crmID && this.nameSpace == ((CustomerID) obj).nameSpace; } public int hashCode() { int result = 0; result = (int)(crmID/12) + nameSpace; return result; } public static void main(String[] args) { Map m = new HashMap(); m.put(new CustomerID(2345891234L,0),"Jeff Smith"); System.out.println(m.get(new CustomerID(2345891234L,0))); } } Compile and run the above code, the output result is Jeff Smith The hashcode distribution for instances of a class should be random. This is exactly what is meant by the third provision of the hashCode contract. Write a correct hashCode method is easy, but to write an effective hashCode method is extremely difficult. For example, From How to Avoid Traps and Correctly Override Methods From java.lang.Object: If you are unsure how to implement hashCode (), just always return 0 in your implementations. So all of your custom objects will return the same hash code. Yes, it turns hashtable of your objects into one (possibly) long linked-list, but you have implemented hashCode() correctly! public int hashCode(){ return 0; } It's legal because it ensures that equal objects have the same hash code, but it also indicates that every object has the same hash code. So every object will be hashed into the same bucket, and hash tables degenerate to linked lists. The performance is getting worse when it needs to process a large number of objects. How to implement a good hash function is a big topic and we will not cover here.

What is 'instanceof'?

The instanceof operator is used to check whether the run-time type of an object is compatible with a given type (15.20.2 Type Comparison Operator instanceof): expression instanceof type The type of an expression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs. The type mentioned after the instanceof operator must denote a reference type; otherwise, a compile-time error occurs. An instanceof expression evaluates to true if both of the following conditions are met:

expression is not null. expression can be cast to type. That is, a cast expression of the form (type) (expression) will complete without raising a ClassCastException.

It is a compile-time error if the type mentioned after the instanceof operator does not denote a reifiable type. If a cast of the expression to the type would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true. Here is an example code: public class Test{ public static void main(String[] args) { String s = "XyzWS.com"; byte[] b = s.getBytes(); System.out.println(b instanceof byte[]); System.out.println(b instanceof Object); //System.out.println(b instanceof Object[]); //byte[] can not cast to Object[] //System.out.println(b instanceof byte); //byte is primitive type } } What are method overloading and method overriding? Each method in a Java class is uniquely identified by its method signature. A method's signature is its name and the number and the type of its arguments. The method return type, method modifiers, and declared thrown exceptions have no effect on the method signature. A class cannot contain two methods with the same "method signature." What is method overloading?

With the Java language, you can overload methods. Overloading is the practice of supplying more than one definition for a given method name in the same class. The compiler will automatically select the most appropriate one based on the arguments with which it is called. Several restrictions govern an acceptable set of overloaded methods:

Any two methods in a set of overloaded functions must have different argument lists (The name of the parameter is irrelevant. The type and order of the parameters is what's important). A difference in return type only is not sufficient to constitute an overload and is illegal.

Method overloading is generally used where a class can perform the same operation on more than one type of data. What is method overriding? A sub class inherits methods from a super class. Sometimes, the sub class may want to provide a new version of methods defined in the super class. This is referred to as method overriding. Method overriding allows a sub class to provide its own implementation of a method already provided by one of its super classes. A sub class method is provided with the same signature and return type as a method that is declared in its super class, the subclass is said to override that method. You can also override a method with the same signature that returns a subclass of the object returned by the original method. This facility (introduced in 5.0) is called covariant return type. The subclass method does not inherit the functionality of its super class method unless it explicitly calls the super class method using the "super" keyword. Several restrictions govern any particular method to override another correctly:

The return type and method signature must be identical to those of a method in the super class. The accessibility must not be more restrictive than original method. The overriding method must not throw checked exceptions of classes that are not possible for the original method.

Example Consider an example from 8.4.10.2 Example: Overloading, Overriding, and Hiding. In the example: class Point { int x = 0, y = 0; void move(int dx, int dy) { x += dx; y += dy; } int color; } class RealPoint extends Point {

float x = 0.0f, y = 0.0f; void move(int dx, int dy) { move((float)dx, (float)dy); } void move(float dx, float dy) { x += dx; y += dy; } } the class RealPoint hides the declarations of the int instance variables x and y of class Point with its own float instance variables x and y, and overrides the method move of class Point with its own move method. It also overloads the name move with another method with a different signature. In this example, the members of the class RealPoint include the instance variable color inherited from the class Point, the float instance variables x and y declared in RealPoint, and the two move methods declared in RealPoint. Which of these overloaded move methods of class RealPoint will be chosen for any particular method invocation will be determined at compile time by the overloading resolution procedure.

Why am I getting unreported exception when the super class default constructor has a 'throws' clause? class Super { public Super() throws Exception { System.out.println("Super Class"); } } public class Sub extends Super { public static void main(String[] args) throws Exception { Sub s = new Sub(); } } Compile it and you have compile-time error: Sub.java:6: unreported exception java.lang.Exception in default constructor public class Sub extends Super { 1 error Here is a Sun's Bug Report which can answer this question: When a superclass constructor has a non-empty throws clause, subclasses must define an explicit constructor with an appropriate throws clause, as a default constructor has no throws clause. (This is stated in JLS 2e 8.8.7,

ruling out the xxxxx alternative of copying the superclass constructor's throws clause. Currently, the compiler generates a default constructor with an empty throws clause, and then generates an error message. Unfortunately, the offending call, the implicit call to the superclass constructor, does not appear in the program text, so the message is confusing. To fix it, you have to explicit to define a default constructor with an appropriate throws clause: class Super { public Super() throws Exception { System.out.println("Super Class"); } } public class Sub extends Super { public Sub() throws Exception { } public static void main(String[] args) throws Exception { Sub s = new Sub(); } } What is the difference between the 'bit-wise AND' and the 'conditional AND' operators? The & and | operators are defined for two integer operands or two boolean operands. The && and || operators are not defined for anything but two boolean operands. For all other operand types and combinations, a compile-time error shall occur. The Integer Type Operands The & operator is the "bit-wise AND" operator and | is the "bit-wise OR" operator. This permits you to manipulate individual bits in a number. The Boolean Type Operands The && is the "conditional AND" operator and || is the "conditional OR" operator. The && and || operators are evaluated in short circuit fashion. This means that when you have an expression like: e1 && e2 if expression e1 evaluates to be false, then the value of the expression e2 is not calculated. Similarly, if e1 evaluates to be true, then the value of e1 || e2 is automatically true, and therefore e2 is not evaluated. For example, in the expression

x != 0 && 1 / x > x + y // no division by 0 the second part is never evaluated if x equals zero. Thus, 1/x is not computed if x is zero, and no divide-by-zero error can occur. The & the (unconditional) "logical AND" operator and | is the (unconditional)"logical OR" operator. When applied to boolean values, the & and | operators yield a boolean value. These operators are similar to the && and || operators, except that the & and | operators are not evaluated in "short-circuit" fashion. That is, both operands are first evaluated before computing the result. For example class Program { public static void main(String [] args){ boolean[] b = new boolean[3]; int count = 0; b[0] = false; b[1] = false; b[2] = false; //The first operand evaluates to false, //the evaluation of the second operand is skipped. //Therefor, the count does not add 1. if (false && b[++count]) { System.out.println("True -- 1"); } else { System.out.println("False -- 1"); } System.out.println(count); //Both operands are evaluated. Therefor, the count adds 1 if (false & b[++count]) { System.out.println("True -- 2"); } else { System.out.println("False -- 2"); } System.out.println(count); } } The output result is False -- 1 0 False -- 2 1

Does Java support multidimensional arrays? The Java programming language does not really support multi-dimensional arrays. It does, however, support arrays of arrays. In Java, a two-dimensional array x is really an array of one-dimensional arrays: String[][] x = new String[5][5]; The expression x[i] selects the ith one-dimensional array; the expression x[i][j] selects the jth element from that array. You may figure out how three-dimensional array y is. It is an array of two-dimensional arrays. String[][][] y = new String[5][5][5]; The expression y[i] selects the ith two-dimensional array; the expression y[i][j] selects the jth one-dimensional array; the expression y[i][j][k] selects the kth element from the y[i][j] selected one-dimensional array. In the Java built-in multi-dimensional arrays, array indices in each dimension range from zero to length - 1, where length is the array length in the given dimension. In the above example, the length for each dimensional is 5. The number of dimensions and the size of each dimension is fixed once the array has been allocated. The important difference between multi dimensional arrays, as in C/C++ and Java arrays, is that each array does not have to be of the same length. If you think of a twodimensional array as a matrix, the matrix does not have to be a rectangle. Consider the following method of initializing an array of arrays: Stirng[][] z = { {"D00"}, {"D10","D11"}, {"D20","D21","D22"} }; This does not produce the same set of data as the following method: String[][] z = new String[3][3]; Both arrays have 3 rows but each row in the first example has a different number of columns, each row in the second example has an equal number of columns. Why the fully qualified name of a static final variable is not allowed in static initialization block? Let's start with the following example: public class Program { static final int var; static {

Program.var = 8; // Compilation error } public static void main(String[] args) { System.out.println(Program.var); } } And, public class Program { static final int var; static { var = 8; //OK } public static void main(String[] args) { System.out.println(Program.var); } } Why the fully qualified name of the static final variable is not allowed in static initialization block? The rules governing definite assignment in Chapter 16. Definite Assignment: Similarly, every blank final variable must be assigned at most once; it must be definitely unassigned when an assignment to it occurs. Such an assignment is defined to occur if and only if either the simple name of the variable, or its simple name qualified by this, occurs on the left hand side of an assignment operator. A Java compiler must carry out a specific conservative flow analysis to make sure that, for every assignment to a blank final variable, the variable is definitely unassigned before the assignment; otherwise a compile-time error must occur According to the above rules governing definite assignment, we can have the following code: public class Program { static final int var1; final int var2; static { var1 = 8; //OK } { this.var2=10; //OK } public static void main(String[] args) { ..... } }

What is the difference (or relation) between the Comparator and the Comparable interfaces? Classes that implement these two interfaces play different roles in the sorting process. A class that implements the Comparable interface, i.e., a Comparable type, is the type that is sorted, while a class that implements the Comparator interface, i.e., a Comparator, is used to compare other types. A Comparable object can compare itself to another Object using its compareTo(Object other) method. The object itself defines how the comparison is done. Interface Comparable<T> has a method: public int compareTo(T o) A Comparator object is used to compare two objects of the same type using the compare(Object other1, Object other2) method. When using a Comparator, the objects being compared don't need to define the rule of comparison. Interface Comparator<T> has a method: public int compare(T o1, T o2) The primary use of a Comparator is to pass it to something that does sorting, either one of the explicit sort methods, or to a data structure than implicitly sorts (e.g., TreeSet or TreeMap). ... Comparator fileComp = new FileComparator(); //... Create a File object for the current directory. File dir = new File("."); File[] children = dir.listFiles(); // Sort using a comparator. Arrays.sort(children, fileComp); ... You use Comparable if you want to implement the comparison method into the value object class itself. If you want to keep the comparison method separate from the value object class, you should use Comparator and create a separate class that implements that interface. Here are some rules of thumb:

If the comparison rules are simple and all the objects in the collection are of a single type, as well as you can change the code of object class. In such case, it's often easier to make them Comparable and let the container do the comparing.

If the comparison rules are complex and/or objects in the collection are a wide variety of object types, it makes more sense to build an external Comparator interface. Sometime, implementing Comparator is the only option because you can't change the code of the object. But you still want to sort these objects in a Collection. You can create a Comparator that will take two objects and compare based on your own criteria, then pass that into the Sorted Collection, or using the Collections.sort() method to sort based on your way of sorting. Sometimes it's desirable to have the comparison method separate from the value object class itself. For example, if there are different possible way of sorting, you could write different classes that implement Comparator interface and choose the one you need at a specific point in the program.

A Comparator is a "third-party" tool used by a container to order its contents. The container will pass two objects to the supplied Comparator each time it needs to compare them. The Comparator is responsible for returning an indication of the ordering of the two objects but has no relationship with the objects other than that. The comparator object does not need to be an instance of any class related to the objects being compared, it just needs to know how to compare them. A Comparable object, on the other hand, knows how to compare itself with another supplied object. If no Comparator is specified then the container must compare its contents by asking each one how it relates to another. Can private method be overridden? The private methods are not inherited by subclasses and you cannot be overridden by subclasses. According to Java Language Specification (8.4.8.3 Requirements in Overriding and Hiding), "Note that a private method cannot be hidden or overridden in the technical sense of those terms. This means that a subclass can declare a method with the same signature as a private method in one of its superclasses, and there is no requirement that the return type or throws clause of such a method bear any relationship to those of the private method in the superclass." What does it mean? It means you can have a private method has the exact same name and signature as a private method in the superclass, but you are not overriding the private method in superclass and you are just declaring a new private method in the subclass. The new defined method in the subclass is completely unrelated to the superclass method. A private method of a class can be only accessed by the implementation in its class. A subclass cannot call a private method in its superclasses. What is the difference between implementing Runnable and extending Thread? One difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same object instance. For example, public class Program { public static void main (String[] args) {

Runner r = new Runner(); Thread t1 = new Thread(r, "Thread A"); Thread t2 = new Thread(r, "Thread B"); Thread s1 = new Strider("Thread C"); Thread s2 = new Strider("Thread D"); t1.start(); t2.start();v s1.start(); s2.start(); } } class Runner implements Runnable { private int counter; public void run() { try { for (int i = 0; i != 2; i++) { System.out.println(Thread.currentThread().getName() + ": " + counter++); Thread.sleep(1000); } } catch(InterruptedException e) { e.printStackTrace(); } } } class Strider extends Thread { private int counter; Strider(String name) { super(name); } public void run() { try { for (int i = 0; i != 2; i++) { System.out.println(Thread.currentThread().getName() + ": " + counter++); Thread.sleep(1000); } } catch(InterruptedException e) { e.printStackTrace(); } } }

The output result is Thread Thread Thread Thread Thread Thread Thread Thread A: B: C: D: A: B: C: D: 0 1 0 0 2 3 1 1

A class that implements Runnable is not a thread and just a class. For a Runnable to become a Thread, You need to create an instance of Thread and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class. When there is a need to extend a superclass, implementing the Runnable interface is more appropriate than using the Thread class. Because we can extend another class while implementing Runnable interface to make a thread. But if we just extend the Thread class we can't inherit from any other class. How does a static method access instance variables? Static methods can not directly access any instance variables or methods. But they can access them by using their object reference. Static methods may even access private instance variables via a object reference. public class Program { private int count; public Program(int ballcount){ count=ballcount; } public static void main(String argv[]){ Program s = new Program(99); //System.out.println(count); //compile time error //add(10); //compile time error System.out.println(s.count); s.add(10); System.out.println(s.count); } private void add(int num) { count += num; } }

The output result is 99 109 All private instance variables are private to its class, they can be accessed by static methods or non-static method of the class. What is the difference between compile time error and run time error? At compile time, when the code does not comply with the Java syntactic and semantics rules as described in Java Language Specification (JLS), compile-time errors will occurs. The goal of the compiler is to ensure the code is compliant with these rules. Any ruleviolations detected at this stage are reported as compilation errors. The best way to get to know those rules is to go through all the sections in the JLS containing the key words "compile-time error". In general, these rules include syntax checking: declarations, expressions, lexical parsing, file-naming conventions etc; exception handling: for checked exceptions; accessibility, type-compatibility, name resolution: checking to see all named entities - variables, classes, method calls etc. are reachable through at least one of the declared path; etc. The following are some common compile time errors:

a class tries to extend more than one class Overloading or overriding is not implemented correctly Attempt to refer to a variable that is not in the scope of the current block An inner class has the same name as one of one of its enclosing classes A class contains one or more abstract methods and the class itself is not declared "abstract" a class tries to reference a private member of another class trying to create an instance of an abstract class trying to change the value of an already initialized constant (final member) declare two (class or instance) members with the same name

Here is a list of conditions that may cause compile-time errors. When the code compiles without any error, there is still chance that the code will fail at run time. The errors only occurs at run time are call run time errors. Run time errors are those that passed compiler's checking, but fails when the code gets executed. There are a lot of causes may result in runtime errors, such as incompatible type-casting, referencing an invalid index in an array, using an null-object, resource problems like unavailable filehandles, out of memory situations, thread dead-locks, infinite loops(not detected!), etc. The following are some common runtime errors:

trying to invoke a method on an uninitialized variable (NullPointerException) ran out memory (memory leaks...) (OutOfMemoryError) trying to open a file that doesn't exist (FileNotFoundException)

trying to pass arguments to a method which are not within the accepted bounds (IllegalArgumentException) trying to invoke the start() method on a dead thread (-) trying to invoke wait() or notify() on an object without owning the object's monitor (IllegalMonitorStateException)

Why doesn't Iterator work for my collection? Let's take a look at the following code: class Program { public static void main(String args[]) { ArrayList<String> alist = new ArrayList<String>(); alist.add(new String("A")); alist.add(new String("B")); alist.add(new String("C")); int i = 0; for (Iterator<String> it = alist.iterator(); it.hasNext(); ) { System.out.println(alist.get(i++)); } } } A runtime exception java.lang.IndexOutOfBoundsException is thrown when it goes beyond the end. What is wrong? The code combines the iterator and index. After hasNext() returns true, the only way to advance the iterator is to call next(). But the element is retrieved with get (index), so the iterator is never advanced. In the above example, the hasNext () will always be true, and eventually the index i for get(index) will beyond the end of ArrayList. Do not mix up the iterator and the index. Let's change the above code to fix the problem: class Program { public static void main (String args []) { ArrayList<String> alist = new ArrayList<String>(); alist.add(new String("A")); alist.add(new String("B")); alist.add(new String("C")); for (Iterator<String> it = alist.iterator(); it.hasNext(); ) { System.out.println(it.next()); } } } or

class Program { public static void main(String args[]) { ArrayList<String> alist = new ArrayList<String>(); alist.add(new String("A")); alist.add(new String("B")); alist.add(new String("C")); for (int i=0; i != alist.size(); i++) { System.out.println(alist.get(i)); } } } What are mutable objects and immutable objects? An Immutable object is a kind of object whose state cannot be modified after it is created. This is as opposed to a mutable object, which can be modified after it is created. In Java, objects are referred by references. If an object is known to be immutable, the object reference can be shared. For example, Boolean, Byte, Character, Double, Float, Integer, Long, Short, and String are immutable classes in Java, but the class StringBuffer is a mutable object in addition to the immutable String. class Program { public static void main(String[] args) { String str = "HELLO"; System.out.println(str); str.toLower(); System.out.println(str); } } The output result is HELLO HELLO From the above example, the toLower() method does not impact on the original content in str. What happens is that a new String object "hello" is constructed. The toLower() method returns the new constructed String object's reference. Let's modify the above code: class Program { public static void main(String[] args) { String str = "HELLO"; System.out.println(str); String str1 = str.toLower(); System.out.println(str1); } }

The output result is HELLO hello The str1 references a new String object that contains "hello". The String object's method never affects the data the String object contains, excluding the constructor. In Effective Java, Joshua Bloch makes this recommendation: "Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, you should still limit its mutability as much as possible." What are the guidelines to implement immutable object? Please visit Immutable Object.

Immutable Object Objects have identity (location in memory), state (data), and behavior (methods). Once constructed, an Immutable Object cannot change state. Immutable objects greatly simplify your program, since they

are simple to construct, test, and use are automatically thread-safe and have no synchronization issues do not need a copy constructor do not need an implementation of clone do not need to be copied defensively when used as a field make good Map keys and Set elements (these objects must not change state while in the collection) Immutable Objects are often also ValueObjects, e.g. when used as Map keys

Make a class immutable by following these guidelines :


always put all data in the constructor, instead of using a no-argument constructor combined with subsequent calls to setXXX methods do not provide any methods which can change the state of the object in any way not just setXXX methods, but any method which can change state ensure no methods can be overridden - make the class final, or use static factories and keep constructors private make fields final if a mutable object field's state is "owned" by the native class, such that no other class is to be allowed to change the state of the field, then when the field "crosses the interface" (as in a get method, when the field is returned to the user, or in the constructor itself), then a defensive copy must be made, in order to maintain encapsulation. if a mutable object field's state is not "owned" by the native class, then defensive copies of the object field are not necessary

Example

import java.util.Date; /** * Planet is an immutable class, since there is no way to change * its state after construction. */ public final class Planet { /** * Primitive data is always immutable. */ private final double mass; /** * An immutable object field. (String objects never change state.) */ private final String name; /** * A mutable object field. In this case, the state of this mutable field * is to be changed only by this class. (In other cases, it makes perfect * sense to allow the state of a field to be changed outside the native * class; this is the case when a field acts as a "pointer" to an object * created elsewhere.) */ private final Date dateOfDiscovery; /** Sole constructor */ public Planet (double mass, String name, Date dateOfDiscovery) { this.mass = mass; this.name = name; //make a private copy of dateOfDiscovery //this is the only way to keep the dateOfDiscovery //field private, and shields this class from any changes //to the original dateOfDiscovery object this.dateOfDiscovery = new Date(dateOfDiscovery.getTime()); } //gets but no sets, and no methods which change state public double getMass() { return mass; }

public String getName() { return name; } /** * Returns a defensive copy of the field. * The caller of this method can do anything they want with the * returned Date object, without affecting the internals of this * class in any way. */ public Date getDateOfDiscovery() { return new Date(dateOfDiscovery.getTime()); } }

Can an overriding method have a different return type than the overridden method? Before Java 5.0, when you override a method, both parameters and return type must match exactly. In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass. For example, the following code compiles and the narrower type B is a legal return type for the getObject method in the subclass, Sub. class A { } class B extends A { } class Super { public A getObject() { System.out.println("Super::getObject"); return new A(); } } class Sub extends Super { public B getObject() { System.out.println("Sub::getObject"); return new B(); }

public static void main(String[] args) { Super s = new Sub(); s.getObject(); } } The output of the above code is: Sub::getObject But, the following code will not compile because String is not a legal return type for the getObject method in the subclass, Sub. String does not extends from either A or B. class A { } class B extends A { } class Super { public A getObject() { System.out.println("Super::getObject"); return new A(); } } class Sub extends Super { public B getObject() { System.out.println("Sub::getObject"); return new B(); } public String getObject() { return "getObject()"; } public static void main(String[] args) { Super s = new Sub(); s.getObject(); } } What is the difference between an abstract class and an interface? An abstract class can be partly finished so that the child class can fill in appropriate missing info. An interface simply demands that an implementing class to implement a certain behavior, leaving it up to the implementing class as to how this is to be done. Neither interface or abstract classes can be instantiated. What is the defferent between them?

An abstract class can contain both non-abstract methods (methods with a body) and abstract methods (methods without a body). An interface only contains abstract methods. A class can implement multiple interfaces, but can only subclass one abstract class. An abstract class can have instance variables and instance initializers. An interface cannot. Any variables defined in an interface are implicitly public, static, and final (the variables of an interface are final they must be initialized). An abstract class can define constructor. An interface cannot. An abstract class can have public or protected methods. An interface can have only public methods. An abstract class inherits from Object and includes methods such as clone() and equals().

Why narrowing primitive conversions from primitive long requires explicit casting? Converting a large primitive type to a smaller primitive type is called narrowing primitive conversion. There's a special case known as an assignment conversion that handles some conversion without explicit casting. Let's take a look at the following code: class Program { public static void main(String[] args) { final int iVar = 10; byte bVar = iVar; fianl int iVar1 = 345; byte bVar1 = iVar1; //Compile time error } } In this example, a variable of type byte is being assigned a value of a constant expression of type int. This implies a narrowing conversion. We know that the value of constant expression must be in the range of variable's type for the assignment conversion to happen. In our example, as long as the value of iVar is for -128 to 127, the narrowing conversion is used in the assignment conversion. The following code does not compile, even with the value of constant expression is in the range of type byte: class Program { public static void main(String[] args) { final long lVar = 10; byte bVar = lVar; //compile time error } } Why the assignment conversion doesn't work here? We have a constant expression and the value is representable for the type byte. Here is answer from JLS:

5.2 Assignment Conversion in Java Language Specification 3rd Edition: In addition, if the expression is a constant expression of type byte, short, char or int: A narrowing primitive conversion MAY BE used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable. A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is : o Byte and the value of the constant expression is representable in the type byte. o Short and the value of the constant expression is representable in the type short. o Character and the value of the constant expression is representable in the type char.

In the above example, the expression is a constant expression of type long and it is not covered by the special case. Therefore, a explicit cast must be used. class Program { public static void main(String[] args) { final long lVar = 10; byte bVar = (byte)lVar; } } When is an explicit object reference casting is required? General speaking, if the left hand side of an assignment is a more specific type (subtype) and the right hand side is a more general type (supertype), then explicit casting is required. On the other hand, when you assign a subclass reference to a variable of superclass, the casting is performed automatically, or not required. Another case is calling methods from an object reference, you can not access methods that are only declared and implemented in its subclass. You have to explicit cast the object reference into the actual object type. For example, class Super { } class Sub extends Super { public void writeLog() { System.out.println("log"); } class Program { public static void main(String[] args) { Sub b = new Sub(); // sub type reference can be assigned to super type

without casting Super a = b; // super type reference has to be casted before assigned to sub type b = (Sub)a; ((Sub)a).writeLog(); // method only defined in sub type } } Java compiler is not responsible for checking if the casting is correct or not, just like some of the bindings only occur at run time ( XyzWs Java FAQ: Run time binding or compile time binding?). Java virtual machine does the checking at run time to find out whether the actual reference object is a legitimate object of the new type. If not, there will be a runtime exception: ClassCastException. When is an object eligible for garbage collection? An object is eligible for garbage collection when there are no more root set of references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. What are root sets of references? The object references in the local variables, operand stack of any stack frame and any object references in any class variables, and object references that were passed to native methods that either haven't been "released" by the native method.

In Reference Objects and Garbage Collection: An executing Java program consists of a set of threads, each of which is actively executing a set of methods (one having called the next). Each of these methods can have arguments or local variables that are references to objects. These references are said to belong to a root set of references that are immediately accessible to the program. Other references in the root set include static reference variables defined in loaded classes, and references registered through the Java Native Interface (JNI) API. All objects referenced by this root set of references are said to be reachable by the program in its current state and must not be collected. Also, those objects might contain references to still other objects, which are also reachable, and so on. In Garbage Collection: The root set in a Java virtual machine is implementation dependent, but would always include any object references in the local variables and operand stack of any stack frame and any object references in any class variables. Another source of roots are any object references, such as

strings, in the constant pool of loaded classes. The constant pool of a loaded class may refer to strings stored on the heap, such as the class name, superclass name, superinterface names, field names, field signatures, method names, and method signatures. Another source of roots may be any object references that were passed to native methods that either haven't been "released" by the native method. (Depending upon the native method interface, a native method may be able to release references by simply returning, by explicitly invoking a call back that releases passed references, or some combination of both.) Another potential source of roots is any part of the Java virtual machine's runtime data areas that are allocated from the garbage-collected heap. For example, the class data in the method area itself could be placed on the garbage-collected heap in some implementations, allowing the same garbage collection algorithm that frees objects to detect and unload unreferenced classes.

What is 'Islands of Isolation' in garbage collection? You may already know that when an object is not referenced by other objects, it's eligible for garbage collection. But do you know the following two statements are also true?

"If an object obj1 is garbage collected, but another object obj2 contains a reference to it, then obj2 is also eligible for garbage collection" "If object obj2 can access object obj1 that is eligible for garbage collection, then obj2 is also eligible for garbage collection"

This is called "Island of Isolation". An "island of isolation" describes one or more objects have NO references to them from active parts of an application. In When is an object eligible for garbage collection?, we talked about: any object, that are not accessible from root set of references, is eligible for garbage collection. If object obj1 is eligible for garbage collection meaning it is not reachable by any objects from root set of references. Then the garbage collection algorithm tries to find any objects that have ONLY refernce to object obj1 (in this case object obj2) which also become eligible for garbage collection. If obj2 was accessible from root then the object obj1 would never be eligible for garbage collection in the first place. Therefore, it must be that the object obj2 cannot be referenced from the active part of the program, and so object obj2 is eligible for garbage collection. Here is an example, class Person { public Person public static Person obj1 Person obj2 obj2.firend firend; void main(String[] args) { = new Person(); = new Person(); = obj1;

obj1 = null; obj2 = null; ..... } }

//Line A //Line B

After Line A executes, The object obj2 still has a reference to the object obj1 and the object obj2 is still referenced by the variable obj2. Therefore, the object obj1 can not be eligable for garbage collection. After Line B exectues, there are no more references to the object obj2. There still is a reference to object obj1 inside the object obj2. Now, the object obj1 and obj2 has no reference from root set of references. Therefore, both of objects are eligible for garbage collection. What are the differences between interrupted() and isInterrupted() method of the Thread class? There are some subtle differences between the Thread (Thread API Document) methods interrupted() and isInterrupted():

The interrupted() is a static method in Thread class that determines if the current thread has been interrupted. "The interrupted status of the thread is cleared by this method". Therefore, if a thread was interrupted, calling interrupted() once would return true, while a second call to it would return false until the current thread is interrupted again. The isInterrupted() is an instance method that tests if this thread instance has been interrupted. "The interrupted status of the thread is unaffected by this method".

Why can any non-final class be casted to an interface? A cast to an interface is always allowed at compile-time unless the class is final class and does not implement this interface. 5.5 Casting Conversion in JLS, you are trying to cast a reference type S to a reference type T:

If S is a class type: o If T is a class type, then either |S| <: |T|, or |T| <: |S|; otherwise a compiletime error occurs. Furthermore, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types, and that the erasures of X and Y are the same, a compile-time error occurs. o If T is an interface type: If S is not a final class, then, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types, and that the erasures of X and Y are the same, a compile-time error occurs. Otherwise, the cast is always legal at

o o

compile time (because even if S does not implement T, a subclass of S might). If S is a final class, then S must implement T, or a compile-time error occurs. If T is a type variable, then this algorithm is applied recursively, using the upper bound of T in place of T. If T is an array type, then S must be the class Object, or a compile-time error occurs.

The idea is that even if the class does not implement the interface, but one of its subclass maght. If the actually object class does not implement the interface then you will get a ClassCastException error at runtime. For example, interface MyInterface{} class MyObject{} public class Program { public static void main(String arg[]){ Program po = new Program(); MyInterface it = (MyInterface)po; //compile fine MyObject obj = (MyObject)po; //compile time error } } Why not final class? The compiler knows at compile time exactly what interfaces are implemented by the final class. If the compiler can determine at compile time that the final class can never be instanceof the interface, that's a compile time error. Can an object access a private member of another object of the same class? Yes, an object can access private instant members of other objects in the same class. Let's re-exam an example from "Why always override hashcode() if overriding equals()?" in XyzWs Java FAQ. public class CustomerID { private long crmID; private int nameSpace; public CustomerID(long crmID, int nameSpace) { super(); this.crmID = crmID; this.nameSpace = nameSpace; } public boolean equals(Object obj) { //null instanceof Object will always return false if (!(obj instanceof CustomerID))

return false; if (obj == this) return true; return this.crmID == ((CustomerID) obj).crmID && this.nameSpace == ((CustomerID) obj).nameSpace; } public static void main(String[] args) { Map m = new HashMap(); m.put(new CustomerID(2345891234L,0),"Jeff Smith"); System.out.println(m.get(new CustomerID(2345891234L,0))); } } In the above example code, you can see that crmID and nameSpace are private fields. ArrayList vs. LinkedList -- Which one is better?

ArrayList implements the RandomAccess interface, and LinkedList does not. Note that Collections.binarySearch does take advantage of the RandomAccess property, to optimize searches. A LinkedList does not support efficient random access An ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. The get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. (see What is the advantage of using an Iterator compared to the get(index) method?) An ArrayList is much faster than LinkedList doing a binary search on the large list of sorted element. A LinkedList are more efficient speed wise than ArrayList when inserting and removing at random places in the list multiple times. If you're just adding to the end of the list, an ArrayList is what you want. A LinkedList is faster than an ArrayList when elements are only added to the beginning of the list. A LinkedList has a simple growth pattern of just adding and removing nodes when it needs to, but the ArrayList has a growth algorithm of (n*3)/2+1, meaning that each time the buffer is too small it will create a new one of size (n*3)/2+1 where n is the number of elements of the current buffer and there will be a significant amount of space wasted at the end. The reversing a LinkedList using Collections.reverse. The internal algorithm does this, and gets reasonable performance, by using forward and backward iterators.

What are the differences between synchronized method and synchronized block (statement)?

The 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 resource while another thread is in the process of using or updating that resource. There two-synchronization syntax in Java Language. The practical differences are in controlling scope and the monitor. With a synchronized method, the lock is obtained for the duration of the entire method. With synchronized blocks you can specify exactly when the lock is needed. Basically, synchronized blocks are more general, and synchronized methods can be rewritten to use synchronized blocks: class Program { public synchronized void f() { ......... } } is equivalent to class Program { public void f() { synchronized(this){ ... } } } For example, You have a method with some parts that need synchronized and others don't. The synchronized block lets you synchronize only the partial line codes that really need it. public class Program { private static Object locker1 = new Object(); private static Object locker1 = new Object(); public void doSomething1() { ... synchronized(locker1) { ......... //do something protected; } .... } public void doSomething2() { ... synchronized(locker2) { ......... //do something protected; } .... } }

The synchronized block can only be executed after a thread has acquired the lock for the object or class referenced, for example the "locker1" or "locker2" in above code, in the synchronized statement. The above code shows that synchronized block can be holding different object monitors. Maybe it's necessary to protect doSomething1() method and doSomething2() method from multiple threads, but it's fine if one thread is in the doSomething1() method and another is in the doSomething2() method. But the synchronized method can not do it. A synchronized method synchronizes on the object instance or the class. A thread only executes a synchronized method after it has acquired the lock for the method's object or class.

static synchronized methods synchronize on the class object. If one thread is executing a static synchronized method, all other threads trying to execute any static synchronized methods, in the same class, will block. non-static synchronized methods synchronize on "this" (the instance object). If one thread is executing a synchronized method, all other threads trying to execute any synchronized methods, in the same class, will block.

These are very public monitors, meaning some other thread could synchronize on them for the wrong reason, leading to slowdowns or deadlocks. What can you catch when try block does not throw exception? Let's take a look at the following code: class Program { public static void main(String[] args) { try { method(); } catch (FileNotFoundException e) { ; } } static void method() { } } The above code will generate a compile-time error: "Unreachable catch block ....". But the following code does not generate a compile time error: class Program {

public static void main(String[] args) { try { method(); } catch (Exception e) { ; } } static void method() { } } The Java compiler does not require you to catch an unchecked exception. If you do catch an unchecked exception even the code does not throwing it, the compiler will not generate a compile-time error. The unchecked exceptions have the benefit of not forcing the client code to explicitly deal with them. The RuntimeException and its subclasses are unchecked exceptions. Error and its subclasses are also unchecked exceptions. The RuntimeException is the subclass of Exception, Therefore, catching the Exception exception without throwing any exceptions in try block will not generate comiple-time error. Summary for try-catch without throw exception:

Catching Throwable, Error (including its subclasses), Exception, and RuntimeException (including its subclasses) always compile. Catching directly subclasses of Throwable except for Exception and Error will generate a compile time error. Catching subclasses of Exception except for RuntimeException will generate a compile time error

Is a class subclass of itself? No. A class is not a subclass of itself. What are the differences between System.gc() and Runtime.gc()? There is no difference between these two methods. Both methods suggest that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects. The System.gc() is a static method so it's a little bit more convenient to use. The call System.gc() is effectively equivalent to the call:

Runtime.getRuntime().gc() Why it is not required to declare the exceptions declared in the superclass' method when overriding it? An implementation of an overriding method in a subclass may be totally different with its overridden method in the superclass. It may not have any exceptions needed to throw at all. The only restriction in Java compiler (8.4.6 Method Throws)is that the overriding method in subclass cannot be declared to throw border or new checked exceptions than the overridden method in the superclass (otherwise, you may break other codes because the runtime polymorphism).

When should I use volatile modifier? A variable that might be concurrently modified by multiple threads (without locks or a similar form of mutual exclusion) should be declared volatile. The volatile modifier can be used to inform the compiler that it should not attempt to perform optimizations on the field, which could cause unpredictable results when the field is accessed by multiple threads. For example, A multiprocessor system(>2 CPUs) with 2 threads sharing a single variable in memory.

Thread 1 reads the variable and caches it in one of the registers for efficient access. Thread 2 reads the memory and changes its value. Now if Thread 1 wants to access the value, it may get it from its cache and thus end up with a wrong value.

To avoid these scenarios a variable can be declared as volatile, thus informing the JVM that the value can change asynchronously and has to be fetched always from memory or in other words it is like saying to JVM "Please do not optimize this variable for any reason". synchronized vs. volatile It is important to understand that atomic operations do not automatically mean threadsafe operations. In addition, whenever multiple threads share variables, it is important that they are accessed in a synchronized method or block, or are declared with the volatile keyword. This ensures that the variables are properly reconciled with main memory, thereby guaranteeing correct values at all times. Whether you use volatile or synchronized depends on several factors. If concurrency is important and you are not updating many variables, consider using volatile. If you are updating many variables, however, using volatile might be slower than using synchronization. Remember that when variables are declared volatile, they are reconciled with main memory on every access. By contrast, when

synchronized is used, the variables are reconciled with main memory only when the lock is obtained and when the lock is released. Consider using synchronized if you are updating many variables and do not want the cost of reconciling each of them with main memory on every access, or you want to eliminate concurrency for another reason. The following summarizes the differences between the synchronized and volatile keywords.

synchronized o Pro: Private working memory is reconciled with main memory when the lock is obtained and when the lock is released. o Con: Eliminates concurrency. volatile o Pro: Allows concurrency. The visibility of the changes made by a thread to the content of the variable respect others threads o Con: Private working memory is reconciled with main memory on each variable access. The volatile has nothing to do with preventing simultaneous execution of a portion of code but synchronized does.

Why can not a variable be volatile and final? A volatile variable means it could be changed by several threads so a thread should always reconcile the value with what is saved in memory rather than assume that the variable it finds is valid. If a variable is final it can't be changed so there is no reason to need to reconcile values. Thus volatile and final are contradictory in a way. It doesn't make sense to be able to combine them thus java does not allow it. How differently does Java handle checked and unchecked exceptions?

If a method may throw checked exceptions, the calling code must handle the exception by either catching it or by declaring in the signature of the method (as throws). Unchecked exceptions do not have to be handled by the calling code. If a method might throw a checked exception, it must be declared in the signature of the method. Unchecked exceptions do not have to be listed in the method signature.

How many ways can I access static members in a class? A static member (static method or static variable) can be accessed by using the dot operator on the class name (e.g., Math.max(..);). This is a standard and right way to access a static member in a class. But Java language also allows you to use an object reference to access a static member. This is bad or at least poor form because it creates the impression that some instance variables in the object are used, but this isn't the case. For example,

//Access static member from within the same class class MyObject1 { static int staticVariable = 10; void m() { MyObject1 o = null; int i1 = staticVariable; int i2 = this.staticVariable; int i3 = MyObject1.staticVariable; int i4 = o.staticVariable; } } //Access static member from outside the class class MyObject2 { void m() { MyObject1 o = new MyObject1(); int i5 = MyObject1.staticVariable; int i6 = o.staticVariable; } } When we access a static member on an object reference, what the value of the object reference is (point to an instance or null). Only the type of the object reference matters. That is why int i4 = o.staticVariable; will not throw a NullPointerException. It's best practice to always invoke static member using the class name rather then an object reference of the class. When to use abstract classes? Abstract classes in Java are just like regular Java classes but you cannot instantiate them directly. They may not completely implement all methods defined in classes. This incomplete implementation may be different in different context. Derived class implements the abstract class in its context. When you have a common implementation, abstract classes shine. Using abstract classes you can enforce an implementation hierarchy and avoid duplicate code. Using abstract classes, however, should not affect your decision to use interfaces to define your behavior. An abstract class allows to add new methods without breaking compatibility. The derived class can just provide working implementation of a subset of the methods defined in the abstract class. While if you add new methods to an interface, you'd need to update all the classes that implements the interface. Why Interface is useful?

In Java, an interface defines new a type including a set of unimplement operation on it. An interface defines a protocol of behavior that can be implemented by any classes. A non-abstract class that implements the interface must implement all the methods defined in the interface. The interface presents what its methods are and leave how to do them to the implementation class. A same method in the interface can have totally different implementation in different classes. The interface provides a clearner separation of behavior and implementation. Because the class must implement all the methods defined in the interface, any changes on the method of the interface will affect to all the classes that implements the interface. Is PriorityQueue an ordered and sorted collection? PriorityQueue is certainly ordered, but is it sorted? Yes it is. However it's not of the type for the sorted collections, such as SortedSet and SortedMap.

Ordered and sorted are not the same thing. All sorted collections are also ordered, but not all ordered collections are sorted. For example, A List is always ordered - its elements have definite positions - but it isn't sorted unless you sort it somehow (e.g. with Collections. sort ()). PriorityQueue orders elements according to an order specified at construction time, which is specified either according to their natural order (see Comparable), or according to a Comparator, depending on which constructor is used. A PriorityQueue does not permit null elements. A PriorityQueue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException). When you do not create the PriorityQueue with a Comparator, the elements that you add to the queue must be mutually Comparable (e.g., This means that your element class need to to implement Comparable interface). The PriorityQueue class and its Iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the PriorityQueue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()). Only the order as seen by the Queue methods (element(), peek(), poll(), remove()) is guaranteed to reflect the sorted order. The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily. Therefore, PriorityQueue is a bit outside Java's "standard" sorted collections as defined by SortedSet and SortedMap. For this reason, some people would say that PriorityQueue is ordered but not sorted. How does the result differ between the String and number operands of the '+' operator?

Let's take a look at the following example, class Program { public static void main(String[] args) { System.out.println(1 + 2 + " fiddlers"); System.out.println("fiddlers " + 1 + 2); } } The output is: 3 fiddlers fiddlers 12 The + operator is syntactically left-associative, the expression a + b + c is always regarded as (a + b) + c. The type analysis to represent string concatenation or addition is based on the evaluation order. In the 1 + 2 + " fiddlers", the first two are int, so the result is 3. Then since the next operand is a String object, 3 is converted to String and "fiddlers" is concatenated to 3, so the result is "3 fidders". In the "fiddlers " + 1 + 2, since the first operand is a String, the rest of the operands are converted to String then concatenated to it, so the result is "fiddlers 12". When initialization occurs in an interface? According to Java language specification, initialization of an interface consists of executing the initializers for fields declared in the interface. Before a class is initialized, its direct superclass must be initialized, but interfaces implemented by the class need not be initialized. Similarly, the superinterfaces of an interface need not be initialized before the interface is initialized. Initialization of an interface does not, of itself, cause initialization of any of its superinterfaces. Here is an example listed in JLS. More detail information and example can find in 12.4 Initialization of Classes and Interfaces. interface I { int i = 1, ii = Test.out("ii", 2); } interface J extends I { int j = Test.out("j", 3), jj = Test.out("jj", 4); } interface K extends J { int k = Test.out("k", 5); }

class Test { public static void main(String[] args) { System.out.println(J.i); System.out.println(K.j); } static int out(String s, int i) { System.out.println(s + "=" + i); return i; } } produces the output: 1 j=3 jj=4 3 The reference to J.i is to a field that is a compile-time constant; therefore, it does not cause I to be initialized. The reference to K.j is a reference to a field actually declared in interface J that is not a compile-time constant; this causes initialization of the fields of interface J, but not those of its superinterface I, nor those of interface K. Despite the fact that the name K is used to refer to field j of interface J, interface K is not initialized. System.out.println(J.i); // The i variable is inherited from I but since it is a constant - you don't have to go through the whole process of initializing I, just reference it and get on with things. System.out.println(K.j); // now this is more complicated. Since the variable holds something other than a constant, the first thing that we have to do is initialize J so that we can figure out what to DO to come up with the value of j. Initializing interface J causes variable j to be initialized first: executing Test.out("j",3) which prints j=3, and setting the variable j to 3 (note the return type on the method). Now jj is initialized executing Test.out("jj",4) which prints jj=4 and sets the variable jj to 4. Now that initialization is done we can evaluate and execute the println for K.j which prints the current value of j which is 3.

Why down casting throws ClassCastException? You cannot assign a superclass reference variable to a subclass reference without a cast of the subclass type. Examples can find in When is an explicit object reference casting is required?. The compiler is happy when you explict cast the superclass reference to subclass reference, but the compiler does not care what the actual object holded by the reference. Does it actually have a superclass object, or just a superclass reference holding a subclass object? No answer from compile time but it has to answer this quesiton.

You can not just take a parent object and suddenly turn it into a child though. The parent object is not an instance of the subclass. If the actual object holded by the reference is a superclass object, casting it to a subclass reference result in a compile time error. class SuperClass { ... } class SubClass extends SuperClass { ... } public class Program { public static void main(String[] args) { // case 1: actual SuperClass object SuperClass p1 = new SuperClass(); // case 2: SubClass object is referred by a SuperClass reference SuperClass p2 = new SubClass(); SubClass s1 = (SubClass)p1; //run time error SubClass s2 = (SubClass)p2; //OK } } Why wait(), notify(), notifyAll() must be called inside a synchronized method/block? In Java, any object can act as a monitor - that's an entity with a single lock, an entry queue, and a waiting queue. An object's method without qualified by the keyword synchronized can be invoked by any number of threads at any time, the lock is ignored. The synchronized method of an object, one and only one thread, who owns the lock of that object, can be permitted to run that method at any time;i.e. a synchronized method is mutually exclusive . If, at the time of invocation, another thread owns the lock, then the calling thread will be put in the Blocked state and is added to the entry queue. The wait(), notify(), and notifyAll() methods should be called for an object only when the current thread has already locked the object's lock. This point sometimes goes unnoticed because programmers are used to calling these methods from within synchronized methods or blocks. Otherwise, you will get "java.lang.IllegalMonitorStateException: current thread not owner" at runtime. When a thread running in a synchronized method of an object is calling the wait() method of the same object, that thread releases the lock of the object and is added to that object's waiting queue. As long as it's there, it sits idle. Note also that wait() forces the thread to release its lock. This means that it must own the lock of an object before calling the wait() method of that (same) object. Hence the thread must be in one of the object's synchronized methods or synchronized block before calling wait().

When a thread invokes an object's notify() or notifyAll() method, one (an arbitrary thread) or all of the threads in its waiting queue are removed from the waiting queue to the entry queue. They then actively contend for the object's lock, and the one that gets the lock goes on to execute. If no threads are waiting in the waiting queue, then notify() and notifyAll() have no effect. Before calling the notify() or notifyAll() method of an object, a thread must own the lock of the object. Hence it must be in one of the object's synchronized methods or synchronized block. A thread in the waiting queue of an object can run again only when some other thread calls the notify() (or the notifyAll) method of the same object. The reason to call wait() is that the thread does not want to execute a block of code until a particular state to be achieved. It wants to wait until a particular state to be achieved. The reason to call notify() or notifyAll() method is that the thread will signal others that "a particular state has been achieved". The state is a communication channel between threads and it must be shared mutable state. For example, one thread read data from a buffer and one thread write data into buffer. The reading data thread needs to wait until the writing data thread completly write a block data into the buffer. The wirting data thread needs to wait until the reading data thread completly read the data from the buffer. If wait(), notify(), and notifyAll() methods can be called by a ordinary method , the reading thread calls wait() and the thread is being added to waiting queue . At just the same moment, the writing thread calls notify() to signal the condition changes. The reading thread misses the change and waits forever. Hence, they must be called inside a synchronized method or block which is mutually exclusive. What is the difference between parseXxx() and valueOf()? The parseXxx() methods and the valueOf() methods are defined in most of the numeric primitive wrapper classes, such as Integer, Long, Double, FLoat, etc. Both methods take a String argument and convert it into the corresponding primitive type with the value that the String represents. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. If the String argument is not properly formed, both throws a NumberFormatException. The biggest difference between these two methods is that:

parseXxx() returns the primitive type; valueOf() returns a wrapper object reference of the type.

Let's take a look at the following examples: int i = Integer.parseInt("100"); // the result is 100 Integer i = Integer.valueOf("100"); // create a Integer object with value 100 double d = Double.parseDouble("12.34");

Double d = Double.valueOf("12.34"); Both methods has a overloaded counter part, which takes a radix as the second argument. The methods that doesn't takes the radix as the second argument, uses 10 as the radix. For example: long l = Long.parseLong("10101010", 2); // binary String to long, the value is 170 Long l = Long.valueOf("10101010", 2); // created a Long object with value 170 What Should I Know about AutoBoxing and UnBoxing in Java 5.0? Within Java 5.0, wrapper classes have become easier to use. Java 5.0 introduced automatic conversion between a primitive type and the corresponding wrapper class. From primitive type to it corresponding wrapper class is called autoboxing, the reverse process is called unboxing. Autoboxing and unboxing also apply to methods calls. For example, you can pass an argument of type int to a method that has a formal parameter of type Integer.

A NullpointerException exception occurs when unboxing a null wrapper class's reference to its primitive type. For example, the code will compile but it will throw a NullpointerException at runtime. ... Long L = null; long l = L; ...

Boxing conversion converts values of primitive type to corresponding values of reference type. But the primitive types can not be widened/Narrowed to the Wrapper classes and vice versa. For example, byte b = 43; //Constant integer value //Cast to int type

Integer I1 = 23; Integer I2 = (int)b;

Long L1 = 23; //compile error because 23 is integer value Long L2 = (Long)23; //can not cast integer value to Long wrapper class Long Long L3 = 23L; L4 = (long)23;

This restriction is also applied to method invocation: public class MyClass { public void method(Long i) {

System.out.println("Here"); } public static void main(String[] args) { MyClass s = new MyClasslass(); //s.method(12); // error s.method(12L); // ok } }

When invoking a method from multiple overloading methods, For the matching method process, the Java compiler will perferance the order of primitive types (Widening Primitive Conversion), wrapper class (Boxing Conversion), and varargs. For example, public class MyClass { public void method(Long x, Long y) { System.out.println("method(Long x, } public void method(long x, long y) { System.out.println("method(long x, } public void method(long... x) { System.out.println("method(long... } public static void main(String[] args) long x, y; x = y = 0; MyClass s = new MyClass(); s.method(x, y); } }

Long y)"); long y)"); x)"); {

The result is "method(long x, long y)". The Java compiler will check for the matching primitive types, then it will search for the Wrapper types. public class MyClass { public void method(Long x, Long y) { System.out.println("method(Long x, Long y)"); } public void method(int x, int y) { System.out.println("method(int x, int y)"); } public void method(long... x) { System.out.println("method(long... x)"); } public static void main(String[] args) { long x, y; x = y = 0;

MyClass s = new MyClass(); s.method(x, y); } } The result is "method(Long x, Long y)". The Java compiler gives preferance to the matching Wrapper class method signature other than the primitive varargs method. public class MyClass { public void method(Double x, Double y) { System.out.println("method(Double x, (Double y)"); } public void method(int x, int y) { System.out.println("method(int x, int y)"); } public void method(long... x) { System.out.println("method(long... x)"); } public static void main(String[] args) { long x, y; x = y = 0; MyClass s = new MyClass(); s.method(x, y); } } The result is "method(long ...x)". The compiler will not narrow down "long" primitive value to "int"; Also, it can not winden long to Double class. Only the var-args method can be used. public class MyClass { public void method(Long x, Long y) { System.out.println("method(Long x, Long y)"); } public static void main(String[] args) { int x, y; x = y = 0; MyClass s = new MyClass(); s.method(x, y); } } The arguments can not winden to "long" and then box to "Long". You will get compile error.

In order to save memory, two instances of the following wrapper objects will always be == when their primitive values are the same. Please read Why does the autoboxing conversion sometimes return the same reference?

Can we synchronize static method/variable in a Java class? Yes, you can do it. A synchronized method or block works on a given monitor. Synchronized non-static methods all synchronize on the Java instance of a class. Each instance has a lock monitor. For the case of static methods, what object does static synchronized methods use for locking? The static synchronized statements obtain a lock on the Class object. The following example show you few ways to access the class object: class MyClass { .... public static void main(String[] args) { //you can access class object through an instance of that class MyClass objectinstance = new MyClass(); java.lang.Class myclass1 = objectinstance.getClass(); //non-instance ways java.lang.Class myclass2 = Myclass.class; java.lang.Class myclass3 = Class.forName("MyClass"); } } The JVM creates a Class object when the class is loaded (When it is used for the first time). Once a class is loaded into a JVM, the same class will not be loaded again. The JVM creates one instance of Class for each class that is loaded, The Class instances are Objects and can be synchronized via static synchronized methods. For example class MyClass { ... public synchronized static someMethod() { ... } ... } It is the equivalent to the following static synchronized block: synchronized (MyClass.class) { ... }

In some situatios, you need to protect access static variables, the locking an object instance does not automatically protect access to static variables, because there may have more than one instances and all of them use the same static variables. You have to obtain a lock on the Class vs an instance of the class. A static synchronized block can be use to protect access to static varibales, a lock on a static method has no effect on any instances of that class (see the Java Language Specification). For example, class BumpTest { int count; static int classCount; void synchronized bump() { count++; try { synchronized (BumpTest.class) { //or synchronized (Class.forname("BumpTest")) classCount++; } } catch (ClassNotFoundException e) { } ... } Static variables, like static methods, are not inherited, but are accessible from within the body of the class definition and through an explicit reference to the defining class's name. Adding a new static synchronized method in a subclass cannot protect other threads to access static variables defined in its superclass nor should you use synchronized(this.getClass()) which locks the actual Class might be the subclass. An explicit block synchronization with "none-instance way to get Class" is the preferred way.

8.4.3.6 synchronized Methods A synchronized method acquires a monitor (??17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used. How to use the synchronized keyword? There are two syntactic forms based on the synchronized keyword, methods and blocks. A synchronized method acquires a lock before it executes. For example, the following synchronized method class MyClass { public synchronized void function() {

.... } } is equivalent to the following synchronized block class MyClass { public void function() { synchronized(this) { .... } } } Few notes about synchronized keyword:

The constructors and initializers cannot be synchronized and a compiler error will occur if you put synchronized front of a constructor. But constructors and initializers of a class can contain synchronized blocks. For example, class MyClass { static int x = 0; static int y = 0; { synchronized (MyClass.class) { x++; } } public MyClass() { synchronized(MyClass.class) { y++; } } }

Although the synchronized keyword can appear in a method header, the synchronized keyword is not part of the method signature. Therefore, it is not automatically inherited when subclasses override superclass methods. The synchronized methods can be overrided to be non-synchronous. The synchronized instance methods in subclasses use the same locks as their superclasses. The interface's methods cannot be declared synchronized. The Synchronization is part of the implementation but not part of the interface. The synchronization of an Inner Class is independent on it's outer class. That means locks on inner/outer objects are independent. Getting a lock on outer object doesn??t mean getting the lock on an inner object as well, that lock should be obtained separately

A non-static inner class method can lock it's containing class by using a synchronized block. The inner class can reference the outer class with OuterClass.this: synchronized(OuterClass.this) { .... }

How to run external programs from java under window? The java.lang.Runtime and java.lang.Process classes are available for executing and communicating with external programs. With an instance of the java.lang.Runtime class, it can execute an external program and return an instance of a subclass of java.lang.Process. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process. import java.io.*; import static java.lang.System.out; public class RumExternal { public static void main(String[] args) { String fileList="cmd /k dir"; try { Runtime rt = Runtime.getRuntime (); Process process = rt.exec (fileList); BufferedReader br = new BufferedReader ( new InputStreamReader( process.getInputStream() ) ); String line; while ((line = br.readLine ()) != null) out.println (line); br.close(); } catch (IOException e) { e.printStackTrace(); } } }

Implement callback routines in Java

Developers conversant in the event-driven programming model of MS-Windows and the X Window System are accustomed to passing function pointers that are invoked (that is, "called back") when something happens. Java's object-oriented model does not currently support method pointers, and thus seems to preclude using this comfortable mechanism. But all is not lost! Java's support of interfaces provides a mechanism by which we can get the equivalent of callbacks. The trick is to define a simple interface that declares the method we wish to be invoked. For example, suppose we want to be notified when an event happens. We can define an interface: public interface InterestingEvent { // This is just a regular method so it can return something or // take arguments if you like. public void interestingEvent (); } This gives us a grip on any objects of classes that implement the interface. So, we need not concern ourselves with any other extraneous type information. This is much nicer than hacking trampoline C functions that use the data field of widgets to hold an object pointer when using C++ code with Motif. The class that will signal the event needs to expect objects that implement the InterestingEvent interface and then invoke the interestingEvent() method as appropriate. public class EventNotifier { private InterestingEvent ie; private boolean somethingHappened; public EventNotifier (InterestingEvent event) { // Save the event object for later use. ie = event; // Nothing to report yet. somethingHappened = false; } //... public void doWork () { // Check the predicate, which is set elsewhere. if (somethingHappened) {

// Signal the even by invoking the interface's method. ie.interestingEvent (); } //... } // ... } In that example, I used the somethingHappened predicate to track whether or not the event should be triggered. In many instances, the very fact that the method was called is enough to warrant signaling the interestingEvent(). The code that wishes to receive the event notification must implement the InterestingEvent interface and just pass a reference to itself to the event notifier. public class CallMe implements InterestingEvent { private EventNotifier en; public CallMe () { // Create the event notifier and pass ourself to it. en = new EventNotifier (this); } // Define the actual handler for the event. public void interestingEvent () { // Wow! Something really interesting must have occurred! // Do something... } //... } How to get default character set for the Java virtual machine? Every instance of the Java virtual machine has a default charset, which may or may not be one of the standard charsets. The default charset is determined during virtual-machine startup and typically depends upon the locale and charset being used by the underlying operating system. In Java 5.0, the java.nio.charset class provides a static method, called the defaultCharset(), to retrieve the default charset. ... public static void main(String[] args) { Charset dfset = Charset.defaultCharset(); out.println(dfset.name());

} ... In the previous version of Java (JDK 1.4), you can get it from the getEncoding() methods of the InputStreamReader and OutputStreamWriter classes. The method returns the name of the character encoding being used. If the encoding has an historical name then that name is returned; otherwise the encoding's canonical name is returned. How Can I Catch All Possible Exceptions in Java? All exceptions come from the "mother class" called java.lang.Throwable and one of two subclasses called java.lang.Error and java.lang.Exception. A block of code that is executed when an exception occurs is called an Exception handler. By catching java.lang.Throwable, it is possible to handle all unexpected conditions. ... try { } catch(Throwable e) { ... } ... There are some special exceptions that used by the JVM, those are the sub-classes of java.lang.Error. We are not supposed the catch them in our real code and we usually catch java.lang.Exception for all application and runtime exceptions. ... try { } catch(Exception e) { ... } ... How to Use StringTokenizer in Java? The string tokenizer class allows an application to break a string into tokens. A token is returned by taking a substring of the string that was used to create the StringTokenizer object. There are three ways to construct a StringTokenizer. public class Program { public static void main(String[] args) { System.out.println("Case 1."); StringTokenizer st = new StringTokenizer("this is a

test"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } System.out.println("Case 2."); st = new StringTokenizer("this,is a=test", " ,="); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } System.out.println("Case 3."); st = new StringTokenizer("this,is a=test", " ,=", true); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } System.out.println("Case 4."); st = new StringTokenizer("this,is a=test", " ,=", false); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } } } The output is Case 1. this is a test Case 2. this is a test Case 3. this , is a = test

Case 4. this is a test StringTokenizer is pretty straight forward. You can separate a String by any delimiters that you choose such as a blank space, or a comma. Once you create a StringTokenizer object with a String, like above example. You can call nextToken() to get the next block of String (token). Advertisement

How to get memory information in Java program? In Java, memory is allocated in various places such as the stack, heap, etc. While your application is running, you can sniff out the memory using: Runtime.getRuntime().freeMemory() and Runtime.getRuntime().totalMemory(). public class Program { public static void main(String... args) { System.out.println("Max Memory : " + Runtime.getRuntime().maxMemory()); System.out.println("Total Memory : " + Runtime.getRuntime().totalMemory()); System.out.println("Free Memory : " + Runtime.getRuntime().freeMemory()); } } How to enable JDBC tracing? A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the system that is related to JDBC operations. If you use the DriverManager facility to establish your database connection, you use the DriverManager.setLogWriter method to enable tracing of JDBC operations. import import import import java.io.PrintWriter; java.sql.Connection; java.sql.DriverManager; java.sql.SQLException;

public class Program { public static void main(String... args) { Connection con = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance( ); DriverManager.setLogWriter(new PrintWriter(System.out)); } catch(Exception e) { System.out.println("Exception: " + e.getMessage()); return ; } try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my db", "usr", "sql"); if(!con.isClosed()) System.out.println("Successfully connected to " + "MySQL server using TCP/IP..."); } catch(Exception e) { System.out.println("Exception: " + e.getMessage()); } finally { try { if(con != null) con.close(); } catch(SQLException e) { } } } } If you use a DataSource object to connect to a data source, you use the DataSource.setLogWriter method to enable tracing. (For pooled connections, you use the ConnectionPoolDataSource.setLogWriter method, and for connections that can participate in distributed transactions, you use the XADataSource.setLogWriter method.)

You might also like