Friday, August 19, 2011

Polymorphic References

class Animal{
void eat() {  System.out.print("animal");      }


class cow extends Animal
{
 void eat() {  System.out.print("cow");      }
void bulb() {    System.out.print("c");      }
}

class myMain()
{
public static void main(String[] args)
{
Animal h = new cow();
h.eat(); //Legal class animal has eat method
h.bulb();  //Illegal. Compile time error.
}

output: cow

Reason.
Animal h = new cow();

Here we created a Object of type animal and it is holding a instance of cow.
In this case the object reference h can only get the methods what are being implemented by Animal. It cannot get methods implemented by cow. So h.bulb() will throw a compile time error.

Coming to h.eat() now the method is in Animal. But as the instance is cow instance it will check if the eat method is overridden or not. If it is over ridden then it will always get the cow implementation of eat.
So the output is cow but not animal.

Happy Coding :)


Controlling Access to members of a class

Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control:
  • At the top level—public, or package-private (no explicit modifier).
  • At the member level—public, private, protected, or package-private (no explicit modifier).
A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes—you will learn about them in a later lesson.)
At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers:private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
The following table shows the access to members permitted by each modifier.
Access Levels
ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN
The first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class — declared outside this package — have access to the member. The fourth column indicates whether all classes have access to the member.

'==' operator behaving different for 1000 and 10

class wrap
{
public static void main(String s[])
{

Integer i3=10;
Integer i4=10;
if(i3==i4)
System.out.println("Same Object-I");

Integer i1=1000;
Integer i2=1000;
if(i1==i2)
System.out.println("Same Object-II");

}}

Output :Same Object-I 

Reason: 
The Rule to be remembered is :
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#190730 

What is the disadvantage of using * in an import statement??

There is no affect on runtime performance. 

The import directive is a compiler directive. The Java source to bytecode compiler reads the Java source file (i.e. a something.java file) and converts that source to one or more bytecode files (.class files). 

Most Java source code in the Java source file is converted into Java bytecodes of one sort or another. But the import directive is not. The import directive specifically tells the compiler to do something. The import directive tells the compiler that when it comes across a class or interface name in the source file, e.g. HashMap, then if it cannot find the class file for that name, it should use the import statement to help it look it up. This way, you don't have to always use fully qualified class names, e.g. java.util.HashMap. 

The import directives themselves do not get put into the compiled bytecode files. They are no longer of any use, as the compiler compiles the fully qualified name into the .class file. 

For example, suppose the source file contains 

import java.util.*; 
// 
... 
HashMap map; 
... 

Then the compiler gets to the HashMap map variable declaration, tries to find a class called HashMap in the default package (i.e. no package name), fails, and uses the import statement to see if there is a java.util.HashMap class. This is found, and a reference to java.util.HashMap is inserted into the .class file. After compilation is completed, there is no use for the import directive, so it is not present at all in the compiled bytecode. Consequently, the import directive cannot affect runtime code execution in any way. 

However, it is worth noting that the directive does affect compilation time. Since the directive tells the compiler how to do a second lookup to find classes, obviously this means that more time is spent looking up class and interface names compared to if one lookup sufficed. 

There are two forms of the import directive: with and without the wildcard '*', e.g. 

import java.util.*; 
import java.util.HashMap; 

Without the wildcard, the directive tells the compiler to look for one specific file in the classpath. With the wildcard, the directive is telling the compiler to look for the named package, and to search in that package for possible matches everytime any name needs to be matched. This latter version is probably going to be more costly (i.e. take longer) for the compiler than the former. 

Also, depending on which compiler you use, and which settings, the compiler may re-compile all of the classes in the wildcard package, which could really make things take longer. 

Finally, many people find that using imports with wildcards makes the source much less readable, since the reader also needs to figure out which package a particular class comes from, rather than just looking it up in the import statement. 

So the full answer is 

* There is no runtime cost from using an import statement 
* The compilation process can take a little more time with an import statement 
* The compilation process can take even more time with a wildcard import statement 
* For improved readability, wildcard import statements are bad practice for anything but throwaway classes 
* The compilation overhead of non-wildcard import statements are minor, but they give readability benefits so best practice is to use them 

Also, in a scenario where your class ends up having 60-70 imports, its a good practice to break up the class into two (or more) on the basis of functionality. In an Enterprise level application the classes are generally focused on the functional segregation rather than all code in one or two classes.

Java Code to obtain all the system properties


import java.util.Enumeration;
import java.util.Properties;


public class props {
    public static void main(String []args)
    {
        Properties p =new Properties();
        p=System.getProperties();
        System.out.println("Properties details");
        Enumeration<?> e = p.propertyNames();
       
        while( e.hasMoreElements())
        {
            String s = (String)e.nextElement();
            System.out.println(s+"--------"+p.getProperty(s));
        }
    }

}


Here the p.PropertyNames() will return a enum with all distinct keys. and <?> means the enum can have key as any thing like object string, int etc
After getting the enums we are just looping and getting single key at a time and then getting the corresponding value.

Enjoy . Happy Coding



Redirecting the Eclipse/Flex Builder Console output to a log file



Usually we write some Java standalone programs / try to debug some web applications in Eclipse, which will generate lots of SOP / log statements. The console has a limited amount of capacity of displaying logs (even though we can change the capacity). Also if we run it again the previous console output will go away. In these cases we would require the output of the console to be written to one log file in the hard disk. You can do this in the following way :

In the eclipse Run / Debug configurations dialogue box, on the right side, you can see several tabs, where you will provide classpath, parameters, etc.
Click on the last tab, labelled as ‘Common’.
Look for the control group with title ‘Standard input and output’. There you can see one checkbox with label ‘File’.
Checking on this will activate the text box next to it. You can give the path of the log file in that text box.
You can otherwise select a directory from either workspace or file system using the corresponding buttons under that.

Don’t forget to check on the ‘Append’ checkbox if you want the log file to be keep on appending.

Now click on ‘RUN’ and you can see the new log file generated on the selected location.

Happy Coding

Friday, August 12, 2011

JVM Internals – What Does the JVM Do?

This video covers in detail what a Java Virtual Machine (JVM) is and what it does for your Java applications. The presenter dives into the inner workings of the JVM and drills down into what compilers and garbage collectors do. In particular, you will learn about common optimizations, well established garbage collection algorithms, and what the current biggest challenge with Java scalability is today.

Enjoy :)