Tag Archives: Java

Interesting Java Facts 3: Cloning a multidimensional Array

Consider the following code

int arr[][]={{10,20,30},{23, 45, 67,}};
int clone[][]=arr.clone();
clone[0][0]=-1;

Q. What should be the value of arr[0][0] and clone [0][0]?

A. It is -1 for both. Why? Let understand 2 things- clone always make a shallow copy of object  & Array is an object in Java.

Shallow copy: When we clone an object in Java, it only creates duplicate copies of primitive types, and for objects, the reference is copied. For example if an Employee object containing an address object is cloned, for address only reference is copied, that is not bot employee and clone are referencing same address object and any change in address is reflected in both.

We can override the clone method for Employee to make sure whenever a clone is made a new object for Address is created as well and all the values are actually copied one by one to new object. This will make sure both the original object and clone are referencing to their own address and changes in one does not get reflected in other.

Array is an object: In java array is an object, so a multidimensional array is actually an object with multiple objects (arrays) in it.

Putting both the above concepts together, we can figure out that while cloning, only the references of array objects  in multidimensional array are copied to cloned object, that means any change in one will get reflected to another.

Java multiple Inheritance: Interfaces and Composition

Inheritance means a class extending other class. Multiple Inheritance means single class extending more than one class. Java does not support this kind of inheritance as one class can inherit only a single class.

Q. Why Java does not support multiple inheritance?

Consider a scenario, there are 2 classes

class A{

public void mymethod(){//some code

}

}

class B{

public void mymethod(){//some code

}

}

class C extends A,B{//illegal in Java

//which implementation of mymethod is imported ?

}

If java allow multiple inheritance, it will be tricky to handle above situation with multiple inheritance, hence Java does not allow it.

Q. How does Java implement Multiple inheritance?

Java does not provide direct implementation of multiple inheritance by extending more than one classes, but it provides you 2 alternatives.

1. Use of Interfaces: A Java class cannot extend more than one class, but it can implement any number of interfaces.

Class C implements A,B{ // this time A and B are interface

public void mymethod(){//interfaces did not provide implementation and hence no conflict

}

}

2. Composition: Other way to use properties of other classes is to use composition, that is have the object of other classes as part of current class.

Class C{//A and B are different classes

A objA=new A();

B objB=new B();

}

Best Approach: A mix of implementing interfaces, extending class and using composition, based on different requirements

AJAX with Java

As a major requirement for AJAX application from server side language is to retrieve the request from client side and then parse it based on the format of the request. The request can be in form of a simple string, or XML, or JSON. And similarly the AJAX application expects a response back from server in one of these formats. Java can fulfill these requirements easily.

As for the first part, the server side language needs to accept the request from AJAX application in client side. Now Java has multiple ways to accept the request like JSPs, Servlets, Struts, JSFs etc. lets take a Servlet example

Public void doGet(HttpServletRequest req, HttpServletResponse res)
{
String ajaxData=req.getParameter(“Data”);
String returnString = executeAJAXRequest(ajaxData);
res.setContentType(“text/xml”);
res.getWriter.write(returnString);
}

Above one is a simple example. I left some of the details on purpose. Like what is executeAJAXRequest method doing. This will actually depend on the kind of request we receive.

The request might be a text based one where we don’t need to do any special parsing.

String executeAJAXRequest(String name)
{
String helloString= “Hello “+name;
return helloString;
}

That’s just a simple example; we could be doing some database operations in the method based on the name we got. But the idea is that the data is being used as it is. If it was a number say employee number we would convert to long and use.

Now if the data is in XML format. We already know that Java has strong XML support. It can parse and create XML documents easily using either DOM or SAX parsers. The following example shows how to parse data (uses apache’s xerces library)

ajaxRequest=”<employees><employee><name>John</name></employee></employees>”;

ArrayList executeAJAXRequest(String ajaxRequest)
{
ArrayList<String> nameValueArray=new ArrayList<String>(10);
try
{
DOMParser parser = new DOMParser();

parser.parse(new org.xml.sax.InputSource(new java.io.StringReader(ajaxRequest)));
DocumentImpl document = (DocumentImpl)parser.getDocument();

//get the root of the XML document
Node root = document.getFirstChild();
NodeList childNodes=root.getChildNodes();

for(int i=0;i<childNodes.getLength();i++)
{
nameValueArray.add(i, childNodes.item(i).getFirstChild().getFirstChild().getNodeValue());
}
}
catch (SAXException e)
{
e.printStackTrace();
//handle exception
}
catch(IOException e)
{
e.printStackTrace();
//handle exception
}

return nameValueArray;
}

