Technical Tips, Tricks and Articles

Archive for the ‘code’ Category

Comparing Wrapper objects values in range –128 to 127

leave a comment »

While debugging through a bug that I encountered in one of my ongoing project. I came to know a strange behavior of Java. Consider the following code segment

1 Integer a = 10;
2 Integer b = 10;
3 
4 if (a == b){
5 	System.out.println("Two values are equal");
6 	}

If you look closely at line no 4, then you would realize that the code is actually comparing “Java objects”. Since “a” and “b” are not wrapper classes not primitive types.  But even then the condition is being true. Ok, some how this makes sense (at least till now unless you read this code segment)

1 Integer a = 150;
2 Integer b = 150;
3 
4 if (a == b){
5 	System.out.println("Two values are equal");
6 	}

Astonishingly, for the above code, the if statement would not execute true. Why?

Well, ever since Java has introduced “auto-boxing” feature, you’ll face this issue. Why is it so? Actually, compiler try to optimize things as much it can. For this, Java has a pool of values from –128 to 127. Whenever, there is some auto-boxing between these values, the reference object for the wrapper class will get the same memory location. In both cases, we are comparing “object references” but in first case, since the value was in the range for both objects hence, Java assigned the same reference location to both objects, making the condition “true” on comparing memory location for two objects.

Now, the question is why between –128 to 127?. Well, the smallest range of values for smallest wrapper class is between –128 to 127 i.e. Byte.

Written by ..alee

July 5, 2009 at 1:06 pm

Posted in code, interview, java, programming

Tagged with , ,

A C Code, getting a string using gets();

leave a comment »

Hi,
last night one of my friend showed me a C code and told me that he was unable to get the string input using gets(); I am posting the code here.

char temp[50];
printf("Please enter your name: ");
gets(temp);
printf("%s", temp);

Now, he was very confused that why this simple code is not working. I asked him to put fflush() before calling to gets(). He did it and the code worked fine. Do you get the reason?

The printf does not flush the memory and when you call the gets() it use the buffer characters already in memory buffer thus returning empty string.

Written by ..alee

January 11, 2007 at 4:01 pm

Posted in C, code, programming

Tagged with , ,