Saturday, 29 August 2015

Read Excel Files In Java Example

If you are using MAVEN you can add these dependencies into your POM.XML file :
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
Below is the excel file :

package com.io.mnb;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadingExcelFile {
public static void main(String[] args) throws IOException {
readExcelFile();
}
public static void readExcelFile() throws IOException {
List<Employee> empList = new ArrayList<Employee>();
File file = new File("EmpData.xls");
Workbook workBook = null;
if (file.getName().contains("xlsx")) {
workBook = new XSSFWorkbook(new FileInputStream(file));
} else {
workBook = new HSSFWorkbook(new FileInputStream(file));
}
Sheet sheet = workBook.getSheet("Emp_Details");
Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
Row row = rows.next();
Employee e = new Employee();
Iterator<Cell> cells = row.cellIterator();
while (cells.hasNext()) {
Cell cell = cells.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
// System.out.print(cell.getNumericCellValue() + "\t");
if (cell.getColumnIndex() == 0)
e.setEmpId((int) cell.getNumericCellValue());
else
e.setEmpSal((int) cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
// System.out.print(cell.getStringCellValue() + "\t");
if (cell.getColumnIndex() == 1)
e.setEmpName(cell.getStringCellValue());
else if (cell.getColumnIndex() == 2)
e.setEmpDesig(cell.getStringCellValue());
else
e.setEmpDept(cell.getStringCellValue());
break;
}
}
// System.out.println("");
empList.add(e);
}
System.out.println("A) Read All employee details form the excel sheet and print it in console");
for (Employee e : empList) {
System.out.println(e);
}
System.out.println("B) Find the employee details who are having salary greater than 10000");
for (Employee e : empList) {
if (e.getEmpSal() > 10000)
System.out.println(e);
}
System.out.println("C) Find the employee details who are having salary between 10000 to 20000");

for (Employee e : empList) {
if (e.getEmpSal() < 20000 && e.getEmpSal() > 10000)
System.out.println(e);
}
Collections.sort(empList, new Employee());
System.out.println("D) Sort the employee names by alphabetical order");
for (Employee e : empList) {
System.out.println(e);
}
}
static class Employee implements Comparator<Employee> {
private int empId;
private String empName;
private String empDesig;
private String empDept;
private int empSal;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpDesig() {
return empDesig;
}
public void setEmpDesig(String empDesig) {
this.empDesig = empDesig;
}
public String getEmpDept() {
return empDept;
}
public void setEmpDept(String empDept) {
this.empDept = empDept;
}
public int getEmpSal() {
return empSal;
}
public void setEmpSal(int empSal) {
this.empSal = empSal;
}
@Override
public String toString() {
return empId + " : " + empName + " : " + empDesig + " : " + 
empDept+ " : " + empSal;
}
@Override
public int compare(Employee o1, Employee o2) {
return o1.empName.compareTo(o2.empName);
}
}
}

Output:
A) Read All employee details form the excel sheet and print it in console
1 : Sachin : SE : Java : 20000
2 : Dhoni : SE : Java : 15000
3 : Rohit : SE : Java : 12000
4 : Kohli : SE : Java : 18000
B) Find the employee details who are having salary greater than 10000
1 : Sachin : SE : Java : 20000
2 : Dhoni : SE : Java : 15000
3 : Rohit : SE : Java : 12000
4 : Kohli : SE : Java : 18000
C) Find the employee details who are having salary between 10000 to 20000
2 : Dhoni : SE : Java : 15000
3 : Rohit : SE : Java : 12000
4 : Kohli : SE : Java : 18000
D) Sort the employee names by alphabetical order
2 : Dhoni : SE : Java : 15000
4 : Kohli : SE : Java : 18000
3 : Rohit : SE : Java : 12000
1 : Sachin : SE : Java : 20000

Saturday, 15 August 2015

How to Find All Permutations of String in Java using Recursion

public class Permutations {

public static void main(String[] args) {
getPermutations("123");
}

public static void getPermutations(String str) {
getPermutations("", str);
}

private static void getPermutations(String prefix, String word) {

if (word == null || word.isEmpty()) {
System.out.println(prefix);
} else {
for (int i = 0; i < word.length(); i++) {
getPermutations(prefix + word.charAt(i), word.substring(0, i) + word.substring(i + 1));

}

}

}
}

Sunday, 9 August 2015

Reading and Writing Files in Java

