+ 1
Can we use .equals() method for integer.... I was using it to match String a= "15" with int b=15
2 odpowiedzi
+ 8
It's possible but you'll have to perform type casting before that. Attached two methods for comparing String and integer:
https://code.sololearn.com/cNktWAdfLgL2/?ref=app
+ 2
Just to add on, it's important to keep in mind that String is a class (hence why it starts with a capital letter while other types, like double, start with lowercase letters). & in this case equals is a method belonging to the String class so any call to equals should be through a String object (all Strings are objects). int on the other hand is a primitive type, hence a type conversion is required here. The String class makes it really easy to convert any primitive type to String. In fact just simply adding an empty String with any primitive type value will convert the whole thing to a String. So to easily convert an int to a String, just use something like:
String s = ""+intVariable;
Edit:
I forgot to mention that there are wrapper classes for primitive types, Integer for int, Double for double, etc. These can be used if you want to treat a value as an object & opens up new ways to manipulate values that would not be possible on primitive data types. For instance if you wanted to do your comparison the other way around, you'd use
int i = Integer.parseInt(stringVariable)
to convert your String to an int & compare the two as integers.