0

why different between using nextLine or without nextLine

str==str2 is false but str4==str5 is true

There are some Example code.

Scanner scan = new Scanner(System.in);
System.out.println("Input data1");
String str = scan.nextLine();
System.out.println("Input data2");
String str2 = scan.nextLine();
String str3 = str;
String str4 = "a";
String str5 = "a";

System.out.println("str==str2 : " + (str==str2));
System.out.println("str2==str3 : " + (str2==str3));
System.out.println("str==str3 : " + (str==str3));
System.out.println("str4==str5 : " + (str4==str5));
System.out.println("");
System.out.println("str.equals(str2) : " + (str.equals(str2)));
System.out.println("str2.equals(str3) : " + (str2.equals(str3)));
System.out.println("str.equals(str3) : " + (str.equals(str3)));
System.out.println("str4.equals(str5) : " + (str4.equals(str5)));

input same data,

output

str==str2 : false

str2==str3 : false

str==str3 : true

str4==str5 : true

str.equals(str2) : true

str2.equals(str3) : true

str.equals(str3) : true

str4.equals(str5) : true

Popcorn
  • 81
  • 1
  • 8
  • some different question – Popcorn Aug 08 '16 at 07:20
  • there answers not using Scanner – Popcorn Aug 08 '16 at 07:22
  • `str4==str5 is true` here `str4` and `str5` are compile time constant so created in pool and share common memory so the refrence are equal unlike `str==str2 is false` where `str` and `str2` are runtime variables so created in heap with `new String()` everytime so the both have different reference. – singhakash Aug 08 '16 at 07:30

0 Answers0