-1

I have this code, why bo3= st1 == st2 gives true ?

are not they in different position in the memory, and by == we compare the position whether it is the same or not !

Also if there is something wrong, please indicate me. Thank you guys.

public static void main(String[] args) {

    String st1 = "HELLO";
    String st2 = "HELLO";
    String st3 = "hello";


    int comp1 = st1.compareTo(st2);  // equal 0
    int comp2 = st1.compareTo(st3);  // -32

    boolean bo1 = st1.equals(st2); //true
    boolean bo2 = st1.equals(st3); // false , if ignoreCase will be true

    boolean bo3 = st1==st2; //true    ??????????? should not be true
    boolean bo4 = st1 == st3; //false


    int ind1 = st1.indexOf("L"); // 2
    int ind2 = st1.lastIndexOf("L"); // 3

    boolean con = st1.contains("LLO"); //true


    System.out.println(bo3);
}

While I have another code when I enter "Mary", the result: Same name and not equal

public static void main(String [] args) {

    Scanner keyboard = new Scanner(System.in);
    System.out.print("What is your name? ");
    String name = keyboard.next();

    if (name.equals("Mary"))
        System.out.print("Same name");
    else
        System.out.print("Different name");

    if (name == "Mary")
        System.out.println("equal");
    else
        System.out.println("not equal");
}
mijcar a
  • 27
  • 4
  • 1
    Java adds Strings to a String Pool to cut down on memory use, so st1 and st2 in your first example will point to the same memory location. – Ray Stojonic Nov 09 '13 at 11:56

2 Answers2

0

This behavior with == is somewhat coincidential in that you created your strings using "test". Many of the == behaviors with strings are implementation-specific. Only equals() is guaranteed to work to compare string values.

When comparing strings, always use equals() where possible, as strings are NOT guaranteed to be interned. When you use such literals, the compiler puts the string into the string pool, and makes all of the same literal string in the code point to the same String object.

when you create a string with concatenation or the constructor, the same is not necessarily true:

String test="test";
String test2=new String("test");
String t="te";
String s="st"
String test3=t+s;

There's no guarantee test==test2 or test2==test3, but with equals() it will still be true.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

st1==st2 is true as they both refer to the same String object.

This post should help: http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html

JamesB
  • 7,774
  • 2
  • 22
  • 21