String Utility Classes in Java

Manipulating strings is a part and parcel of a programmer’s day to day life. There are many string related operations which we use quite often. Some of the string operations are provided by Java (classes like String, StringBuilder etc.) and some we devise ourselves. For example, as a good practice the first thing we do while working with string is to check it for null and emptiness as shown below:

if (myString != null || !"".equals(myString)) {
// work with myString
}

For the above and some other frequently used cases of string manipulation we can use the string utility classes already provided by the third party libraries. The string utility class available in apache commons project, org.apache.commons.lang3.StringUtils, is one of the widely used string utility classes. This class has many utility methods which take care of commonly used string operations and most of these are null safe.

For example we can use the isBlank, isNotBlank methods from the StringUtils class to validate the string for empty and null as shown below:

if(StringUtils.isNotBlank(myString)) {
//work with myString
}

The java documentation of the StringUtils.isBlank method says:

public static boolean isBlank(CharSequence cs)
Checks if a CharSequence is whitespace, empty ("") or null.

StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false

Based on requirements we can also consider using isEmpty and isNotEmpty.

You can check the API documentation of org.apache.commons.lang3.StringUtils and have a look on other utility methods it provides.

If you are already using Spring framework in your application, you can consider using the StringUtils class available in Spring Framework for the utility methods it provides. This class has been mainly used inside Spring Framework but as it is available, we can use this. Some of the methods I liked from this class are:

// Convert an array or a collection to a comma delimited string (say, for creating a csv file) and vice versa
public static java.lang.String arrayToCommaDelimitedString(java.lang.Object[] arr)
public static java.lang.String[] commaDelimitedListToStringArray(java.lang.String str)

public static java.lang.String collectionToCommaDelimitedString(java.util.Collection<?> coll)
public static java.util.Set<java.lang.String> commaDelimitedListToSet(java.lang.String str)

//Trim an array of strings
public static java.lang.String[] trimArrayElements(java.lang.String[] array)

For more information on Spring Framework’s StringUtil class, check it’s API documentation.

Enjoy Learning,
Kamlesh

Advertisements

JSP: Problem Using Spring Message with JSTL

Couple of days back I was trying to externalize the labels and messages in a JSP file to a property file. As I was using Spring MVC, decided to use <spring:message> tag to achieve this. Everything else worked fine except when I used <spring:message> tag as a value attribute of <c:set>. Albeit it sounds very simple, I had to spend some time finding out the way. And hence considering this a candidate for my blog.

Problem:

Unable to use <spring:message> tag with the JSTL  <c:set> tag like below:

<c:set var=”someVar” value=”<spring:message code=’some.value’/>” />

Solution:
Nest the <spring:message> tag in the JSTL tag.

<c:set var=”someVar”>
<spring:message code=”some.value”/>
</c:set>

Enjoy Learning,
Kamlesh

Inside Java: Concurrent modification when using collection and iterator

ConcurrentModificationException may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible. This exception is encountered more often in case of collections when one thread is iterating over the collection and other tries to modify it.

This article explains how java detects concurrent modifications to a List with the help of an example. The comments provided along with the code are self explanatory so let us go through the example first:

ConcurrentModificationTest.java

package com.technicalmusings.examples.collection;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
* The class explains how concurrent modification is detected in List.
*/

public class ConcurrentModificationTest {

public static void main(String[] args) {

// Instantiating the list sets the modCount field of list to 0
// modCount is a protected integer variable defined in the AbstractList class.

List<Object> myList = new LinkedList<Object>();

myList.add(new Object()); // modCount incremented to 1
myList.add(new Object()); // modCount incremented to 2
myList.add(new Object()); // modCount incremented to 3

// Getting an iterator sets the value of expectedModCount field
// equal to that of the modCount field of list.

Iterator<Object> itr1 = myList.iterator(); //itr1: expectedModCount = 3
Iterator<Object> itr2 = myList.iterator(); //itr2: expectedModCount = 3

// The first Iterator traverses the list once
itr1.next();

// The second iterator traverses and removes the first element
itr2.next();
itr2.remove();
// In the previous step Itr2 modifies the list and sets the
// expectedModCount field to 4. The modCount field of the list
// has also been now incremented to 4

// The first iterator again tries to traverse the list
itr1.next();

// java.util.ConcurrentModificationException is thrown at this stage
// because itr1 finds its expectedModCount (which is still 3) to be not
// matching with the modCount field of the list
}
}

The ConcurrentModificationTest.java class shown above explains how java works behind the scenes to detect concurrent modification and throw the ConcurrentModificationException in case of a List. List has an integer field modCount, which is incremented each time a structural modification is done in the list. Structural modification includes methods like add, remove, clear etc. The Iterator on the other hand uses another integer field, expectedModCount, to take care of concurrent modifications in the list. Iterator expects both the variables modCount and expectedModCount to be the same. In case the list is modified by any other means the modCount and expectedModCount differs and the exception is thrown.

Java Threads: Thread and Exception Handling

Whenever an uncaught exception occurs in a thread’s run method we get a default exception dump which gets printed on System.err stream. We may not always want to live with this default behavior and might think about logging the exception message in a more sophisticated way or doing something else as per business requirement.

Such custom exception handling can be achieved using the UncaughtExceptionHandler interface of the Thread class. The ThreadGroup class also implements the Thread.UncaughtExceptionHandler interface. The interface has only one method defined, which is:

void uncaughtException(Thread t, Throwable e);

This handler interface is invoked when a thread abruptly terminates due to an uncaught exception. The below excerpt from Java documentation explains the UncaughtExceptionHandler interface:

When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler’s uncaughtException method, passing the thread and the exception as arguments. If a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements for dealing with the exception, it can forward the invocation to the default uncaught exception handler.

Thread class has two methods viz. setDefaultUncaughtExceptionHandler() and setUncaughtExceptionHandler(). The setDefaultUncaughtExceptionHandler() which is a static method of Thread class can be used to provide a common exception handler for all the threads. On the other hand setUncaughtExceptionHandler() is a non static method of Thread class which is used to provide handler to a given thread.

The below example shows how to handle the uncaught exception thrown from a Thread:

MyThreadTest.java

package com.technicalmusings.examples.thread;

/**
* The below class creates a thread which is supposed to throw an exception.

* A handler is added to the thread before calling the start method of thread.
* When the thread executes the exception is handled by the handler
* and the custom exception message is displayed on the console.
*/

public class MyThreadTest {

public static void main(String[] args) {

Thread newThread = new Thread(new ThreadWithException());

// Add the handler to the thread object
newThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){

@Override
public void uncaughtException(Thread t, Throwable e) {

System.out.println("ERROR! An exception occurred in " + t.getName() + ". Cause: " + e.getMessage());
}
});

newThread.start();
}
}

/**
* This thread throws a custom exception in its run method.
*/

class ThreadWithException implements Runnable {

@Override
public void run() {
throw new RuntimeException("Application Specific Exception!!");
}
}

Output:

ERROR! An exception occurred in Thread-0. Cause: Application Specific Exception!!

Enjoy Learning,
Kamlesh

We’ve always done it that way

We’ve always done it that way.

How many times you have heard this punch line and how many times implemented the same in your work or life? Sounds like a Déjà vu, isn’t it?

In the book Code Complete 2, Steve McConnell has referred to a very nice story to emphasis that we should not always adhere to the above line. The story goes as below:

Beth wanted to cook a pot roast according to an award-winning pot roast recipe handed down in her husband’s family. Her husband, Abdul, said that his mother had taught him to sprinkle it with salt and pepper, cut both ends off, put it in the pan, cover it, and cook it. Beth asked, “Why do you cut both ends off?” Abdul said, “I don’t know. I’ve always done it that way. Let me ask my mother.” He called her, and she said, “I don’t know. I’ve always done it that way. Let me ask your grandmother.” She called his grandmother, who said, “I don’t know why you do it that way. I did it that way because it was too big to fit in my pan.

Cheers,

Kamlesh

Scripting API in Java: Invoking JavaScript from Java

Scripting languages like JavaScript sometimes prove to be more flexible over the normal Java code. The Scripting API (javax.script.*) introduced in Java 6 allows to use the advantage of JavaScript in Java.

With the help of a Scripting Engine, the Scripting API can invoke scripts in the Java code. Java 6 comes with an implementation of JavaScript interpreter by Mozilla, Rhino. Scripting engines for other scripting languages can be found at http://scripting.dev.java.net.

Let us see an example of how to invoke JavaScript from a Java class.

package com.technicalmusings.sample.js;
import java.util.List;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptRunner {

public static void main(String[] args) throws Exception{

    //the script manager
    ScriptEngineManager scriptManager = new ScriptEngineManager();

    //Check the available script engines
    List<ScriptEngineFactory> scriptFactories = scriptManager.getEngineFactories();

    System.out.println("Available Engines in Java 1.6.0_17:");
    for (ScriptEngineFactory factory : scriptFactories){
        System.out.println(factory.getEngineName());
    }
    System.out.println("-----------------------------------");

    System.out.println("Java Script Variables");
    System.out.println("-----------------------------------");

    //Get the java script engine
    ScriptEngine engine = scriptManager.getEngineByName("JavaScript");

    /*
    * USING A JAVASCRIPT VARIABLE:
    * Variables evaluated in JavaScript engine defaults to engine scope.
    * In the below example I am using the method engine.eval(String
    * script) to invoke JavaScript. In case you wish to store JavaScript
    * in a file like abc.js, you can use the overloaded version of the
    * same method which takes a Reader object; engine.eval(Reader
    * reader);
    */

    engine.put("i", 10);
    System.out.println("i * 10 : " + engine.eval("i * 10"));//100
    System.out.println("i : " + engine.eval("i"));//10
    System.out.println("i = i * 10 : " + engine.eval("i = i * 10"));//100
    System.out.println("i : " + engine.eval("i"));//100

    //using javascript variable in java
    int i = ((Double)engine.eval("i")).intValue();
    System.out.println("JavaScript variable in Java; i : " + i);
    System.out.println("-----------------------------------");

    /*
    * USING JAVASCRIPT FUNCTION:
    * Script engines provide the feature of invoking a function. In order
    * to be able to invoke a function the script engine must implement
    * the Invocable interface. Following example shows how to use a
    * simple function in JavaScript.
    */

    System.out.println("Java Script Function");
    System.out.println("-----------------------------------");
    //Check whether engine implements Invocable as it depends on the engine’s implementation.
    if(engine instanceof Invocable){
    //Declare the function
        String functionScript = "function display(message){ return message }";
        engine.eval(functionScript);

        //Invoke the function with a String parameter
        String message = "Hey JS! Greetings from Java";
        Object result = ((Invocable)engine).invokeFunction("display", message);
        System.out.println(result);

        //Invoke the function using a pre defined variable
        result = ((Invocable)engine).invokeFunction("display", "i is " + engine.eval("i"));
        System.out.println(result);
    }
    System.out.println("-----------------------------------");
 }
}

The output of the above example is given as below:

Available Engines in Java 1.6.0_17:
Mozilla Rhino
-----------------------------------
Java Script Variables
-----------------------------------

i * 10 : 100.0
i : 10
i = i * 10 : 100.0
i : 100.0
-----------------------------------
Java Script Function
-----------------------------------
Hey JS! Greetings from Java
i is 100.0
-----------------------------------

I have shown very basic use of the scripting APIs in this post. There are many other features which a scripting engine provides. For example if we require executing a script multiple times we can compile the script once and use that as required. The engine in that case must implement the Compilable interface.

The Scripting API also solved the problem of using a JavaScript variable in java and vice-versa. Most of the times we face this problem in a JSP where we have to use workarounds. Though I still need to test this but this should work. Let me know if you have tested the same.

Enjoy Learning,

Kamlesh

Java Interview: Checklist

I am listing below the checklist of concepts and keywords in java which are most frequently asked in interview. Please excuse me for presenting it in a random order.

Following are the topics/keywords/concepts which require a crisp knowledge and understanding. These are basisc only.

  • JVM – About JVM, JIT compiler, Bytecode, Classloader
  • Garbage Colection – Conditions when JVM invokes garbage collection, System.gc()
  • Static and Instance initializer block
  • Datatypes – character especially
  • enum – where to declare, defining constructor, methods and variables in enum
  • OOP concepts – inheritance, polymorphism, aggregation vs Composition, abstraction
  • Multiple Inheritance in java
  • Difference/Similarities between interface and abstract class
  • Software Engineering Concepts – Coupling and Cohesion
  • String, StringBuffer and StringBuilder
  • Exception Handling – Checked vs Unchecked Exceptions, Assertion, Error, Exception Hierarchy, throw vs throws
  • final, finally and finalize
  • Method Overriding (Rules for the same)
  • Method Overloading – Covariant Return (Java5)
  • Autoboxing
  • Array – Declaring an anonymous and multidimensional array
  • Keywords like super and this
  • The Object classs – equals and hashcode methods
  • Access Specifiers – default, public , protected and private
  • Marker Interface, Wrapper Classe and Adapter Class
  • Classes like Math, StrictMath, Scanner, Console
  • Java IO: Important classes in IO, NIO.
  • Reading and writing XMLs in java. Type of parsers – SAX, DOM and STAX.
  • Java UI: AWT vs Swing, Different Layouts, Event handling, Calback methods
  • Serialization, Transient keyword
  • Multithreading – Runnable vs Thread, How to write a thread, difference between run and start method.
  • Java5 Concurrency and advanced threading – Callable, Future, Executors, Thread pooling, Locks and Conditions
  • Collection and Generics – Map, Set and List; Conventional Questions like ArrayList vs Vector, HashTable vs HashMap etc; Comparator and Comparable; Important collection classes.
  • Methods of java.util.Collections – Synchronizing a collection, Creating views
  • JDBC: The JDBC code, Type of JDBC Drivers, Type of Statements, execute, executeUpdate and executeQuery

We can discuss these further in case of queries/suggestions. Feel free to comment and add in case I missed something.

Enjoy learning,

Kamlesh