Overwrite String variable contents if variable is blank [duplicate] - java

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

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];
}

Java String == operator with String Literal [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Why does this return true?
This seems a little odd since I have two Strings which are separate objects but are said to be aliases of each other.
public boolean stringEquals() {
String tmp1 = "hello";
String tmp2 = "hello";
return tmp1==tmp2;
}
String literals are interned by the JVM, so their reference will be the same.
In other words, each String literal used will be stored exactly once, hence their object will be similar. See
Taken from here: https://www.geeksforgeeks.org/interning-of-string/
The == operator compares the reference of the 2 objects and not their values. So unless we use .equals() we must expect to see false as these are 2 separate objects.
But this special case happens with strings. In Java Strings are immutable. Meaning their value cannot change. JVM uses this property to optimize memory. The strings in Java are stored in a separate space in memory called String Pool. Since these 2 strings are the same and that they are immutable, JVM stores "hello" in the pool and reuses the same reference for both objects. This is safe as strings are immutable. ( If you assign it something else later in code, it would create a new value elsewhere in pool and reference to it).
At the same time it is interesting to note that this isn't the case when using constructor. If we use the constructor to construct a new string, it always creates a separate object with unique reference regardless of whether the value is same or not.
String a = new String("Hello");
String b = new String("Hello");
return a==b;
Would return false.
The string pool concept applies only when using string literals without the constructor.

BigInteger Constant behaviour [duplicate]

This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 4 years ago.
Why below statement return false?
BigInteger bigInteger = new BigInteger("0");
System.out.println((BigInteger.ZERO == bigInteger));
What should i pass in new BigInteger(?) so condition will be true.
By specification, new always creates a new instance (or it fails).
Whatever instance is assigned to BigInteger.ZERO, it's not the one you create in your code with new BigInteger("0").
Since it's not the same instance, and == only returns true if the operands refer to the same instance (provided they are both reference types, which they are in this case), the result is false.
You almost never want to compare objects using a == b or a != B. You should use a.equals(b) or !a.equals(b) instead. (Or Objects.equals, if a might be null).

Why does `==` sometimes work for Strings? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
String Constant Pool
(5 answers)
Closed 8 years ago.
Consider this piece of code:
String baz = "Hello";
String foo = "Hello";
return foo.equals(baz); // Returns true as expected
return(baz == foo); // Also returns true!
Why does the == operator also return true in this case? It should be comparing the locations of the objects themselves, not their values.
I'm assuming that Java does some sort of internal work and determines these two are of type String (or Integer, etc.) so it implicitly calls the .equals() method.
I'm curious to know exactly how this is done (ie. what goes on in the background), and why this is done, what if I actually wanted to test their location in memory?
return(baz == foo) is also returning true because all literal strings are interned in Java. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
So in short due to use of String intern pool for your case return(baz == foo) is behaving same as return(baz.equals(foo))
Read more about String literals in Java Specs

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

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.

Categories

Resources