Tuesday, October 1, 2013

What is the difference between String == and .equals method in Java

It has been long time that I visited my blog to post any update. Today I'm going to explain the difference between string == operator and .equals method.

Before we start lets define what is string intern pool.String intern pool is a process of maintaining only one copy of distinct strings on heap

Basically, String in Java is a object not a primitive data type. When you declare any variable in java as a string without new operator is called string literal. String created with new operator is called a string object. When a string literal is declared in java, during the execution process the java runtime enviroment (JVM) checks the string intern pool to see if the current string exists in it, if so the java runtime environment assigns existing string literal address to the current string, if not the current string will be added to the string intern pool.

When a string object is created with new operator, a new string object is created on heap. Even if you try to create another string with the same content, a new memory location will be allocated for it.

Lets see them with the help of examples

String a = "abc";
String b = "abc";

If there is no string 'abc' in string intern pool when you run this piece of code, the string 'abc' will be added to string intern pool when the first line of code is executed by JVM.When the second line is executed, JVM checks the string intern pool to see if the string 'abc' exists. It exists in this case hence it just assigns address of a to b.

String c =  new String("abc");

The above line of code creates a new string object on heap. If you try to create another string with the same content like String d = new String("abc"); it will be a new object on heap even though the object with the same content exists on heap, thats what the new operator does.

When you use == operator to check if two strings are equal, it actually checks the address of the two strings, returns true if the address of the two strings is same else returns false.

When you use .equals method, it checks the content of the strings. If the content is same it will return true else returns false.

As per above description, see the output of below statements
System.out.println(a == b); returns true
System.out.println(a.equals(d)); return true
System.out.println(a == c); returns false
System.out.prinln(a.equals(c)); returns true

Friday, March 11, 2011

Inheritance Explained

Everyone is aware of what is inheritance if they are in the world of Java. Let me dig some what deeper into that with casting objects and things like that.
Classes can be derived in java by deriving members of other class. Here members are public/protected fields, methods and nested classes. Constructors are not members of the class, so they are not inherited, but they can be invoked from the subclass.

Here the subclass is the class which derives members of the other class. It is also called derived class, child class, or extended class. The class from which the subclass is derived is called base class or super class or parent class.

What all we can do in subclass?
  1.  We can also inherit the members of a class (super class) with no modifier (package-private) if the subclass is in the same package. (modifiers restrict access to members of a class. Ex: public, private, protected and no modifier or package-private)
  2. We can use members of the super class in sub class like as they are defined in sub class
  3. We can declare new methods and fields in sub class. They don't affect super class in no way
  4. We can declare a new field in the sub class with the same name as in the super class, thus hiding the one in super class (Its not recommended) 
  5. We can create a new instance method in the sub class with the same method signature as in the super class, thus overriding it
  6. Sub class can inherit private fields and no package-private fields if the super class  has public or protected methods to access these fields
  7. If the super class has a public or protected nested class, it has access to all the members of it enclosing class. If the sub class is derived from the nested class, it has access to all the members of the class, which encloses the nested class
There will be a little bit confusion when we cast objects, if there exists inheritance.

Let us take an example, there are two classes A and B. A is the super class and B is the sub class. We can always cast sub class object to super class object, but not vice-versa. If we try to do it, we'll get ClassCastException, which is a run-time exception.

Let us take an example of casting.

public class A {
    public void display()
    {
        System.out.println("Dispay in A");
    }
}
public class B extends A {
    public void display() {
        System.out.println("Display in B");
    }
}

Class Test with main method to test the above scenario

public class Test {
    public static void main(String[] args) {
        A a = new A();
        B b = (B)new A(); //ClassCastException is thrown at run-time
        a.display();
        b.display();
    }
}


If we change B b = (B)new A(); to A b = new B(); and call b.display, guess which display method is called? Its the display method in B class. Because we created object for B class and casted it to object of type A. So it depends on which class is instantiated and not on to which object its casted when there is inheritance while calling methods.

Wednesday, July 7, 2010

Exception Handling in Java (when to use try catch/throw/throws)

Exception Handling is one of the important thing in any programming language. It was made easy in java using run-time error management. People wonder that what is exception? Exception is an event, which occurs during the execution of a program that disrupts the normal flow of program's instructions. Then the next point is why these exceptions arise? Answer to this question is very simple, Exceptions are thrown when a program violate the rules of any programming language or the constraints of the execution environment.

Exceptions are generated in two ways: 1. By Java run time environment 2. Manually generated by code written by a programmer.

A program can handle the exceptions or leave it to the callers of the program or to the default run time exception handler(are called uncaught exceptions).

The first doubt arise is why we use exception handling if there is a default run time exception handler? Becoz there are two benefits: it is easy to fix the error, and second it prevents the program from automatically terminating.

There are four ways to handle exceptions

1. Using try catch block
2. Using Throw
3. Using Throws
4. Using finally


Let me examine each way with simple example and discuss each in detail

1. Try Catch: Try catch is the very simple form to handle exceptions. Enclose the code inside try block to monitor any exceptions. Immediately after try block, include catch block to catch any exceptions thrown in try block as shown in the below example

