Saliya's Blogs

Mostly technical stuff with some interesting moments of life

Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Java Strings: literal.equals(param) OR param.equals(literal)

Comparing strings is bit tricky :) Say for an example you want to test a String reference against the literal "hello". In simple terms you have a String (say helloStr) and you want to see if the content of that is equals to "hello". You have two choices here,

1. helloStr.equals("hello")

2. "hello".equals(helloStr)

Both will do fine, but which is the better one? I've been using the second form but never thought of the difference (hmm, that's bad ;) anyway people do remember certain things bit later). In one of the code reviews at WSO2 it was revealed. The first form can lead to a Null pointer exception in the case when the helloStr is null. The second option will save you from this since the literal "hello" is not null always and you are invoking a method of a not null object. In this case even if the helloStr is actually null it doesn't matter because it'll only cause the program to check "hello" against null which results false.

If you are checking two String references then you have no option, but always try to invoke the equals() from the most probably not null reference.

Little things do matter :)

Convert ByteArrayInputStream to String

Recently one of my friends wanted to get the string contained in a ByteArrayInputStream in Java. The method do this was bit tricky and I thought it'd be nice to share it.

ByteArrayInputStream bais = // get your ByteArrayInputStream instance

int length = bais.available();
byte [] buff = new byte[length];
bais.read(buff);

That's it!!