Consider Enums Instead of Constants

Using constants can be error prone. You always need to validate that the value being passed is valid.

<pre class="prettyprint"><span class="kwd">class</span> <span class="typ">Suit</span> <span class="pun">{</span>        
    <span class="kwd">public</span> <span class="kwd">static</span> <span class="kwd">final</span> <span class="kwd">int</span><span class="pln"> CLUBS </span><span class="pun">=</span> <span class="lit">1</span><span class="pun">;</span>
    <span class="kwd">public</span> <span class="kwd">static</span> <span class="kwd">final</span> <span class="kwd">int</span><span class="pln"> SPADES </span><span class="pun">=</span> <span class="lit">2</span><span class="pun">;</span>
    <span class="kwd">public</span> <span class="kwd">static</span> <span class="kwd">final</span> <span class="kwd">int</span><span class="pln"> HEARTS </span><span class="pun">=</span> <span class="lit">3</span><span class="pun">;</span>
    <span class="kwd">public</span> <span class="kwd">static</span> <span class="kwd">final</span> <span class="kwd">int</span><span class="pln"> DIAMONDS </span><span class="pun">=</span> <span class="lit">4</span><span class="pun">;</span>
<span class="pun">}</span></pre>
<pre class="prettyprint"><span class="kwd">void</span><span class="pln"> method</span><span class="pun">(</span><span class="kwd">int</span><span class="pln"> suit</span><span class="pun">)</span> <span class="pun">{</span>
    <span class="kwd">if</span> <span class="pun">(</span><span class="pln">suit </span><span class="pun"><</span> <span class="lit">1</span> <span class="pun">||</span><span class="pln"> suit </span><span class="pun">></span> <span class="lit">4</span><span class="pun">)</span> <span class="pun">{</span>
        <span class="kwd">throw</span> <span class="kwd">new</span> <span class="typ">IllegalArgumentException</span><span class="pun">(</span><span class="str">"Invalid suit value: "</span> <span class="pun">+</span><span class="pln"> suit</span><span class="pun">);</span>
    <span class="pun">}</span>
    <span class="pun">...</span>
<span class="pun">}</span></pre>

What happens if we add a suit? What happens if we remove a suit? All the client code needs to be updated!

</pre>
<pre class="prettyprint"><span class="kwd">enum</span> <span class="typ">Suit</span> <span class="pun">{</span><span class="pln">     
    CLUBS</span><span class="pun">,</span><span class="pln"> SPADES</span><span class="pun">,</span><span class="pln"> HEARTS</span><span class="pun">,</span><span class="pln"> DIAMONDS
</span><span class="pun">}</span></pre>
<pre class="prettyprint"><span class="kwd">void</span><span class="pln"> method</span><span class="pun">(</span><span class="typ">Suit</span><span class="pln"> suit</span><span class="pun">)</span> <span class="pun">{</span>
    <span class="typ">Validate</span><span class="pun">.</span><span class="pln">notNull</span><span class="pun">(</span><span class="pln">suit</span><span class="pun">);</span>
    <span class="pun">...</span>
<span class="pun">}</span></pre>
<pre>

Client code:

</pre>
<pre class="prettyprint"><span class="pln">method</span><span class="pun">(</span><span class="typ">Suit</span><span class="pun">.</span><span class="pln">CLUBS</span><span class="pun">);</span></pre>
<pre class="prettyprint"><span class="kwd">import</span> <span class="kwd">static</span> <span class="pun">....</span><span class="typ">Suit</span><span class="pun">.*;</span>
    <span class="pun">...</span><span class="pln">
    method</span><span class="pun">(</span><span class="pln">CLUBS</span><span class="pun">);</span>
    <span class="pun">...</span></pre>
<pre>

Enums can also define their own instance variables and methods, so you can remove the if-else blocks from the clients and instead push specific behaviors or values to the enums.

StringBuilder Class

I wrote a blog post about String and StringBuilder last week but I haven’t discussed more in detail about StringBuilder. So in this blog post, I will talk about more in detail on StringBuilder class in Java.

StringBuilder is a mutable sequence of characters. It means that when you modify the contents of the StringBuilder object, java does not instantiate intermediate String objects (except for any String literal you pass into the StringBuilder) unlike String.


new StringBuilder("Live").append("What").append("You").append("Love");

//LiveWhatYouLove

Since StringBuilder is mutable, it can perform these operations:

  1.  Append – appends the string representation of the parameter(boolean, int, char, double, object, etc) to the char sequence.

Append method is overloaded so it can receive different data types like int, long, double, boolean.


new StringBuilder("You are").append(true).append(2).append("me");

//You are true2me

2.  Insert – appends the string representation of  the parameter(boolean, int, char, double, object, etc) to the char sequence. It differs to append because in insert, you can specify the place where you insert whereas append you just adding or concatenating the string after the last character.


StringBuilder couple = new StringBuilder("JunaldBeverly");

couple.insert(6, " Love ");

//Junald Love Beverly

3. Delete – deletes the substring in the char sequence based on the starting index and ending index.


StringBuilder greeting = new StringBuilder("Happy New Year");

greeting.delete(5, 8);

//Happy Year

4. Reverse –  reverses the char sequence.


StringBuilder food = new StringBuilder("stressed");

food = food.reverse();

//desserts

There are lot of methods in StringBuilder like substring, replace, trimToSize. If you want to learn more about those methods you must check out the Java documentation.

If you liked this post, don’t forget to share! Thanks

 

String and StringBuilder

In this blog post, I’ll talk about String and StringBuilder.

String is immutable. Immutable means its contents cannot be altered.


String message = &quot;I Love You&quot;;

message = &quot;I Love You Beverly&quot;;

Consider the code above, the value of the message variable has not altered but actually java creates two different objects.

“I Love You” value does not garbage collected right away after being deferenced. The value is actually stored in “String Pool”, a special memory for Strings.

This is what happens in the String Pool after the code above is executed,
string-pool1
After the “I Love You” value is being deferenced, the value still exists in the String Pool. So that if the value is needed elsewhere in the application, java does not need to instantiate new String object.

For example,
string-pool1
Assuming the “I Love You” value is needed somewhere in the application, java does not instantiate new String object, it rather finds the existing value in the String Pool.

This helps with performance if certain strings are used over and over in the application because there are no cost of repeated String instantiation. However things get complicated if we try to “modify” a string.

String greeting = &quot;Happy&quot;
greeting = greeting + &quot; &quot;;
greeting = greeting + &quot;Birthday&quot;;
greeting = greeting + &quot; &quot;;
greeting = greeting + &quot;Beverly&quot;;

As what I’ve discussed earlier, Strings are immutable, you can never modify a String, instead you create new one.

For the code above 9 String objects are instantiated:

  1. “Happy”
  2. ” “
  3. “Happy “
  4. “Birthday”
  5. “Birthday “
  6. “Beverly”
  7. “Happy Birthday”
  8. “Happy Birthday “
  9. “Happy Birthday Beverly”

This is what happen in the String Pool

string-pool1

This could lead to large memory consumption because of multiple String instantiation. In the other words, performance will suffer if you will use String that will handle multiple string manipulations.

If your application needs to handle a lot of String manipulation, consider using StringBuilder.

StringBuilder is mutable sequence of characters unlike String.

Since StringBuilder is mutable, the contents of the strings can be altered without making multiple instantiation, hence, performance will not suffer.

For StringBuilder click here.

Conclusion

Use String if have only few String manipulation like concatenating short messages.

If a string-manipulation might leave a lot of objects in the StringPool, or performance is a high priority, consider StringBuilder.