2
public class ExampleString {
    public static void main(String[] args) {
        String s1="u cannot change me!";
        String s2="u cannot change me!";
        String s3="u cannot"+" change me!";
        String s4="u cannot";
        String s5=s4+" change me!";
        final String s6="u cannot";
        String s7=s6+" change me!";

        System.out.println("s1==s2 "+(s1==s2));//true
        System.out.println("s1==s3 "+(s1==s3));//true
        System.out.println("s1==s5 "+(s1==s5));//false  why  it is false
        System.out.println("s1==s7 "+(s1==s7));//true   why  it is true
        System.out.println("s4==s6 "+(s4==s6));//true 
      //  System.out.println("s5 "+s5);
       // System.out.println("s7 "+s7);
        System.out.println("s5==s7 "+(s5==s7));//false  why                     
    }
}

in case of s5 am doing concatenation but it will give ouput false in case of s7 also am doing concatenation it will give true. am declaring s6 am declaring string as final string am getting true my question is why it is giving like that or what is the difference between them

  • i want to know difference between string and final string in case of why s1==s5 false and why s1==s7 true – Indra Nandu Dec 24 '17 at 10:18
  • 1
    @Anon this question is about comparing two reference of String object. How does it relevant to look into equals method? – Vimal Bera Dec 24 '17 at 10:22
  • 1
    [This question](https://stackoverflow.com/questions/19418427/comparing-strings-with-which-are-declared-final-in-java) explains the difference `final` makes. – raina77ow Dec 24 '17 at 10:26
  • @IndraNandu Do you want to test if the String contents is the same OR if the String object/reference itself is the same? – pirho Dec 24 '17 at 10:27
  • in case of .equals(); it will check content comparison .but hear content is same in all cases . so it will give true .but i want to know about reference comparison(==) how it will stored like – Indra Nandu Dec 24 '17 at 10:30
  • in case of s1,s5,s7 content is same but in case of s1,s7 referring same object but in case of s5 it's is referring different object – Indra Nandu Dec 24 '17 at 10:38
  • For (s4==s6) check [this answer](https://stackoverflow.com/a/3801355/6413377) – pirho Dec 24 '17 at 10:39
  • s4==s6 that's ok one is string and another one is final string but both are refering same object – Indra Nandu Dec 24 '17 at 10:42
  • @IndraNandu Yes and the linked answer tells you why they are the same object. – pirho Dec 24 '17 at 10:44

0 Answers0