What is the difference "" and null for string?

D

Darren

What should I put in the fllowing program?

"" or null

public static void main(String args[]) throws IOException{
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
String line = stdin.readLine();
while(!(line.equals(""))){
System.out.println(line);
line = stdin.readLine();
}
}

Thanks in advance!
 
P

Patricia Shanahan

Darren said:
What should I put in the fllowing program?

"" or null

public static void main(String args[]) throws IOException{
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
String line = stdin.readLine();
while(!(line.equals(""))){
System.out.println(line);
line = stdin.readLine();
}
}

Thanks in advance!

You need to test for null, because BufferedReader's readLine
returns "A String containing the contents of the line, not
including any line-termination characters, or null if the
end of the stream has been reached".

You may also need to make the println conditional on line
not being equal to "", if you don't want to print empty lines.

In general, line==null asks whether there is a line at all.
line.equals("") assumes there is a line, and asks whether it
contains any characters.

Patricia
 
R

R.F. Pels

Darren said:
What should I put in the fllowing program?

"" or null

The first is a string containing zero characters, and the second is a string
(or - more general, an object) that does not exist. The convention here is
that a function that returns a string either returns a string or - if there
is nothing available - null. The latter is equivalent to: sorry, caller,
there is nothing to give you.

So basically, this:

String foo = null;

is equivalent to saying:

foo does not exist.

while:

String bar = "";

means:

bar contains zero characters.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top