jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes What is Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What is "empty String"?" Watch "What is "empty String"?" New topic
Author

What is "empty String"?

Roger Zhao
Ranch Hand

Joined: Aug 05, 2003
Posts: 73
Hi, all:
Puzzles come again.
Which correctly create an array of five empty Strings?
A. String a [] = new String [5];
for (int i = 0; i < 5; a[i++] = "");
B. String a [] = {"", "", "", "", ""};
C. String a [5];
D. String [5] a;
E. String [] a = new String [5];
for (int i = 0; i < 5; a[i++] = null);
Answer: a,b
Adding the following codes to output the String array:
for(i=0;i<5;i++)
{
println(a[i])
}
For option A: null
null
null
null
null
For option B: nothing happened but five empty lines.
A & B are both right answers via the same means(put "" to each item in the array). But why output about the array is different at all !?
What is "empty String" in the question on earth?
Thanks.


"There is a will,there is a way!"<br />SCJP1.4
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
It's a string with no characters. Consider the string "a", now remove the character 'a' from the string. It's now empty: "". An empty string can be created in Java by a literal: String s = ""; or less efficiently by using the no-argument constructor: String s = new String();
Note that String s; does not create an empty string, but a reference to no string, a null reference.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1871
hi roger
it seems it might be depending upon jdk. because i ran the option A on my machine with j2sdk1.4.1_02 and i get empty strings in output as option B.
regards
maulin
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1871
hi Barry
i c ur point but it seems roger is having question as he expected same output as option B in option A which is logically correct and i'm able to produce that output but he seems doesn't get that output.
regards
maulin
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
I confirm that both a and b print correctly. I can only guess that the for-loop was omitted in the case of option a.
Roger Zhao
Ranch Hand

Joined: Aug 05, 2003
Posts: 73
Hi,Maulin,Barry:
I try this puzzle codes on J2K1.4 environment. It runs well.
Same results come out both A & B.

Thank you both!
 
GeeCON Prague 2014
 
subject: What is "empty String"?