Alessandro Lacava’s Blog

Google
 

December 3, 2008

Java split() of String | Multiple whitespace characters

Filed under: Computer, Java, RegEx — alessandrolacava @ 12:47 pm

The split method of the String class is very useful when you want to tokenize a string. Its power lies in the fact that it accepts a string, as a parameter, which can be a regular expression. However you must be careful when you want to split a string using the whitespace character as a delimiter. Consider the following snippet of code:

JAVA:
  1. String str = "Testing split using two  whitespace characters";
  2. String[] tokens = str.split("\\s");
  3. for(String token : tokens)
  4. {
  5. System.out.println("-" + token + "-");
  6. }

What's the output produced by the previous code? If you think it is the following one you're wrong:
-Testing-
-split-
-using-
-two-
-whitespace-
-characters-

The actual output is instead the following one:

-Testing-
-split-
-using-
-two-
--
-whitespace-
-characters-

Where in the hell did that empty string come out from? It comes out from the two whitespace characters that are between the word two and whitespace of the str string. If this is what you want OK. However, most of the time, you will want to discard that empty string from your resulting string array. You can obtain this result by using the \\s+ regex in place of \\s. Basically, the previuos code becomes:

JAVA:
  1. String str = "Testing split using two  whitespace characters";
  2. String[] tokens = str.split("\\s+");
  3. for(String token : tokens)
  4. {
  5. System.out.println("-" + token + "-");
  6. }


July 22, 2008

OutOfMemoryError in Eclipse | Java Virtual Machine (JVM)

Filed under: Computer, Java, IDE, Eclipse — alessandrolacava @ 10:53 am

OutOfMemoryError in Eclipse | Java Virtual Machine (JVM)

It might happen that while running a Java application within the Eclipse environment you get an OutOfMemoryError due to the maximum amount of memory dedicated to the heap. You can fix it by increasing the minimum (-Xms parameter) and maximum (-Xmx parameter) heap size. You can do it in two different ways:

1. By editing your eclipse.ini file you find under your Eclipse installation directory. Within that file you should find two lines similar to the following ones:

-Xms40m
-Xmx512m

You might want to change them depending on your hardware. For example I changed them as follows:

-Xms256m
-Xmx1024m

It means: "start with an initial heap size of 256 MB and grow to a maximum of 1024MB, that is 1GB."

2. By editing the Run Configurations in Eclipse. To do this, right-click on the class you want to run (the one with the main method) and then select:

Run As -> Run Configurations

Click on the Arguments tab. In the VM Arguments box type:

-Xms256m -Xmx1024m

or whatever you prefer, depending on the hardware you possess.

IMPORTANT NOTE: It is strongly recommended that you make a backup copy of your eclipse.ini file before editing it in any way.


Next Page »