Tips For Sun Certification

Access modifiers for instance variables and methods
a. public
b. private
c. protected
d. none (default / package)
Access modifiers for classes
a. public
b. none
Modifiers for classes, methods and instance variables
a. abstract
b. final
a. abstract
b. final
c. native
d. synchronized
e. static
Instance Variables
a. final
b. static
c. transient
d. volatile
Local variables
The only allowed modifier is final. Otherwise none.

A table of information on integer data types

TYPE       BITS     BYTES       RANGE              CAPACITY
byte       8        1           -2^7 to (2^7)-1    2^8
short      8x2      2          -2^15 to (2^15)-1   2^16
int        8x4      4          -2^31 to (2^31)-1   2^32
long       8x8      8          -2^63 to (2^63)-1   2^64
char       8x2      2           0 to 2^16-1        2^16

Tip: An int type can hold 4 bytes. That is 4×8=32 bits.
Can range from minus 2 to the power (32-1) TO 2 to the power (32-1) minus 1.
Capacity: -2^31 to (2^31)-1 is exactly 2 to the power 32 values including the 0.

Allowed implicit assignments for Integer Types


For example a byte can be assigned to a short implicitly without giving a compile time error.
A char and a short can both be safely assigned to an int type. And so forth.


o A class with abstract methods must itself be declared abstract.

o A static method can only access static instance members (members denote methods, instance variables, inner classes).

Scope or Visibility of methods

diff class    diff class/   extended class extended class
/same package /diff package /same package /diff package
private      X                X              X             X
default     YES               X              YES           X
protected   YES               X              YES          YES
public      YES              YES             YES          YES

private ->default ->protected ->public
· Automatic variables (local variables) are not initialized by the system; every automatic variable must be explicitly initialized before being used. Otherwise a compile time error occurs.
· Final arrays itself cannot change their original reference but all the elements of the array can be assigned new values.
· Reading may be informative, but the inquisitive mind seeks practical answers. So there is no other way to crack the certification than getting your hands dirty with code. And try to avoid using an IDE.
If class greenheads extends class vegetable and class vegetable extends class food and class food extends class eatable; and class meat extends class food then we have the following scenario:
Vegetable and meat both extend eatable as well as food. And greenheads extend vegetable, food and eatable; meat extends both food and eatable.

When an object is cast to something that is not its original class type, a class cast exception occurs.
The compiler will not let you make a cast if there is no chance for the cast to succeed.
Suppose you have an array of Employee objects called staff[] that includes a couple of Manager objects that extends Employee, and you have an unrelated class called Cat.

Cat bert= (Cat) staff[i]; // will give a compile time error
Manager boss= (Manager)staff[i];//will compile fine
//but will give a runtime error when staff[i] is just Employee

In this case ClassCastException) occurs if staff[i] does not happen to be a Manager object.
All runtime errors are unchecked.
Checked exceptions and unchecked exceptions inherit from class Exception.
Exception class and errors inherit from Throwable. Checked exceptions have to be caught or declared else the code will not compile. Unchecked exceptions can be caught with a catch clause but it is not imperative to do so. They will cause a program to terminate if not caught. Run time exceptions usually represent program bugs. Programmers can however throw a run time exception under specific conditions and then catch them to perform some other activity.

· instanceof operator returns true if the object is an instance of the named class or any of its subclasses.
· None of the components inside a loop construct are compulsory


is perfectly legal and executes an infinite loop.
· Any number type may be compared with another number type. For instance a float may be compared with an int type.
· Strings that have the same value at compile time, share the same memory space and hence when compared with == will return true. (== checks whether the storage locations are same, in case of objects).
· Strings that are created at run time do not share the same memory and the test with == will return false.
· The switch construct can only accept data types that can be converted to int. Going by the discussion at the beginning of this post, that includes byte, short, char and int itself.