try
{
//block of code to execute
}
catch(Exception1)
{

}
catch(Exception2)
{

}

Exception1 and Exception2 are type of exceptions thrown by code in try block.

2. Throw: Throw is used when the programmer wants to throw an exception explicitly using Throwable instance not by the java run time environment. More specifically throw is used when the programmer wants to throw his/her own exceptions. Throw statement requires a single argument: throwable object. Flow of execution stops immediately after throw statement; all subsequent statements are not executed.

Example:

class Throw
{
static void hello()
{
try
{
throw new NullPointerException("throw")
}
catch(NullPointerException e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
hello();
}
}

Output of the above program is: java.lang.NullPointerException: throw

Here I'm trying to throw NullPointerException which is a subclass of Exception.

3. Throws: If a callable method is capable of causing an exception that it doesn't handle, it must specify the behavior of the exception so that the callers will handle the exception. In this case we can use throws as shown in the below example.

type method-name(parameter list) throws exception-list
{
//body of method
}

type is the return type of the method, method-name is the name of the method and exception-list is the list of exceptions that a method can throw. If other class methods wants to call this method, it has to handle the exceptions thrown by this method.

4. Finally: When exception occurs, the code after the statement which causes the exception will not be executed. For example, if we open a file and an exception occurs without closing the file, it lead to memory shortage. Finally block is provided to avoid this problem. Code written in finally block is get executed even after the exception arises except when System.exit(0) is used inside try or catch block.

Please refer to this article for more information on finally block

Monday, July 5, 2010

Difference between Application Server and Web Server

Whoever is reading this article must have little bit of knowledge on what is server, application server and web server.

Web server handles HTTP (Hyper Text Transfer Protocol) requests, where as Application server servers business logic to application programs through many protocols like RMI IIOP (Remote Method Invocation Internet Inter-Orb Protocol), TCP/IP including HTTP. Web servers basically respond to user requests using HTTP. To process a request, A web server may respond with static HTML page, image, send a redirect, or delegate dynamic response generation to some other programs like JSP, ASP, server side java script or some other server side technology.

Web server delegation model is very simple. When a request comes into web server, it simply passes the request to other program which can efficiently handle the request, it doesn't provide any additional functionality beyond simply providing an environment in which the server side program can execute and pass back responses to web server.

Application Server exposes its business logic to its client applications through many protocols including HTTP. Application server provides access to business logic for use by client application programs. The application program can use this logic just as it would call a method on object. The information traveling back and forth from application server to its clients is not restricted to HTML. Instead, the information is a program logic. Since the program logic takes the form of data and method calls and not static HTML, the client can employ exposed business logic however it wants.

Application server also behaves like a web server but the converse is not true. Using application server, the business logic is separated from the markup. So that the code can be reused.

Please refer this example which differentiate application server and web server

Application server also provides some additional services like transaction management, security management, resource management and so on. If the application server is used, then the developer can only concentrate on business logic, not on additional services as they are already provided by the application server.

Web Server Examples: Apache, Apache Tomcat

Application Server Examples: Glassfish, Websphere, weblogic

Tuesday, June 15, 2010

Difference between Delete, Truncate and Drop in SQL

Delete is a DML (Data Manipulation Language) command where as Truncate and DROP are DDL (Data Definition Language) commands.

Three are used to remove rows from the table, but there are few differences

If we use Delete on any table, all rows in that table are deleted, but it doesn't free the space containing the table.

Ex: DELETE FROM TABLE_NAME WHERE CONDITION

If 'where' condition is not specified in the above example, all the rows in the corresponding table are deleted.

Truncate is also used to delete the rows from the table, but it frees the space containing the table

Ex: TRUNCATE TABLE TABLE_NAME

Drop is used to delete the entire table including rows, privileges, relationships with other tables.

Ex: DROP TABLE TABLE_NAME

Delete operation can be rolled back (B'coz Delete is a DML command), where as Truncate and drop operations can't be rolled back (B'coz these two are DDL commands).

Tuesday, June 8, 2010

Why Multiple Inheritance is not supported in java using classes

Why Multiple inheritance is not possible in java using classes means that it can be achieved using something else. We can use interfaces to make multiple inheritance possible in java.

Let us first discuss why its not possible with classes using a simple example

Let us assume we've two programmers A and B

A has written a class named ClassA which is inheriting ClassSuper and overriding one of its methods called Hello()

B has written a class named ClassB which is inheriting ClassSuper and overriding one of its methods called Hello()

Now, if multiple inheritance is allowed in java, another programmer called C wanted to extend both the clasess ClassA and ClassB which are written by A and B programmers respectively.

He is not overriding the method Hello() in his class. What if he calls method Hello()?

How does Java Virtual Machine(JVM) know which Hello() method (from ClassA or ClassB) to call?

This is the reason why multiple inheritance is not possible in java. But, still it can be achieved using interfaces. One must implement all the methods presented in interface if he is implementing interface. So, there is no possibility of confusion that which method to call, because java doesn't allow same method signatures in one class or interface.