Output of System.out.println(object) - java

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());
}

Related

why hashCode() gives different output for same object in java?

I have this code
class A
{
public static void main(String reds[])
{
A ob=new A();
System.out.println("Object "+ob);
System.out.println("HashCode "+ob.hashCode());
}
}
Output is:
Output image
The output for above code gives different value most of the time.
Also, the below link mentions that printing a reference variable prints ClassName#hashcode.
printing reference variable is not printing the object's address
However, the output for printing reference varibale differs from hashCode().What is actually happening here?
Just wanted to clear my concepts of hashcode in java.
When you call println() on your object (of type A), it prints getClass().getName() + "#" + Integer.toHexString(hashCode()) (which is the default implementation of toString() in Object class) i.e, it converts hashCode to hexString. If you do the same for your hashCode (when printing), you will get the same value.
If your class overrides toString, then it will be printed.
Object.toString() uses the hashCode in hex. You are printing it yourself in decimal.

String literal with toCharArray() producing garbage in Java

I wanted to create a char array of the alphabet. I looked at this post:
Better way to generate array of all letters in the alphabet
which said this:
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
So in my code I have:
public class Alphabet {
private char[] letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
public String availableLetters(){
return letters.toString();
}
}
When I call the function availableLetters() from main() and printit to the console, it outputs this garbage:
[C#15db9742
What am I doing wrong?
The array is correct, the problem is that you are not printing it correctly.
If you print your array one character at a time, you would get a correct result:
for (char c : letters) {
System.out.print("'" + c + "' ");
}
demo
Unfortunately, Java standard class library does not provide a meaningful override of toString() for arrays, causing a lot of trouble for programmers who are new to the language.
If you want to print it in array form, then use:
System.out.println(Arrays.toString(letters));
BTW: The [C#15db9742 is not really garbage. It's what gets printed out when a class does not override the toString() method.
From Object.toString():
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())
You can pass the char array to the String constructor or the static method String.valueOf() and return that instead.

What happens when printing an object in java

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!

what is the number that it shows when I print out the **this** pointer in java?

This program
public class HelloWorld{
public void testFunc(){
System.out.println("Class = "+this);
}
public static void main(String[] args){
HelloWorld hw = new HelloWorld();
System.out.println("Hello, World");
hw.testFunc();
}
}
gives me this output:
Hello, World
Class = HelloWorld#7c6768
What does #7c6768 after HelloWorld in the second line mean?
Object's toString() is implemented as follows:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
Since your HelloWorld class doesn't override it, this is the method called.
The toString() method 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())
As per Docs of toString() method in Object class
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:
When
getClass().getName() + '#' + Integer.toHexString(hashCode())
When you call toString() on object ,If you ovveride like below ,you get your own implementation
#Override
public String toString() {
//return something
}
Otherwise gives the default implementation,which you are seeing right now
From Object class Source code
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())
Returns:
a string representation of the object.
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
From the API:
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
If you see the toString() method in Object class
/**
* 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.
* <p>
* 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:
* <blockquote>
* <pre>
* getClass().getName() + '#' + Integer.toHexString(hashCode())
* </pre></blockquote>
*
* #return a string representation of the object.
*/
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
It returns Class name followed by its hash code. That is the number you are getting.
HelloWorld#7c6768 is a string representation of the current object, and #7c6768 is a hashcode. In fact you are invoking toString() of current object
Here is java doc for toString() http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#toString()
That is this.hashCode(). Since you do not redefine hashCode(), this number is the memory address in the JVM where the object is stored.
Look inside Objects' toString() method:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
It is a hash value of the object.
The number that identifies the object uniquely. It is Hexadecimal representation of hashcode. In simple terms, the whole String printed is the reference returned after instantiating the class.

How to print the strings in an array?

At the moment I have an array of
public Module[]moduleArray = new Module[4];
and to output it i'm using
public void displayModules()
{
for (int i = 0; i < moduleArray.length; i++)
{
System.out.println(moduleArray[i]);
}
}
However it's outputting
Module#1f5e4ae5
Module#67871079
null
null
Implement / override toString() in the Module class. When you see the Module#xyz String representation it is because the only implementation of toString() for the Module class is the Object class's implementation. Since Object doesn't know anything about Module it just outputs the class name and an instance id.
The class Module needs a meaningful toString() method. What you're seeing is the output of the default Object.toString() method. For example, if Module had String properties name and type you could have a toString method like:
#Override
public String toString()
{
return "Module named: " + name + " of type: " + type;
}
You would then see the String returned above instead of the output of the default toString method.
Overriding toString() method in array's content class, in your example Module class, will help you to print every value from array while iterating array.
There is quick way to print arrays content without iterating over array elements, convert array to list using Arrays.asList() utility method.
System.out.println("Convert Array to List " + Arrays.asList(moduleArray));

Categories

Resources