Friday, January 29, 2010

Things to watch out for Java novices


In the process of learning Java one encounters many points to which a novice should pay special attention. Doing Sun tutorials obviously helps people to come to grips with some of these points but some salients points have been highlighted here in random order.
No constructor can have a return type (not even void).
We can override a private member of a superclass in the subclass with a private/public/protected member. Effectively it is not override as subclass is not even aware of the superclass private member and sees it as a new definition. The rules of overriding do not apply, so you can make this newly-declared-but-just-happens-to-match method declare new exceptions, or change the return type, or anything else you want to do with it.
No modifier means method has default access. Default is similar to protected. However in protected subclass can be in different package but in default access it has to be in the same package.
default = package; protected = package+subclasses access.
Protected member can be accessed through inheritance but not not through access to an instance of parent object, if it is in a different package. Once the subclass-outside-the-package inherits the protected member, that member (as inherited by the subclass) becomes private to any code outside the subclass.
There is never a case where an access modifier can be applied to a local variable. It will not compile. We can only use 'final' modifier for local variables.
A reference variable marked final can’t ever be reassigned to refer to a different object. The data within the object, however, can be modified, but the reference variable cannot be changed. There are no final objects, only final references.
If you declare a final instance variable, you’re obligated to give it an explicit value, and you must do so by the time the constructor completes.
Static methods can’t be overridden, they are hidden.
You can put as many classes in a source code file as you like, but only one (or none) can be public. The file name should match the name of the public class, but if no public class is in the file, you can name it whatever you like. The order in which the classes appear makes no difference.
Not having a proper main() method is a runtime error, not a compiler error!
All variables defined in an interface must be public, static, and final, ie only constants. If we don't give these modifiers or give only part of them, they are automatically given these three characteristics.
An interface is free to extend multiple interfaces.
An inner class instance has access to all members of the outer class, even those marked private.
Just because a series of threads are started in a particular order doesn't mean they'll run in that order.
sleep() and yield() static methods always affect the thread that's currently executing and not another thread.
If a thread goes to sleep, it holds any locks it has—it doesn't release them.
Default exception handler
– Provided by Java runtime
– Prints out exception description (e.getMessage())
– Prints the stack trace (e.printStackTrace()) , ie hierarchy of methods where the exception occurred
– Causes the program to terminate
Collections.disjoint(l1, l2) — determines whether two Collections are disjoint; that is, whether they contain no elements in common.
All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
The constructor for an enum type must be package-private or private access.
An enum cannot be declared within a method.
As an inner non-static class is associated with an instance, it cannot define any static members itself. An inner class must be static to be called from static method.
Polymorphism doesn't apply to static methods.
Polymorphism only applies to instance methods and not instance variables
System class maintains aProperties object that describes the configuration of the current working environment. To maximize portability, never refer to an environment variable (extracted from System.getnnv) when the same value is available in a system property (extracted from System.getProperties). Use latter value.
For example, to get the value of path.separator, use the following statement: System.getProperty("path.separator");
System.exit, which terminates the Java virtual machine with an exit status, invokes SecurityManager.checkExit to ensure that the current thread has permission to shut down the application.
By convention, an exit status of 0 indicates normal termination of the application, while any other value is an error code.The exit status is available to the process that launched the application.
All byte stream classes are descended from InputStreamand OutputStream.
All character stream classes are descended from Readerand Writer.
To use line-oriented I/O use two classes BufferedReader andPrintWriter. Latter is used in servlets.
Channel I/O reads a buffer at a time.
There are four buffered stream classes used to wrap unbuffered streams:BufferedInputStream andBufferedOutputStream create buffered byte streams, whileBufferedReader andBufferedWritercreate buffered character streams. They improve I/O performance.
When you need to create a formatted output stream, instantiate PrintWriter, notPrintStream.
Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int,long,float, and double) as well as String values. All data streams implement either theDataInput interface or theDataOutput interface.
Just as data streams support I/O of primitive data types, object streams support I/O of objects.
Using a int as a return type on byte input stream allows read()to use -1 to indicate that it has reached the end of the stream. We can use (char) cast to see the value of int read, ie int 65 is same as 'a' after cast. For line-oriented I/O use inputStream.readLine() != null to detect end of file.
Notice that DataStreamsdetects an end-of-file condition by catching EOFException, instead of testing for an invalid return value.
When a method accepts a varargs argument, you can pass it a comma-separated list of values or an array of values. The vararg has to be the last argument and there can be only one vararg.
String s = "Java"; s.concat( " Rules); System.out.println(s); will give 'Java' not 'Java Rules' as the output of s.concat(0 is not placed in our reference for s. To get 'Java rules' we have to say s = s.concat(). Without this syntax the newly created string has no reference. In the case of StringBuffer sb, sb,.append() will append the value without assigning to the reference.
Static variables are never saved as part of serialisation as they belong to class and not object.
If serializable subclass is serialised and parent is non-serialiazable then parent will have initial values as per creation of new object.
When using classpath the last directory in the classpath must be the super-directory of the root directory of the package, ie if package is com.my... then the classpath should have directory which has com as subdirectory.
Put jar file in jre\lib\ext and java finds it without specifying in classpath.
Static imports can be used when we want to use a class's static members.
Collection (singular) is an Interface, but Collections (plural) is a helper class.
equals() returns false if the wrapper object types are different. It does not raise a compiler error.
No inner class (non-static inner class) can have a static member.

No comments:

Post a Comment