0

What is my mistake?

Hi, I made a Java code but something went wrong... import java.util.Scanner ; public class Program { public static void main(String[] args) { Scanner java=new Scanner(System.in); System.out.print("Data of "); String readname=java.nextLine(); System.out.println(readname); System.out .println(); if (readname==null ||readname.length()==0){ System.out.println("plz enter your name.") ; } if (readname=="John"){ System.out.println("hey!"); } else{ } } } I think that the mistake is somewhere here: if (readname=="John"){ System.out.println("hey!"); } But I didn't know what the mistake is. You should write in the input: John and then it should output "hey".

24th Jan 2020, 5:05 PM
Philipp Makarov
Philipp Makarov - avatar
4 Antworten
+ 11
In most cases (except comparing primitive types), == operator performs referential equality: it returns 'true' if both references point to the same object, and 'false' otherwise. Take a look on a simple example which illustrates the differences: final String str = new String("bbb"); System.out.println("Using == operator: "+ (str == "bbb") ); System.out.println("Using equals() method: "+ str.equals("bbb") ); From the human being prospective, there are no differences between str=="bbb" and str.equals("bbb"): in both cases the result should be the same as str is just a reference to "bbb" string. But in Java it is not the case: Using == operator: false Using equals() method: true Even if both strings look exactly the same, in this example they exist as two different string instances. **If you deal with object references, always use the equals() to compare for equality, unless you really have an intention to compare if object references are pointing to the same instance. /*by Andriy Redko, "Advanced Java"*/
24th Jan 2020, 8:17 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 7
To compare two strings you have to use .equals() If readname.equals("John") https://www.sololearn.com/post/171078/?ref=app
24th Jan 2020, 5:12 PM
Denise Roßberg
Denise Roßberg - avatar
+ 5
Philipp Makarov Your welcome :)
24th Jan 2020, 5:17 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
Thank you
24th Jan 2020, 5:15 PM
Philipp Makarov
Philipp Makarov - avatar