package com.file.examples;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReadAndWrite {

public static void main(String[] args) {

String filePath = System.getProperty("user.home") + File.separator + "Downloads" + File.separator;
String sCurrentLine;
int lineNo = 1;

try (BufferedReader br = new BufferedReader(new FileReader(filePath + "Madivada.txt"))) {

BufferedWriter writeEven = new BufferedWriter(new FileWriter(filePath + "Naresh_Even.txt"));
BufferedWriter writeOdd = new BufferedWriter(new FileWriter(filePath + "Babu_Odd.txt"));

while ((sCurrentLine = br.readLine()) != null) {

if (lineNo % 2 == 0) {
writeEven.write(sCurrentLine);
writeEven.newLine();

} else {
writeOdd.write(sCurrentLine);
writeOdd.newLine();
}

lineNo++;
System.out.println(sCurrentLine);
}

System.out.println("Total number of lines : " + (lineNo - 1));
writeEven.close();
writeOdd.close();

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

}

}

Saturday, 1 August 2015

Object Cloning in Java

Cloning is a process of creating an exact copy of an existing object in the memory. In java, clone() method of java.lang.Object class is used for cloning process. This method creates an exact copy of an object on which it is called through field-by-field assignment and returns the reference of that object. Not all the objects in java are eligible for cloning process. The objects which implement Cloneable interface are only eligible for cloning process. Cloneable interface is a marker interface which is used to provide the marker to cloning process.

The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

protected Object clone() throws CloneNotSupportedException

CloneNotSupportedException is a checked type of exception. Therefore, you have to keep calling statement to clone() method in try-catch blocks or specify it using throws clause.

clone() method is a protected method. So, you can’t use it outside the class without overriding it.

Shallow Copy In Java :               
                


The default version of clone() method creates the shallow copy of an object. The shallow copy of an object will have exact copy of all the fields of original object. If original object has any references to other objects as fields, then only references of those objects are copied into clone object, copy of those objects are not created. That means any changes made to those objects through clone object will be reflected in original object or vice-versa. Shallow copy is not 100% disjoint from original object. Shallow copy is not 100% independent of original object.

class Course
{
    String subject1;

    String subject2;

    String subject3;

    public Course(String sub1, String sub2, String sub3)
    {
        this.subject1 = sub1;

        this.subject2 = sub2;

        this.subject3 = sub3;
    }
}

class Student implements Cloneable
{
    int id;

    String name;

    Course course;

    public Student(int id, String name, Course course)
    {
        this.id = id;

        this.name = name;

        this.course = course;
    }

    //Default version of clone() method. It creates shallow copy of an object.

    protected Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}

public class ShallowCopyInJava
{
    public static void main(String[] args)
    {
        Course science = new Course("Physics", "Chemistry", "Biology");

        Student student1 = new Student(111, "John", science);

        Student student2 = null;

        try
        {
            //Creating a clone of student1 and assigning it to student2

            student2 = (Student) student1.clone();
        }
        catch (CloneNotSupportedException e)
        {
            e.printStackTrace();
        }

        //Printing the subject3 of 'student1'

        System.out.println(student1.course.subject3);         //Output : Biology

        //Changing the subject3 of 'student2'

        student2.course.subject3 = "Maths";

        //This change will be reflected in original student 'student1'

        System.out.println(student1.course.subject3);       //Output : Maths
    }
}


Deep Copy In Java :
                                                                          

Deep copy of an object will have exact copy of all the fields of original object just like shallow copy. But in additional, if original object has any references to other objects as fields, then copy of those objects are also created by calling clone() method on them. That means clone object and original object will be 100% disjoint. They will be 100% independent of each other. Any changes made to clone object will not be reflected in original object or vice-versa.

class Course implements Cloneable
{
    String subject1;

    String subject2;

    String subject3;

    public Course(String sub1, String sub2, String sub3)
    {
        this.subject1 = sub1;

        this.subject2 = sub2;

        this.subject3 = sub3;
    }

    protected Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}

class Student implements Cloneable
{
    int id;

    String name;

    Course course;

    public Student(int id, String name, Course course)
    {
        this.id = id;

        this.name = name;

        this.course = course;
    }

    //Overriding clone() method to create a deep copy of an object.

    protected Object clone() throws CloneNotSupportedException
    {
        Student student = (Student) super.clone();

        student.course = (Course) course.clone();

        return student;
    }
}

public class DeepCopyInJava
{
    public static void main(String[] args)
    {
        Course science = new Course("Physics", "Chemistry", "Biology");

        Student student1 = new Student(111, "John", science);

        Student student2 = null;

        try
        {
            //Creating a clone of student1 and assigning it to student2

            student2 = (Student) student1.clone();
        }
        catch (CloneNotSupportedException e)
        {
            e.printStackTrace();
        }

        //Printing the subject3 of 'student1'

        System.out.println(student1.course.subject3);         //Output : Biology

        //Changing the subject3 of 'student2'

        student2.course.subject3 = "Maths";

        //This change will not be reflected in original student 'student1'

        System.out.println(student1.course.subject3);       //Output : Biology
    }
}
  • The default implementation of clone() method does shallow copy of an object. This type of copying an object is dangerous and unsecured when an object contains the references to other objects. So. try to avoid the shallow copy by overriding the clone() method.
  • Cloning is an unsecured operation. That why whenever Java run time sees cloning, it expects one marker from the developer. We are providing that marker in the form of Cloneable interface.
  • While cloning, copy of the object is created by field-by-field assignment. No constructor is called while cloning.
Shallow Copy Vs Deep Copy In Java :

Shallow Copy
Deep Copy
Cloned Object and original object are not 100% disjoint.
Cloned Object and original object are 100% disjoint.
Any changes made to cloned object will be reflected in original object or vice versa.
Any changes made to cloned object will not be reflected in original object or vice versa.
Default version of clone method creates the shallow copy of an object.
To create the deep copy of an object, you have to override clone method.
Shallow copy is preferred if an object has only primitive fields.
Deep copy is preferred if an object has references to other objects as fields.
Shallow copy is fast and also less expensive.
Deep copy is slow and very expensive.