All you need to know about ENUM in JAVA

Java enums are special java types used to define costants. Enum in Java is a keyword, which act as a special class. It can contain constants, methods etc. Enums were first introduced in java 1.5.

Example: 

public enum DayOfWeek{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}

you can refer to enum as below:

DayOfWeek  day = DayOfWeek.FRIDAY;

Here variable day is of type DayOfWeek, which can take one of the value DayOfWeek enum constant value.

Enums by default are final and static.

Delete a non empty directory in Java

In java, we can delete a file or directory using file.delete() method. it will returns when successfully deleted else false is returned.

When deleting a Directory, it will only delete if it is empty, that means it does not contain any data in it. If there is some data in directory then delete() method will return false, that means directory is not deleted.

To delete Non-empty directory you must have to delete its contents first. you can do so in many ways, i have written a recursive way to delete non-empty directory as below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
 public static void main(String[] args) {
  File file = new File("C:\\Test1");
  System.out.println("File/Directory Deleted: " + deleteDirectory(file));
 }
 
 
 public static boolean deleteDirectory(File file) {
  if (file.isDirectory()) {
   if (file.list().length != 0) {
    for (File f : file.listFiles()) {
     deleteDirectory(f);
    }
   }
  }
  return file.delete();
 }


Please leave a comment if you liked it.

Find First Non Repeated Character in a String - Technical Jana Interview Question


Finding First Non repeated character in a string

This question is mostly asked in technical java interview, either interview ask for logic or might ask you to write code for it.

It is better to practice such question before hand than facing embarrassment in front of interviewer.

First we will try to understand the question, We need to find first non repeated character in a string, means first character which is not appearing in string again. For example: 

If the String is "Twitter", then answer is w
if the String is "embarrassment", then answer is b

Solution:

there are many ways to solve this problem but we will discuss an optimized way to do it. We need two nested for loops, first to pick each character from string and another one is to compare this character with other characters and break the second loop as soon as you find duplicate character, and continue for next character.

Java program is as below:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Scanner;

public class FirstNonRepeatedChar {

	public static void main(String[] args) {
		System.out.println(" Please enter the input string :");
		Scanner in = new Scanner(System.in);
		String s = in.nextLine();
		char c = check(s);
		System.out.println("The first non repeated character is :  " + c);
	}

	private static char check(String str) {
		char unique = '!';
		boolean found = false;
		for(int counter = 0; counter < str.length(); counter++) {
			unique = str.charAt(counter);
			for (int j=0; j<str.length(); j++) {
				if(str.charAt(j) == unique && j != counter) {
					found = true;
					break;
				}
			}
			if(found) {
				found = false;
			} else {
				return unique;
			}
		}
		return unique;
	}
}

Output:


Please enter the input string :
embarrassment
The first non repeated character is :  b

Hope this helps.

Embed image in Excel file using Apache POI

Embed image in excel sheet using POI and Java

In this example, I will walk you through step by step guide to explain how to embed Image into  Excel sheet using Java and Apache POI library.

Many a times we face a requirement to add image to our templates or reports, that image could be company logo or country flag or some other image. In this example you will learn how to embed image in Excel worksheet.

Step 1: Create Workbook and WorkSheet
The first step is to create Workbook and Sheet, that will hold image and text we wish to display, below are the code lines responsible for workbook and sheet creation.

HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Welcome");

Step 2: Create InputStream of image.
Next step is to create Inputstream with image data and convert it into byte array, below code lines are responsible for this,

       InputStream logo_image = new FileInputStream("C:\\logo.jpg");
       byte[] bytes = IOUtils.toByteArray(logo_image);

Step 3: Add Image to Excel Sheet
Next step is to add image to excel using addPicture of workbook, addPicture methods return index of image with respect to workbook. This index is required to position image in any sheet.

       int picIndex = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
       logo_image.close();

In next step is to create Patriarch Object and set picture to it along with ClientAnchor which assigns picture size and location, as below.

       HSSFPatriarch drawing = sheet.createDrawingPatriarch();
       ClientAnchor my_anchor = new HSSFClientAnchor();
       my_anchor.setCol1(2);
       my_anchor.setRow1(1);
       HSSFPicture my_picture = drawing.createPicture(my_anchor, picIndex);
       my_picture.resize();

Note: If you run the program and face below exception, include commons-codec.jar jar in your claspath.

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/codec/digest/DigestUtils
        at org.apache.poi.hssf.usermodel.HSSFWorkbook.addPicture(HSSFWorkbook.java:1580)
        at AddImageExample.main(AddImageExample.java:18)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.codec.digest.DigestUtils
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 2 more