How to convert a String to int / Integer in Java

When you want to convert a String to int or Integer you can use two simple methods from the Integer class.

To convert a String to primitive int use Integer.parseInt(String s)

String a = "1234";
int x = Integer.parseInt(a);

To convert a String to an instance of Integer use Integer.valueOf(String s)

String a = "1234";
Integer x = Integer.valueOf(a);

Continue reading


How to compare Strings in Java

A common mistake Java novices do is using the == operator to compare Strings. This does almost certainly lead to unexpected and unwanted behaviour. There is a simple solution to this problem and a not so simple explanation why it is such a common mistake.

The simple solution is to use String.equals instead of the == operator.

So when you want to know if two String objects hold the same value instead of

String a = "Test";
String b = "Test";
if (a == b) {
  // Do something
}

just use this:

String a = "Test";
String b = "Test";
if (a.equals(b)) {
  // Do something
}

But look out for null Strings, == handles null Strings nicely but when you call

String a = null;
String b = "Test";
if (a.equals(b)) {
  // Do something
}

it will result in a NullPointerException!

Continue reading