4

Here is the snippet of the code

public class Test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        char[] a={'a','b','c',97,'a'};
        System.out.println(a);
        int[] a1={8,6,7};
        System.out.println(a1);
        Integer[] b={10,20,30};
        System.out.println(b);
        }
}

Here is the output

abcaa
[I@239d5fe6
[Ljava.lang.Integer;@5527f4f9

I know it has to deal with toString() method. It has been Overridden in char to return the value. hence we are getting the first output as expected here is the overridden toString() method of java.lang.Character ..

public String toString() {
      char buf[] = {value};//The value of the Character.
      return String.valueOf(buf);
   }

But looking at Integer there is also the overridden toString() method

public String toString() {
        return String.valueOf(value); //The value of the Integer.
     }

Then why printing a1 and b code calls the default toString() implementation of the Object class, that is:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Also since valueOf makes another Object but then it's common in both the overridden methods.

0

6 Answers 6

7

Because there is a dedicated method for printing char arrays:

https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println(char[])

public void println(char[] x)

Prints an array of characters and then terminate the line. This method behaves as though it invokes print(char[]) and then println().

Parameters:
x - an array of chars to print.

Implementation:

public void println(char x[]) {
    synchronized (this) {
      print(x);
      newLine();
   }
}

It has nothing to do with the toString implementation of the char[] class.

Sign up to request clarification or add additional context in comments.

2 Comments

Try to actually add the text section you're talking about, instead of just letting the link.
So for int[] a={10}; while printing a it get passed into Object parameter of println(Object o) method and hence default Object toString() method is called hence giving me hashCode as output . While if i write Integer a=new Integer(10); and print a , it get passed into Object parameter of println(Object o) but since Integer has toString() method overridden it gives me 10 as output instead of hash code. Right ? Point me if i've misunderstood this and where
1

It's beacause in java.io.PrintSream class you've an implemtation for char[]

/**
 * Prints an array of characters and then terminate the line.  This method
 * behaves as though it invokes <code>{@link #print(char[])}</code> and
 * then <code>{@link #println()}</code>.
 *
 * @param x  an array of chars to print.
 */
public void println(char x[]) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

Which at the end call an inner method

private void write(char buf[]) {
        try {
            synchronized (this) {
                ensureOpen();
                textOut.write(buf);
                textOut.flushBuffer();
                charOut.flushBuffer();
                if (autoFlush) {
                    for (int i = 0; i < buf.length; i++)
                        if (buf[i] == '\n')
                            out.flush();
                }
            }
        }
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
            trouble = true;
        }
    }

Which loop trough all elements for char[]

When you call println whith int[] or Integer[], as there is no method having those array in signature, it tooks the one having Object

 public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

2 Comments

Why do you add two answers. You already answered and you're able to edit this answer.
@Loki To keep trace of my wrong answer
0

This is because when you call :

 int[] a1={8,6,7};
 System.out.println(a1);

You're calling Integer[].toSTring() and not Integer.toSTring()

You need to either loop on each on your element, or override Integer[].toSTring() to call toString() on each of its element.

See for yourself if you write :

 System.out.println(a1[0]);
 System.out.println(a1[1]);
 System.out.println(a1[2]);

It'll print you the expected output.

4 Comments

Is there anything called Integer[].toSTring() ? I haven't seen that anywhere ~
It's not defined, that's why you're getting the default behaviour @AnkurAnand
i understood that . Have pointed that out in my comment on accepted answer too . point me if i'm wrong at any place there !
@AnkurAnand No i think you got it. Congratz !
0

printStream has a specific method for printing char[] but does not have method for printing int[] or some other arrays, so when dealing with arrays that are not fo type char[] you are calling the method with Object as parameter whic delegates to toString() method which does not iterate on the single elements.

If you want always print the content of the array there is a standard api

System.out.println(Arrays.toString(array));

3 Comments

This answer misses an explanation why the char[] got printed correctly.
@Tom you are right I edited my response
Maybe the downvoters will revert their vote now.
0

Because you are converting those object to string. You should use toString() method of java.util.Arrays like: "Arrays.toString(a1); Arrays.toString(b)".

Comments

-2

Because you're not calling int's toString, or Integer's toString, you're calling Integer[] toString. This creates a textual representation of the objects stored in the Array, not a textual representation of the value of the individual objects that are stored.

3 Comments

This answer misses an explanation why the char[] got printed correctly.
Because that answer was already given above. Adding another would be redundant.
Well, the downvoters thought differently. Maybe they will revert their vote after your comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.