Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please Help

 
Vivek Shrivastava
Ranch Hand
Posts: 277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi ,
Can someone please explain what is going on here
Q#1
if( "String".endsWith(""))
Sytem.out.println("True");
else
System.out.println("False");
The code produces �True�
Q#2
if( "String".startsWith(""))
Sytem.out.println("True");
else
System.out.println("False");
The code produces �True �
I really don�t have any idea of output ?( why �True�?)
Regards
vivek

 
Vivek Shrivastava
Ranch Hand
Posts: 277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looking forward to hear from u guys.
I would realy appreciate it.
vivek
 
Ram Prasad
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vivek,
I think the result is correct.
Just compile this code and see.
class javaprog {
public static void main(String [] ag)
{
//blank string
if("String".endsWith(" "))
System.out.println("True");
else
System.out.println("False");
}
}
 
Vivek Shrivastava
Ranch Hand
Posts: 277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Thanks for your time and effort. I know it does print 'true' but my question is why???

please help me!
vivek
 
hemanshow
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try:
if( "string".equals( "string" + "" ) ){
System.out.println( "wow, true" );
}else{
System.out.println( "see, false :-)" );
}
AND try ..........
if( "".equals( null ) ){
System.out.println( "wow, true" );
}else{
System.out.println( "see, false :-)" );
}

so every String object can have as many "" object at end.
NOTE : "" != null
 
Vivek Shrivastava
Ranch Hand
Posts: 277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi hemanshow,
Thanku so much. i really appreciate it.
thanks
vivek
 
rajsim
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a documented explanation from String API:
startsWith:
...
Note also that true will be returned if the argument is an empty string
...
endsWith:
...
Note that the result will be true if the argument is the empty string
...
 
Vivek Shrivastava
Ranch Hand
Posts: 277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks rajsim.
vivek
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic