15 Sept 2012

Return type does not matter in method overloading, why ?

In Java Specs 
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

Start with a example following is a definitions of overloaded get() method.
           int get(int x){
                               return x;
            }

         String get(String str){
                          return str;
          }

when resolving overloaded method calls compiler cares about only formal method argument passed in method call. So a valid call would be
                String str = get("java");
                 int i=get(4);

So now lets back get to the question of return type. Lets say compiler allows to overload the methods on the basis of return type, now formal arguments does not matter. Lets change the method definition.

         int get(){
                      return x;
              }

        String get()
              return str;
           }

when get() method is called compiler slap you with a error. Compiler get confused when finds two methods with a same name.
Java Specs says
Two methods have same signature if they have same name and argument types
Overloading on the basis of return type will not work since compiler does not count the return type for resolving overloading method. Although language like Perl and Haskell do overload methods on return type but Java forget about it.

Please share your view in comments.
 I hope you will return to my blog to read more in-depth posts on java.



25 Aug 2012

Sending java compiler messages to a file


javac is standard tool to compile the java source files. Successful compilation will result in bytecode whereas the unsuccessful compilation will result in the error message(s). By default all  error messages goes to System.err (which is console window).


javac has number of standard and non-standard optins which you can supply at the time of compiling a file.The standard options are those options which a supported in current jdk and will also be supported in future releases.The non-standard options are those options which are supported in current jdk but subject to change in future releases.

One of non-standard option is -Xstdout filename ,this option sends the compiler messages to the specified file rather than sending to System.err (which is console window). filename is a name of file with extension. It  could be any text file (poi.txt). Interesting thing is one can even specify filename as a html file (poi.html). You can experiment with other files extensions.
The specified file may or may not be present. If file is not present then specified file will be created in current directory and compiler messages would be sent to that file.

Lets walk with code :
In following class Stdout.java  there is two errors in line 6 and 8. Error in line 6 is becuse of local varuable "name"is not being initialized. Error in line 8 is because of a Exception object is neither handled nor declared to be thrown.


Now compile Stdout.java with -Xstdout filename option. The poi.txt is file which will contain the compiler messages. At the time of issuing following command poi.txt is not present that means it will be created.

           cmd>javac -Xstdout poi.txt Stdout.java


And here is the content of poi.txt file consisting two error messages.
             

It  is fun to find out the different things one can do with in-built java tools.
I hope you will find it fun too, please share your comment.

22 Aug 2012

Problem of images in a jar file


I was creating a small application using Swing API  in which i had to use some images for various
labels. Then i had to bundle this application in a jar file. The created jar file should display all of the images on execution.


Code for creating a jar file
cmd>jar cmf manifest.txt gui.jar abc/GuiClinet.class images/dice.gif 

Structure of the application :

I created and bundled the application but things didn't turn out as expected. The jar file on execution was not displaying the images.

There is how i add images to labels


/*
                       ImageIcon img = new ImageIcon("images/dice.gif");  
                       JLabel imglab = new JLabel(img);  
                        panel.add(imglab);         
                        frame.add(panel);           
*/




Lets figure out what i was doing wrong and how i corrected it.

1. Use getResource() to get image reference.
Problem : on executing the jar file it was not showing the images.
Solution :The reason for problem was the jar file was not able to get the references of the images. Using the ImageIcon() to get the image reference is not a way to go when looking for image inside a jar file.
So i changed the code  to
/*
String path = "images/dice.gif";
URL  imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);

else {
System.err.println("Couldn't find file: " + path);
return null;
}
*/