String java= “Java”
String va= “va”;
if(java==(“Ja”+va))//returns false
{//this is a runtime check
if(java== “Ja”+ “va”)//returns true
{//this is a compile time check

The nuances of inheritance
If class Child inherits from class Parent and both Parent and Child have methods called bawl() and instance variables called temper then :

Parent p = new Child();//Child is the father of man?

p.bawl() will invoke the bawl() in the Child class
p.temper will be the value of temper in the Parent class.

A funny expression
Will the following piece of code compile?

int i=1;do while(i!=0){}while(i>1);

On further observation the above expression can be expanded into

//at least one execution being do while loop
//might not execute even once being while loop

Overloading and Overriding
Overloaded methods have the same method name but a different parameter list. (different signature) They may or may not have the same return type.
Overridden methods on the other hand have same name, same parameter list and same return type.(Signature+return type)
· The overridden method must have the same or more accessibility than the parent method.
· It must throw the same or subset of the exceptions thrown by the parent method.

Math functions
sqrt(0.0) returns 0.0
sqrt(-1) returns NaN or the java equivalent of NotANumber

· All sorted collections begin with Tree
· All mapped collections begin with Map and use keys
· HashMap is a non synchronized Hashtable
· ArrayList is a non synchronized Vector
· Maps allow duplicates and use a key
Summary on Collections

Non duplicating , Unordered SET
Duplicating, Ordered LIST
Duplicating, Ordered with Keys MAP

Non Duplicating, Sorted SORTEDSET -TreeSet
Duplicating, Sorted, with Keys SORTEDMAP -TreeMap

Concrete classes that implement the LIST interface includes ArrayList.
A List is an duplicating, ordered Collection
A Vector is similar to an ArrayList, except that it is synchronized.

Concrete classes that implement SET include HashSet
A HashSet is a non-duplicating, unordered collection..

Concrete classes that implement the SORTED SET interface include TreeSet.
A TreeSet is a non-duplicating, ordered collection that contains unique elements.

Concrete classes that implement the MAP interface include HashMap
A HashMap is a duplicating, unordered collection that contains key value pairs.
A Hashtable is similar to a HashMap except that it is synchronized and does not allow null values.

HashSet allows only one null key, but HashMap can allow one null key + multiple null values. A HashSet is implemented in terms of a HashMap. It’s a mapping between the key and PRESENT object.

Concerte classs that implement the SORTED MAP interface include TreeMap
A TreeMap is a duplicating, ordered collection that contains key value pairs. Keys must be unique.

To Applet Or Not To Applet

Applets may not be a “perfect” delivery vehicle for intranets (or extranets for that matter) as we might be made to believe.
1. They provide richer “GUI”
2. They take the load off the server (because the client machine does processing).
3. For special circumstances e.g. If non-text data is to be processed at the client side etc.
1. It is slower (initial load time) for the user.
2. It requires installation of the java plug-in at the client browser.
3. The capabilities of an untrusted applet are limited (because of security). No printing, copy-paste, accessing client machine files etc.
The disadvantages get mitigated in an intranet environment because
a. The users are internal (or rather captive); they can be made to tolerate a slower application.
b. The application deployer can control the client environment i.e. instruct the user to install such and such plug-in etc
Having said this, the usual procedure is – don’t go for applets (whether in an intranet or extranet) unless there is a compelling reason to do so. The most likely instance is, if you have UI requirements that cannot be satisfied by plain old HTML.
Then again, it is not an either-or decision. It is usually the case to have a mix and match of JSP and Applet screens in the same application.
Architectures for Applet based Applications
There is no difference in the network environment requirements (intranet /extranet/LAN etc.) as far as Applets are concerned. It would operate in the same environment as a JSP/ J2EE Application.
There are two possible architectures for applet-based applications.
1. Client-Server
This is very rarely (if at all) used. In this architecture the applet code directly accesses the back-end database. This has none of the advantages of J2EE – no database transaction integrity, no scalability, etc. Also, this would require extra database related set-up on the client machine.
Also, this has an overriding disadvantage that it will ONLY work in an intranet/ LAN environment. In a extranet application, firewall administrators allow remote machines to connect to only port 80 for HTTP, port 21 for FTP etc.
It’s unlikely that applets running on remote machines on an extranet will be permitted to access the database ports (whichever port number that is, depends on what database is being used).
2. Applets in a J2EE setup
This is the more common way of using applets. Applets replace the JSPs used in the application. Everything else in the J2EE setup remains the same- servlets, EJBs etc.
This is ideal for using a mix and match of JSPs+Applets in the application.
The Applet communicates with a servlet on the application server and passes serialized java objects back and forth using a technique called HTTP tunneling. It uses the regular HTTP port for communication and hence is not at risk for firewall port blocking.

Some FAQs:

Q. What do you mean by an applet running on a remote machine?
A.An applet runs within a browser installed on the client machine. Its nothing but a piece of java code that executes within the scope of a client machine browser. To “run” it you need the java plug-in. (runtime environment) installed on the client machine.
It is more than just dumb display of text (which is what HTML is).
Hence it is more powerful than HTML.

Q. What is the security manager? What is a trusted applet?
A. If you need the applet to do some usually “prohibited” things (like printing, copy/paste, file access etc.) then you need to use a trusted applet. It involves a security certificate to be installed and some other stuff.
The reason for this “prohibited” restriction is that, while browsing the World Wide Web you don’t want any tom, dick and harry’s applet to gain access to your personal machine and create havoc.

NB: In the above discussion for all purposes intranet is synonymous with LAN.

Common Issues with JSPs and Servlets

Include directive versus include action
There are two ways to include files in a jsp.

<%@include file= (directive)

In this case the two files are combined together before the jsp is compiled. So you can have java as well as taglibs in the included file.

<jsp:include =   (action)

In this case the included file is combined with the main page only after jsp compilation. So whatever the included file contains is simply sent to the browser. One cannot have java or tags in the included file, because the included file is never compiled.

Avoiding caching in jsp pages
To avoid caching of jsp page” use the following HTTP header tags.


Struts also has a nocache attribute that prevents caching.

Special characters may need to be encoded while using URL rewrite. Otherwise special characters such as a space inside a parameter string may cause some data to get lost.

xyz="par1="+URLEncoder.encode(value1)+"&par2="+ URLEncoder.encode(value2)+"&par3="+ URLEncoder.encode(value3);

Note that only parameters are encoded not the entire string.
Then use

<a href='/servlet/com.mattiz.MyServlet?<%=xyz%>'>

Interesting problem with transaction integrity
The user is logged in using the flow:
Now suppose the user logs out and then presses the back button on the browser window till he reaches Login.jsp (address bar now displays the URL of AuthenticationServlet ) and when he clicks enter he gets logged in again! If response.sendRedirect is used (the address bar shows the URL of the jsp on the address bar instead of the servlet ) this behaviour is not seen.
This behaviour is also seen when a form on a jsp page is submitted. If before the next page loads, refresh is clicked; duplicate data is processed again, such as data entry into a database. Again this is seen with RequestDispatcher, not with reponse.sendRedirect.
There are cases when it is essential to use the RequestDispatcher to move from servlet to jsp. If you want the request object to hold request parameters/attributes the only option is to use the RequestDispatcher forward in the servlet. (response.sendRedirect does not retain any request values)
To avoid this we use tokens as follows:
In the page containing the form being submitted include a hidden field with the value:

In the servlet put the logic (to insert into the database) within an if statement like this
//do processing
//then this last line at the end of if block

The explanation of this is as follows:
The first time the jsp is submitted, the hidden field value is passed to the servlet, which does processing and then sets the token value in the session.
If refresh button is clicked the request token value is the same as the session token value and duplicate processing does not happen.
On the other hand if the page is revisited and resubmitted, the request token gets updated with the new value (new current time in Millis) but the session still holds the old value (based on previous visit). In this case control passes through the if block and processing is done again.

Checking whether the user has a valid login
If you need to check whether the user has logged in based on whether the session object is valid or not you would need to structure your jsp page thus:

<%@page session="false"%><!--turns off implicit session object created by JSP -->
//get session if exists; else don’t create a new one if not
javax.servlet.http.HttpSession expSession = request.getSession("false");
//check for session
//no access to page=invalid session
forward to login page
//valid session
allow access to jsp contents

The Hyphe about XML

XML : What It Is, And What It Is Not!
What it is:
XML is a structure for data formatting, no more and no less.
Imagine this scenario:
Some corporation ABC has to upload data from text files and has a format like this:
01:Hanks,Tom:7850:Assistant Manager:B
1. This format does not make any sense to any one except the program that ABC corporation uses to upload information.
2. The program has to specifically read this formatting and interpret what the first value is, the second value and so forth.. and load it into a database.
3. Creating such a file is also a menial and error prone task.
4. A missing colon could create havoc. Custom written programs would have to check the health of the file structure to know if it is malformed or not.
Compare and contrast with this structure:

<id> 01 </id>
<name> Hanks, Tom</name>
<salary> 7850 </salary>
<position> Assistant Manager </position>
<grade> B </grade>

1. Any one can interpret what this is all about
2. Programs can use XML-specific APIs to read data more easily
3. XSL tranformation makes it easy to convert data from one structure to another (for instance from xml to pdf or html)
4. XML Validators (pre-written generic programs) can check malformed-ness, so there is no need for check-sum, byte counting and other primitive methods of checking if data is valid.
What it is not:
1. It is not a programming language (although XSLT is a programming language, or rather a transformation language that converts from one text format to another).
2. It is not specific to any programming language including java. Any language that can do input/output (read and write text) can work with XML. This is what makes XML the unifying bond between disparate systems written in different programming languages.
3. It is not the optimized way of storing data. If you see the structure, the data is not compact. For example if data about 10 employees is to be stored each of the tags (id, name, etc..) would be repeated ten times.
4. It is not meant to replace traditional relational databases. XML cannot deal with too much data. It is after all, just text that is processed sequentially.
It is easier to work on XML with the java language because java has a good set of APIs that are prewritten, that can be utilized for parsing, creating and validating XML files.
Another advantage that java has is that XML files can be mapped to java classes easily. For example, the above example can be mapped to the java class:

public class employee {
String id;
String name;
float salary;
String position;
char grade;

And so on and so forth…

Where it is useful:
There are two situations that XML is used:
1. Small amounts of data – interchange between disparate systems. This interchange can be real-time or off line. Real-time data interchange using XML is what soap/ web services is all about.
If systems that need to communicate in real-time are both in java, we might as well use RMI or CORBA to pass java classes into remote methods.
2. As configuration files
In the traditional days, configuration files that hold data was of this structure
In XML this can be replaced with a structure that looks like

<weight-unit> kilograms </weight-unit>
<temperature-unit>  Celsius </ temperature-unit>

For example that is how ejb engines store data for EJB configuration. (deployment descriptors)
Because of the ease of creating and manipulating XML files, most EJB engines provide a GUI front end that allows you to enter data into screens that are then transformed into XML format and stored, and will then be used for getting values necessary for the ejb engine to work.

SOAPing it Up

Introduction to Web Services
In distributed computing, the geeks like to see the world divided into various “service providers” and “service users”. The service provider typically is the owner of a “software component” that does some unit of work. The service user has a system that does a complete task (involving many units of work)for which it needs the service of one or many such service providers.
Let us take the example of Google (which effectively uses Web Services currently). Google provides the service of searching the Internet. This service is being used by multiple other clients either directly or integrated with other functionality inside its applications. Google charges clients on a per-search basis (maybe just a few cents per search, but adds up to a substantial amount if traffic is good).
The beauty of it is that Google can provide the service over the Internet using Web Services technology. These other clients who use Google’s search engine need not be connected to Google’s services through LAN or WAN. Other companies like Reuters (to provide real-time news on a per-demand basis), Amazon (to provide e-commerce through web-sites) could also provide web services. Some Wall Street firms can provide a service that would provide stock quotes over the Internet.
Any applications that need to incorporate these function into their design simply act as clients to the web-service.
The mechanics of Web Services
To access the Google Web Services, the essential information that a client needs to provide is the “search string” (the text that you provide the search engine). The string should travel from the client’s machine across the Internet to Google’s server. Google’s server would do its searching business and get some content which would be the result of the search. This result needs to travel from the Google’s server back to the client’s machine.This is essentially the equivalent of executing the method
String doGoogleSearch(String searchString).
The essential difference here is that the logic for the method would exist on Google’s servers while the method needs to be executed from some client location. The two are only connected through the Internet.
To make this work, the Web-Service client and provider need to communicate using HTTP (the language of the Internet of course). Whoaaa… You would say … HTTP is used for browsers to communicate with applications.. what this all about two applications talking to each other using HTTP? Thats the new way that HTTP is being used by the Web Services.
So let us imagine that Google’s clients send it information pertaining to what method it wants to execute, and the parameters to the method. The http traffic would look like this:

POST /EndorsementSearch HTTP/1.1
Content-Type: text/xml; charset="utf-8"
SOAP Action: ""
<SOAP-ENV:Envelope xmlns:SOAP-ENV=""
            <m:DoGoogleSearch xmlns:m="">
                <searchString>Sammy Sosa</searchString>
    </SOAP-ENV Body>
    </SOAP-ENV: Envelope>

As you can see, SOAP is just a specific XML format to make the content understandable to service providers and users.
If you ignore the rest of the extraneous material, you’ll see that the essential information is the name of the Web Service, the method to be executed is doGoogleSearch() and parameter passed is “searchString” whose value is “Sammy Sosa”.
You’ll admit that this HTTP traffic looks pretty different from a regular HTTP traffic coming from the browser which will be more like

<html> <head>blah.. blah.. </head></html>

The Google servers should have an outward facing Web Service that can interpret this kind of traffic coming in, parse out essential information and execute relevant method and transmit back information.This is done by the “soap engine” . In Java, the soap engine is usually a special servlet which would trap all HTTP messages that hit a specified url pattern. Let’s say our Google Web Server’s soap engine interprets all URLs that end with service /* and assumes that it’s a soap request (as opposed to an HTML request).
The soap engine would execute the relevant method doGoogleSearch(…) and get the result (in this case it is “LARGE STRING SEARCH RESULT”) and transmit it back as HTTP response. The return transmit would look like this:

<?xml:namespace prefix = soap-env />
<SOAP-ENV:Envelope xmlns:SOAP-ENV="" SOAP-ENV:encodingStyle="">
<m:DoGoogleSearchResponse xmlns:m="">
<searchResults>LARGE STRING SEARCH RESULT</searchResults>

The client can extract the search result from the SOAP message and do whatever it likes with it.
If you look at the http traffic, you will see that
1. It is normal text traffic travelling on tcp/ip (HTTP) (no custom data formatting)
2. It follows http request/response style protocol(so soap engines can use servlet/php/asp architecture)
3. It can flow through regular http ports 80. etc… that normal webservers use.(this makes Web Services very pervasive to firewalls)
4. The interpretation of messages going back and forth is in XML and can be standardised and shared (between Web Service providers and users) by using commong DTDs. All Java, .NET, ASP, PHP languages are capable of doing the above four things, so Web Services can effectively connect components between these disparate systems together.
That’s what all these guys are harping about. The Web Services can connect components in disparate worlds together to build a complete application.
Some caveats however-
1. Web Services make sense only if disparate systems are involved connected by the Internet. If you need two servers both using Java to talk to each other on a LAN, there is no need of Web Services, we can might as well use RMI or CORBA.
2. The Web Service provider should build a Web Service only if it is likely to be useful to many external entities. There’s no point in creating Web Services that the clients don’t need (they could write their own code to do it).
3. Web Services are slow. The slow response that we normally experience for traffic between browsers and applications will now appear within and between applications performing their tasks. Web Service defines only the structure to communicate. It does not provide inbuilt infrastructure for security and payment.For example Google will have to figure out the security/ authentication required to identify the service users who are allowed o use its service. Because this service is available only out on the world wide web anyone can become a user of the service unless restricted by specific means.
Also Google will figure out how to charge its customers for providing the service.

A deeper look at Java Web Services and SOAP

Let us say you invoke a method Foo getFoo(String blah). In this scenario the code that invokes getFoo() is called the client while the class that implements this method is called the server. This is easily done when both client and server objects reside on the same JVM. (Please note client and Server are relative terms).
However if the client and server reside on separate JVMs as maybe in the case of EJBs, in Java we need to to do a remote invocation using RMI-IIOP. However RMI is a proprietary protocol in Java and will not work when say the client uses Java and the server uses say, .NET.
This is where web services comes in. With Web Services you have different technologies communicating with each other. This kind of communication is useful when integrating different systems as in EAI (Enterprise Architecture Integration).
Web Services use http, the same protocol between browser and server, except that here there is no browser as client, the client and server are both application servers communicating via HTTP protocol.
If the client system needs to invoke a method on the server system, let’s say, Foo getFoo(String blah), then the client needs to send the server the “blah” parameter and in return get the “Foo” object, that is through HTTP.
So as you can see it is pretty much a request- response model.
So let’s say the client creates a small xml


and sends it across via http to the Server which reads it and creates a Foo object and sends back a response again as xml.
So as you can see the data is sent as Strings embedded in an xml file which both server and client can construct into a java object. (Here we are dealing with both server and client using Java technologies, not disparate systems). This conversion to xml is also serialization, just that it is easier to read than what RMI does during serialization. This process is called XML over HTTP.
The problem with this technique is the client and server need to come up with some agreement on the XML syntax being used for data transfer.
This is where SOAP comes in. It is basically structured XML which tells you how the xml will look like, which part of the xml holds the parameters, where the result lies in the XML, etc. It’s just an envelope around the real data xml and hence called the SOAP envelope. It structures the data so both client and server can interpret the http requests and responses.
The way it works is-
The server creates a file called wsdl(pronounced visdel) – which describes the structure of the xml for specific data involved.
If there is a service available at a server with url say then the client gets the wsdl from the server by typing, and creates a java class using java utility classes and a SOAP client, usually a jar file. The java class is like the RMI stub for EJBs and acts as a proxy class – you invoke methods on the stub and it will do the communication for you; so you don’t need to worry about what is on the server, you just work with the wsdl you got. The SOAP client (a jar file) needs to be on the client classpath when running as well, not only for creating the proxy.
The server party has a tougher job that includes installing the web service (the SOAP engine). Just as there is a SOAP client on the client side, the SOAP engine, usually a war file, acts as the SOAP server on the server side.
The Server guy has written a java class manually with the implementation of the getFoo() method which he intends to make available through the web service. For this he deploys the war file on the web server. Then he writes a deployment descriptor called wsdd where he describes the java class containing the getFoo() method and configures the server war file to read it and make it available. So it is the war file that reads the deployment descriptor file(wsdd) and makes the service available.
When the web server, say Tomcat, with the SOAP server, is running, it is listening to http. The client makes a http request to the SOAP server after opening the http port on the server side, just like a standalone application can. The configuration for the deployment descriptor can be done through a web console similar to weblogic or websphere.
Sometimes you would not need a deployment descriptor, wsdd file, in case you rename .java to .jws. The SOAP engine (SOAP server) can read the .jws file and analyze it, after you point out your jws file through the web console configuration apparatus. You could also use the configuration console to point out your deployment descriptor to the SOAP engine, too.
This is an optional feature and allows you to dynamically discover web services. For example if you want to know today’s interest rates, there may be multiple web services providing that information – so to get one you like, you look up it in the UDDI – it is like a registry. UDDI is not practical mostly, because usually the client has to know very well which server it’s going to talk to and what is the format of the SOAP request it expects, and so it’s hard to dynamically search and use web service this way.