Access Modifiers in Java

HOME

There are two types of access modifiers in Java – access modifiers and non access modifiers.

The access modifier of Java specifies the scope of variable, method, constructor or class. We can change the access level of variables, methods, constructors, class by applying access modifiers to them.

There are 4 types of access modifiers.

  1. Private: The code is only accessible within the declared class. It cannot be accessed from outside the class.
  2. Default: The code is only accessible in the same package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
  3. Protected: The code is accessible in the same package and subclasses. If you do not make the child class, it cannot be accessed from outside the package.
  4. Public: The class is accessible by any other class. It can be accessed from within the class, outside the class, within the package and outside the package.

Java Access Modifiers

Private

The private access modifier is accessible only within the class.

In this example, I have created one class – Demo_1 in package Parent_A. It contains private variable and private method. We can access private variables and methods within the class.

package Parent_A;

public class Demo_1 {

	private int x = 10; // private variable

	private void display() { // private method
		System.out.println("Display private method");
	}

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();

		System.out.println("Value of X :" + obj1.x);
		obj1.display();
	}

}

In the below example, we have 2 classes – Demo_1 and Demo_2. Class Demo_1 contains private data member and private method. We are accessing these private members from outside the class, another class Demo_2 so there is a compile-time error.

package Parent_A;

public class Demo_1 {

	private int x = 10; // private variable

	private void display() { // private method
		System.out.println("Display private method");
	}

}

package Parent_A;

public class Demo_2 {

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();
		System.out.println("Value of X :" + obj1.x);
		obj1.display();
	}

}

Private Constructor

In the below example, private constructor is accessible within the class.

package Parent_A;

public class Demo_1 {

	private int x = 10; // private variable

	private Demo_1() {

		System.out.println("Private Constructor");
	}

	private void display() { // private method
		System.out.println("Display private method");
	}

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();

	}
}

Output
Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the class.

package Parent_A;

public class Demo_1 {

	private int x = 10; // private variable

	private Demo_1() {

		System.out.println("Private Constructor");
	}

	private void display() { // private method
		System.out.println("Display private method");
	}

}

package Parent_A;

public class Demo_2 {

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();
	}

}

Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The constructor Demo_1() is not visible

Default

If we don’t use any modifier, it is treated as default access modifier. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public.

In this example, we have created two classes – Demo_1 and Demo_2 in package – Parent_A. We are accessing the class Demo_2 from within its package, since it is default, so it can be accessed from within the package.

package Parent_A;

public class Demo_1 {

	int x = 10; // default variable

	Demo_1() { // default constructor

		System.out.println("Default Constructor");
	}

	void display() { // default method
		System.out.println("Display default method");
	}

}



package Parent_A;

public class Demo_2 {

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();
		System.out.println("Value of X :" + obj1.x);
		obj1.display();
	}

}

Output
Default Constructor
Value of X :10
Display default method

Protected

The protected access modifier is accessible within package and outside the package but through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can’t be applied on the class.

In the below example, I have created the two packages Parent_A and Parent_B. The class Demo_1 of Parent_A package is public, so can be accessed from outside the package. But variable, constructor and method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.

package Parent_A;

public class Demo_1 {

	protected int x = 10; // protected variable

	protected Demo_1() { // protected constructor

		System.out.println("Protected Constructor");
	}

	protected void display() { // protected method
		System.out.println("Display protected method");
	}

}


package Parent_B;

import Parent_A.Demo_1;

public class Demo_3 extends Demo_1 {

	public static void main(String[] args) {

		Demo_3 obj1 = new Demo_3();

		System.out.println("Value of X :" + obj1.x);
		obj1.display();

	}

}

Output
Protected Constructor
Value of X :10
Display protected method

Public

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

In the below example, I have created the two packages Parent_A and Parent_B. The variable, constructor and method of this package is declared as public, so it can be accessed from outside the class or outside the package also.

package Parent_A;

public class Demo_1 {

	public int x = 10; // public variable

	public Demo_1() { // public constructor

		System.out.println("Public Constructor");
	}

	public void display() { // public method
		System.out.println("Display public method");
	}

}

package Parent_B;

import Parent_A.Demo_1;

public class Demo_3 {

