Output data to excel file by template with jxls

Let’s assume we have a Java collection of Car objects that we want to output into Excel. The Car class may look like this

To use Jxls to output this object collection into an Excel we need to do the following

Continue reading “Output data to excel file by template with jxls”

How to repeat string ‘n’ times in java?

Suppose you have the string ‘qwe’ and you need to repeat string ‘n’ times. Here’s how to do it:

Using java 8 stream api

Using String.format

Let us examine this example in more detail. Primitive types ( char[] , in this case) are instantiated with nulls “number of times”, then a String is created from the char[] , and the nulls are replaced() with the original string str.

Using StringBuilder and loop

And last but not least, you can use StringBuilder and loop

Using third-party libraries

You could use Apache commons-lang (which has an impressive collection of handy string utilities):

 

How to convert ‘ArrayList to String array in Java

Using Collection.toArray method

First way to convert arraylist is to use built-in for every java collection method toArray(T[] ts)

For example:

The toArray()  method without any argument returns Object[].  So you have to pass an array as an argument to use method toArray(T[] ts) . This array will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

Important note: Originally the code above used new String[list.size()] . But this blogpost reveals that due to JVM optimizations, using new String[0]  is better.

Using Java 8 stream api

An alternative ways to convert arraylist is to use new Stream API available in Java 8:

 

How to compare strings in Java?

Test strings equality

==  tests object references, .equals()  tests the string values.

Sometimes it looks as if == compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object.

For example:

Correct null handling

== handles null strings fine, but calling .equals() from a null string will cause an exception:

 

JShell – Java 9 interpreter (REPL) – Getting Started

What is REPL

Many languages include tools (sometimes called REPL) for statements interpretation. Using these tools you can test code snippets quickly without creating full project.

For example python. Creating project can sometimes take a long time, but using repl you can getting started with the language more quickly. Each entered expression gives you returned value and it’s type – that’s very valuable information.

In java, instead, we have to create a test or main method which prints results and needs to be recompiled every time you make a change.

Continue reading “JShell – Java 9 interpreter (REPL) – Getting Started”