-8

public class test{ //declaring class with name "test"

static public void main(String[] args)
{
    Long a=111L;  //declaring Long type variable
    Long b=111L;  //declaring Long type variable
    Long c=222L;  //declaring Long type variable
    Long d=222L;  //declaring Long type variable
    System.out.println((a==b)+" "+(c==d)); /*output is "true false". I dont know Why? Please explain  */
}

}

  • 2
    You know that isn't how you compare objects, right? – Rabbit Guy Aug 01 '17 at 19:07
  • Do you have a specific question, a specific point where you get confused? The code itself is very basic, it just compares some objects and outputs the results of the comparisons. – Zabuzard Aug 01 '17 at 19:08
  • Possible duplicate of [Compare two objects with .equals() and == operator](https://stackoverflow.com/questions/13387742/compare-two-objects-with-equals-and-operator) – jmoerdyk Aug 01 '17 at 19:13
  • *"What is the output of this code?"* Run it and see for yourself. – Andreas Aug 01 '17 at 19:15
  • Possible duplicate of [Why aren't Integers cached in Java?](https://stackoverflow.com/questions/5277881/why-arent-integers-cached-in-java) – Philipp Claßen Aug 01 '17 at 19:19
  • 1
    You are getting mostly getting downvoted because of the "What is the output of this code" part of the title. It smacks of laziness. You're real quesiton is: Why would 111L == 111L be true, but 222L == 222L be false? which I explain below. – Novaterata Aug 01 '17 at 19:20

2 Answers2

4

Long is a boxed wrapper about the primitive long. You should be using long. Primitives are compared with ==, but objects like a Long are compared with aLong.equals(otherLong); otherwise, when you compare with == you are comparing for reference equality. source

The reason one might be true and the other false, is because -128 through 127 are cached Source. So any object that is a Long with a value of 111L will be the same object, but a Long with a value of 222L will different from another Long with a value of 222L.

Due to this uncertainty, you should always compare objects with .equals unless you specifically want to know if they are the exact same object.

In this case though, I would suggest you use primitives and compare as you are.

Novaterata
  • 4,356
  • 3
  • 29
  • 51
0

Java caches the wrapper class(Long) objects instances from the range -128 to 127

Long variables with the value 111 (cached), the same object instance will be pointed by all references. (N variables, 1 instance)

Long variables with the value 222 (not cached), you will have an object instance pointed by every reference. (N variables, N instances)

Sreemat
  • 616
  • 10
  • 28