Why is a certain boolean false though it should be true? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I wrote a Java program that should support English and German language. If a parameter is set and if it equals "english" or "English", it shall call a method that does the English version and if there is no parameter or it doesn't equal "English" or "english", it shall call the method for the German version.
However, (args[0]=="english"||args[0]=="English") is false no matter what my parameter is, even if it should be true and I don't get why that's the case.
Here is the main method, the other ones aren't important, so I'll leave them away.
public static void main(String[] args){
boolean input=args.length==1;
System.out.println(input);
boolean mode = false;
if (input) mode=args[0]=="English"||args[0]=="english";
System.out.println(mode);
if(input&&mode) english();
else german();
}
Does anyone have a clue why it won't be true, regardless of my parameter?

Use the equals() method for String value comparison.
args[0].equals("English")||args[0].equals("english")
or even better(in this case)
args[0].equalsIgnoreCase("English")
== is for object reference comparisons. Don't use it for comparing the values.

You can't compare strings in Java in this way because Java Machine compare pointers to the string objects. To make correct compassion use function equals:
if( "english".equalsIgnoreCase( args[0] ) ) {
// English language
}

Strings should not be compared with == but with equals method.
Use
args[0].equalsIgnoreCase("English")
it will compare for both, "english" and "English".
better version is
"English".equalsIgnoreCase(args[0]);
this will make sure, if args[0] is null, i.e no argument in your case, it will not throw NPE.
Explaination : Because in Java, == compares objects not there values, i.e if two references are holding same object or not. Objects content are compared with equals method of Object class, which String class overrides.

Related