	public static void main(String[] args) {

		Demo_1 obj1 = new Demo_1();

		System.out.println("Value of X :" + obj1.x);
		obj1.display();

	}

}

Output
Public Constructor
Value of X :10
Display public method

Iterators in Java

HOME

‘Iterator’ is an interface which belongs to collection framework. It allows us to traverse the collection, access the data element and remove the data elements of the collection.

java.util package has public interface Iterator and contains three methods:

  1. boolean hasNext(): It returns true if Iterator has more element to iterate.
  2. Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element.
  3. void remove(): It removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next(). The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
  4. forEachRemaining – Performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller.

Below is an example of use of Iterator. The iterator() method is used to get an iterator for any collection:

public class IteratorDemo {

   public static void main(String[] args) {

		ArrayList<String> cars = new ArrayList<String>();
		cars.add("Audi");
		cars.add("BMW");
		cars.add("Ford");
		cars.add("Duster");

		// Get the iterator
		Iterator<String> it = cars.iterator();

		// Print the first item
		System.out.println("First element from list :"+it.next());

	}
}

Output
First element from list :Audi

Looping through Collection

In the below example, we are looping through the collection using hasNext() and next() methods of Iterator.

public class IteratorDemo {

	 public static void main(String[] args) {

		ArrayList<String> cars = new ArrayList<String>();
		cars.add("Audi");
		cars.add("BMW");
		cars.add("Ford");
		cars.add("Duster");

		// Get the iterator
		Iterator<String> iterator = cars.iterator();

		System.out.println("List elements : ");

		while (iterator.hasNext())
			System.out.print(iterator.next() + " ");

		System.out.println();
	}
}

Output
List elements : 
Audi BMW Ford Duster 

Removing elements from Collection

Iterators are designed to easily change the collections that they loop through. The remove() method can remove items from a collection while looping. In the below example, I’m deleting the items whose reminder are not 0.

public class IteratorDemo {

	 public static void main(String[] args) {

		ArrayList<Integer> numbers = new ArrayList<Integer>();
		numbers.add(20);
		numbers.add(8);
		numbers.add(10);
		numbers.add(50);

        // Get the iterator
		Iterator<Integer> it = numbers.iterator();

		System.out.println("List of Numbers : ");
		while (it.hasNext()) {

			Integer i = it.next();

			if (i / 10 == 0) {
				it.remove();
			}
		}
		System.out.println(numbers);
	}

}

Output
List of Numbers : 
[20, 10, 50]

I hope you are cleared about Iterators now. Enjoy learning. Cheers!!

HashMap in Java

HOME

A HashMap store items in “key/value” pairs, and you can access them by an index of another type (e.g. a String).

One object is used as a key (index) to another object (value). It can store different types: String keys and Integer values, or the same type, like: String keys and String values. We need to import java.util.HashMap or its super class in order to use the HashMap class and methods.

It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap.

Create a HashMap object as shown below from:-

import java.util.HashMap;

Syntax of HashMap

HashMap<String, String> employeeDetail = new HashMap<String, String>();

HashMap<String, String> employeeDetail = new HashMap<>();

HashMap<String, Integer> employeeDetail = new HashMap<String, Integer>();

Add Items

Below is an example where we are adding items to HashMap by using put() method.

public class HashMapDemo {

	public static void main(String[] args) {

		/* This is how to declare HashMap of key and Value as String  */
		HashMap<String, String> employeeDetail = new HashMap<String, String>();

		// Add keys and values (Name, Designation)
		employeeDetail.put("Tim", "DBA");
		employeeDetail.put("Dong", "SDET");
		employeeDetail.put("Nisha", "BA");
		employeeDetail.put("Ulana", "Dev");

		System.out.println("Detail of Employees");
		System.out.println(employeeDetail);
	}
}

Output
Detail of Employees
{Dong=SDET, Tim=DBA, Nisha=BA, Ulana=Dev}

Below is an example where we are adding items to HashMap by using put() method. Here, key is String and Value as Integer.

public class HashMapDemo {

	public static void main(String[] args) {

		// Combination of String(key) and Integer(value)
		HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

		// Add keys and values (Name, Age)
		employeeAge.put("Tim", 25);
		employeeAge.put("Dong", 26);
		employeeAge.put("Nisha", 29);
		employeeAge.put("Ulana", 34);

		System.out.println("Age of Employees");
		System.out.println(employeeAge);
    }
}

