Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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 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.

Friday, June 4, 2010

Different types of variables in java

There are three types of variables in java
1. Instance Variables
2. Static Variables
3. Local Variables

1. Instance Variables: Instance variables are also called global variables. Each instance of the class has its own copy of instance variables (This is the fact that they are called instance variables). These variables are not declared with in any of the methods in a class but they are declared with in the class. These variables are also called non-static fields.

2. Static Variables: Static variables are defined with in the class with static key word (This is the fact that they are called static variables). Static modifier tell the compiler that there is only one copy of this variable exists regardless of how many times the class has been instantiated.

3. Local Variables:
Local variables are defined with in the method. They are only accessible with in that method.

Here is the example for variables

public class Variables
{
public static int staticVariable = 0;
int instanceVariable = 0;
public static void main(String args[])
{
String localVariable = "Hello";
System.out.println(localVariable);
}
}

From the example:

Instance Variable is int instanceVariable = 0;
Static Variable is public static int staticVariable = 0;
Local Variable is String localVariable = "Hello";

Thursday, May 27, 2010

When to use Interface and abstract class

Interfaces are contracts between groups of programmers who write code without any knowledge of what other programmers are writing. To keep them (Programmers) know what other programmers are doing, interfaces are the way in java.

Abstract classes are same as interfaces, with few differences. They can contain implemented method bodies, fields which are not static and final. They are useful when some methods are common for classes and some method implementations are different. So, we can implement common methods in abstract class and write method (which are not implemented) signatures in it. What ever the class is implementing abstract class will provide their own method implementations for methods which are not implemented in abstract class.

Look at this tutorial if you've more doubts on this topic.

Wednesday, May 26, 2010

Need for Just In Time compiler


Basic function of just in time compiler is to transform bytecode into machine dependent code. Instead of interpreting bytecod line by line, it converts bytecode into machine dependent code very fast (It tries to identify which instructions will be executed next, so that it can execute code in advance). It's used to increase the performance. One can see the performance difference if the same method is called more than one time.

Difference between Synchronized method and Synchronized block

Why we need synchronization in multithreading?

Because multithreading introduces asynchronous behavior to your programs, there must be a way to enforce synchronicity when you need it. For example, when you want two threads to communicate and share a complicated data structure, you need some way to ensure that they never conflict with each other.

One way to synchronize object methods is using synchronized methods as shown below

synchronized void call(String message)
{
System.out.println(message);
}

But, it'll not work in all cases. For example, if you want to synchronize access to objects of a class that was not designed for multithreading or what if the class was not created by you, but by some third party and you don't have access to the code? Solution is that you simply put calls to the methods defined by this class inside a synchronized block as shown below

Synchronized(Object)
{
statements to be synchronized
}

Here Object is a reference to the object being synchronized. Synchronized block ensures that a call to a method that is member of this object occurs only after the current thread has successfully entered object's monitor. (Monitor is an exclusive lock for the object being synchronized)

Tuesday, May 25, 2010

Difference between final, finally and finalize

Final is used to declare constants as shown in below example.

int final a = 10;

Class can also be a final class, which shows that the class can't be subclassed.

Method can also be final method, which shows that the method can't be overridden.

Finally is used to release any resources used in try catch block to free memory. It is placed after try-catch block. Code in finally block is executed always irrespective of the exception thrown except when System.exit(0) is called. It is shown in the below example

try
{
System.out.println("Enter your name:");
String name = scan.next();
System.out.println(name);
}
catch(IllegalArgumentException e)
{
System.out.println(e.getMessage());
}
finally
{
scan.close();
System.out.println("Closed");
}
Code in finally block is get executed. If you put System.exit(0) inside try block or inside catch block, then finally block is not called.

finalize() method is called before an object is collected by garbage collector to free any resources being used by that object

Difference between String and String Buffer in java

String is a immutable object, where StringBuffer is a mutable object in java. Still you'll be able to change string using '+' operator. But every time you add some thing to string object using '+', a new string object is created, So, more memory is need to hold those new objects. If you just use concat method of string object, it'll not concatenate the new string as shown in below example.

String abc = "Hello ";
abc.concat("changed");
System.out.println(abc);

Most of the people think that output of the above example is 'Hello changed' (with out single quotes). That's correct, but new object has been created with value 'Hello changed' (Without single quotes) and the previous value is recommended for garbage collection.

String abc = "Hello ";
abc += "changed";
System.out.println(abc);

Output of the above code is 'Hello changed' (without single quotes). But, a new string object is created to hold the string "Hello changed".

If you use StringBuffer instead of String in the above two examples you'll save memory(example 2) and you'll get the output what you intended for (example 1) as shown in the below example

StringBuffer abc = new StringBuffer("Hello ");
abc.append("changed");
System.out.println(abc);

Output: Hello changed

Thursday, May 20, 2010

How to access method variable in a innser class declared inside method

Variables declared inside a method can be used inside the inner class declared inside this method. But, those variables must be declared as final variables as shown in the below example.


public class InnerClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
InnerClass ic = new InnerClass();
ic.inner();
}
public void inner()
{
final int a = 10;
class Inner
{
public Inner()
{
System.out.println(a);
}
}
new Inner();
}
}

Output: 10

How to call Constructor from Constructor in the same class

You can call one constructor from another constructor if the class has more than one constructor in java. Here is the example. Note that constructor call must be the first statement in a constructor

public class Constructor {
int a;
int b;
Constructor()
{
this(1, 2);//This must be the first call.
System.out.println("hello");
}
Constructor(int a, int b)
{
System.out.println(a+", "+b);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Constructor();
}
}

Output:
1, 2
hello