Skip to main content

Posts

Showing posts from August, 2010

What are differences among throw, throws, and Throwable?

-- In Java, all error's and execption's class are drieved from java.lang.Throwable class. It is the top of the hierarchy of classes of error and exceptions. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. throws is a post-method modifier and specifies which execptions may be thrown by the method. If they are checked exceptions, the compiler will guarantee the code invoking that method must catch these checked exceptions.  throw statement is used to throw an error or exceptions. throw statement requires a single argument: a instance of any subclass of the Throwable class or Throwable class. Executing throw statement triggers the JVM to throw this exception and causes an exception to occur.

What are the differences among greedy, reluctant and possessive quantifiers?

-- Quantifiers are used to indicate the number of instances of the element (to which they are applied in the regular expression) required for a successful match. Java supports three quantifier types namely greedy, reluctant, and possessive. Greedy quantifiers try to match as much as possible while their reluctant counterparts (with ? at the end) try to match the least required to fulfill a match. What this means is that a greedy quantifier will try to match the entire line whether or not a successful match has occurred. It can turn into real performance overhead when the target text is big. Reluctant (or lazy) quantifiers quit as soon as a successful match occurs without bothering to run through the entire line. Possessive quantifiers (with + appended) are useful in optimizing the match operations since they don't keep the prior match states around (Quote from Simplify Pattern Matching by Anant Athale ) For examp...

LinkedHashMap vs. HashMap?

-- A LinkedHashMap differs from HashMap in that the order of elements is maintained. A HashMap has a better performance than a LinkedHashMap because a LinkedHashMap needs the expense of maintaining the linked list. The LinkedHashMap implements a normal hashtable, but with the added benefit of the keys of the hashtable being stored as a doubly-linked list.  Both of their methods are not synchronized. Let's take a look their API documentations: The HashMap is a hash table with buckets in each hash slot. Like in the API documentation: This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very...

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. 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.

Can an anonymous inner class implement an interface?

-- Yes. An anonymous inner class can implement interface or extends class. Anonymous inner interfaces are always implicitly static . Here is how to create an instance of inner class and inner interface: Anonymous Inner Class class Outer{ abstract class InnerClass { abstract void doSomething(); } } public class Program { public Program() { super(); } public static void main(String[] args) { Outer.InnerClass obj = new Outer().new InnerClass(){ public void doSomething(){ System.out.println("InnerClass."); } }; obj.doSomething(); } }

What are operator precedence and the order of operand evaluation?

-- We had found precedence vs. order of evaluation and Re: *p++ great posts by Steve Summit in comp.lang.c. Here is summary of his posts in term of Java: The important thing about precedence is not that it tells us in what order things will be evaluated. The important thing about precedence is that it tells us which operators are matched up with which operands. The precedence determines which operations will be performed first and not the order of operand evaluation. The precedence can affect or influence order of evaluation. Now let's start looking at all of the ways that order of evaluation is determined by things other than precedence. In Java, operands are always evaluated from left to right. For example, multiplication and division are done before addition and subtraction, because multiplication and division have higher precedence than addition and subtraction. Therefore, a + b *c is the same as a + (b*c) , not (a+b)*c . The s...

How to use the toArray() method of Collection?

-- There are two versions of toArray() in the Collection interface: Object[] toArray() without parameter and Object[] toArray(Object[] a) with parameter. toArray() without parameter will always return an array of type Object[] that you won't be able to cast. The toArray(new String[0]) will return an array of type Object[] that you may cast to String[] . The toArray() and toArray(Object[] a) method act as bridge between array-based and collection-based APIs. Further, the toArray(Object[] a) method allows precise control over the runtime type of the output array, and may, under certain circumstances, be used to save allocation costs. The following is from the Javadoc: public Object[] toArray() Returns an array containing all of the elements in this collection. If the collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order. The returned array will be "safe...

How to specify multiple class search directories in the '-classpath' option of javac?