Output
Age of Employees
{Dong=26, Tim=25, Nisha=29, Ulana=34}

Access an Item

To access a value in the HashMap, use the get() method and refer to its key:-

public class HashMapDemo {

	public static void main(String[] args) {

		// Combination of String(key) and Integer(value)
		HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

		// Add keys and values (Name, Age)
		employeeAge.put("Tim", 25);
		employeeAge.put("Dong", 26);
		employeeAge.put("Nisha", 29);
		employeeAge.put("Ulana", 34);

		System.out.println("Age of Employees");
		System.out.println(employeeAge);

		// Access a value
		System.out.println("Access Value of Key Nisha");
		System.out.println(employeeAge.get("Nisha"));
   }
}

Output
Access Value of Key Nisha
29

Remove an Item

To remove an item, use the remove() method and refer to the key:

public class HashMapDemo {

	public static void main(String[] args) {

		// Combination of String(key) and Integer(value)
		HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

		// Add keys and values (Name, Age)
		employeeAge.put("Tim", 25);
		employeeAge.put("Dong", 26);
		employeeAge.put("Nisha", 29);
		employeeAge.put("Ulana", 34);

		System.out.println("Age of Employees");
		System.out.println(employeeAge);

		// To remove an item, use the remove() method and refer to the key
		employeeAge.remove("Ulana");
		System.out.println("List of Employee after removing Ulana :" + employeeAge);
   }
}

Output
Age of Employees
{Dong=26, Tim=25, Nisha=29, Ulana=34}
List of Employee after removing Ulana :{Dong=26, Tim=25, Nisha=29}

To remove all items, use the clear() method:-

public class HashMapDemo {

	public static void main(String[] args) {

		// Combination of String(key) and Integer(value)
		HashMap<String, Integer> employeeAge = new HashMap<String, Integer>();

		// Add keys and values (Name, Age)
		employeeAge.put("Tim", 25);
		employeeAge.put("Dong", 26);
		employeeAge.put("Nisha", 29);
		employeeAge.put("Ulana", 34);

		System.out.println("Age of Employees");
		System.out.println(employeeAge);

		// To remove all items, use the clear() method:
		employeeAge.clear();
		System.out.println("List of Employes after clear:" + employeeAge);
   }
}

Output
Age of Employees
{Dong=26, Tim=25, Nisha=29, Ulana=34}
List of Employes after clear:{}

Checking whether HashMap is empty or not

We are using isEmpty() method of HashMap class to perform this check.

public class HashMapDemo1 {

	public static void main(String[] args) {

		/* This is how to declare HashMap */
		HashMap<String, String> employeeDetail = new HashMap<String, String>();

		// Add keys and values (Name, Designation)
		employeeDetail.put("Tim", "DBA");
		employeeDetail.put("Dong", "SDET");
		employeeDetail.put("Nisha", "BA");
		employeeDetail.put("Ulana", "Dev");

		System.out.println("Detail of Employees");
		System.out.println(employeeDetail);

		// Checking whether HashMap is empty or not
		System.out.println("Is HashMap Empty? " + employeeDetail.isEmpty());

		// Delete all items from HasMap
		employeeDetail.clear();

		System.out.println("Is HashMap Empty now? " + employeeDetail.isEmpty());
    }
}

Output
Detail of Employees
{Dong=SDET, Tim=DBA, Nisha=BA, Ulana=Dev}
Is HashMap Empty? false
Is HashMap Empty now? true

Check if a particular key exists in HashMap

We will be using containsKey() method of HashMap class to perform this check.  This method returns a boolean value.

public class HashMapDemo1 {

	public static void main(String[] args) {

		/* This is how to declare HashMap */
		HashMap<String, String> employeeDetail = new HashMap<String, String>();

		// Add keys and values (Name, Designation)
		employeeDetail.put("Tim", "DBA");
		employeeDetail.put("Dong", "SDET");
		employeeDetail.put("Nisha", "BA");
		employeeDetail.put("Ulana", "Dev");

		System.out.println("Detail of Employees");
		System.out.println(employeeDetail);

		// Check if a particular key exists in HashMap
		boolean flag = employeeDetail.containsKey("Nisha");
		System.out.println("Key Nisha exists in HashMap? : " + flag);

		boolean flag1 = employeeDetail.containsKey("Shawn");
		System.out.println("Key Shawn exists in HashMap? : " + flag1);
    }
}

