this is the difference between static and non-static

Thursday, June 30, 2011

Corrections in 'The class of JAVA' book

The following are corrections in 'The class of JAVA' book.


Page 11, exercise 2
    (e) Java output generated by Java compiler is
should be replaced with
    (e) The output generated by Java compiler is

Page 17, first line below the figure 2.1
    codejavadoc -d ../docs Hello.java
should be replaced with
    javadoc -d ../docs Hello.java

Page 17, first line after the first paragraph.
    codejavadoc -d ../docs -package Hello.java
should be replaced with
    javadoc -d ../docs -package Hello.java

Page 34, lessons learned last bullet point, last line
    by using \following
should be replaced with
    by using following

Page 34, exercise 1
    (m) \0905 is a valid identifier in Java (\0905 is a letter in the ...
should be replaced with
    (m) \u0905 is a valid identifier in Java (\u0905 is a letter in the ...

Page 37, Listing  4.1, line 6
    System.out.println("i = "+i+", j = "_j);
should be replaced with
    System.out.println("i = "+i+", j = "+j);

Page 87, lessons learned
    An interface can have any non-abstract methods,...
should be replaced with
    An interface cannot have any non-abstract methods,...

Page 120, third last line
    If the returned value is positive then x is considered to precede y.
should be replaced with
    If the returned value is negative then x is considered to precede y.

Page 121, Listing 10.3 line 5
    public class NameComparator<Account> implements Comparator<Account>
should be replaced with
    public class NameComparator implements Comparator<Account>

Page 123, line 3
    The String class implements Comparabe interface
should be replaced with
    The String class implements Comparable interface

Page 130, in last three lines
    In Line 7, the balance would be 15000, now Line 9 makes ac in the method refer to
    a new Object, so the Object refered by ac in Line 1 is unaffected. Line 9 would make the
    method loose the reference to the object which was passed as a parameter in Line 4.
should be replaced with
    In Line 3 of the method, the balance would be 15000, now Line 5 in method makes ac refer to
    a new Object, so the Object refered by ac in Line 1 is unaffected. Line 5 in method would make the
    method loose the reference to the object which was passed as a parameter in Line 4.

 Page 143, in listing before Section 11.4, line 1
    public class Car extednds Vehicls {
should be replaced with
    public class Car extends Vehicle {

Page 163, Listing 12.7 line 61
    for (transactionIndex = 0; transactionIndex < nextTransactionIndexInPassbook; transactionIndex++)
should be replaced with
    for (transactionIndex = 0; transactionIndex < nextIndexInPassbook; transactionIndex++)

Page 168, Listing 12.10 line 16
    private (int maxDays)
should be replaced with
    private Month(int maxDays)

Page 168, Listing 12.10 line 27
    (this.ordinal() >= to.ordinal()));
should be replaced with
    (this.ordinal() >= from.ordinal()));

Page 186, Listing 13.14 line 3
    public Object setValue()
should be replaced with
    public Object setValue(Object o)

Page 187, in code snipped listing line 1.
    DateFormat dateFormat = new DateFormat("dd-MMM-yyyy");
should be replaced with
    DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");

Page 193, Listing 13.20 line 3
    public boolena hasNext();
should be replaced with
    public boolean hasNext();

Page 220, Listing 14.4 Line 6 and 7
    long m1 = d1.lastModified();
    long m2 = d2.lastModified();
should be replaced with
    long m1 = d1.getTime();
    long m2 = d2.getTime();

Page 227, Listing 14.4, line 6
    public void mark(itn readlimit)
should be replaced with
    public void mark(int readlimit)

Page 241, BufferedOutputStream paragraph, 2nd line
    Filter- OutputStream
should be replaced with
    FilterOutputStream

Page 267, Section 15.1.1.3, 2nd paragraph, line 7,
    10101000 0101000 00000001 ...
should be replaced with
    10101000 0101100 00000001 ...

Page 270, 7th line after listing 15.1
    byte[] ipaddress = byte[]202,153,27,54;
should be replaced with
    byte[] ipaddress = new byte[]{202,153,27,54};

Page 318, Listing 17.7 title
    Listing 17.7.Hello world using getGraphcis()
should be replaced with
    Listing 17.7.Hello world using getGraphics()

Page 336, Listing 18.14, line 1
    public MenuBAr()
should be replaced with
    public MenuBar()


Readers can send comments and corrections to pravin@classofjava.com
Thanks
Pravin

Thursday, February 19, 2009

A dream come true

It was a dream come true. Every java developer hopes to meet the 'Father of Java' - James Gosling, at least once in their lifetime. A bunch of us got this wonderful opportunity, the other day, at Hyderabad, India. We were a team of 7 people from Vadodara, India; visiting Hyderabad, in the hopes of catching a glimpse of James Gosling from close quarters, at The Sun Tech Days, 2009. However exceeding all our expectations, we not only got to personally meet 'The Father of Java', and even take a bunch of photographs with him.



















When we left our hotel on the morning of 17th February, 2009; to go sight-seeing in Hyderabad, we had not even in our wildest dreams, hoped to have such a wonderful encounter. Our first stop was at the Birla Mandir. When we were leaving the temple we unexpectedly ran into the 'Guru of Java' - James Gosling. After overcoming the initial shock, we ran behind him to confirm if it was really him. And to our surprise it indeed was James Gosling. This chance made our trip worthwhile, even if we were to miss the Tech Days.

Saturday, January 31, 2009

Hello world

Exercise

Create a java file named Hello.java and define two classes named HelloWorld and AnotherHelloWorld containing the main method for defining an application, the main method should have statements to print “Hello world!” and “Another Hello world!” respectively. Compile the java file and check the output of compilation(what files are generated). Now execute the application.

The content of the file can be as follows:
Content of file Hello.java follows:


class HelloWorld {
public static void main(String[] args} {
System.out.println(“Hello world!”);
}
}

class AnotherHelloWorld {
public static void main(String[] args} {
System.out.println(“Another Hello world!”);
}
}


The above code compiles without errors.
The output of compilation is two class files named, HelloWorld.class and AnotherHelloWorld.class.
Both the applications run and produce the output.

Lessons learned:
1.A single java file may contain any number of class definitions,
2.Each class defined in java is compiled into a separate class file whose name matches the class name.
3.Each class definition has its own separate class file.
4.The main method is used to create an application in java, and an application is embedded in a class definition.
5.Applications are executed by using the class name which contains the application(main method).

Monday, October 27, 2008

init() is not the First life-cycle method of an Applet

What is an Applet?

Applet is a Panel (inherits from Panel), which can be embedded in a web(HTML) page. What are the additional features of Applet compared to a Panel. It has the capability of interacting with the Browser, and has a life cycle defined by the Browser, when it is viewed in a web page on the browser. The life cycle is defined by the help of methods invoked by the browser. For applet to work in a browser, the browser must have JVM, the JVM needs to be started before the Applet can be used. When is the JVM started? It is normally started with the help of method main(). In the case of Browser the main is already started by the browser, before the web page is loaded. The web page has several html tags.

Lets look at the sequence of events within the browser. Firstly the JVM is already started within the browser with the help of some main. When a web page is loaded which contains atleast one tag for an Applet, then the java application within the browser would first create an instance of AppletContext. ie. one instance of AppletContext would be created per html page, which contains one or more Applet tags. The java application would parse the data between the <applet.....> and </applet> tags and create an instance of AppletStub for each such applet tag in the page. This instance has all the information specified between the <applet...> and the </applet> tags. In the applet tag one of the attributes is code, eg. <applet code="....."> some class name is specified. The class name specified should be the name of a class which extends the Applet class. The browser would now send a request to the server from where the web page was loaded to get the contents of the applet class specified in the code attribute. The applet class is stored on the server and needs to be downloaded to the client machine. After downloading the content of the class file the browser would now load the downloaded class and then create an instance of the class using its default constructor. The public default constructor must be available for the applet class. After creating the instance, the browser would invoke the first method on the instance. which is the first method invoked on an instance of Applet? is it init()? no. The first method invoked on the instance of Applet is



void setStub(AppletStub stub)


This is the first method invoked on the instance of Applet and not init(). this method is a final method in the Applet class. The instance of AppletStub created by the browser corresponding to this applet tag is passed to the Applet instance. Also the AppletStub has a method getAppletContext(). This method would return the AppletContext instance corresponding to the web page of this applet. The AppletContext instance can be used for interaction with the browser. The Applet instance can get the information in the <applet...> and </applet> tags with the help of methods in the AppletStub instance which is given to it in the setStub method. This appletstub instance is also used for getting access to the appletcontext instance for interacting with the browser. so after invocation of setstub the applet instance has the knowledge about the info in the applet tag (mainly the parameters) and the capability to interact with the browser. It is after this that the init method is invoked. The init method in the applet class has a blank implementation and can be overridden by the sub class of applet to do any kind of initialization. the browser maintains the state of the applet instance as being active or inactive. The instance of applet is active when the web-page containing it is currently being shown. the browser then invokes the method start() and puts the applet in the active state. if the applet is becoming inactive because it is not on an active page. then the browser would invoke the stop() method on the instance and puts it into inactive state. so start and stop methods may be invoked by the browser any number of times depending on the activity of the user. finally when the web-page containing the applet is being destroyed, in the browser. Then the browser would call the method destory() on the instance of applet to indicate to the applet that it is now going to be destoryed. so the life cycle of an applet starts with setStub(), followed by init() followed by start() and then depending on the user activity may call stop and start any no. of times. and ultimately the the last method invoked is destory(). In the java.applet package there is one class and three interfaces. you have the applet class, and the 3 interfaces are AppletStub, AppletContext and AudioClip. The AppletStub has methods for getting the information from the applet tag. eg.



void appletResize(int width, int height) // invoked to set the size of the corresponding
// applet instance.
String getParameter(String paramname) // returns the value of the given parameter
URL getCodebase() // returns the URL from where the classes can be loaded
URL getDocumentBase() // returns the URL from where the web page was loaded.
boolean isActive() // gives the active state of the corresponding applet instance


The Applet tag has attributes like code, width, height, codebase, archive, name and some other attributes related to the positioning of the applet within the browser. The code attribute is used for specifying the name of the applet class which should be loaded from the server. width and height specify the dimensions of the applet instance within the browser. When a applet class is loaded from the server, during the execution of any of the methods in the applet, it may refer to some user-defined classes which are not part of the jdk. in such a case these user-defined classes also needs to be loaded. loading of user-defined classes would be done from the codebase mentioned in the tag. The codebase tag should refer to the directory on the server where all the classes are kept, including the applet class. The archive tag can be used to mention the java archive file on the server which contains all the classes. ie. if you have a jar file which contains all the class files, then it may be mentioned in the applet tag. if archive is mentioned in the tag then the browser would download the entire jar file first on the local machine and then load the classes locally instead of loading the classes over the network. The name tag is used to assign an identification to the applet instance. when it is created. The AppletContext instance keeps track of all the applet instances which are created in the browser on a single web page. The AppletContext has methods to get access to the applet instances in the corresponding web page as:



Enumeration getApplets() // returns an Enumeration containing all the applet
// instances on the corresponding web page
Applet getApplet(String name) // return the applet instance with the name as its id.


What is a URL class? The URL class(defined in the java.net package) encapsulates the information within a url. what are the different parts of a typical url. lets take a typical url.



http://forum.java.sun.com/forum.jspa?forumID=24



So a url has protocol, host, port, file, querystring or reference a reference is mentioned as # followed by a reference within the file.

An instance of URL could be used to parse all the information in a urlstring u can create an instance of URL by calling the constructor with string as parameter



URL(Sring urlstring) // urlstring can be any kind of url.
URL(URL location, String s) // url created relative to an existing URL.


There are other contructors where u can create instance of URL by specifying all the parts of the URL.

Now coming to the AppletContext instance, if the applet wants to interact with the browser, it can invoke methods on the AppletContext instance available to it thru the AppletStub, which was given to it in the setStub method. The methods in the AppletContext are:



void showStatus(String msg) // show a message on the status bar of the browser.
void showDocument(URL webpage, String target) // load the webpage and show on
// the target. as mentioned in the API.


The main activity of a browser is to load resources from a give URL. These resources could be webpage or some other content type. like images and audio. In java.awt. there is a class called Image. which can be used for rendering on any Component by using the drawImage method of Graphics class. The AppletContext has methods to create an instance of Image from a give URL location on the web. It has methods like:



Image getImage(URL imagefile) //downloads the content of image file from the
// URL and creates an instance of Image from the
AudioClip getAudioClip(URL audiofile)//downloads the content of audio file from the
// URL and creates an instance of Audioclip from the
// content.


Now if we look at the methods of the Applet class. It has inherited methods from the Panel. and additional methods are the life cycle methods plus the methods which would in turn interact with the AppletStub or AppletContext. most of these methods are the same as methods in either AppletStub or AppletContext.

Methods from the stub



String getParameter(String name)
URL getCodeBase()
URL getDocumentBase()
void resize(int w, int h) // this would in turn invoke appletResized on the
//corresponding stub
void resize(Dimension d)
AppletContext getAppletContext()
boolean isActive()



Methods from the AppletContext



void showStatus(String msg)
Image getImage(URL iamgefile)
Image getImage(URL location, String imagefile) // imagefile relative to the location
AudioClip getAudioClip(URL audioFile)
AudioClip getAudioClip(URL location, String audioFile)
void play(URL u) // gets the AudioClip from the url and calls play on the AudioClip
void play(URL u, String audiofile)


Additionally the Applet has methods which are informative, ie. they may be overridden to provide into about the the applet and its parameters.



String getAppletInfo() // u may return author name, purpose etc.
String[][] getParametersInfo() // u may return a 2-dimension string array describing
// info about the parameters which this applet may look from
// the web page in the param tag


These is another method which may give information about the Locale of the client, ie. the machine on which the browser is running. The instance of Locale typically encapsulates information about the Language and country settings. so u also have a method in the Applet class called.



Locale getLocale().


The AudioClip interface whose instance would be created when an audiofile is downloaded by the browser has following methods:



void play()
void loop()
void stop()



So Applet is a GUI container with capability to interact with the web browser in which it has been enbedded. Now if we look at the way an applet is loaded, we find that the applet can be loaded whenever a user loads a webpage in his browser. The user when loading the webpage may not have the idea whether the page contains an applet or not. applet is a java code which runs inside the users browser, without the knowledge of the user. ie. the user may not specifically invoke the applet code. This could lead to some security issues. The security from applets is the responsibility of the browser. The java
application which is started initially uses a SecurityManager to ensure that the applet does not get access to critical resources on the local machine. It would ensure that the applet is not allowed to:
1) read, write, delete or create files on the local file system.
2) It cannot open a socket connection to any host other than the host from where it was loaded.
3) it cannot load libraries, cannot terminate the jvm (System.exit()).