-- In developing a Java application, your class search path will contain numerous directories and JAR archives. The -classpath option to javac and java allows multiple entries to be specified. Enter the class path, using the appropriate separator character (colon for UNIX platforms, semicolon for Windows): On UNIX, we would do this: javac -classpath dir1:dir2:dir3 ... whereas on Windows we have: javac -classpath dir1;dir2;dir3 ... The reason for the difference is that Windows uses the colon (:) character as part of a filename, so it can't be used as a filename separator. Naturally the directory separator character is different as well: forward slash (/) for UNIX and backslash (\) for Windows.

How to specify JAR files in the classpath?

-- A JAR file (or J ava Ar chive) is a ZIP file, file that contains an optional META-INF directory, used to distribute a set of Java classes and interfaces . The java compiler and run-time can search for classes in JAR files. The classes in a JAR file must be under the right directory that is "directory name = package name". To include a JAR file in the class search path, the classpath points to the JAR itself, not the directory that contains the JAR. For example, you have a JAR myLibs.jar in directory /myLibs . To have the Java compiler look for classes in this jar, you need to specify: javac -classpath /myLibs/myLibs.jar ... and not directly point to the directory myLibs References Packaging Programs in JAR Files Java Archive (JAR) Files JAR File Specification

Why can't we have a static member within an inner class?