2 Directory structure of images inside jar is important.
Problem : After i changed the code and create a new jar file , while creting the jar file i got the error                   Couldn't find fiel images/dice.gif
The reason for the problem i was giving the relative name "images/dice.gif" to the directory "abc" (which is a pacakge  to store .class file) .So the compiler was looking for image files in home_dir/myapp/images/*gif , but since images is not placed under abc directory  thats why i was getting the error
Solution :Placed the /images directory under /abc ,so compiler can now find images in home_dir/myapp/images/dice.gif.
now application structure look something like this





And issued new jar file creation command :
cmd>jar cmf  manifest.txt  gui.jar abc/GuiClient.class abc/images/dice.gif 



Now problem is solved and everybody is happy.

13 Aug 2012

Setting the class path


A classpath is a path required by JVM to look for .class and other resources. Basically by setting the classpath you are telling the JVM  " hey , look for .class files
and other resouces like .jar or .zip files in this directory(s) ONLY". You can set more than one directory for a classpath. A default entry for a classpath is current directory which is represented by a period (.). .

I have Employee.class file in E:\Codes\ directory (Windows 7) . I'm going to set classpath to this directory and run the Employee.class file. I'll use this as an example in all of the methods described below.

Method #1:  jdk_tool -classpath path1;
For Windows, Linux and Solaris 
The jdktool are command line tools such as java , javac, javadoc or apt. One can use -classpath. or -cp (abbreviation form).
Open a commad prompt and issue the following command
>java -classpath E:\Codes Employee
This will tell the JVM to "set the classpath to directory to E:\Codes and run Employee.class file".
Note that if the Employee class would have been under a package, say org,  then fully qualified name of class must be specified.
>java -cp E:\Codes org.Employee

Points to remember
  • There must be a space after -classpath or -cp
  • Multiple path enries must be separated by semicolon (;)
  • This method will overrides the class-path entries defined by CLASSPATH and default value(which is a current directory).



CLASSPATH is a Envionment variable which can be set to a classpath name. There are two methods to set this variable.You can either use set CLASSPATH=path1; command or  System utitliy in Control Panel ( it depends on the operating system).


Method #2:  setting  CLASSPATH variable 
For Windows systems 
One can set the classpath explicity by issuing set CLASSPATH=path1;path2; command at the command prompt. Here the steps for that.
1.open command prompt .
2. type  >set CLASSPATH=E:\Codes
3. run the .Employee.class file using >java Employee.
note that once you closed the command prompt , the classpath gets cleared itself. Next time you have to set it explicitly 
You can unclear the classpath in case if classpath is not set correctly by using : 
>set CLASSPATH=
Points to remember
  • Multiple path entries must be separated by semicolon (;).
  • There should be no space around =.
  • The order in which these path are specified is important since JVM will search in that particular order.
  • The path must either be a file name (.class or .jar or .zip) or directry(which have the .class file(s)).
  • The value of the CLASSPATH environment variable, which overrides the default value (current directory). So if you want the current directory to be searched then you should use "."( period) .
For Linux and Solaris 
To set the classpath in csh shell , use following command
          >setenv CLASSPATH=path:
To set the classpath in csh shell , use following command 
                  >CLASSPATH=path:
                  >export  CLASSPATH

To unclear the classpath in csh shell , use following command
       >unsetenv CLASSPATH
To unclear the classpath in csh shell , use following command 
             >unset CLASSPATH


Method #3: System utility in Control Panel
For Windows XP
       control panel-->System-->Advanced tab
For Windows 7
control panel-->System--> Advanced system setting





For Linux and Solaris 
In csh shell , examine the .cshrc file for setenv command.
In sh shell ,  examine the .profile file for export command.


So many methods to set the classpath , which should one use ?
Method 2 is a recommended way to set the classpath. Because each application can have its own set of  classes to work without  interfering  with any other application.


19 Jun 2012

How Java array is an object.


Every person who has the java basics clear would agree that array is an object. I too agree but have you given a thought about it ? How does an object can be created of primitive type when creating a primitive array.
In this article i am going to deconstruct that phrase “Array is an object”. But before I do that this is a brief view of what class and objects are all about
An object is a instance of a class. For example String is a class in java.lang package and  one may create the instance of String class like
String stringObject =new String(“java”);
Here String is a class and stringObject is an reference variable pointing to the String object. There is a corresponding relation between a class and its object.My point is to create an object there needs to be a class from which it can be created.

What about the array ,  from which class one can create array object ?

int[] arrayObject = new int[3];
To which class that arrayObject belongs to?  As we have seen in case of String class , there is a corresponding relation between a class(java.lang.String) and its object(stringObject). Certainly There is no int[] class  in whole java api.
Before i go further let me point very intersting point in Java Specification 1.7 which says
Java Specs  4.3.1  '"An object is a class instance or an array." 
 This statement clearly distinct between a class’s instance and a array. It is clear that the stringObject and arrayObject are objects but not the same since stringObject is a class's instance and arrayObject is an array.

So how does an array become an object? Here is the answer.
An array consists of its component elements. For example int is an component element  of  arrayObject. A component type,
T,  can be primitive or reference. If component type of array is T ,then type of an array itself is T[].
So it means that the type of arrayObject is int[].



Can we prove that ? of course.Lets see some code :
                       int[] val = new int[2];
                      val[0]=44;
                      val[1]=55;
                     System.out.println(val instanceof int[]); //true

It proves that the int[] is a class  But it does not exist in java api.  Where does it come from ?
The Gotcha is that the  class structure for array is built-in thing in compiler (JVM). This class only comes into play when compiler encounters an array in the code.
I would like to rephrase the term “Array is an object” to “Array is a dynamically created object”
There is a special way in which JVM represents an array of both primitive and reference types.


Lets see some code :
                       System.out.println(val.getClass());
                       System.out.println(val[].class);
                       System.out.println(Class.forName("[I"));
All above line prints : “[I”.
Where “[I” is a run-time signature for class object of int[].



And that is how an array becomes an object , not just a object but a  dynamically created object. I hope you must have learned something new about array, as I have.


10 Mar 2012

Reading a text file from a JAR file.


The InputStream and OutputStream of java.io package can be used to read the content of a text file and write to the text file respectively. But when a text file is bundled inside a jar file , Is this possible to read that text file (which is in a jar file) ? In this post we will find out if that is possible (Of Course) or not.

Lets say i have a text file "poi.txt" having its content  as "I Love Java Programming ". And it is placed inside a jar file "jkl.jar" using following command
                         cmd>jar cf  jkl.jar  poi.txt
The the task is to read poi.txt from within the jkl.jar file.The java.io.File class is used to represent a file but for jar file this does not work.

 The java.util.jar package is the one to look for when you are dealing with the jar file. This package contains the classes like JarFile and JarEntry  which can be used to get the reference of any file which is placed inside the jar file.
Before i begin further it should be noted that the jar file must be in the CLASSPATH. Here is the code which read the poi.text file from a jar file and print the "I Love Java Programming ".



The JarFile jf = new JarFile(jarFile); gets the reference of a "jkl.jar" file in the current directory. The content of the jar file are represented as a entry in the jar file.It means "poi.txt"is an entry in the jar file. the JarEntry entry = jf.getJarEntry(txtFile); is used to get the reference of "poi.txt" file.which is inside of jar file.
Now we want to read from poi.txt , so first get the inputstream using InputStreamin = jf.getInputStream(entry); second is to read using read() method. And it prints the "I Love Java Programming" as an output.

That was something "cool" thing to learn. Hope you will find it useful.
Please share your comment.








2 Mar 2012

Singleton Class

A Singleton class is an implementation of a Singleton Design Pattern. This design pattern states that a singleton class has only one instance and provide global way to access it..But at same time it also allow  flexibility to creating more instances if needed.  Such a class can be used for creating the database connection java.lang.Runtime is an example of a singleton class
So how can this pattern can be implanted in java ?  There are different ways to implement a singleton class , in this post i'll discuss two implementation techniques.


The most common technique is to create a singleton class which have 
  •  a private static field which is a reference to a singleton object, 
  •  a static method which returns the singleton object and 
  • a private no-arg constructor which prevent any instance being created.
Whenever a class is loaded static field are assigned only once. Therefore a instance can be created at loading time by assigning a newly created ob object to static filed.

Listing 1


In another technique the instance can be created in lazy fashion. Instead of creating a instance of singleton class at loading time , it can be created on demand.


Listing 2



When first time  getSingletonInstance() is called if(obj==null) condition results true thereby a new object of singleton class is created and its reference is stored in static field obj. If  getSingletonInstance() is called again , if(obj==null) condition results false.Thereby returning same instance which was created on first call.
In next part i'll discuss few issues related to the singleton class which must be considered when implementing singleton class.




When a Singleton is not a Singleton
Multiple instance of singleton may be created if synchronization is neglected. For example if one threads invokes the constructor and simultaneously another thread calls the getSinletonInstance() method , then there will be two instance of a singleton class. That is why synchronized keyword is used in method signature.


When multiple instance of singleton is needed, then singleton class should have a default constructor so that it can be subclassed by other class.Then this sub class may provide a public constructor allowing anyone to make instance of a singleton class.


Two different class loaders used to load a singleton class will have two different instance of a singleton class.The different class loader have different namespace that distinguish classes , even though class name are same.


When a singleton object is serialized  it must be ensured that only one  ObjectOutputStream object  is used for serialization.If  ObjectOutputStream is closed or reset , then there will be two distinct instance of a singleton class.




That's all on Singleton class. Hope you find it useful.


10 Feb 2012

Truth of Primitive Conversion


Size does not matter
The data type with smaller bit size can be assigned to the data type of higher bit size. It has been considered a more obvious way to understand the primitive conversion. For example char whose bit size is 16 can be assigned to the int with bit size 32.
If that is true then what happens when you convert byte (8 bit) to char (16 bit)?


Error: Possible loss of precision

As shown in above figure , it is perfectly legal and very obvious to assign char(16 bit) value to a int(32 bit) but compiler complains when a byte(8 bit) is assigned to a char(16 bit).  Why there should be problem in second case? 
The truth is the primitive conversion does not happens on the basis of size of respective data types at all. The primitive conversion always happens on the basis of range of respective data types.


Suppose data type s is to be assigned to t i.e. t=s , then t must represent every single value from the range of s. Range of int is -2147483648 to 2147483647 and range of char is o to 65535. As in above figure char to int is allowed since int can represent every possible value of char data type. But in second case byte cannot be assigned to char because char cannot represent -22 since range of char is 0 to 65535


Lets take another example to make this clear. The long data type has 64 bit size that still can be fit into float data type of 32 bit size.

long to float conversion


The reason why above code compiles and run fine is that because float can represent every possible value of a long variable, since the range provided by the float is wide enough for the long data type. So assignment form long to float is not a problem.


Well that is all about the truth behind the primitive conversion. Just remember that size does not matters only range matters.


16 Jan 2012

A Blank Final Variable

A final variable can only be assigned once in its lifetime. It means they can only be initialized only once. A blank final variable is a one which lacks an initializer.
:



a blank final variable behave differently than instance or static variable. And in this post I'll explore abut how they behave differently and why they do so.


The big statement is The compiler do not assign any default value for a blank final variable. Unlike the instance and static variable who gets default value by the compiler , the blank final do not get any default value.


Compiler Compiler complains on line 13 :  final variable c might  not nave been be initialized  
Therefore a final variable must be explicitly initialized. Initialization can be done either at the time of declaration or any time before using the final variable 


Now the question is how to explicitly initialize a blank final variable.It is also another aspect in which a blank final variable differs from a instance or static variable Lets see how it works
a blank final instance variable can only be initilazed inside the constructor or a instance initializer block but not inside a instance method.
Yes you read right a blank final variable cannot be initilazed inside a instance method.


Have a look


Compiler complains on line 13  cannot assign value to a value to final variable c.


the reason for this is all instance variable must be initilazed by the time object is crested. 


Similarly a blank final  static variable  can only be initilazed into the static initializer block.And yes... yes not inside the static method.This is because by the time class is loaded all static variables must be initialized.


Consider above points before you use a blank final variable next time.So this was all about the blank final variable.

14 Jan 2012

Apache Tomacat versions and Java Servlet/JSP specifications

The Java Servlet and JSP (Java Server Pages) specifications are designed by the JCP community.And the Apache Tomcat software are developed by the Apache Software Foundation having the specific version number.Each Tomcat  version implements the specific specification of the Servlet and JSP..One more thing is that for each upgraded specification of  Servlet and JSP specification the Java platform version is also upgraded or vice-versa.

Here is a mapping table of the Tomact version and a Java Servlet and JSP specification plus Java platform version.


Apache Tomcat version_no. Servlet Specification JSP Specification Java palform (minimum)

7.0x


3.0

2.2

1.6

6.0x

2.5

2.1

1.5

5.5x

2.4

2.0

1.4

4.1x

2.3

1.2

1.3

3.3x

2.2

1.1

1.1

11 Jan 2012

Introduction of Apache Tomcat

 I have been looking  to learn (and work) some open source project .After extensively searching various open source projects online , I set my eye on Apache Tomcat. It is widely popular  web server used for J2EE enterprise applications and most importantly it is purely written in java. Another advantage of learning Tomcat is that one can consolidate the Servlet and JSP topics.
So what is a Apache Tomcat ? It is a web server which implements the specification of  Servlet and JSP. 
How about Tomcat as a servlet container ?  A servlet container an environment in which a servlet is born, live and prosper.Whenever  there is request for the dynamic resource , Tomcat delegates this request to the servlet container and responsible for generating the response.
A figure below will depicts the basic working of Tomcat






A tomcat provides the administrative support for the servlet and other low level services like session management ,class loading etc.
what is the basic architecture of servlet container or Tomcat ?. It is interesting to note that the Tomcat's architecture follows the construction of a Matryoshka doll from Russia.It is all bout the containment of an entity within another entity.







In Tomcat 'container is a generic term used to refer to any component that can contain another component like Server, Service, Engine, Host or Context.
The Server and Service are Top level elements as they represents the running instance of  Tomcat.The Engine, Host and Context are designated as the Containers they are responsible for processing the incoming request and generating the response.Nested components are sub-elements of either top-level elements or Containers such as Valve, Resources, Realm, Loader, Manager  etc.
A Connector is major component of Tomcat architecture. It represents the connection between the client (web browser) and the Tomcat.
So this was the brief introduction to the Apache Tomcat. I'll explore more as i dive into it


 note: Apache Tomcat project is developed under the Apache Software Foundation.