Many
times we want to execute the same test case with different input and
expectations. Instead of writing each test separately, it is much better to
abstract the actual test into a class and inject input values and expected
results into the test class. Junit4 provides Parametrized test, which is a standard
solution to achieve this.Let’s
write a simple square() method to return square of a number. We’ll consider this square() method
for writing our Parametrized test case:

To
write Parametrized test cases a test class should satisfy following conditions: 1. Test
class should be annotated with @RunWith(Parameterized.class) annotation. 2. Test
class should have a static public method annotated with @Parameters annotation
and returning a collection of test data elements (which in turn are stored in
an array). 3. Test
class should have a single constructor which accepts test data elements from
the previously mentioned array and inject into object appropriate states.

When
running a parametrized test class, a new test class is created for the
cross-product of the test methods and the test data elements. It means for a
test class if there is 1 test case and 5 input data then there will be total 5(1*5)
instances of parameterized test class with their own set of input data.Let’s
write Parameterized test to test square()
method for inputs [0,5] and their corresponding expectations.

It is clearly evident from the console prints that there are total 6(1 test-case*6 input) instances of SqaureTest class.Identify Individual Test CaseIn
order to easily identify the individual test cases in a Parameterized test, you
may provide a name using the @Parameters annotation. This name is allowed to
contain placeholders that are replaced at runtime:

In our example we named the test case as "Test#{index}:
square[{0}]={1}". Actual test names can be easily viewed in the Result snap.Writing
Parameterized test is pretty simple and useful to run the same test for various
inputs.

Numerous times we write Junit tests where we need to create temporary files and folders for executing the testcase. Usually, we create temporary folder at some physical location and write temporary files in it. Major pain in this approach is that we need to take care of creation and cleanup of all such files during the test lifecycle.Junit4 comes with special Rule TemporaryFolder which automatically takes care of all such things. It creates the temp folder when a test starts and deletes the temp folder when the test finishes. It does this for every test method in the class. It will always clean up the files, whether the test passes, fails, or throws an exception.Under the hood, TemporaryFolder uses the File.createTempFile() method to create the folder, so it's storing the folder in operating system's temp folder. It also assigns a unique name to the folder, so if the JVM crashes and TemporaryFolder does not clean up your files, the results of next test run will not be skewed by the files from the previous run.Let’s see how it works:

Note: It’s clearly evident from the output that on each repetition newFile() creates a new file within the temporary directory with a random file name[If a file name is not passed into the method, then it will generate a random file name]. Here, we used RepeatRule(10) to repeat the same testcase 10 times. For more information on RepeatRule, please read the previous post “Repeating a test case in Junit”.Now after the test execution, let’s do a quick look up for the temp folder "junit8242036959618829704" in the system’s temp folder to see whether it exists or not:

You can see that the temp folder "junit8242036959618829704" has been cleaned up by TemporaryFolder.It’s really very useful feature of Junit, which takes out the pain involved with temp files management in unit testing.Hope this article helped. Happy learning... :)

Many
times we need to createJunit tests which needs to be repeated over and over (may
be with different data set). Many of us did this by writing custom Runner or
sometimes using parameterized test.Junit4 comes with @Rule, which can be used for repeating a testcase. Actually, rules
are used to add additional functionality which applies to all tests within a
test class, but in a more generic way. Using @Rule for such a requirement is preferable
because it does things in a more clean way. Moreover by using @Rule we still has option to use pretty useful runners like @RunWith(PowerMockRunner.class) etc.Let’s
create a simple Rule to repeat a test case to ‘N’ number of times:

If we observe the source code of the above three methods
provided by String class, it is very clear that length() is simply a getter
method and returns length of the String. It’s obvious that any String having
length 0 is always an empty string and so, the following code is able to detect whether
the string is empty or not:

str.length() == 0;

The same reason holds behind using isEmpty() method.
Moreover this method seems much verbose by its signature itself.

On the other hand, if we take a look on equals method, it seems to be relatively heavyweight. It does a lot of computation and consumes relatively more CPU cycles for the same operation. So, simply for such a basic check, using equals() method will result in lot of waste of CPU cycles.

String
is a special class in Java. It has very high importance in concurrent
programming as well because String is immutable.
Since, String is immutable, so they should be reused. In order to reuse String
objects JVM maintains a special pool called “String literal pool” or “String constant pool” to store referencesof String Objects.