Output
Detail of Employees
{Dong=SDET, Tim=DBA, Nisha=BA, Ulana=Dev}
Key Nisha exists in HashMap? : true
Key Shawn exists in HashMap? : false

Check if a particular value exists in HashMap

We will be using containsValue() method of HashMap class to perform this check.

public class HashMapDemo1 {

	public static void main(String[] args) {

		/* This is how to declare HashMap */
		HashMap<String, String> employeeDetail = new HashMap<String, String>();

		// Add keys and values (Name, Designation)
		employeeDetail.put("Tim", "DBA");
		employeeDetail.put("Dong", "SDET");
		employeeDetail.put("Nisha", "BA");
		employeeDetail.put("Ulana", "Dev");

		System.out.println("Detail of Employees");
		System.out.println(employeeDetail);

		// Check if a particular value exists in HashMap
		boolean valueExists = employeeDetail.containsValue("Dev");
		System.out.println("String Dev exists in HashMap? : " + valueExists);

		boolean valueNotExists = employeeDetail.containsValue("Test");
		System.out.println("String Test exists in HashMap? : " + valueNotExists)
    }
}

Output
Detail of Employees
{Dong=SDET, Tim=DBA, Nisha=BA, Ulana=Dev}
String Dev exists in HashMap? : true
String Test exists in HashMap? : false

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to set style in Excel in Java using Apache POI

HOME

In the previous tutorial, I have explained about How to add Formulas in Excel in Java. In this tutorial, I will explain How to customize the style of cells in Excel in Java using Apache POI.

I’m using Apache POI to write data to the excel file. To download and install Apache POI, refer here.

If you are using maven, then you need to add below dependency in pom.xml.

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.0.0</version>
</dependency>
   
   
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.0.0</version>
</dependency>

To know more about various interfaces and classes for managing Excel, please refer to this tutorial.

In the below example, I have an existing excel with the name of “EmployeeDetails.xlsx”.

Steps to Customize the style in Excel

Step 1 – Create a blank work and then a sheet with name Write_TestData.

XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Write_TestData");

Step 2- XSSFWorkbook and XSSFSheet are imported from the below consecutive packages.

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;

Step 3 – Write data to the sheet. To know more about this part, refer this link.

Step 4 – Set the auto Size for column 0.

sheet.autoSizeColumn(0);

Step 5 – To create a cell style, we only need a reference to the excel workbook:

	CellStyle style = workbook.createCellStyle();

Step 6 – CellStyle is imported from package mentioned below.

import org.apache.poi.ss.usermodel.CellStyle;

Step 7 – To create font style and add attributes to this font

XSSFFont font = workbook.createFont();

Step 8 – XSSFFont is imported from below package

import org.apache.poi.xssf.usermodel.XSSFFont;

Step 9 – To set the Background Colour of the cell.

style.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

Step 10 – BackgroundColor and FillPattern are imported from the below consecutive packages.

import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.FillPatternType;

Step 11 – Write data to an OutputStream. Use the below code to write output stream.

FileOutputStream out = new FileOutputStream(new File("Styled_EmployeeDetails.xlsx"));
workbook.write(out);

