Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String split method

 
Christian Lombardo
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am working on a simple Java code and cannot seem to understand why the empty string (in the String tokens array) is not detected by the if statement, see below for the code:

public class SplitTest {

public static void main( String[] args )
{
String data = "Hello,,I am me, DO IT,NOW,yeah MON!,,,,,5,";
String[] tokens = data.split("\\,");
for (int element = 0; element < 11 ; element ++) {
System.out.print(">");
System.out.print(tokens[element]);
System.out.println("<");

if (tokens[element] == "")
System.out.print(" Empty String here");

if (tokens[element] == null)
System.out.print(" NULL here");
}
}
}
 
Henry Wong
author
Marshal
Pie
Posts: 21395
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It may be a good idea to read the Javadoc... The default split() method truncates trailing zero length matches.

Henry
 
Christian Lombardo
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do not understand. When you run the code it prints an empty string.

The Javadoc: http://java.sun.com/javase/6/docs/api/ does not explain details of the split() method in regards to empty strings.
 
Henry Wong
author
Marshal
Pie
Posts: 21395
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, when you do string comparison, use the equals() method -- the == operator is for references comparison only.

Henry
 
Christian Lombardo
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Henry.
 
Manish Singh
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And instead of doing

for (int element = 0; element < 11 ; element ++) {

use the .length property of the arrays
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic