This question already has answers here:
The connection between 'System.out.println()' and 'toString()' in Java
(3 answers)
Closed 4 years ago.
it may seem as a very basic question, but I do not understand why the method toString is printed on the screen when I didn't even called it, I just instantiated a Car object. Thanks
public class Car {
public void m1() {
System.out.println("car 1");
}
public void m2() {
System.out.println("car 2");
}
public String toString() {
return "vroom";
}
}
public static void main(String[] args) {
Car myCar = new Car();
System.out.println(myCar);
}
The String.valueOf(Object) method is called implicitly, see the doc of println(Object x):
Prints an Object and then terminate the line. This method calls at
first String.valueOf(x) to get the printed object's string value, then
behaves as though it invokes print(String) and then println().
and the doc of String.valueOf(Object obj):
if the argument is null, then a string equal to "null"; otherwise, the
value of obj.toString() is returned.
Because there's no System.out.println(Car) method, the Java compiler picks the closest match it can, which is System.out.println(Object). That calls String.valueOf on what you pass in to get the string version of it to print. String.valueOf uses the toString method of your object to get the string. From its documentation:
Returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
In this line System.out.println(myCar) the toSring method is internally called because println calls at first String.valueOf(myCar) to get the printed object's string value. valueOf uses myCar.toString() if myCar is not null.
So the full flow would be like this:
System.out.println(myCar) > String.valueOf(myCar) > myCar.toString()
Related
This question already has answers here:
How is an overloaded method chosen when a parameter is the literal null value?
(8 answers)
Closed 5 years ago.
class Jaguar
{
void method(Object o)
{
System.out.println("Object Called");
}
void method(String s)
{
System.out.println("String Called");
}
public static void main(String[] args)
{
Jaguar j=new Jaguar();
j.method(null);
}
}
Question:The o/p of the code is String Called and not ObjectCalled..Why?? null value is applicable to objects also..
Java will always try to use the most specific applicable version of a method that's available see: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5
Object and String can all take null as a valid value. Therefore all 3 version is applicable, so Java will have to find the most specific one.
Since Object is the supertype of String, the String version is more specific than the Object-version. So if only those two methods exist, the String version will be chosen.
Each pair of these three methods is ambiguous by itself when called with a null argument. Because each parameter type is a reference type.
The following are the three ways to call one specific method of yours with null.
doSomething( (Object) null);
doSomething( (String) null);
If you add one more method with object subclass example Integer then the compiler will throw ambiguous method error as in that case compiler cannot decide if which method can be called string one or integer one.
I hope this helps.
This question already has answers here:
when to use toString() method
(9 answers)
Closed 6 years ago.
I've been learning Java currently and am confused about a certain piece of code. I come from a C, Python background, so I'm more learning the syntax and small niches of Java.
Below I have 2 classes. My Main class and a class that contains a method to return the decorated input string of the class.
I'm confused as to why calling myObject automatically calls the "toString()" method which returns the message? Shouldn't I need to define the method I want to call on the object? Why can you do this in Java?
I thought it was because the class is called "OtherClass" and the method inside OtherClass is called "OtherClass" but when I test this hypothesis out with another class, calling the object returns the object and it's address location.
Any help would be great. Thanks!
public class HelloWorld
{
public static void main(String[] args)
{
int i = 0;
OtherClass myObject = new OtherClass("Hello World!");
// This calls method toString()
System.out.print(myObject);
// This calls method toString()
System.out.print(myObject.toString());
}
}
public class OtherClass
{
private String message;
private boolean answer = false;
public OtherClass(String input)
{
message = "Why, " + input + " Isn't this something?\n";
}
public String toString()
{
return message;
}
}
public void print(Object obj)
Prints an object. The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
public static String valueOf(Object obj)
Returns the string representation of the Object argument.
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
And as #Andreas said in the comments, toString() prints the hashcode if this method isn't overridden by the subclass:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
"I thought it was because the class is called "OtherClass" and the method inside OtherClass is called "OtherClass" but when I test this hypothesis out with another class, calling the object returns the object and it's address location."
In fact, the method which holds the same name as the class(OtherClass for example) is the constructor method, which will be called automatically when you initialize the class.
In this case, when you run OtherClass myObject = new OtherClass("Hello World!");, the constructor method
public OtherClass(String input)
{
message = "Why, " + input + " Isn't this something?\n";
}
is called and set message value.
And when it comes to System.out.print(myObject);, myObject.toString()will be called and return String message.
So the key point here is to override toString() method in your class, you may print whatever message you want by modifying toString()method, if this method is not override, it will return something associate with hashcode. (Just try and enjoy~)
in Java there is a class that called Object, any other classes that you define
inherit from that , it has a method named 'toString'
/**
* Returns a string representation of the object. In general, the
* {#code toString} method returns a string that
* "textually represents" this object. The result should
* be a concise but informative representation that is easy for a
* person to read.
* It is recommended that all subclasses override this method.
*
* The {#code toString} method for class {#code Object}
* returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character `{#code #}', and
* the unsigned hexadecimal representation of the hash code of the
* object. In other words, this method returns a string equal to the
* value of:
*
*
* getClass().getName() + '#' + Integer.toHexString(hashCode())
*
*
* #return a string representation of the object.
*/
So you can simply run your main method in debug mode and set a break point
in toString of Object
System.out.println(new Object());
If you want to represent any object as a string, toString() method comes into existence.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
Java was designed to easily print objects as strings.
System.out is a PrintStream (see https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#print-java.lang.Object-)
When you pass an object to the method print (or println), you're actually calling
String.valueOf(Object) (see https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#valueOf-java.lang.Object-)
Which in turn will do the following
"if the argument is null, then a string equal to "null"; otherwise,
the value of obj.toString() is returned."
If your object has an explicit toString() implementation, this method will be called, otherwise the interpreter will try to find an object in the hierarchy that implements it.
This is a build in feature in java. You dont need to write .toString() to print information about the Object.
You can use this feature everywhere, even with java operators:
System.out.print(myObject1 + myObject2);
is the same like:
System.out.print(myObject1.toString() + myObject2.toString());
toString() is a method in java.lang.Object, so every object contains this method. The default implementation displays the hashcode. You can override it with your own implementation.
I've got some classes which include toString functions which work very well as:
snipped of declaration:
public String toString() {
return "Port info: "+myPort.variable;
}
snipped of main():
Port myPort;
myPort.fillInfo();
system.out.println(myPort);
output:
"Port info: 123"
I'm trying to replace all my system.out.println(myPort) calls with myWindow.println(myPort) calls where myWindow contains:
public void println(String toPrint)
{
textArea.append(toPrint+"\n"); //or insert
}
However, I'm getting:
The method println(String) in the type window is not applicable for the arguments (Port)
In other words, my declaration is expecting the String type, and I'm trying to pass it the Port type.
Somehow, system.out.println() will take any class that's got a toString() declared.
How does system.out.println take any class and print it out, and run its toString() method if it exists? And, more to the point, how can I replicate this functionality for my own println() function?
Change your Window to
public void println(Object obj)
{
textArea.append(obj +"\n");
}
PrintStream.println has an overload that takes an Object argument. You can make your println do the same.
First, please don't use \n as a line separator (it isn't portable). In addition to overloading println(Object), you could make your method generic. Something like
public <T> void println(T obj)
{
textArea.append(String.format("%s%n", obj));
}
or
public void println(Object obj)
{
textArea.append(String.format("%s%n", obj));
}
or
public void println(Object obj)
{
textArea.append((obj == null ? "null" : obj.toString())
+ System.lineSeparator());
}
The problem is that System.out has a method to print to console an object as it contains for all primitive data types. The thing about this is that as all methods have the same name and just change the data type of the parameter you want to print, you think you can pass an object by a string and is not. The method .println() automatically takes which passes an object. Within this method .println() he takes the object that you indicated by parameters and calls his method .toString() to obtain the string representation of the object and printed on the console.
If you want to print any type of object you must declare your parameter as object type and invoke the method .toString() from the object and print that information.
If I am printing an object of the class then it is printing the toString() method implementation even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?
You're not explicitly calling toString(), but implicitly you are:
See:
System.out.println(foo); // foo is a non primitive variable
System is a class, with a static field out, of type PrintStream. So you're calling the println(Object) method of a PrintStream.
It is implemented like this:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
As we see, it's calling the String.valueOf(Object) method.
This is implemented as follows:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
And here you see, that toString() is called.
Every object in Java IS-A(n) Object as well. Hence, if a toString() implementation has not been provided by a class the default Object.toString() gets invoked automatically.
Object.toString()'s default implementation simply prints the object's class name followed by the object's hash code which isn't very helpful. So, one should usually override toString() to provide a more meaningful String representation of an object's runtime state.
even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?
toString() is one of the few methods (like equals(), hashCode() etc.) that gets called implicitly under certain programmatic situations like (just naming a few)
printing an object using println()
printing a Collection of objects (toString() is invoked on all the elements)
concatenation with a String (like strObj = "My obj as string is " + myObj;)
Everything inherits from Object, so the toString on Object will be called if you have not defined one.
toString() method is present in Object class, so when u put obj in System.out.println(obj);, impliciyly it will call toString() present in Object class since every user created class will implicitly inherits Object class so as ur newly created class, that means that toString() is available in ur class so it will print something like for example: "PkgNamePackage.Classname#12cf4"
However if u explicitely override toString method and give ur own implementation then it will written the string what ever u give in Overriden tostring method();
ex:
public class DogArray {
#Override
public String toString() {
return "Im the newly created Object";
}
public static void main(String args[]) {
DogArray d1 = new DogArray();
System.out.println(d1);
}
}
output: Im the newly created Object
In java object class is super class to the each and every class.whenever your passing parameter to the system.out.println internally object class to string method will be excuted.it returns class name#reference value given but as per our application requirement object class to string method will override in collection and string class.it returns their content.
This question already has answers here:
Strange Java null behavior in Method Overloading [duplicate]
(4 answers)
Closed 8 years ago.
When I run this program why it is calling method overloaded with string parameter.
public class StaticBindTest {
public static void main(String args[]) {
StaticBindTest et = new StaticBindTest();
et.sort(null);
}
//overloaded method
public void sort(Object c){
System.out.println("Inside Collection sort method");
}
//another overloaded method
public void sort(String hs){
System.out.println("Inside HashSet sort method");
}
}
In case if I re-write my method as
public void sort(String hs){
if(hs instanceof String)
System.out.println("Inside HashSet sort method");
}
It will display blank console, which means it is not a instance of String then why it call in this manner?
t's because In case of method Overloading
The most specific method is choosen at compile time.
As 'java.lang.String' is a more specific type than 'java.lang.Object'. In your case the method which takes 'String' as a parameter is choosen.
Clearly mentioned in DOCS
When I execute your code, I found Inside HashSet sort method is in output. null is empty reference to object. Both methods have Object as input that is why the method with more narrow hierarchy String is called.
Do not write StaticBindTest et = new StaticBindTest(); Just call sort(null) without object et.
The full methodology is explained in section 15.12.2 of the JLS, and in particular 15.12.2.5 (choosing the most specific).
The summary is that Java always chooses the most specific overload that is applicable. Since null can be an instance of any class, both methods are candidates. And since String is a subclass of Object, it is definitely more specific. Hence the String overload is called.
As for your closing paragraph, null is not an instanceof anything. If you had written your Object-overload method in a similar way, it also would not have printed anything - so this is not strong evidence as to whether Java should have chosen one overload or another.