0

Lets say i have a piece of code like that:

String name1 = someObject.getClass().getName();
System.out.println(name1);//The result of println in console is: entities.player.Shotgun

String name2 = someObject.getClass().getSimpleName();
System.out.println(name2);// The result of println in console is: Shotgun

String name3 = someObject.getClass.getName().substring(16);
System.out.println(name3);//The result of println in console is: Shotgun

if(name1 == "entities.player.Shotgun")System.out.println("condition1 true");
if(name2 == "Shotgun")System.out.println("condition2 true");
if(name3 == "Shotgun")System.out.println("condition3 true");

In my opinion all three if clauses are true but in reality only first fires in console: condition1 true. My question is why? What is the problem here?

Bogdan
  • 47
  • 2
  • 10
  • use `.equals` of the `String` class. Example: `name2.equals("Shotgun");` – 3kings Nov 23 '15 at 21:03
  • `String name1` is a *reference* to a String object. When you use `==` you are checking if the references are to the same object, not two objects which contain the same data. – Peter Lawrey Nov 23 '15 at 21:05
  • Hi Peter thaks for you comment. what you are saying make total sense, but if that is true why the first condition is true. I think all should be also false? – Bogdan Nov 23 '15 at 21:18
  • @Bogdan That's because `Class#getName()` interns the string value returned. Whereas, `getSimpleName()` creates a new string in heap. Same for `substring()`. See this: [`String#intern()`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()) – Rohit Jain Nov 23 '15 at 21:19
  • @Rohit Jain Ok I just read about string interning and I think I understand now. Thanks for your answer! – Bogdan Nov 23 '15 at 21:35

0 Answers0