A String Comparison problem

public class StringComparison{

public static void main(String[] args) {
            String hello1="hello";
            String hello2="hello";
            if(hello1==hello2){
                System.out.println("hello1==hello2");
            } else {
                System.out.println("hello1!=hello2");
            }

            String hello3=new String("hello");
            String hello4=new String("hello");
            if(hello3==hello4){
                System.out.println("hello3==hello4");
            } else {
                System.out.println("hello3!=hello4");
            }
}
}

Hope you guys read the code. Ok, As an introduction I would say its an old school technique. So this post is intended to beginners.  Lets move to the code. What should be the expected output? “hello1==hello2″, and “hello3==hello4″ right? Ok in that case you have to compile and run the code.

Now what is the output you get now? “hello1==hello2″ , “hello3!=hello4″, right? . How could it be possible ?

The answer is simple String Literal Pool

We know all object allocation need memory so do the String( You know unlike in C, in java String is a class).  Here the JVM performs something special to reduce the memory overhead. To reduce the objects of string used in code, JVM keeps an internal String pool. When ever you create a String in the code, JVM checks that internal String pool. If the same String is available in the pool a reference to the pooled instance is returned. Else a new String object will be created in the pool. The Strings are immutable in nature so it wouldn’t cause any problems too. So here in first case, JVM do the optimisation and both ‘hello1′ and ‘hello2′ refers to the same object. in the second case, we are externally asking the JVM to create separate objects for ‘hello3′ and ‘hello4′. So when we do the ‘==’ operation, first one returns the ‘true’ and second one returns ‘false’

 

Can you print a different output without modifying the main function?

So, what is today’s question? It’s a direct question I will write down the code:

System.out.println("Peter");

In main function, But I need to get an output like

“Hai Peter, Nice To Meet You.”

And I want it without modifying the main function, That is my main function will be

public static void main(String args[])
    {
		System.out.println("Peter");
	}

But I want it to print like “Hai Peter, Nice To Meet You.”

The Solution

import java.io.PrintStream;
public class DontModifyMainBlock{
    static{  
		        PrintStream newOut = new PrintStream(System.out){  
		            public void println(String s){  
		            	print("Hai ");  
		                print(s);  
		                super.println(", Nice To Meet You.");  
		            }    
		        }; 
		        System.setOut(newOut);  
	} 
	public static void main(String args[])
	{
		System.out.println("Peter");
		System.out.println("Kavitha");
	}
}

Output

Hai Peter, Nice To Meet You.

Hai Kavitha, Nice To Meet You.

What is this solution?

Here what we have done is, “we have just reassigned the print stream”. That’s it. Ok now people, the ones who understood what I just mentioned, You can rise your hands. And the ones who raised your hands can go out of the class, the others let’s see in detail. I hope you all have basic knowledge of a static block. The static block is the block that get executed first on an execution of a program. So here, before executing main(), the static block get executed so the code in the block. The following are the steps we executed to achieve the ouput.

1) We used a static block to execute the code at the beginning
2) Created a custom printStream object
3) Reassigned the normal stream with this custom stream using setOut() method.

IN DETAIL:

Create a custom printStream object
Here we have created an object ‘newOut’ of type PrintStream. We have used an ‘anoymous inner function‘ to create this object.

What is this anonymous inner Class?

If an inner class has been defined within a code block (typically within the body of a method), then such an inner class is called a local inner class. If an inner class has been declared without a name and within a code block (typically within the body of a method) then such an inner class is called an anonymous inner class. Since such an inner class doesn’t have a name associated, so it’ll be accessible only at the point where it is defined [courtecy: geekexplains.blogspot.in][reference:c2.com]

Back to code:

PrintStream newOut = new PrintStream(System.out){  
    	            public void println(String s){  
		            	print("Hai ");  
		                print(s);  
		                super.println(", Nice To Meet You.");  
		            }    
		        };

Here we are creating the anonymous inner class and assigning it to a reference of type PrintStream, which is ‘newOut’. As you can see, inside the block, we are over riding the println function.

public void println(String s){  
    	            	print("Hai ");  
		                print(s);  
		                super.println(", Nice To Meet You.");  
		            } 

Then inside it we are calling the ‘print’ function, and the println() function of its parent. And this is used to override the normal definition of println() function.

Reassigned the normal stream with this custom stream using setOut() method.

According to javadoc setout() function does

Reassigns the “standard” output stream.First, if there is a security manager, its checkPermission method is called with a RuntimePermission("setIO") permission to see if it’s ok to reassign the “standard” output stream.