As a Container the Applet extends from Panel and so by default it has the FlowLayout as the default LayoutManager.

The JApplet in the javax.swing has one typical feature. ie. it can have Menus. The JApplet has most of the capabilities of JFrame.

Friday, September 5, 2008

Non-english letters in Java source code

Rules for defining identifiers in Java:
1. An identifier is composed of a sequence of letters, digits, the currency symbol $ and the separator character _.
2. An identifier cannot start with a digit.
3. An identifier cannot be a reserved from the Java language.

This is not different from the rules in the C programming language. The difference is of the character set used by the programming language. Java uses the Unicode character set and hance the letters and the digits used here are not restricted to the letters and digits available from the ASCII character set, which is used in the C programming language. In Java the letters and digits from any language can be used for example, anyone can use (the devanagari letter A, unicode code point value +U0905) in an identifier. The question arises as how can we use these characters in our java source code while using an editor which supports only ascii files. In java source code one can use the unicode escape to specify any unicode character. A unicode escape is written as \uhhhh where hhhh are the four hexadecimal digits for the unicode code unit according to UTF-16. The java compiler would first interpret these unicode escapes before identifying the lines and tokens from the source code. The following are a few interesting examples:

char \u0905 = '\u0905'; is a valid code where the variable named अ (devanagari letter A) is assigned the value 0905(hex).