Below is the complete program to show various cell setyles for Row 0 (Header Row).

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelStyleExample {

	public static void main(String[] args) {

		try {
			// create blank workbook
			XSSFWorkbook workbook = new XSSFWorkbook();

			// Create a blank sheet
			XSSFSheet sheet = workbook.createSheet("Write_TestData");

			ArrayList<Object[]> data = new ArrayList<Object[]>();
			data.add(new String[] { "Name", "Id", "Salary" });
			data.add(new Object[] { "Jim Lawrence", "001A", 10000 });
			data.add(new Object[] { "Jack", "1001B", 40000 });
			data.add(new Object[] { "Tim", "2001C", 20000 });
			data.add(new Object[] { "Gina", "1004S", 30000 });

			// Iterate over data and write to sheet
			int rownum = 0;
			for (Object[] employeeDetails : data) {

				// Create Row
				XSSFRow row = sheet.createRow(rownum++);

				int cellnum = 0;
				for (Object obj : employeeDetails) {

					// Create cell
					XSSFCell cell = row.createCell(cellnum++);

					// Set value to cell
					if (obj instanceof String)
						cell.setCellValue((String) obj);
					else if (obj instanceof Double)
						cell.setCellValue((Double) obj);
					else if (obj instanceof Integer)
						cell.setCellValue((Integer) obj);

					// Set Column width to the maximum for Column 0
					sheet.autoSizeColumn(0);

					if (rownum == 1) {

						CellStyle style = null;

						// Creating a font
						XSSFFont font = workbook.createFont();

						font.setFontHeightInPoints((short) 10);
						font.setFontName("Verdana");
						font.setColor(IndexedColors.BLACK.getIndex());
						font.setBold(true);
						font.setItalic(false);

						// Creating cell Style
						style = workbook.createCellStyle();

						// Setting Foreground Colour
						style.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());
						style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

						// Setting Alignment of font
						style.setAlignment(HorizontalAlignment.CENTER);

						// Setting font to style
						style.setFont(font);

						// Setting cell style
						cell.setCellStyle(style);

					}
				}
			}

			// Write the workbook in file system
			FileOutputStream out = new FileOutputStream(new File("Styled_EmployeeDetails.xlsx"));
			workbook.write(out);

			System.out.println("Style of Excel is updated successfully");

			out.close();

			// Close workbook
			workbook.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

How to add Formulas in Excel in Java

HOME

In the previous tutorial, I have explained How to update data in existing excel in Java. In this Java Excel tutorial, I will explain how to create an Excel with formula in a Java program. Excel is very excellent in calculating formulas. The Apache POI library provides excellent support for working with formulas in Excel.

I’m using Apache POI to write data to the excel file. To download and install Apache POI, refer here.

If you are using maven, then you need to add below dependency in pom.xml.

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.0.0</version>
</dependency>
  
  
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.0.0</version>
</dependency>

To know about various Interfaces and Classes in Excel, please refer this link.

Below are the steps which explain how to add Formulas in Excel.

Step 1 – Create a blank workbook.

XSSFWorkbook workbook = new XSSFWorkbook();

Step 2 – Import XSSFWorkbook from package.

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Step 3 – Create a sheet and pass name of the sheet.

XSSFSheet sheet = workbook.createSheet("Calculate Salary");

Step 4 – Import XSSFSheet from package.

import org.apache.poi.xssf.usermodel.XSSFSheet;

Step 5 – Create a Row. A spreadsheet consists of rows and cells. It has a grid layout. I have created object called Header of XSSFRow.

	XSSFRow header = sheet.createRow(0);

Step 6 – Below syntax create new cells within the row at index 0 and set a string value for the cell.

header.createCell(0).setCellValue("Employee_Name");

Step 7 – Below syntax creates a cell at index 4 and sets formula for cell.

dataRow.createCell(4).setCellFormula("B2+C2+D2");

Step 8 – The following line of code sets formula for the cell at the row #1 and column #5 (remember index is 0-based):

In case the column (Cell) does not exist (but the row does), use the following code.

XSSFRow dataRow = sheet.createRow(1);
dataRow.createCell(5).setCellFormula("SUM(B2:C2)");

In the above line, note that you should make sure that the cell at position (1, 5) does exist, otherwise you get a NullPointerException.

Let us see a program where I have created a cell which contains the formula.

public class FormulaExample {

	public static void main(String[] args) {

		// Create object of XSSFWorkbook class
		XSSFWorkbook workbook = new XSSFWorkbook();

		// Create object of XSSFSheet class
		XSSFSheet sheet = workbook.createSheet("Calculate Salary");

		// Create Header row using XSSFRow class
		XSSFRow header = sheet.createRow(0);
		header.createCell(0).setCellValue("Employee_Name");
		header.createCell(1).setCellValue("Base_Salary");
		header.createCell(2).setCellValue("Variable_Pay");
		header.createCell(3).setCellValue("Other_Benefits");
		header.createCell(4).setCellValue("Total Salary");
		header.createCell(5).setCellValue("Base_Variable Salary");

		XSSFRow dataRow = sheet.createRow(1);
		dataRow.createCell(0).setCellValue("George");
		dataRow.createCell(1).setCellValue(5000);
		dataRow.createCell(2).setCellValue(650);
		dataRow.createCell(3).setCellValue(1200);

		// Set formula
		dataRow.createCell(4).setCellFormula("B2+C2+D2");
		dataRow.createCell(5).setCellFormula("SUM(B2:C2)");

		try {

			// Write the workbook in file system
			FileOutputStream out = new FileOutputStream(new File("Salary_Slip.xlsx"));
			workbook.write(out);
			out.close();
			System.out.println("Excel written successfully.");

		} catch (IOException e) {
			e.printStackTrace();

		}
	}
}

That’s it! Well Done! Cheers!!

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to update existing excel in Java

HOME

In the previous tutorial, I have explained about create a new excel file and write data in that new excel file using Java. In this tutorial, I will explain How to open and update existing excel files in Java.

I’m using Apache POI to write data to the excel file. To download and install Apache POI, refer here.

If you are using maven, then you need to add below dependency in pom.xml.

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.0.0</version>
</dependency>
  
  
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.0.0</version>
</dependency>

To know more about various interfaces and classes for managing Excel, please refer to this tutorial.

In the below example, I have an existing excel with the name of “EmployeeDetails.xlsx”

This is excel which I am going to update. I will add 2 rows below the last row in the excel.

Below is the complete example of updating the data in existing excel. One thing we need to note here is that we can update the excel file only when we close it first.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelFileUpdateExample {

	public static void main(String[] args) {

		try {

			FileInputStream fis = new FileInputStream(new File("EmployeeDetails.xlsx"));

			// Create object of XSSFWorkbook class
			XSSFWorkbook workbook = new XSSFWorkbook(fis);

			// Create object of XSSFWorkbook class
			XSSFSheet sheet = workbook.getSheet("Write_TestData");

			Object[][] bookData = { { "SeleniumTest", "0000A", 9999 }, { "JavaTest", "0000B", 9990 }, };

			// Get last row in Sheet
			int rowCount = sheet.getLastRowNum();

			for (Object[] Book : bookData) {

				// Create row for all the new data
				XSSFRow row = sheet.createRow(++rowCount);

				int columnCount = 0;

				// Create new cell for each row
				XSSFCell cell = row.createCell(columnCount);

				for (Object field : Book) {

					cell = row.createCell(columnCount++);
					if (field instanceof String) {
						cell.setCellValue((String) field);
					} else if (field instanceof Integer) {
						cell.setCellValue((Integer) field);
					}
				}

			}

			fis.close();

			// Write the workbook in file system
			FileOutputStream outputStream = new FileOutputStream("EmployeeDetails.xlsx");
			workbook.write(outputStream);
			System.out.println("Excel is updated successfully");

			// Close the workbook
			workbook.close();
			outputStream.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Below is the updated excel.

Update a specific cell in the Excel file

In the below example, I will update the value in a specific cell. As you can see the above image, I will update 1004S to “Updated Value”. Below is the code snippet for the same.

XSSFCell cell = sheet.getRow(4).getCell(1);

cell.setCellType(CellType.STRING);
cell.setCellValue("Updated Value");

Below is the entire program.

package com.example.seleniumdemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class UpdateExcelDemo {

	public static void main(String[] args) {

		try {

			// Create an object of FileInputStream class to read excel file
			FileInputStream fis = new FileInputStream(new File("EmployeeDetails.xlsx"));

			// Create object of XSSFWorkbook class
			XSSFWorkbook workbook = new XSSFWorkbook(fis);

			// Read excel sheet by sheet name
			XSSFSheet sheet = workbook.getSheet("Write_TestData");

			// Print data present at row 0 column 2
			System.out.println(sheet.getRow(4).getCell(1).getStringCellValue());

			// Get the Cell at index 3 from the above row
			XSSFCell cell = sheet.getRow(4).getCell(1);

			cell.setCellType(CellType.STRING);
			cell.setCellValue("Updated Value");

			// Write the output to the file
			FileOutputStream fileOut = new FileOutputStream(new File("EmployeeDetails.xlsx"));
			workbook.write(fileOut);

			System.out.println("Id column in Excel is updated successfully");
			fileOut.close();

			// Closing the workbook
			workbook.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

That’s it! Well done.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to download and install Apache POI

HOME

This tutorial describes how to download and install Apache POI.

Selenium does not have inbuilt method to read data from Excel File. But, there are various libraries in JAVA which helps in reading/writing data from Excel files. Apache POI is one of the most used libraries, which provides various classes and methods to read/write data from various formats of Excel files(xls, xlsx etc).

What is Apache POI?

Apache POI,  where POI stands for (Poor Obfuscation Implementation)  is the Java API for Microsoft Documents that offers a collection of Java libraries that helps us to read, write, and manipulate different Microsoft files such as excel sheets, power-point, and word files.

Download Apache PO

Step 1 – To download Apache POI, go to its official site, here. Click on the Download as shown in the image. This link will navigate to the page showing the latest release of Apache POI. 

Step 2 – This page shows the latest Apache POI Release Artifacts. Here, you can see POI 5.0.0 is the latest one. Download any one of the Binary Distribution options. One option is .ztar.gz and another option is .zip. I have selected .zip option.

Step 2 – After clicking on the link, it navigates to another page as shown below. I have used highlighted link to download the POI library files.

Step 4 – Once POI.zip is downloaded and extracted, this is how the folder looks like

How to add POI libraries in Eclipse?

Step 1 – Below is the Java project present in Eclipse.

Step 2 – To add POI libraries to this project, Right-click on the project, hover over the Build path, select Configure Build Path.

Step 3 –  It will open the “Properties ” of the project. After that, select the Libraries tab. Finally, click on the Add External JARs as highlighted below.

Step 4 – Select the JARs in the parent folder of the unzipped POI files. Subsequently, click on the Open button to include them in the Eclipse project.

Step 5 – Next, select the JARs under the ooxml-lib folder in the unzipped POI folder as highlighted below:

Step 6 – Select the JARs under the lib folder in the unzipped POI folder as highlighted below.

Step 7 – After that, once all the POI JARs add, click on the Apply and Close button as highlighted below.

Step 8 – Once all the POI libraries successfully install in the Eclipse project, they will reflect under the Referenced Libraries folder in the left pane of the Eclipse project structure, as shown below:

How to add POI libraries to Maven Java Project

You can add the poi and poi-ooxml jar files to the Maven project by mentioning the dependencies in pom.xml.

 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.0.0</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.0.0</version>
</dependency>

You need to make sure that these two dependencies should be of the same version.

That’s it! We have downloaded and installed Apache POI.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to create a Java project in IntelliJ

Home

In the previous tutorial, I have explained how to download and install IntelliJ on Windows. In this tutorial, I will explain about how to create a Java project in IntelliJ.

  1. Open the IntelliJ. It will look as shown below. To create a New Project, click on New Project Icon.

2. Select Project SDK as Java version present on your system and select option as Java. Click on Next button.

3. The next screen provides options to choose Project Template as shown below. Click on the Next Button.

4. I have mentioned Project Name as Java Demo and path where I want to save my project on my computer.

5. Click on the Finish Button to create the project. It will also ask to create the directory as shown below.

6. Click Create button to grant permission. It will launch IDE as shown below.

Now, I have created a new Java Project named as Java Demo. Let me create a new Java Class – HelloWorld.

  1. Expand the Project Hello Word and right-click on the src folder, hover on New Option and click on Java Class Option as shown below.

2. I have provided the Java Filename with the package as shown in below image. Now press Enter Key to create the packages and Java file.

3. It will show a message to Add the File to Git. Depending on your requirement select Add or Cancel. I don’t want to add File to Git, so selected Cancel.

4. I have updated the HelloWorld class to print First Java Class -Hello World on the console as shown in the below image.

5. Now right click on the HelloWorld class file and choose Run HelloWorld.main() Option or press Ctrl + Shift + F10 to compile and execute the program as shown in below image. It will also build the project.

6. The final output of the program will be displayed on the console as shown below.

This is how we can create the Java Demo project to execute our first program in Java – HelloWorld.

That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to install IntelliJ on Windows

HOME

IntelliJ IDEA is one of the smartest IDE for Java development. It’s also the base of the official Android IDE i.e. Android Studio used for Android mobile application development. This tutorial provides all the steps required to install IntelliJ Idea on Windows 10 for Java development.

Download IntelliJ on Windows

  1. Click this link to download IntelliJ IDEA on your machine. It will open the download page as shown below. The IntelliJ IDEA provides two different installers i.e. Ultimate and Community. The Ultimate edition is commercial version (which has trial version for 30 days post which you needs license). The Community edition can be used for free. This tutorial shows the steps required to install the Community edition.

2. Download IntelliJ by clicking on Download button and use any one of the option either .exe or .jar. Below image shows IntelliJ.exe on your machine.

Installation of IntelliJ IDEA

  1. To start installation, double click on the idealC-2021.exe (this version can change in future).

2. It will show the welcome screen as shown below. Click on the Next Button to continue with the installation.

3. It will provide options to choose the installation location as shown in below image. Make sure that you have sufficient space available on the selected drive since it will consume around 1.6 GB storage. Click on the Next Button after choosing the appropriate installation path.

4. It will show the Installation options as shown below to configure system path, create 64-bit desktop launcher icon, Open Folder as Project, and file association for Java, Groovy, and Kotlin files. I have selected the option to create a desktop launcher icon. You may choose the options based on your requirements. Click on the Next Button after choosing the Installation Options.

5. After choosing the Installation Options, the next screen shows options to configure the Start Menu Folder as shown below.

6. Click on the Install Button after selecting the Start Menu Folder option. It will show the installation progress as shown below.

7. It will show the final screen after successfully installing IntelliJ IDEA as shown below.

8. Click on the Finish Button to close the installer. Below image shows that IntelliJ icon is placed at Desktop as we have selected in the previous step.

That’s it! We have downloaded and installed IntelliJ. Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

In the next tutorial, I’ll explain how to create a new project in IntelliJ.

Difference between Abstract Class and Interface

HOME

Abstract Class and Interface are used to achieve Abstraction where abstract methods are declared. We can’t instantiate Abstract Class and Interface.

Abstract ClassInterface
Abstract Class can have both abstract method and
non-abstract methods.
Interface can have only abstract methods.
Abstract Class does not support multiple Inheritance.Interface supports multiple Inheritance.
Abstract Class can be implemented by using keyword “extends”. Interface can be implemented by using keyword “implements”.
Abstract class can provide the implementation of interface.Interface can’t provide the implementation of abstract class.
Abstract Class can have static, non-static, final &
non-final variables.
Interface can have only final & static variables.
Abstract Class can have class members as private, protected, etc.Interface can have class members as public by default.
Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}
An abstract class can extend another Java class and
implement multiple Java interfaces.
An interface can extend another Java interface only.
Abstract keyword is used to declared abstract classInterface keyword is used to declare interface.

Below is an example of Abstract Class. In the below example, there is an abstract class with abstract method. This abstract method is implemented in SubClass.

//Abstract Class
public abstract class Bank {
 
    // Abstract method
    abstract void getRateOfInterest();
}

SubClass

//Subclass (inherit from Bank)
public class SBI extends Bank {
 
    // The body of getRateOfInterest is declared here
    public void getRateOfInterest() {
 
        System.out.println("Interest Rate of SBI Bank :" + 5.3);
 
    }
}


Test Class

public class AbstractionTest {
 
    public static void main(String[] args) {
 
        Bank bank1 = new SBI();
        bank1.getRateOfInterest();
 
    }
 
}

Below is an example of Interface. In the below example, Interface has two abstract methods and the implementation of abstract methods are declared in Test Class.

public interface MyInterface {
 
    // Abstract methods
    public void method1();
 
    public void method2();
}

Test Class

public class InterfaceTest implements MyInterface {
 
    public void method1() {
        System.out.println("Implementation of Method 1");
    }
 
    public void method2() {
        System.out.println("Implementation of Method 2");
    }
 
    public static void main(String[] args) {
        MyInterface interTest = new InterfaceTest();
        interTest.method1();
        interTest.method2();
 
    }
}