Here we are using this particular method to override the normal functionality.Ok now we have ‘newOut’ the ‘PrintStream’ with new function definition. And we reassign the stream with this ‘newOut’

System.setOut(newOut); 

So by using the above code we have successfully overridden the default functionality of System.out.println() .

Check if a number is even or odd without any conditions

Today I would like to share a more logical question. This can be implemented in any language. But since I am more familiar with java I am going to use Java itself.

The Question

Write a program to find out if a number is even or odd”, pretty simple hah…, the ‘%’ will do it duty, right?  But my question is not over yet. “Do it without using any conditions “. Yea, write a program to print if a given number is even or odd without using any conditions (like if, else, for, == so on…)

The Solution

public class NoCondition {
    public static void main(String args[]){
		findOddorEven(12);
        findOddorEven(15);
	}
	private static void findOddorEven(int input){
	String[] evenodd=new String[2];
	evenodd[0]="The Number Is Even";
	evenodd[1]="The Number Is Odd";
	System.out.println(evenodd[(input%2)]);	
	}

}

Output

The Number Is Even
The Number Is Odd

A simple Java memory allocation problem

Today I would like to share a question, which was asked me by one of my colleagues.  So as usual let’s start with the code itself

Execute the code and predict the output and why?

import java.util.ArrayList;
public class BufferTest {
    
	public static void main(String args[]){
		ArrayList<StringBuffer> buffer = new ArrayList<StringBuffer>(); 
		StringBuffer buf = new StringBuffer(); 
		buffer.add(buf); 
		buf.append("Hello"); 
		System.out.println("********* OUTPUT **********"); 
		System.out.println(buffer); 
		buf.append("world"); 
		System.out.println("before setting to null: "+buffer);
		buf=null; 
		System.out.println("after setting to null: "+buffer);
	}

}

Output:
********* OUTPUT **********
[Hello]
before setting to null: [Helloworld]
after setting to null: [Helloworld]

Ok readers, if you got the correct output don’t go forward through this post (Don’t waste your time you can go SO and answer a couple of questions). To the other ones like me, who got the wrong output or to the ones who don’t know how does I get the correct output “let’s go forward”.

What is the big deal with this code? (One way of thinking)
First I have created an Arraylist here “buffer”. Then I have created a StringBuffer “buf”  and  added the  it  to the  “buffer”.  Now I am going to modify the StringBuffer “buf”, I have appended the word “Hello ” to the buf, And printed the ArrayList “buffer”. The modification on the object “buf” reflects in the Arraylist. Now I have again modified the “buf” by appending “world”. It also get reflected in Arraylist. Now the key portion, I have set “buf” to null. So it should also modify the Arraylist, right? Like the previous. And the expected output should be:

after setting to null: [null]

But what we got instead?

after setting to null: [Helloworld]

Oops!!! What Went Wrong?

Memory management by JVM

Here to understand this problem we should have a little knowledge about JVM Memory Structure.

Theory:
The JVM divides the memory to the following sections Heap,Statck,Code,Static.
Heap: It mainly contains the objects and some reference variables
Stack: It contains local variables, methods, reference variables
Code: Contains byte codes
Static: Static data and methods

Good reference
http://www.erpgreat.com
http://javapapers.com

Back to problem

 

What is the big deal with this code? (Right  way of thinking)
When the following

ArrayList<StringBuffer> buffer = new ArrayList<StringBuffer>();

Code executes, A heap memory location will be given a name ‘buffer’ and that ‘buffer’ will be pointing (more correctly referring) to a heap memory location containing the newly created object of the ArrayList. When the StringBuffer ‘buf’ get created, it undergoes the same above steps. Likewise the ‘buf’ will also be pointing to a heap location.

When executing the below below code
buffer.add(buf);

The ArrayList ‘buffer’ object will (which is on heap) point to the buf’s object location. So now we have a stack location ‘buf’ pointing to the Object (Which will later contain the word “Hello world”), And also An Arraylist object (Object which is pointed by ‘buffer’) pointing to the same location. In short now we have two references variables (buf and buffer) that point to a single Heap memory location.

Now we execute “buf.append(“Hello “); and buf.append(“world”);” it will affect the heap location since ‘buf’ points to that location. So the heap location content will be “Hello ” first and it will be modified to “Hello world”. The result will also reflect in ‘buffer’ since it is also pointing to the same heap location. Hence when we print ‘buffer’ the results will be as shown above.

Now comes to our key part
buf=null;

What happens now? , It is simple, the reference of ‘buf’ is set to null. That is the ‘buf’ No longer point to the heap. But what about ‘buffer’? It will still be pointing to the same heap location. So we can access it through the ‘buffer’ ArrayList.

