Java toString method difference [duplicate] - java

This question already has answers here:
Java int to String - Integer.toString(i) vs new Integer(i).toString()
(11 answers)
Closed 6 years ago.
I enjoy CodeFights at the moment and at the end of my last fight i found something interesting. The code in those two cases (mine and the opponent) was said to be correct. Is there a difference between this source code:
return Integer.toString(Character.getNumericValue(ch1) + Character.getNumericValue(ch2));
and this one:
return new Integer(Character.getNumericValue(ch1)+ Character.getNumericValue(ch2)).toString();
What is the key that i am missing?

From javadoc https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
String toString()
Returns a String object representing this Integer's value.
static String toString(int i)
Returns a String object representing the specified integer.

Integer's toString method is implemented as Integer.toString(value), so the second answer merely has a redundant instantiation.
#Override
public String toString() {
return Integer.toString(value);
}

Related

Passing by reference in Java. Help me understand [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Immutability of Strings in Java
(26 answers)
Closed 5 years ago.
I have the following code
public static void main(String[] args) {
String word = "Super";
reverseString(word);
System.out.println(word);
}
public static String reverseString(String word) {
String helper = "";
int i = word.length() - 1;
while (i >= 0) {
helper += word.charAt(i);
i--;
}
return helper;
I do not understand why when I'm printing the "word" variable it still prints "Super" even though I changed it in the reverseString method. I understand that strings are passed by reference and not a copy like primitive values.
If I do word = reverseString(word) it prints the reverse what I expect, "repuS"
Thanks
You're not changing the string in reverseString, you're creating a new one and returning the new one (which you've called helper).
A second thing to note about strings in Java is that they're immutable - all string methods return a new string rather than modifying the one you're calling the method on.

Error for String Comparison in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I have this
public void otis() {
println("What is Otis?");
String otis = readLine(">");
println("You said " + otis);
println(otis);
println(otis);
if (otis == "dog"){
println("you got it right!");
}
else {
println("try it again!");
otis();
}
}
But for some reason even when I respond "dog" it doesn't find a match. I can print the "otis" variable and it says "dog" but apparently that's not equivalent to "dog" somehow?
Can you try the code below? Java doesn't recognize strings as equivalent from two different instantiations even if their values are equivalent. This is because each string is a pointer, and their pointer values aren't equivalent. Try using the String.equal method!
otis.equals( "dog" )
Because == means "is the same exact object in memory", the constant string "dog" and the string it reads from the console are not the same object, even if they have the same contents. When doing comparisons in Java, always use .equals().
As a possible side effect of this, you have to be careful when comparing things that might be null in Java. If you try to do
String dog = null;
if(dog.equals("dog")) { do_something(); }
You'll end up with a NullPointerException. For this reason, many coders prefer to compare strings like this:
if("dog".equals(dog)) { do_something(); }
since you always know the constant string will not be null.

Java: Converting Integer to String. Comparing with == equals operator [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
public static void main(String[] args) {
Integer i = new Integer(4);
System.out.println(i.toString());
if (i.toString() == i.toString()) {
System.out.println("true how");
} else {
System.out.println("false how");
}
}
While executing above code, I am getting output as "false how".
Can you explain how Jvm treats this object?
toString() creates a new string object every time and your code is actually checking if both references are the same, which is never the case so it runs the else case. If you try
i.toString().equals(i.toString())
you'll get the desired output.
You must compare objects with equals() method.
i.toString().equals(i.toString())

Print only certain elements in an Array [duplicate]

This question already has answers here:
How to use the toString method in Java?
(13 answers)
Closed 8 years ago.
I've been given the following array
tests[] b = new tests[50];
So, there are some null elements in this array and I don't want to print those in my array.
for(int i = 0; i < b.length; i++){
if(b[i] != null){
System.out.println(b[i]);
}
}
So, this prints out '#251970e2' but I need to be able to print out each valid elements contents which should be like 'batman', 'joker', 'batgirl'
Sorry if this has been answered previously, I had a look but haven't had much luck :(
You need to override toString method in your class because it is going to give you clear information about the object in readable format that you can understand.
The merit about overriding toString:
Help the programmer for logging and debugging of Java program
Since toString is defined in java.lang.Object and does not give valuable information, so it is
good practice to override it for subclasses.
#override
public String toString(){
// I assume name is the only field in class test
return name ;
}
Override toString method in your Tests class ..
class Tests{
..... your code
#Override
public String toString(){
... return the value
}
}
You need to override the toString() method in your tests class.
For further discussion, see How to use the toString method in Java?

Understanding Java 7 implicit method calls in Enum classes [duplicate]

This question already has answers here:
Implementing toString on Java enums
(4 answers)
Closed 8 years ago.
I'm new to Java and I'm learning the language fundamentals.
Can someone explain to me how the toString method is called when there is no function call to it? I think it has something to do with the actual enumerator words on the second line such as:
KALAMATA("Kalamata"), LIGURIO("Ligurio") ...
The whole purpose for this enum class is so the ENUM values don't print to screen in all upper case characters.
Can someone please explain me how toString method is used in this class? Like when is it called? How is it called?
public enum OliveName {
KALAMATA("Kalamata"),LIGURIO("Ligurio"),PICHOLINE("Picholine"),GOLDEN("Golden");
private String nameAsString;
//for enum classes, the constructor must be private
private OliveName(String nameAsString) {
this.nameAsString = nameAsString;
}
#Override
public String toString() {
return this.nameAsString;
}
}
Pretty much like any object.
OliveName oliveName = OliveName.KALAMATA;
System.out.println(oliveName.toString());
or
System.out.println(oliveName);

Categories