Java array in if statement not working as expected [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
So I have been writing a game and was looking to make the code base more useable. I originally wrote the following code once and worked fine. But for reuse and fewer lines, I was adjusting it. Now it's not working
Main java file:
builder.setStats("p, divine,0,1,2,2,1,2,4");
Builder file:
String [] holder = new String[8];
public void setStats(String sentstats){
holder = sentstats.split(",",8)
if(holder[0]== "p"){
charsheet.style = holder[1];
}
}
So the issue is the if never does the proper response. I know I have full access to all associated files as I have tested for that. And I know I could get it to work other ways. But to reduce redundancy. And make parts of the code recursive I have done it like this.
Use equals() instead of == as you are using String not a character
From:
if(holder[0]== "p"){
charsheet.style = holder[1];
}
, To:
if("p".equals(holder[0])){
charsheet.style = holder[1];
}
Stings are not primitive types in Java. They are treated like objects. When you use == for objects, Java checks if both objects have the same reference in memory rather than checking for the values (or similarities in global values) between both objects. This means that Java doesn't care what the values of the strings are; as long as they are not the exact same object referenced in memory, Java will return false. Therefore, you should use equals() or compareTo(), both of these methods actually check the value of the string rather than checking if both objects have the same reference.
METHOD 1
if("p".equals(holder[0])){
charsheet.style = holder[1];
}
METHOD 2
METHOD 1
if("p".compareTo(holder[0]) == 0){ //compareTo returns 0 if both strings equal
charsheet.style = holder[1];
}

Issue with Java program validating Username [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
My Java program isn't working!
Here is my code:
import javax.swing.JOptionPane;
public class practice
{
public static void main(String[] args)
{
String userName = "Eddie"; //username is Eddie
String passWord = "hI"; // passsword is hI
String name;
name = JOptionPane.showInputDialog("Whats your username? ");
if (name == userName)
JOptionPane.showMessageDialog(null, "Exepted!");
System.exit(0);
}
}
Its supposed to ask for my username, and if I type "Eddie" it has to show message dialog "Accepted".But after I type "Eddie" the program closes instead!
Any suggestions?
if (name == userName) should be changed to if (name.equals(userName))
Both equals() and "==" operator in Java is used to compare objects to check equality but main difference between equals method and == operator is that former is method and later is operator.
Read more here to identify the differences: http://javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-equality-operator-java.html#ixzz44dFcXkwr
Needs to be if (name.equals(userName)) also, I believe your word "exepted" needs to be accepted
It should be noted that == compares whether two references point to the same object, while the equals() method (for String) checks whether two objects have the same value. What do I mean by this? What's really the difference?
When you use == to compare Strings, it's checking to see if the two Strings you're comparing point to the exact same location in memory. Note that I could have String a = "abc" and String b = "abc", but a and b don't reference the same memory (they might represent two different memory locations, and those memory locations both happen to hold the same value, "abc"). This is exactly what is happening in your example, except the value of your Strings is "Eddie". equals(), on the other hand, compares any two Strings to see if they have the same characters.
Crummy analogy:
Image the JVM is a waiter. Say you see your friend Bob with a bacon cheeseburger with crispy onions, and it looks appetizing. Further assume you want to ask the JVM if you can have what Bob is having. If you use ==, the JVM will rip the burger Bob is eating right out from under his nose, and hand you that burger. That exact burger. If you use equals(), the JVM will get you another bacon cheeseburger with crispy onions from the kitchen. You almost always want equals() with String comparisons. Don't steal Bob's burger!!!

Overwrite String variable contents if variable is blank [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am having trouble with a piece of my program, shown here:
String degree1 = degree.getText();
if(degree1 == ""){
degree1 = "Undergrad";}
I want the program to get the text in a textField into a variable, and if that field is blank, to change the contents of the variable to 'Undergrad'
Whenever I test my program, it returns a blank instead of 'Undergrad'
It is because you are using == for string comparison. Use if ("".equals(degree1)) instead.
Operator == compares references, i.e. it returns true for the same object only. If 2 objects are equal but not identical == returns false. This is why class Object contains method equals() that can (and typically should) be overridden by subclasses.
In Java strings are compared using equals method of String class not == operator

Difference in string comparison result b/w == and String#replace with == [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String comparison and String interning in Java
I have small doubt regarding String comparisons in Java, consider the following code:
if("String".replace('t','T') == "String".replace('t','T')) {
System.out.println("true");
}
else {
System.out.println("false");
}
The above code always print's false, where as if I try like this:
if("STring" == "STring") {
System.out.println("true");
}
else {
System.out.println("false");
}
It will always print me true. Yes, I know String comparisons should be done with String.equals() or equalsIgnoreCase() method. But this is one of the question was asked in interview and I am confused. Can anyone guide me on this behavior?
As per my knowledge, in code snippet 1, "String.replace('t','T') is returning object, so object comparisons returns in false. Am I right?
"String.replace('t','T') is returning object, so object comparisons
returns in false. Am I right?
Yes, as for this case, you are right. String#replace(or any method of String class for that matter), will return a new String object (You can guess why? Immutability). And thus you would have to do the comparison using equals method, to compare their contents.
Now, in the second case: -
"STring" == "STring"
You are comparing two string literals. Now, since String literals are interned in Java, so both the literals are same (in the sense, they point to the same memory location), and hence == comparison gives you true.
The difference in comparison using == and equals is that, == compares the reference value - i.e value of memory location of objects, which will be different for two different string objects, as you are having in first case. Whereas, equals compares the actual content in those objects.
"String.replace('t','T') is returning object, so object comparisons
returns in false. Am I right?
Yes, == compares object references, and your first code is comparing two different objects.
As far as the second code is concerned its due to string interning.
ok lets do it like this, your both String objects "String" are referering to the same object.
So they are "basicly" equal. That is a thing the compiler does for you
but the method replace, does create and return a new String object, and that is why your second code is not equal.
Java always compares the basic types (int, byte, etc) or references for objects when using ==.
The java compiler optimizes the two string constants you entered to use the same object, thus the same reference, thus the == return true
DO this way
("String".replace('t','T').Tostring() == ("String".replace('t','T')).ToString()
This will solve your problem because the replace statement should be converted to string before eveluation.
You can also user the String.Equals for this or better you use ignore case as you mention in your question.
Try this:
if(string1.equals(string2)){
...
}

Weird Java Behaviour in string comparison [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java string comparison?
I have encounter the following problem, I have an object called "lang", is a result from a method LanguageDetector.detect() which output a string.
lang = LanguageDetector.detect();
So I would want to check whether the language is english, so I am checking,
lang == "en"
The following screen is my debug screen, my lang is showing "en", however my lang == "en" is showing false and lang.toString() == "en" is false, does anyone encounter following problem before and have a possible solution?
Use equals() method of String object instead of direct comparison.
String first = new String("Hello");
String second = new String("Hello");
first == second will return false.
first.equals(second) will return true.
In Java, == always does a reference comparison. You need a value comparison though (with the equals() method for instance).
You're comparing the references to the Strings rather than the contents of the strings themselves. See here for more info.
Note that this issue doesn't apply just to Strings, but to all objects. As such, you may have to define appropriate equals() methods for any objects you create yourself.
Additionally String interning will confuse matters if you're not careful. See here for more details.
Use lang.equals("en") instead of lang == "en". The latter compares the two string references for equality, whereas the former compares the contents of the two strings.
See http://www.devdaily.com/java/edu/qanda/pjqa00001.shtml for an overview of different string comparison methods in Java.
By using == you are checking that both string references point to the same object.
For strings that are created on the fly, and not interned, this will equal false.
To compare the strings for equality, letter by letter, use string1.equals(string2) or even string1.equalsIgnoreCase(string2).
Use "en".equals(lang) instead of lang == "en"
Its better to use the equals as said
but if its necessary for performance reasons you can try
the intern() function.
lang.intern() == "en"

Categories

Resources