For more details, I have included an image of what happening in the memory.

Note:
Here StringBuffer is “sb”, and ArrayList is “al”
Image courtesy Nidhish Krishnan

A try without catch?

Today I would like to share an interview question that I was asked once.

Prologue:
The question was simple “can you use a try without catch?”. My answer was even more simple “No”. By the end of the interview my interviewer asked me “would you like to know anything more?”, I asked him the correct answer of the above question. He said “Yes, You can use a try without catch”.

Yes, You can use a try without catch
Now the question is “how?” how could I use a try without catch?, I have always seen the try accompanied by catch. It could be impossible. No, Its not. Nobody is asking you to use try alone, but try without catch. Then what is the next option, the “finally”. Yes you can use the try with a finally.

try {
    //for example try to get a database connection
}
finally {
  //close the database connection
}

Real time example:
An example where try… finally without a catch clause is appropriate in Java is usage of Lock in concurrent utilities locks package.

Lock l = ...;
     l.lock();
     try {
         // access the resource protected by this lock
     } finally {
         l.unlock();
     }

More details

 Now something more interesting :

Predict the output

public class TestTryFinally {
	public static void main(String args[]){
		System.out.println(" RETURN VALUE : "+returnValue());
	}
	public static boolean returnValue()
	{
	    try {
	        return true;
	    }
	    finally {
	        return false
	    }
	}
}

OUTPUT:
RETURN VALUE : false

What have you just seen? Was that like try block was being ignored?
Yea, It’s a kind of true statement.

Lets see the definition of finally by java doc

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

So from the definition we can come to the following conclusion

  1.  The finally block should be executed independent of ‘what is happening’ in try block
  2.  So even if a return statement is issued from the try block, the finally should be executed(replace ‘what is happening’ in the (1) with ‘return’)
  3.  Since by definition finally block has a high priority it can return whatever it like without considering the try(hence it will be discarded).
  4.  The only thing that can affect the finally block is a System.exit() call or a failure in JVM or a failure in application itself

Note:
eclipse shows a warning “finally block does not complete normally”
Anyway in general, You should use finally blocks for cleaning up/closing resources.
The finally block is typically used for closing files, network connections, etc. that were opened in the try block.

 

Boxing Conversion

This is my first post, So I would like to share something that made me wonder, Let’s go direct to code.

Execute the below.

//Case 1
Integer a = 10;
Integer a1 = 10;
System.out.println(a == a1);

//Case 2
Integer a = 127;
Integer a1 = 127;
System.out.println(a == a1);

//Case 3
Integer a = 128;
Integer a1 = 128;
System.out.println(a == a1);

The output
true
true
false

Here you can see Case 1&2 is true, and what about “case 3”? How could it be a ‘false’? really strange, isn’t it? How could the value of a variable affect the result?

The answer lies in one of java’s stand alone features “Boxing Conversion

So, What is this “Boxing Conversion” ?

Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions:

From type boolean to type Boolean
From type byte to type Byte
From type short to type Short
From type char to type Character
From type int to type Integer
From type long to type Long
From type float to type Float
From type double to type Double
From the null type to the null type

Back to our code:

//Case 3
Integer a = 128;
Integer a1 = 128;
System.out.println(a == a1);

What is happening here,

Our code(Case 3) compiles into

Integer a = Integer.valueOf(128);

And
Integer a1 = Integer.valueOf(128);

The boxing uses Integer.valueOf(), which internally caches Integer objects for small integers (-128 to +127), the JVM will return you the same objects in that range. Otherwise it will create a new object and return you that. Here we have 128 as the value hence these statements will return two different objects. So the == operation will return a ‘false’

/**
* Returns a &lt;tt&gt;Integer&lt;/tt&gt; instance representing the specified
* &lt;tt&gt;int&lt;/tt&gt; value.
* If a new &lt;tt&gt;Integer&lt;/tt&gt; instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Integer(int)}, as this method is likely to yield
* significantly better space and time performance by caching
* frequently requested values.
* @param  i an &lt;code&gt;int&lt;/code&gt; value.
* @return a &lt;tt&gt;Integer&lt;/tt&gt; instance representing &lt;tt&gt;i&lt;/tt&gt;.
* @since  1.5
*/
public static Integer valueOf(int i) {
if (i &gt;= -128 &amp;&amp; i &lt;= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}

Note: IntegerCache.high defaults to 127 unless set by a property.

The key note to remember:

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), let a and a1 be the results of any two boxing conversions of p. It is always the case that a == a1 will return true, else false.

Some Helpful Links to refer in detail.

java documentation

Stackoverflow