char ch = '\u000A'; is not valid since the unicode escape \u000A is a new line character and would be seen follows:

char ch = '
';

Thus creating a compilation error. anyone can easily obfuscate the source code by using the unicode escapes for space and semicolon characters, this will make the code totally unreadable.

Currently most of the programmers use the letters and digits from the english language in defining the identifiers. It may be worth trying to create obfuscators which could change the identifiers to non-english letters and digits.

Thursday, September 4, 2008

What is UTF?

UTF is an abbreviation for UCS Transformation Format.
UCS is an abbreviation for Universal Character Set.
The Universal Character Set is synchronized with the Unicode standard.
There are three commonly known types of UTF encodings, namely UTF-8, UTF-16 and the UTF-32.
The UTF-8 encodes Unicode characters into a sequence of 8-bit values known as code units. In the UTF-8 the encoding unit is 8 bits long. Similarly the UTF-16 and the UTF-32 each uses 16 and 32 bits for encoding the Unicode characters.

There are over a million characters included in the latest version of Unicode Standard(v5.1.0). The range of code points for the unicode characters is from 0 - 10FFFF (in Hex). Out of this range of code points the values in the range from D800 - DFFF are reserved for creating surrogate pairs and is not assigned to any abstract characters. The range D800 - DBFF is for High Surrogate and DC00 - DFFF is for low surrogate. The surrogates are used for encoding supplementary characters using the UTF-16, as will be discussed later in this article. Let us look at how UTF-8 encoding is done.

