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.
Related
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.
I was experimenting with toCharArray() and found some strange behavior.
Suppose private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
System.out.println(HEX_CHARS);
/* prints 0123456789abcdef */
System.out.println("this is HEX_CHARS "+HEX_CHARS);
/* prints [C#19821f */
Any theoretical reason behind this?
It is because the parameter to println is different in the two calls.
The first parameter is called with char[] and the second is called with a string, where HEX_CHARS is converted with a call to .toString().
The println() have an overriden method that accepts a charArray.
The first line calls the method
print(char[] s)
on the PrintStream which prints what you expect. The second one calls the method
print(String s)
Where is concatenating the string with the toString implementation of the array which is that ugly thing you get ([C#19821f).
Arrays are objects, and its toString methods returns
getClass().getName() + "#" + Integer.toHexString(hashCode())
In your case [C#19821f means char[] and #19821f is its hashcode in hex notation.
If you want to print values from that array use iteration or Arrays.toString method.
`System.out.println(Arrays.toString(HEX_CHARS));`
The strange output is the toString() of the char[] type. for some odd reason, java decided to have a useless default implementation of toString() on array types. try Arrays.toString(HEX_STRING) instead.
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!
{
List list= new ArrayList();
list.add("one");
list.add("second");
System.out.println(list);
}
How can the object "list" be used like it has been in the print statement? Don't we need to use the object to access a method to print the list?
prinln(someObject) will print out whatever is implemented in someObject's toString() method.
You can use toString() which is (supposed) to be implemented for all objects:
System.out.println(list.toString())
Note that you ought not to use the returned string as anything you can actually parse; it's really for a visual representation. It also doesn't need to uniquely represent the object.
When you write
System.out.println(list)
you are, in fact, using the toString() method implicitly.
Docs Says about toString() in Collections:
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
When we pass any object to println() method, it will implicitly call that object's toString() method. So, what is actually executed is
System.out.println( list.toString() );
ArrayList is inherited from the class java.util.AbstractCollection and that class has toString() method. So, in your case, that toString() should be executed.
That toString() method returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
Looking at your question and comments, I think your confusion ultimately stems from you being unsure how printing works. In general in such cases, I recommend to get the JDK sources and simply take look inside.
In this case, we would first go to the System class and check out the out member (because println is called on System.out):
public final class System {
...
public final static PrintStream out = null;
Since we know now that out is a PrintStream, let's check out that class:
public class PrintStream extends FilterOutputStream
implements Appendable, Closeable
{
...
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
(we know it's calling this method, since the other println signatures don't match the type List)
OK, so we see that println converts the given Object (your List in this case) to a String using String.valueOf(Object). Let's check out that method:
public final class String {
...
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
So now we know that your List's toString() method is used to generate the output. As others have pointed out, it is overriden in ArrayList to provide the output you see.
It can be used like this because class List inherits the Object class, and the Object class has the toString() method, which means every object can be turned into a String.
printing a list directly will give the the string representation of the list.
If you want to access the objects in the list you need to use iterator or loops or advanced for loops for collections.
e.g.
for(String s : list){
System.out.println(s);
}
Well you can study and try out all the list methods to modify it. e.g. add, remove.
Also if you are printing an object, then toString() method is implicitly called.
You can loop through all the items in the list in order to print them out. you can do this using a while loop of a for loop.
while (list.hasNext) {
System.out.println((String) list.next());
}
for(String i in list){
System.out.println(i) ;
}
Not sure if this is what your looking for but its an option.
Yo need toString() method. when you print object Reference , by default toString() method is called. If you look at toString() method by default it prints
getClass().getName() + '#' + Integer.toHexString(hashCode())
Now as per your requirements you can override this to print the values in list(String Class overrides it too)
Here you are creating List interface.So it will allow to add duplicate values in list also.Also we can directly print object like System.out.println(obj);
And inside the List class the, toString method is being overridden so that it will print all its contents rather than the address of the object.
System.out.println(Arrays.toString(myList.toArray()));
I was experimenting with toCharArray() and found some strange behavior.
Suppose private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
System.out.println(HEX_CHARS);
/* prints 0123456789abcdef */
System.out.println("this is HEX_CHARS "+HEX_CHARS);
/* prints [C#19821f */
Any theoretical reason behind this?
It is because the parameter to println is different in the two calls.
The first parameter is called with char[] and the second is called with a string, where HEX_CHARS is converted with a call to .toString().
The println() have an overriden method that accepts a charArray.
The first line calls the method
print(char[] s)
on the PrintStream which prints what you expect. The second one calls the method
print(String s)
Where is concatenating the string with the toString implementation of the array which is that ugly thing you get ([C#19821f).
Arrays are objects, and its toString methods returns
getClass().getName() + "#" + Integer.toHexString(hashCode())
In your case [C#19821f means char[] and #19821f is its hashcode in hex notation.
If you want to print values from that array use iteration or Arrays.toString method.
`System.out.println(Arrays.toString(HEX_CHARS));`
The strange output is the toString() of the char[] type. for some odd reason, java decided to have a useless default implementation of toString() on array types. try Arrays.toString(HEX_STRING) instead.