The third way to pass data from client to server and vice versa is by using JSON. There are many libraries available in Java to parse and create JSON strings. Here is an example of code parsing a JSON String from client side using json-simple library (http://code.google.com/p/json-simple )

JSON string received from client is something like “{\”Employee\”: [{\”name\”: \”Eric\”, \”EmployeeNum\”: \”1232\”, \”Designation\”: \”SE\”}]}”

void executeAJAXRequest(String ajaxRequest)
{
JSONParser jsonParser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory(){

public List creatArrayContainer() {
//Add Details if required
return null;
}

public Map createObjectContainer() {
//Add Details if required
return null;
}
};

try{
Map jsonMap1 = (Map)jsonParser.parse(ajaxRequest, containerFactory);

Iterator iter1 = jsonMap1.entrySet().iterator();
while(iter1.hasNext()){
Map.Entry entry1 = (Map.Entry)iter1.next();
String valueString=entry1.getValue().toString();
String dataString=valueString.substring(1,valueString.length()-1);

Map jsonMap2 = (Map)jsonParser.parse(dataString, containerFactory);

Iterator iter2 = jsonMap2.entrySet().iterator();
System.out.println(“Here are the Employee Details”);
while(iter2.hasNext()){
Map.Entry entry2 = (Map.Entry)iter2.next();
System.out.println(entry2.getKey() + “=>” + entry2.getValue());
}
}

}
catch(ParseException pe){
System.out.println(pe);
}
}

Interesting Java Facts -2

Here is a interesting Java question. What should be values of x and y in below to make the while loop infinite / non terminating

while (x <= y&& x >= y && x != y) {
System.out.println(“hello”);
}

Hint: Answer lies in autoboxing.

Ok, the answer is

Integer x = new Integer(0);
Integer y = new Integer(0);

Now try to think why?

Wrapper Classes and Autoboxing in Java

We know in Java everything is an object, except, primitive types. Primitive types are char, int, boolean etc. As all other things in Java are objects, it is desirable to use our primitve types as Objects. An example situation is when we want to add int to an ArrayList which only accepts objects. The answer to this problem is wrapper classes like Integer class. We can wrap our primitive types into these class objects.

Integer iVal=new Integer(123);

So that is a wrapper class. Lets understand autoboxing now.

How to increment the value of iVal by 10?

Normal Scenario

Integer iVal=new Integer(123);
int temp=iVal.intValue();
temp+=10;
ival=new Integer(temp);

Java knows this is bit of a pain so it provides you help in form of autoboxing.

Autoboxing works

Integer iVal=new Integer(123);
iVal++;

How to use switch statement for String before Java 1.7

How to use switch statement for String before Java 1.7

We know that Java has provided us the functionality of using switch statements directly using Strings. If you are using an older version for some reasons, you can achieve the similar functionality using enums.

Here is an example

public class test2 {

private enum MyEnum{
red, green, blue;
}

public static void main (String s[])
{
MyEnum e=MyEnum.valueOf(“blue”);

switch(e)
{
case red:System.out.println(“red string”);break;
case green:System.out.println(“green string”);break;
case blue:System.out.println(“blue string”);break;
default: System.out.println(“default string”);
}

}
}

What is Type Erasure?

Since Java 5, Java has come up with the concept of Generics. Idea of generics came from the fact that developers at times faced issue with assignment of data types to Lists and other structure. In case a wrong type was assigned or was tried to fetched, error could be caught at run time only

Example

ArrayList arr=new ArrayList();
arr.add("kamal");
Integer i=arr.getIndex(0); //run time error

So Java gave us an option

ArrayList arr=new ArrayList();
arr.add("1");
Integer i=arr.getIndex(0); //compile time error

But we should note that Generics is a compile time concept. When Java convert the code to bytecode for JVM, it removes all generics related info. So finally

ArrayList arr=new ArrayList();

will be converted to

ArrayList arr=new ArrayList();

This concept is known as Type Erasure. This was necessary for Java in order to give backward compatibility, otherwise the code written earlier would not have been supported by newer JVMs.

Interesting Java Facts

I am working with Java for more than 7 years now and still it surprises me with some very basic stuff

Can you guess what is the output of this statement in Java

System.out.println(1+2+” = “+1+2);

3=12

Why? Apparently Java starts treating everything as a String once it has encountered a string in System out statement

Exception Handling- Basic Principles

Do not catch unchecked exceptions
Exceptions in java can be divided into checked and unchecked exceptions. Java compiler would force you to catch the checked exceptions but not the unchecked exceptions. Unchecked exceptions includes error and Runtime exception. These are the conditions in which program will not be able to handle the flow even if these are caught, so better let the JVM throw error and print stack rather than trying to handle these.

Error- A condition which occurs outside the program and causes failure, example, hardware failure.
Runtime Exceptions- An exception condition which occurred because of bad programming practice or unexpected input from user. For example, null value assigned to a variable being used or division by zero. Ideally these errors should be handled by code checks and not exception handling.

This means we should avoid catching superclass Exception as that will cover RuntimeExcpetions

Throw more relevant exceptions
Exception handling is done at multiple levels in code. For example you have, action->Process->Data layer. Now you might catch an exception in Database layer, but you might want to handle the exception actually in Action layer. So rather than throwing back filenotfound or sqlexception, you can create a DAOException and throw it instead. which will travel through Process layer and then to Action. This will help Action to handle fewer exceptions which are relevant at that layer.

Caveat- You might want to make sure you are passing all the relevant information back to the upper layers.

Using multiple try-catches
Instead of using one big block of try catch, create multiple blocks for better handling of exceptions. Make sure to take care of flow, once an exception is handled, the code will move to next try block.

Handle Exceptions late in code flow
Throw exceptions back to higher layers rather than absorbing them at lower layers. E.g. If an exception is caught at DAO layer, you might still want to throw it back to action layer for better handling.


Extend Exception and not Throwable

Here is the hierarchy of Exception class structure. Ideally we should try to extend a class as low as possible in hierarchy

Object->Throwable
Throwable->Exception and Error
Exception-> RuntimeExceptions and [other exceptions like filenotfound]
RuntimeException-> ArtithmeticException, NullPointerException

References:
http://wikijava.org/wiki/10_best_practices_with_Exceptions
http://docs.oracle.com/javase/tutorial/essential/exceptions/