In UTF-8 encoding a single unicode character is encoded into multiple octets depending on the value of the character being encoded. The following table shows the no. of bytes or (code-units) used for encoding the characters in the different code point ranges:


Code Point Values No. of Code Units (bytes)
0 - 7F (ASCII) 1
80 - 7FF 2
800 - FFFF 3
10000 - 10FFFF 4


For 7-bit ASCII values the code point is encoded and stored in a single byte with the value of the code point. For code-points in the second range (11-bits) the character is encoded into 2 bytes where the first byte has the initial 3-bits set as 110 to indicate that it is the first byte of a 2 byte encoding. and the second byte has the initial 2-bits set as 10 to indicate that it is a continuation byte. The 11-bits to be encoded are now encoded as follows:

1st byte = 110mmmmm where mmmmm are most significant 5 bits(bits 10 - 6) from the 11-bits to be encoded
2nd byte = 10nnnnnn where nnnnnn are the remaining 6 bits(bits 5 - 0) to be encoded.

For code-points in the third range (16-bits) the character is encoded into 3 bytes where the first byte has the initial 4-bits set as 1110 to indicate that it is the first byte of a 3 byte encoding and the next two bytes have the initial 2-bits set as 10 to indicate that it is a continuation byte. The 16 bits to be encoded are now encoded as follows:

