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];
}
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 9 months ago.
First of all, yes, I know I have to iterate through an array and print its elements one by one in order to actually "print" an array. I was just wondering what the output of explicitly printing an array such as in the code below actually means. My guess is that it's the memory location of the array?
I know it's a fairly newbie question but I'm new to java (and coding in general) so please enlighten me.
public class Tests {
public static void main(String[] args) {
String[] strArray = {"1", "2", "3"};
System.out.println(strArray);
}
}
The println(Object) method invokes Object::toString on its parameter, so you are really asking about the meaning of the toString method on arrays. And arrays do not override toString, so the result comes from the implementation of toString in Object.
The default implementation of toString includes the name of the object's class and a numeric representation derived from its object identity. In the absence of a better toString, this allows you to see the object's type, as well as be able to differentiate different instances (since they'll have different identities). This is a "least common denominator" approach; it is a reasonable minimum the system can provide.
It's the default toString method of Object class.
It's the name of the class plus # plus the return value of hashCode method, which may be implemented differently in every class.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
Integer ki=new Integer("50");
System.out.println(ki);//Here I would expect to print the objects name something like package_name.Class#15db9742 but this didn't happen.
ki=3;//Here I would expect an error but this actually works.
When System.out.println(ki); executed then 50 appeared in the console but when I print other objects some thing like package_name.Class#15db9742 appears why 50 appeared instead of something like package_name.Class#15db9742?
I though ki is type Integer so when I assign the primitive value of 3 I should get an error but I didn't why?
You have two separate questions there:
System.out.println(ki);//Here I would expect to print the objects name something like package_name.Class#15db9742 but this didn't happen.
Because Integer overrides toString. Its implementation:
public String toString() {
return String.valueOf(value);
}
Hmm...or because println(int) exists on PrintStream.
Nope, it's calling System.out.println(Object), which then uses toString on the object. This is because (as the specification tells us) the rule is to first try to find a matching signature without auto-(un)boxing and without varargs; then just with auto-(un)boxing, then at last with both.
ki=3;//Here I would expect an error but this actually works.
That's because of autoboxing: The Java compiler inserts the necessary code to take that primitive 3 and create an Integer instance for it. The bytecode it actually emits does this:
ki = Integer.valueOf(3);
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
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Which constructor is chosen when passing null?
I recently came across this curiosity while coding a few days back and can't seem to figure out why the following happens:
Given the class below
public class RandomObject{
public RandomObject(Object o){
System.out.println(1);
}
public RandomObject(String[] s){
System.out.println(2);
}
}
When the call new RandomObject(null); is made the output is always 2 regardless of the order in which the constructors were created. Why does null refer to the string array rather than the object?
The key here is that Object is the super type of String[]
Java uses the most specific available method to resolve such cases. Null can be passed to both methods without compilation errors so Java has to find the most specific method here. The version with String[] is more specific - therefore it will be chosen for execution.
Someone else has had this question earlier, check this post
If there are two cases to choose from, the compiler will first try to pick the more specific case. In this case, String will be picked over Object.
In the other question it was String str instead of String[] s
Thus, since String[] is a more specific datatype than its super type Object, it is picked.