-- JLS: 8.1.3 Inner Classes and Enclosing Instances : An inner class is a nested class that is not explicitly or implicitly declared static . Inner classes may not declare static initializers (8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (15.28). Java programming language allows you to use nested classes: a class inside another class. For example: class OuterClass { ... class InnerClass { ... } } When a nested class is a static member of its enclosing class, the nested class is called a static nested class . When a nested class is a non-static, or instance member of its enclosing class, the nested class is called an inner class . An inner class can access the non-static fields/methods of the enclosing class. The instances of an inner class only exist within the instance of the enclosing class. The only static context can be defined in an inner class are these comp...

How does 'instanceof' work with interface?

-- An instanceof interface expression always allowed at compile time if the left hand of instance's class is not defined as final class. If the compiler can determine at compile time that the left hand side can never be casted to the interface, that's a compile time error. If the class is not a final class, the compiler can not determine what interfaces are implemented by it. Even if the class does not implement the interface, but one of its subclass might. If the actually object class does not implement the interface then you will get "false" at runtime.   interface MyInterface {} class MyObject {} public class Program { public static void main(String[] args) { MyObject obj = new MyObject(); String s = "hello"; // false, but legal   System.out.println(obj instanceof MyInterface); // compiler error, String is final class System.out.println(s instanceof MyInterface); } }

How to specify multiple class search directories in the '-classpath' option of javac?

-- In developing a Java application, your class search path will contain numerous directories and JAR archives. The -classpath option to javac and java allows multiple entries to be specified. Enter the class path, using the appropriate separator character (colon for UNIX platforms, semicolon for Windows): On UNIX, we would do this: javac -classpath dir1:dir2:dir3 ... whereas on Windows we have: javac -classpath dir1;dir2;dir3 ... The reason for the difference is that Windows uses the colon (:) character as part of a filename, so it can't be used as a filename separator. Naturally the directory separator character is different as well: forward slash (/) for UNIX and backslash (\) for Windows.

How to setup and use system classpath (CLASSPATH)?

-- Some utility code that you have developed or have obtained from a third party can usually be used in more than one Java program. These may sometimes be stored as packages, just as the Java utilities are in packages such as java.util.* . Whether or not they are packages or just a set of classes, you will want to store them in one place, separate from the directory where you are developing your program. Sometimes these libraries have a set of files stored in a single jar file (which is a file using zip format with a .jar extension). In order to make this work, the Java compiler and JVM must be able to find them. Rather than specifying class search path on the javac command line by using the -classpath , we can make use of a 'system' class path . The CLASSPATH is an environment variable , in both Unix and Window systems, which will be used by both the Java compiler and the JVM to determine where to look f...

SAP Walk-ins at HCL-Axon @ Channai, Hyderabad and Noid aon Aug 28th 2010

Please find below the walk-in event for Saturday, Aug 28, 2010 (between 9 am to 3 pm). Dont forget to mention My Employee No: 40184032 on your resume as reference. ·        Location Skills Contact Person(s) CHENNAI: HCL Technologies Ltd. #184, NSK Salai, Vadapalani, Chennai–26 Tel: +91 044 42004700 SAP BW,  SAP FICO,  SAP HR &  SAP MM Karunakaran V karunakaranv@hcl.in HYDERABAD: HCL Technologies Limited, (SEZ Unit), H08, Building, HITEC CITY–2 Phoenix Info city Pvt. Ltd. SEZ, Survey No. 30, 34, 35 and 38 Madhapur, Hyderabad–500081 Land Mark: Behind Cyber Gateway SAP SD, SAP BW, SAP FICO,  SAP HR , SAP MM Ajay Tanwar Ajay_Tanwar@hcl.in NOIDA: HCL Technologies Ltd. Maple Towers, Plot No.1 & 2, Tower B Sector–125, Noida 201301, U.P. SAP BW,  SAP FICO,  SAP SD &  SAP MM Neha Puri neha.puri@hcl.in   The candidate should have:   ·          More than 3 years of total experience, of which more than 2 ye...

Can a Java application run without a main method?

Yes, you can but do not count on it when you develop your application. In Java, a static initializer gets executed as soon as the class is loaded, even before the main method is called. Here is an example, public class WithoutMain { static { System.out.println( "Hello World" ); System.exit(0); } } The JVM finds and loads the class into memory when you run this code, the static initializer is executed during the loading and initialization of the class. System.exit(0) is called at the end of the static block to terminates the program. If not, then the JVM would have next used reflection on that class to find the main() method. If it does not find the main method, it throws an exception. Click below links to know more

What is the difference between getPath() and getAbsolutePath() and getCanonicalPath() methods?

File is one of the most deceiving classes in the API. It does not represent a file, it does not represent a directory. Remember that creating a File object does not imply you have got a corresponding file or directory in the file system. A File object represents an abstract path name for a file or directory that may exist (or not) in the file system. Read the API for more details on that. Let's take a look these API: public String getPath() returns the name of the File object including the path name, whether relative or absolute. public String getAbsolutePath() returns the absolute path name of the File object. If the file contains a relative path name, it figures out what the absolute path name would be and returns it. No IOException is thrown if the path name is impossible under the file system naming convention. public String getCanonicalPath() returns an absolute and unique pathname of the File object. An IOExceptio...

What is the difference between absolute, relative and canonical path of file or directory?

Absolute path is the full directory such as C:\abcd\test.txt. The definition of absolute pathname is system dependent. On UNIX systems, a pathname is absolute if its prefix is "/". On Win32 systems, a pathname is absolute if its prefix is a drive specifier followed by "\\", or if its prefix is "\\". For example, We have two directories: abcd and abcd1 and test.txt file is in abcd directory. C:\abcd C:\abcd1 In Java under Windows, you may have the following possible absolute paths that refer to the same file test.txt. c:\abcd\test.txt C:\abcd\test.txt c:\abcd\TEST.TXT c:\abcd\.\test.txt c:\abcd\..\abcd\test.txt Relative path is relative to the directory you are in, so if you are in the above directory, then if you reference file test.txt as relative, it assumes the same directory you are in. When you do ../ then it goes back one directory. Canonical paths are a bit harder. For starters, all canonical pat...

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: If T is a class type, then either |S| <: |T|, or |T| <: |S|; otherwise a compile-time 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. 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 compile time (because eve...

What are the rules for initializing variables?

In Java, every variable in a program must have a value before its value is used. Member variables (both static and instance) are initialized implicitly by default: Most primitives except boolean are default initialized to zero (e.g., the value for integer type is 0, 0.0f is for float type, and 0.0d is for double type) char variables are default initialized to '\u0000' boolean variables are default initialized to false. The reference type variables are default initialized to null. Final variables must be initialized explicitly in declaration or constructors (instance final variable.) Local variables are not assigned a default value. A local variable must be explicitly given a value before it is used, by either initialization or assignment, in a way that can be verified by the compiler using the rules for definite assignment. Click below links to know more

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 ". Click below links to know more

Why an interface can't be defined in an inner class

According to JLS: 8.1.3 Inner Classes and Enclosing Instances , inner classes may not declare static initializers or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields. According to 8.5.2 Static Member Type Declarations , "Member interfaces are always implicitly static. It is permitted but not required for the declaration of a member interface to explicitly list the static modifier". They are always top-level, not inner. Therefore, an interface can't be defined in an inner class. The member interface can only be defined in inside a top-level class or interface. For example, interface OuterInterface { // Top-level interface interface NestedInterface {// top-level nested interface } }

How to create instances of static nested classes and inner classes?

The semantics for creating instances of static nested classes/inner classes can be confusing. creating an instance of the inner class requires a reference to an instance of the enclosing class creating an instance of the static nested class does not require an instance of the enclosing class Here is an example which is a simple class that defines a static nested class and an inner class: public class EnclosingClass { private String name = "instance name"; private static String staticName = "static name"; public static void main(String[] args) { EnclosingClass enclosingClass = new EnclosingClass(); EnclosingClass.InnerClass innerClass = enclosingClass.new InnerClass(); EnclosingClass.StaticNestedClass staticNestedClass = new EnclosingClass.StaticNestedClass(); }

What are the precautions for implementing Serializable?

In Effective Java Programming Language Guide , Joshua Bloch wrote many thoughts about serialization. Here is a summary of some precautions recommended: If you do not get to the effort to design a custom serialized form, but merely accept the default, the class's private and package instance fields becomes part of its exported API. In this way, it decreases the flexibility to change a class's implementation once it has been released. Serial versions UIDs are automatically generated based on the name of the class, the names of their interfaces, and of all public and protected members. If a change is made to the class but you do not provide a custom serial UID the compatibility will be broken. Serialization is a extralinguistic mechanism, deserialization is a hidden constructor. All the invariants for an object should be checked in the process of deserializing an object, as a constructor would do. Classes design for i...

What is Numeric Promotion?

5.6 Numeric Promotions in JLS: Numeric promotion is applied to the operands of an arithmetic operator. Numeric promotion contexts allow the use of an identity conversion or a widening primitive conversion, or an unboxing conversion. Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. The two kinds of numeric promotion are unary numeric promotion and binary numeric promotion . Example of unary numeric promotion produces compile error: byte b = 15; // assign byte value byte b1 = +b; // result int but required byte. Compiler error This is covered by "if the operand is of compile-time type byte , short , or char , unary numeric promotion promotes it to a value of type int " by a widening conversion". You must explicit cast the value to byte type. Examples of Binary Numeric Promotion produces compile-errors: // result int can not assign to va...

Why sometime the compound assignment operators don't work the way as expected?

The answer is not always. Let's start with the following example:   public class Program { public static void main(String [] args){ int x = 1; int y = 1; System.out.println(x += 1); System.out.println(y = y + 1); } } output 2 2   In this case, x+=a is the same as x=x+a. Let's look at another example: public class Program { public static void main(String [] args){ short x = 1; short y = 1; System.out.println(x += 1); System.out.println(y = y + 1); // compile error } }

How do compound assignment operator work for byte primitives?

public class Program { public static void main(String [] args){ byte x = 100; System.out.println(x += 100); } } output -56 The result seems not quite expected at first. Let's see what happens step by step: Firstly we expand the compound operator += to:   byte x = 100; x = (byte)(x + 100); Secondly, the addition gets evaluated: x + 100 = 200. Then, the implicit conversion occurs: 200 int type is converted to the type of byte: 00000000 00000000 00000000 11001000 -> 11001000. Java simply truncate the higher bits that won't fit the size of the destination type. For a byte value, the first bit is the sign. Since the first bit is 1 , 110001000 is a negative number. To figure out the value of the number, just flip all the bits and then add 1 to it: 11001000 -> 00110111 00110111 + 1 ------------- 00111000 00111000 is 56. That's why the final result is -56. Click below links to know more

Why overloading a varargs method doesn't work for the primitive type and its object wrapper type?

Let's take a look at the following example: Example I. public class Program { public void operation(String str, Integer... data) { String signature = "(String, Integer[])"; out.println(str + "= > " + signature); } public void operation(String str, int... data) { String signature = "(String, int[])"; out.println(str + "= > " + signature); } public static void main(String[] args) { Program ref = new Program(); ref.operation("(String, int)", 1); //compile error } } Example I does not compile. The error is "The method operation(String, Integer[]) is ambiguous for the type Program".

Can the ternary operator be used instead of simple if-else statement?

The ternary operator op1 ? op2 : op3 works just like a condensed if-else statement. If op1 is true, returns op2; otherwise, returns op3. Can we use the tenery operator anywhere that applies to an if-else statement? The answer is no. Under some circumstances, we have to use the if-else statement. The following sample code is taken from  Conditional Operator.com and a compile-time error will occurs: class Program { static void doSomethingX() { } static void doSomethingY() { } pubic static void main(String[] args) { int x; ... //the following line causes compile-time error System.out.println((x==5)?doSomethingX():doSomethingY()); } }

What is resurrection (in garbage collection)?

An object that has been eligible for garbage collection may stop being eligible and return to normal life. Within a finalize() method, you can assign this to a reference variable and prevent that object's collection, an act many developers call resurrection .   The finalize() method is never called more than once by the JVM for any given object. The JVM will not invoke finalize() method again after resurrection (as the finalize() method already ran for that object). For example,   class Obj { protected void finalize(){ System.out.println("finalize invoked"); System.out.println("resurrect this object"); Program.objRef = this; //resurrection } } public class Program { static Obj objRef = null; public static void main(String args[]) { objRef = new Obj(); for(int i=0;i<2;i++){ method(i); System.out.println("objRef = " + objRef); } } static void method(int i) { S...

What are the precautions for implementing Serializable?

In Effective Java Programming Language Guide , Joshua Bloch wrote many thoughts about serialization. Here is a summary of some precautions recommended: If you do not get to the effort to design a custom serialized form, but merely accept the default, the class's private and package instance fields becomes part of its exported API. In this way, it decreases the flexibility to change a class's implementation once it has been released. Serial versions UIDs are automatically generated based on the name of the class, the names of their interfaces, and of all public and protected members. If a change is made to the class but you do not provide a custom serial UID the compatibility will be broken. Serialization is a extralinguistic mechanism, deserialization is a hidden constructor. All the invariants for an object should be checked in the process of deserializing an object, as a constructor would do.

What is difference between User and Daemon Thread in Java?

Java makes a distinction between a user thread and another type of thread known as a daemon thread. The daemon threads are typically used to perform services for user threads. The main() method of the application thread is a user thread. Threads created by a user thread are user thread. JVM doesn't terminates unless all the user thread terminate. You can explicitly specify a thread created by a user thread to be a daemon thread by calling setDaemon(true) on a Thread object. For example, the clock handler thread, the idle thread, the garbage collector thread, the screen updater thread, and the garbage collector thread are all daemon threads. A new created thread inherits the "daemon-status" of the thread that created it unless you explicitly calling setDaemon on that Thread object to change its status. Note that the setDaemon() method must be called before the thread's start() method is invoked.Once a thread has started executing (i.e., its start() metho...

How to avoid an java.util.ConcurrentModificationException with ArrayList?

You need to add/delete an item in an ArrayList when you are iterating the list. You will receive the java.util.ConcurrentModificationException exception. For example, the following code will throw an exception after adding an item into list: public class Sample {   public static void main(String[] args) {     List   iList = new ArrayList ();     for (int i = 0; i != 100; i++)       iList.add(i);     int addValue = 1000;     for (Integer i: iList) {       if (i%10 == 0) {         iList.add(addValue++);       }     }   } To avoid java.util.ConcurrentModificationException exception, we can add an item through the iterator of list. If we do the same as the above code, the next access item in list via the iterator will generate the same exception. public class Sample {   pub...

Can finalize() be called more than once on an object?

The finalize() method is never called more than once by the JVM for any given object, but it can be also programatically called any number of times.   class MyObject { public void finalize () throws Throwable { super.finalize(); System.out.println("finalize"); } } class Program { public static void main(String[] args) throws Throwable { MyObject obj = new MyObject(); obj.finalize(); //Line A obj.finalize(); //Line B System.out.println("Prepare GC..."); obj = null; System.gc(); } } The output is finalize finalize Prepare GC ... finalize  

Why label statement causes compile time error?

The following code has compile time error and why?   public class Program { public static void main(String[] args) { int counter = 0; label1: for (int i=0; i!=10; i++) { label2: int j = 0; //compile time error while (j++ < 10) { if (j > i) break label2; if (j == i) { counter++; continue label1; } } } System.out.println(counter); } } From JLS : Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break (?14.15) or continue (?14.16) statements appearing anywhere within the labeled statement.

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.  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.  

Why some of the Unicode character literals can't be used in Java source code?

Java provides escape sequences for several non-graphical characters. All characters can be specified as a hexidecimal Unicode character (\uxxxx) with some as an octal character (\ddd where the first d is limited to 0-3, and the others 0-7 - same as \u0000-\u00ff). There are certain special characters which can be represented by escape sequences: Esc Char Unicode Definition \b \u0008 backspace \t \u0009 tab \n \u000a newline(line feed) \f \u000c form feed \r \u000d carriage return \" \u0022 double quote \' \u0027 single quote \\ \u005c backslash The compiler translates Unicode characters at the first step of the compile cycle. Using the Unicode escape characters '\u000a' for newline and '\u000d' for return in a String or comment produces a compile-error as they are interpreted, literally, as 'end-of-line'. Instead, you should use the equivalent escape sequences: '\n' or '\r'.  

What is 'Islands of Isolation' in garbage collection?

You may already know that when an object is not referenced by other objects, it's eligiable for garbage collection. But do you know the following two statemenats 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 garb...

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 set 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 incl...

Why this method can not be overloaded?

Consider the following code in Java 5.0, why the function() method can not be overloaded? public class Program { void function(String... names){ System.out.println("in function(String... names)"); } void function(String[] names){ System.out.println("in function(String[] names)"); } } In the first function() method, the names argument is defined as type String... . This tells the compiler that calling code can pass a variable number of String parameters. At compile time a vararg is converted to an array (see USING THE VARARGS LANGUAGE FEATURE ). The String... equates to a String array ( String[] ). Therefore, the compiler will treat the second function() method as the duplicate method in the class.  

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(); } }

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 { publi...

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"); }

Why does the autoboxing conversion sometimes return the same reference?

Although Java programming language is an object-oriented language, in a lot of cases that you would need to deal with primitive types. Before J2SE 5.0, working with primitive types required the repetitive work of conversion between the primitive types and their wrapper classes. In this FAQ, you will see how the new autoboxing feature in J2SE 5.0 handles conversions -- for example, between values of type int and values of type Integer . For example, class Program { public static void main(String[] args) { Integer i1 = 20; Integer i2 = 20; Integer i3 = 201; Integer i4 = 201; System.out.println(i1 == i2); System.out.println(i3 == i4); } } The output is true false What we have discovered is that for small integral values, the objects are cached in a pool much like String pool.

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 alist = new ArrayList (); alist.add(new String("A")); alist.add(new String("B")); alist.add(new String("C")); int i = 0; for (Iterator 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 .