How to use plain text and variables in the same Println statement (JAVA) [closed]
How is it possible? I have tried:
System.out.println("Your answer is: " + answer);
and
System.out.println("Your answer is: ", answer);
You would have found that
System.out.println("Your answer is: " + answer);
Works! :)
The first line of code is fine as you are concatenating the string and outputting it.
But the second line will not be valid (If your indented result, is the same as the first one), you are passing the name string object as a parameter to the println method. You could use something like String.format
that will allow you to use printf style string (If I can call it that ... ) .
Example:
String.format("Blah %d Blah", i)
so in your example:
System.out.println(String.format("Your answer is: %s", answer));
Haven't tested this code, wrote it of the top of my head.
System.out.println("Your answer is: " + answer);
if you are asking how is it possible,
its because of answer objects toString()
method. as we know println()
takes String and when its sees a string at first, it calls toString()
method of next variable/Object and make it a String. If that is int
value it does AutoBoxing
and converts it into Integer()
object and calls its toString()
method
System.out.println("Your answer is: " + answer);
should work.
Note that if answer
points to an object (i.e. is not a primitive), the toString()
method is implicitly called. Primitives are just converted to their string representation. Primitives are wrapped by a corresponding wrapper class (see my comment below), on which toString()
is invoked. Still, you don't have to worry about that in the case of primitives, since the wrappers override toString()
in way that one expects (having a primitive int i = 100
would result in 100
being printed).
For String
objects that returns the string itself, but for arbitrary objects that might just be the class name and the memory address.
Example:
mypackage.Answer answer = new mypackage.Answer("yes");
System.out.println("Your answer is: " + answer);
This might just print the following if Answer
doesn't override toString()
:
Your answer is: mypackage.Answer@15ff48b
Overriding toString()
like this:
class Answer {
private String text;
Answer(String t) {
text = t;
}
public String toString() {
return text;
}
}
Would then result in:
Your answer is: yes
精彩评论