1st byte = 1110wwww where wwww are most significant 4 bits(bits 15 - 12) from the 16-bits to be encoded
2nd byte = 10xxxxxx where xxxxxx are the next 6 bits(bits 11 - 6) to be encoded
3rd byte = 10yyyyyy where yyyyyy are the remaining 6 bits(bits 5 - 0) to be encoded.

For code-points in the fourth range (21-bits) the character is encoded into 4 bytes where the first byte has initial 5-bits as 11110 to indicate that it is the first byte of a 4 byte encoding and the next two bytes have initial 2 bits as 10 to indicate that it is a continuation byte. The 21 bits to encoded are not encoded as follows:

1st byte = 11110www where www are most significant 3 bits(bits 20 - 18) from the 21-bits to be encoded
2nd byte = 10xxxxxx where xxxxxx are the next 6 bits(bits 17 - 12) to be encoded
3rd byte = 10yyyyyy where yyyyyy are the next 6 bits(bits 11 - 6) to be encoded
4th byte = 10zzzzzz where zzzzzz are the remaining 6 bits(bits 5 - 0) to be encoded.

This shows how unicode characters are encoded using the standard UTF-8 encoding.

There is a variation to the standard UTF-8 encoding, called the modified UTF-8. This variation is used in Java by the writeUTF, and readUTF methods appearing in the DataOutputStream, DataInputStream and the RandomAccessFile classes. According to the variation when encoding a zero, it is encoded into 2 bytes using the 11-bit encoding which results in the 2 bytes 11000000 10000000 (C0 80 Hex). This is done to ensure that all bits = 0 is not a valid byte in this encoding. Another change is with regard to the values in the fourth range. While encoding the supplementary characters, any supplementary character will be available as 2 char values (high-surrogate followed by low-surrogate). This results in these characters getting encoded as six bytes each (3 bytes for high-surrogate and 3 bytes for low-surrogate).

Let us now look at the UTF-16 encoding.
In case of UTF-16 encoding the Unicode characters get encoded as 1 16-bit code unit or 2 16-bit code units depending on the value of the code point. We know that the range of code points for the unicode characters is from 0 - 10FFFF(hex). The characters in the range from 0 - FFFF(hex) are encoded into a single 16-bit code unit, retaining the value of the character as it is, The characters in the range from 0 - FFFF(hex) are the characters in the BMP (Basic Multi-lingual Plane). The auxillary characters which are in the range from 10000(hex) - 10FFFF(hex) are encoded into 2 16-bit values as follows:
The first step is to subtract the value 100000(hex) from the value of the code point, which would bring the value in the range from 0 - FFFFF(hex) which would be a 20-bit number. Now these 20 bits are encoded into 2 16-bit values as follows:

1st 16-bit = 110110xxxxxxxxxx where xxxxxxxxxx are the most significant 10 bits(bits 19 - 10) from the 20-bits to be encoded.
2nd 16-bit = 110111yyyyyyyyyy where yyyyyyyyyy are the remaining 10 bits(bits 9 - 0) from the 20 bits to be encoded.

so the 1st 16-bit value will be in the range from 1101100000000000 - 1101101111111111 (D800 - DBFF) which is the range for high surrogate and the 2nd 16-bit value will be in the range from 1101110000000000 - 1101111111111111 (DC00 - DFFF) which is the range for low surrogate.

This shows how unicode characters are encoded using the UTF-16 encoding.


Wednesday, September 3, 2008

Is Jane an Object or a Class?

Very often people trying to give examples about inheritance create confusion about the relationship between 'Object and Class' and the relationship between 'sub class and super class'. For example, I recently observed an article at http://java.sun.com/developer/technicalArticles/wombat_world/ which gives an example of inheritance as
public class Jane extends Person {...}
The relation between Jane and Person is more observed as Jane being an instance of Person, and not Jane being a sub class of Person, as is being implied by the example. The class is like a template using which instances can be created. A sub class is also a class, and so it is also a template which either inherits or overrides methods defined in the super class. A better example to show inheritance would be something like
public class ShopKeeper extends Person {...}