Jaikant Bhagwan Das
Jaikant Bhagwan Das

Reputation: 227

output is null when passing String str=null

public class StringTest
{
    public static void main(String... args)
    {
        String str=null;
        System.out.println(str);
    }
}

why this code display null? when we pass reference variable into println() method it will call toString() method. For String class, toString() method will be call that returns current object. String str=null means no object is existing.

Upvotes: 2

Views: 3223

Answers (3)

Maroun
Maroun

Reputation: 95948

Your answer is here:

Print a string. If the argument is null then the string "null" is printed.

Note that "This method behaves as though it invokes print(String) and then println()"

Upvotes: 1

Lucas Bertollo
Lucas Bertollo

Reputation: 383

Try String str="";

null means theres nothing in that memory space... if you use "" that blank space inside will count, will make a space memory for that variable at same time will show nothing ( i think thats it)

Upvotes: 0

jason
jason

Reputation: 241601

The documentation reports System.out.println(String):

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().

and the documentation for print(String) reports:

Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

Upvotes: 5

Related Questions