Category: Java

Java split() of String | Multiple whitespace characters

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:

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

What’s the output produced by the previous code? If you think it is the following one you’re wrong:

Read more...

OutOfMemoryError in Eclipse | Java Virtual Machine (JVM)

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**

Read more...

How to get the number of columns in a ResultSet in Java

In Java it is possible to retrieve the number of columns of a ResultSet dinamically, thanks to the ResultSetMetaData class. Here’s an example:

   
// Here you get the conn object. E.g.:
// Connection conn = DriverManager.getConnection(...);

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM your_table");
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
System.out.println("Number of columns in your_table: " + numCols);

The previous code retrieves and displays the number of columns of your_table.

Read more...