There are slight differences in various methods of creating
String objects.

1. Creating String Directly [Using String
Literals]:

String str = “hello”;

All the string literals are created and their references are placed in the pool while JVM loads the class. So, the literal(String Object) "hello" will be created in the heap and have a reference in the pool(at the class load time itself) before execution of the following statementString str = “hello”;.Hence, whenever our code tries to create a String literal, JVM checks the String Literal Pool and since the string already exists in the pool, a reference to the pooled instance is returned back to the caller.So, String literals used in Java code always refers to the pooled object of String pool.JVM keeps at most one object of any String in the literal pool.

2. Creating String Using Constructor:

String str = new String(“hello”);

In this case since we are creating String object using “new” keyword, String object will be created in heap memory and this is separate from the String Literal Pool. So, it may happen that String Literal Pool might have the equal String object available but using “new” we will always be able to create different String object with same content.java.lang.String.intern():It is String literals that get automatically interned/added to the String pool. String objects created with the “new” operator do not refer to objects in the String Literal Pool but can be made to by using String’s intern() method. The String.intern() returns an interned String, that is, one that has an entry in the global String Literal Pool. Using intern(), if the String is not already in the global String Literal Pool, then it will be added.

You can inspect constant pool of a class by running javap -verbose for that class.

An object is eligible for garbage collection if it has no live references from active parts of the JVM/application. In the case of String literals, they always have a reference to them from the String Literal Pool and therefore, they are not eligible for garbage collection until the class and its class-loader is unloaded.

All the string literals are created and their references are placed in the pool while JVM loads the class.

Recursion
simply means calling the same function inside its own body repeatedly to
complete some task. This is one of the
standard approaches to achieve some task. While programming using recursion,
there is one basic thing one must fix is the base condition to stop the
recursion, otherwise we’ll run into an infinite recursion.

Let’s have a look on a very simple recursive function “sum”
which can be used to compute the sum of n numbers.

In this example, the base
condition is n == 1 i.e. call to sum will be stop when n=1. So, we start
summing up numbers starting from n till 1 using recursion.

It works perfectly… J

But, what will be the depth of recursion for various values
of n in the above “sum” function.
Obviously, it will depend on the input. For
large values of n like 10000 or more, the program will throw StackOverflowError
and JVM may crash.

But notice that it may be curable, but a better solution would be to
work out how to avoid

recursing so much.

2. Change the implementation to an iterative
solution:

Most of the recursive solutions can easily be converted to iterative solutions, which will make the code scale to larger inputs much more cleanly. Otherwise we'll really be
guessing at how much stack to provide, which may not even be obvious from the input.

This should the most preferred solution.

3. Using
Tail Recursion:

Using tail-call optimization we are able to
avoid allocating a new stack frame for a function because the calling function will
simply return the value that it gets from

the called function. The most common use is
tail-recursion, where a recursive function

written to take advantage of tail-call
optimization can use constant stack space.

It is
supported by many functional languages but it is not supported by Java.

Coming to the best practices, we should prefer
iterative solution over recursion wherever

In our day to day life, we need to debug various issues with
the help of several log files e.g. application logs, server access logs, error
logs etc. and during this process we try to fetch relevant information from the
log file(s).

While working on windows with such files, we use various editors like
Notepad++,JujuEdit etc. But,
what if the log files are really big, somewhere in GB’s…? Most of these editors
get hanged while opening or they simply refuse to open such big files because
these editors support files up to 2 GB.

For such requirements there are few editors
like EmEditor,
Glogg etc. which can
open big files easily. These editors are really good and very fast for big files.

But here clicks a good question - “Can we execute 'grep' like Unix command(s) on such big files in our Windows command prompt...?” It would be great if we can get such luxury
on windows as well.

Fortunately it’s a “Big YES”. There are several open source software’s
which can be used to get most of the Unix
Commands running on Windows machine
in our familiar Windows command prompt.
Few such software's are- UnxUtils,Cygwin etc.

I have been using UnxUtils for a long time now on
my Windows machine. It’s a lightweight alternative among similar software’s. Getting
started with UnxUtils is pretty simple and
easy.

Let’s jump directly on the steps to get UnxUtils working on Windows
machine: