class Data {
int a = 5;
}
class Main {
public static void main(String[] args) {
int b=5;
Data dObj = new Data();
System.out.println(dObj);
System.out.println(b);
}
}
I want to know what's happening when printing a object or number or string.
I ran the above code, I'm getting the result as "data#1ae73783" for System.out.println(dObj); and "5" for System.out.println(b);
Then I did debug to check whats really happening when printing a object, there was lot of parameter called in a debug mode(like classloader,theards)
I know for the first print the value represent class name followed by address. But don't know what's really happening in debug mode, for the 2nd print only variable assignment happened in the debug mode i.e b=5.
Please explain whats really happening?
You don't need a debugger to know what's happening. System.out is of type PrintStream. The javadoc of PrintStream.println(Object) says:
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().
The javadoc of String.valueOf(Object) says:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
And the javadoc of Object.toString() says:
Returns a string representation of the object. In general, the 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 toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', 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())
Please explain whats really happening?
As other have told you, using System.out.println with an object will call to toString method on that object. If the class doesn't have it's own toString method, then it's a call to the super class's toString. If the super class call goes all the way back to java.lang.Object, the default toString method prints the name of the object's type (what class it is), followed by an # sign, and the memory location of the object--the hexidecimal address of where that object is stored in memory.
ClassName#MemoryLocation
when we print object of any class System.out.print() gives string of class name along with memory address of object (ClassName#MemoryAdress)
All objects inherit from java.lang.Object which has a default implementation of toString. If an object overrides this method then out.print (obj) will put something useful on the screen.
Primitive data types are handled by a different, much simpler implementation of println. The println method is overridden for every data type in addition to Object.
First, int isn't an Object. It's primitive type.
Second, when Class haven't overrived toString() method, toString() from Object class is invoked.
data dObj = new data() does not exist in the source code;
you want to print the string value of the object (Data), you have to override the toString method;
try this
public class Program {
public static void main(String[] args) {
Data data = new Data();
System.out.println(data);
}
}
class Data {
int a = 5;
#Override
public String toString() {
return String.valueOf(a);
}
}
In Addition to #JB Nizet answer,
To Provide our own string representation, we have to override toString() in our class which is highly recommended because
There are some classes in which toString() is overridden already to get the proper string representation.
Examle: String, StringBuffer, StringBuilder and all wrapper classes
Integer ob1 = new Integer("10");
String ob2 = new String("Doltan Roy");
StringBuffer ob3 = new StringBuffer("The Rock");
StringBuilder ob4 = new StringBuilder("The Joshua");
System.out.println(ob1);
System.out.println(ob2);
System.out.println(ob3);
System.out.println(ob4);
Output:
10
Doltan Roy
The Rock
The Joshua
Hope this would help!
Related
I am a bit confused about the StringBuilder. It seems that when I print a StringBuilder, there it no need to add .toString() because it will automatically give me a string representation. However, when I return a StringBuilder object, I have to add the .toString(). Is that true? and why?
Also, I am bit confused about the following code:
package com.tutorialspoint;
import java.lang.*;
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("India ");
System.out.println("string = " + str);
// append character to the StringBuilder
str.append('!');
// convert to string object and print it
System.out.println("After append = " + str.toString());
str = new StringBuilder("Hi ");
System.out.println("string = " + str);
// append integer to the StringBuilder
str.append(123);
// convert to string object and print it
System.out.println("After append = " + str.toString());
}
}
For the different println, sometimes this code use toString and some other times it didn't. Why? I tried deleting the toString and the results are the same. Is it still necessary to use toString in println?
Thanks so much for helping a newbie out!
When you print an object to a print stream, the String representation of that object will be printed, hence toString is invoked.
Some classes override Object#toString, amongst which StringBuilder does.
Hence explicitly invoking toString for StringBuilder is unnecessary.
On the other hand, other objects don't override toString. For instance, arrays.
When you print an array, unless using a utility such as Arrays.toString, you're getting the array's class type # its hash code, as opposed to a human-readable representation of its contents.
From the documentation:
Note that println() prints a string builder, as in:
System.out.println(sb);
because sb.toString() is called implicitly, as it is with any other object in a println() invocation.
If you try to append an object to a string like this : "string = " + str, the toString() method is implicitly called.
So no, it does not matter, if you specify it.
Also the toString() method itself (even when you are not append it to string) calls the toString() method.
Therefore System.out.println(str) and System.out.println(str.toString()) gives same result.
The first thing you should know about Java is that we work with objects and that all objects inherit methods from the class Object: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html
This class has a toString() method and since every object inherits this method it can always be called on every object. When you do not override it, it usually returns the physical address of the object.
Like stated in other answers, whenever a string is expected in println for instance and you pass an object it automatically calls the method which requires an Object (note the capital, we are talking about the class Object here), it will then use the toString method on the object passed along as parameter. The reason you get the string you want is because StringBuilder overrides the toString() method for you.
When you in your own code want to pass the string in your StringBuilder you have two options. You can either pass StringBuilder.toString() or change the return type to Object or StringBuilder and call toString() when you actually need it.
Hope this clarifies why you can just pass the object instead of the string.
When we do:
String string = new String("Ralph");
//This creates a reference called string that points to a sequence of
//characters in memory
This is the same as:
String string = "Ralph";
When we print both, we get the actual value of the string.
If we print any other object in Java, we get an address for that object.
My question is, is there any dereferencing that is taking place behind the scenes?
When you pass an object reference to the System.out.println() method, for
example, the object's toString() method is called, and the returned value of toString() is shown in the following example:
public class HardToRead {
public static void main (String [] args) {
HardToRead h = new HardToRead();
System.out.println(h);
}
}
Running the HardToRead class gives us the lovely and meaningful,
% java HardToRead
HardToRead#a47e0
Now,
Trying to read this output might motivate you to override the toString()
method in your classes, for example,
public class BobTest {
public static void main (String[] args) {
Bob f = new Bob("GoBobGo", 19);
System.out.println(f);
}
}
class Bob {
int shoeSize;
String nickName;
Bob(String nickName, int shoeSize) {
this.shoeSize = shoeSize;
this.nickName = nickName;
}
public String toString() {
return ("I am a Bob, but you can call me " + nickName +". My shoe size is " + shoeSize);
}
}
This ought to be a bit more readable:
% java BobTest
I am a Bob, but you can call me GoBobGo. My shoe size is 19
The class String is a special class in Java.
But it gets out printed the same way every other class does.
If we call System.out.println("Ralph") the function println takes that String and then displays it.
The class Objects toString() method is implemented, so it displays the hash code of the Object, by calling the hashCode() function. If you overwrite the toString() method, it will display something else.
If you take any object other than a String and give it to a method that takes a String (or in fact cast it to a String) java will call the toString()method of that Object, to convert it to a String.
So 'printing' always does the same thing, it's just implemented in different ways, using the toString() method.
new String("Ralph") copies the character data array of the literal string and stores it in the new String instance.
However, you only get the address of an object when you print it because printing uses the toString() method of that object. If that method is not implemented, the default implementation defined in Object is used, which returns the class name plus the hash code (that seems like an address if hashCode() is not implemented).
I believe the primary types are printed with auto dereferencingString, int, float, etc., while the objects other than primary types, only with de-referencing function object.toString() that are implemented on the object level.
So this first code returns the memory address of the integer array, but I want it to print out the actual array.
import java.util.Arrays;
public class FinalsReview{
int[] list = new int[]{12, 435,546, 7, 24, 4, 6, 45, 21, 1};
public static void main(String[]args){
FinalsReview hello = new FinalsReview();
System.out.print(hello.create());
}
public int[] create(){
Arrays.toString(list);
return list;
}
}
However, the following code prints the actual array.
import java.util.Arrays;
public class FinalsReview{
int[] list = new int[]{12, 435,546, 7, 24, 4, 6, 45, 21, 1};
public static void main(String[]args){
FinalsReview hello = new FinalsReview();
hello.create();
}
public void create(){
System.out.println(Arrays.toString(list));
}
}
Why does the first one return the memory address?
it is not memory address, it is the hashCode() and classname that is how toString() is defined in Object, when you don't specify toString() method for int[] class you inherit it from Object
and that is implemented like
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
while this Arrays.toString(list) is explicitly iterates over the Collection and printing value of each element
and why that from http://bugs.java.com/view_bug.do?bug_id=4168079
One caveat: the toString() method is often used in printing diagnostics.
One would have to be careful if very large arrays were involved. The
Lisp language deals with this using the print-level/print-length mechanism.
Something similar would be needed in Java as well. In practice, the
'toString' method provided in every class should be preferred as the
brief option suitable for use in concise diagnostics, and a more verbose
representation provided by additional application-specific conversion methods
if needed by the application logic.
Regardless of its technical merit, however, it is doubtful that we can make
such a change at this late date due to compatibility/stability concerns.
william.maddox#Eng 1998-08-31
I concur. It would definitely have been the right thing in 1.0, or
maybe even 1.1, but it's almost certainly too late for all of these changes
except perhaps the toString change. One consolation is that it's amazingly easy
It's because you're returning the array from the method create, and when you attempt to print it, the display is what Jigar Joshi described. Simply calling Arrays.toString(list) will not reformat the array so that it will give the output that you expect when you try to print it.
If you want it to print the elements of the array, have your method return String instead, and use return Arrays.toString(list).
Arrays.toString(list) merely returns a String that is being printed at System.out.println(Arrays.toString(list)), however in your first method you are just returning the Array without saving the result of Arrays.toString(list). You're only printing yourList.toString(), so to say:
int[] myList = ... //initialize
String s = Arrays.toString(list); //Save the returned String in a variable
System.out.println(myList); //Prints myList.toString()
System.out.println(s); //Prints out the contents of the array
The line
System.out.print(hello.create());
is evaluated by first invoking the create() method, the passing its return value (a reference to an object of type int[]) to the print() method of System.out. That method's Javadoc reads:
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 Javadoc of String.valueOf() reads:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
Ok, our array reference isn't null, so what does its toString method do? The answer is in section 10.7 of the Java Language Specification, which reads:
The members of an array type are all of the following:
The public final field length, which contains the number of components of the array. length may be positive or zero.
The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
Therefore, the toString method must be inherited from Object. The Javadoc of Object.toString reads:
Returns a string representation of the object. In general, the 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 toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', 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())
... and that's why you see the type and hashCode of the array object when you print your array. (Incidentally, a hash code is not quite the same as a memory address. For one, several objects may have the same hash code; otherwise java would be limited to about 4 billion objects per application).
That's why Arrays.toString is a useful method to have, as it returns a String with the contents of the array. (You do invoke this method in create(), and it builds that String, but then you don't do anything with that String object, which is why it isn't printed).
In your first example, you are running Arrays.toString(list); but youare throwing away the result (a single String), and returning the original value of list. System.out.println is then trying to convert the whole int[] array into a string, which it doesn't know how to do, so it is giving you the unexpected output.
In the second example, you are running the same utility function, but this time passing its output to System.out.println. The input to System.out.println is now the string you wanted.
What you need to do is make the create function return the String given by Arrays.toString(list), rather than the original int[].
When I use System.out.println(obj.getClass()) it doesn't give me any error. From what I understand getClass() returns a Class type.
Since println() will print only strings, how come instead of a class, println is getting a String?
System.out.println(someobj) is always equivalent to:
System.out.println(String.valueOf(someobj));
And, for non-null values of someobj, that prints someobj.toString();
In your case, you are doing println(obj.getClass()) so you are really doing:
System.out.println(String.valueOf(obj.getClass()));
which is calling the toString method on the class.
All objects in Java inherit from the class Object. If you look at that document, you'll see that Object specifies a toString method which converts the object into a String. Since all non-primitive types (including Classes) are Objects, anything can be converted into a string using its toString method.
Classes can override this method to provide their own way of being turned into a string. For example, the String class overrides Object.toString to return itself. Class overrides it to return the name of the class. This lets you specify how you want your object to be output.
See the code:
787 public void println(Object x) {
788 String s = String.valueOf(x);
789 synchronized (this) {
790 print(s);
791 newLine();
792 }
793 }
Note the String.valueOf(x).
Bonus for asking a good question:
632 public void print(String s) {
633 if (s == null) {
634 s = "null";
635 }
636 write(s);
637 }
That's why it prints null when the object is null :)
As you probably know, every class in Java inherits from the Object class. This means that every class automatically has the method toString(), which returns a representation of the object as a String. When you concatenate a string with an object, or if you pass an Object into an argument where there should be a String, Java automatically calls the toString() method to convert it into a String. In your case, the toString() method has been overridden to return the name of the class.
You can see this happen with other objects, too:
Set s = new Set();
s.add(1);
s.add(3);
s.add(5);
System.out.println(s);
will output "[1, 3, 5]".
I want to know what exactly the output is when I do the following.
class Data {
int a = 5;
}
class Main {
public static void main(String[] args) {
data dObj = new data();
System.out.println(dObj);
}
}
I know it gives something related to object as the output in my case is data#1ae73783. I guess the 1ae73783 is a hex number. I also did some work around and printed
System.out.println(dObj.hashCode());
I got the number 415360643. I got an integer value. I don't know what hashCode() returns, still out of curiosity, when I converted 1ae73783 to decimal, I got 415360643!
That's why I am curious about what exactly is this number. Is this some memory location of Java's sandbox or some other thing?
What happens is that the default toString() method of your class is getting used. This method is defined as follows:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', 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())
The value returned by the default hashCode() method is implementation-specific:
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
When you print an instance of your class, that does not override the toString method, then the toString method of Object class is used. Which prints an output in the form: -
data#1ae73783
The first part of that output shows the type of the object.
And the 2nd part is the hexadecimal representation of the hashCode
of your object.
Here's the source code of Object.toString() method, that you can find in the installation directory of your jdk, under src folder: -
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
The Javadoc for hashCode() and toString() in the Object class should be able to clarify this for you.
That code calls the default toString() implementation of the Object class, that is:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}