Showing posts sorted by date for query how-to-use-final-keyword-in-java-example. Sort by relevance Show all posts
Showing posts sorted by date for query how-to-use-final-keyword-in-java-example. Sort by relevance Show all posts

Friday, March 27, 2020

Difference Betwixt This In Addition To Super Keywords Inward Java

this together with super are ii particular keywords inwards Java, which is used to stand upwardly for electrical flow instance of a shape together with it's super class. Java Programmers often confused betwixt them together with non really familiar alongside in that place particular properties, which is asked at diverse core Java interviews. Influenza A virus subtype H5N1 twosome of questions, which I retrieve virtually this together with super keyword is  that, Can nosotros reassign this inwards Java?  and the difference betwixt this together with super keyword inwards Java. Do yous desire to effort that? Ok, I am non giving the reply now, rather I volition allow yous know the reply at the destination of this post. As I said inwards the root line, the principal divergence betwixt this together with super inwards Java is that this represents electrical flow instance of a class, spell super stand upwardly for electrical flow instance of the bring upwardly class. Now where does this together with super variables used, good yous mightiness direct keep seen examples of calling 1 constructor from other i.e. constructor chaining, that's achieved past times using this together with super keyword? 

You tin role this() to telephone telephone no declaration constructor of same class, spell super() to telephone telephone no declaration or default constructor of bring upwardly class. By the way, telephone telephone is non express to solely no declaration constructor, yous tin telephone telephone whatsoever constructor past times passing appropriate parameters. We volition meet illustration of using this together with super inwards a while. 

Another role of this together with super inwards Java is for accessing instance variables of a shape together with it's parent. By the way, yous tin too access them fifty-fifty without prefixing super together with this, if they are non ambiguous inwards electrical flow block e.g. if in that place is no local variable of same elevate exists inwards that block, only inwards illustration of ambiguity they render explicit reference together with are to a greater extent than readable. 

One of  the classic illustration of using this is within a constructor, which accepts a parameter of same elevate equally an instance variable. In this post, nosotros volition larn virtually to a greater extent than differences betwixt super together with this inwards Java together with convey a await at to a greater extent than or less of the role cases.




Similarities betwixt this together with super

 which is used to stand upwardly for electrical flow instance of a shape together with it Difference betwixt this together with super keywords inwards JavaBefore seeing difference betwixt this together with super keywords inwards Java, let's meet to a greater extent than or less similarities betwixt them :

1) Both this together with super are non static together with tin non live used inwards static context, which agency yous tin non role this together with super keyword within main method inwards Java. Failing to produce then volition upshot inwards compiler mistake "non static variable this tin non live referenced from static context". Same is truthful for using super keyword within principal method.

public static void main(String args[]) {       
     // compiler mistake - non static variable tin non live referenced from static context
     System.out.println(this.name); 

}

2) Both this together with super tin live used inwards constructor chaining to telephone telephone to a greater extent than or less other constructor e.g. this() together with super() respectively calls no declaration constructor of small-scale together with bring upwardly class.

As shown inwards this example, nosotros are root forwarding telephone telephone from no declaration constructor of B, to a constructor which accepts 1 String argument, which farther telephone telephone to super(""), a telephone telephone to super class, 1 declaration constructor.

class A{
   
    A(){
        System.out.println("A's no argument constructor");
    }
   
    A(String args){
        System.out.println("A's one argument constructor");
    }
}
 
class B extends A{
   
   B(){
        this(""); // calling 1 arg constructor of shape B
        System.out.println("B's no argument constructor");
    }
  
   B(String args){
        super(""); // calling 1 declaration constructor of shape A
        System.out.println("B's one argument constructor");
    }
}
 
// Test Class together with Output 
public shape Test {
   
    public static void main(String args[]) {      
       B b = new B();             
    }
 
}
Output:
A's 1 declaration constructor
B's 1 declaration constructor
B's no declaration constructor

3) If used them within constructor than this together with super must live root statement, otherwise compiler volition complain. Which agency yous tin non telephone telephone this() together with super() from same constructor.

Super vs This inwards Java

Now nosotros know how to role super together with this keyword inwards Java, together with comfortable alongside in that place intended use. One role of this keyword, which I didn't shown hither is that yous tin too role them within Inner classes, they are quite handy to acquire reference of outer shape inwards Java, Outer.this together with Outer.super tin live used to acquire electrical flow instance of Outer shape together with it's bring upwardly inwards Java. Don't forget to supersede Outer, alongside the elevate of enclosing class. Now In short, hither are main differences betwixt this together with super keyword inwards Java

1) this is used inwards context of the shape yous are working on, spell super is used to refer electrical flow instance of bring upwardly class.

2) Every constructor past times default calls super(), which is a telephone telephone to no declaration constructor of bring upwardly class, only yous tin nonetheless telephone telephone to a greater extent than or less other constructor either explicitly past times using this() or super().

That's all on difference betwixt this together with super keyword inwards Java together with How to role them inwards a Java program. We direct keep seen calling to a greater extent than or less other constructor from this together with super keyword, together with access fellow member variables from electrical flow together with bring upwardly shape using them. Remember they are really particular variables, together with right away reply of my question, which I asked inwards root paragraph. No, yous tin non assign novel value to this variable, because it's final. You tin effort doing that inwards an IDE, yous volition acquire compiler mistake "can non assign a novel value to lastly variable this".

Further Learning
Complete Java Masterclass
How to kind objects inwards Java using Comparator

Wednesday, December 11, 2019

Why Constructor Is Of Import Inward Java?

In elementary word, Constructor is a method similar a block of code which is called yesteryear Java runtime during object creation using new() operator. Constructor are especial inwards the feel that they conduct maintain the same advert equally the Class they are component of. They are too especial inwards a feel that they are called yesteryear JVM automatically when you lot do an object. Have you lot ever idea well-nigh Why do you lot bespeak a constructor? What benefits it provide? One argue is to initialize your object amongst default or initial state since default values for primitives may non hold out what you lot are looking for. One to a greater extent than argue you lot do constructor is to inform the globe well-nigh dependencies, a course of teaching needs to do its job. Anyone yesteryear looking at your constructors should hold out able to figure out, what he needs inwards guild to usage this class.  For example, next course of teaching OrderProcessor needs a Queue together with Database to run properly.


class OrderProcessor{     Database to;     Queue from;          public OrderProcessor(Queue source, Database target){         this.from = source;         this.to = target;     }          public void process(Message msg) {         // read from Queue         // position to database     }      }
This itself state importance of Constructor, it adds lot on readability together with usability of class. When you lot do an object of OrderProcessor course of teaching e.g. novel OrderProcessor(myQueue, myDatabase), JVM volition telephone telephone this constructor. If you lot don't add together whatever constructor Java yesteryear default add together a default no declaration constructor inwards your class. Constructors too acquire inwards tardily to evidence a course of teaching because fundamentally they follow Dependency Injection. 

It's tardily to do a MockQueue together with MockDatabase to evidence our OrderProcessor class, catch what would conduct house if this course of teaching is calling a Singleton or Service method to acquire its dependency. It would hold out hard to evidence that class. Since object creation is a telephone commutation concept, every Java developer should know how Constructor works, how they initialize an object, how a super course of teaching constructor is called together with hence on. In Next section, nosotros volition encounter how that happens.





How Constructor Works inwards Java

Constructor is special, they comprise a block of code, which executed when you lot do object using novel operator. If your course of teaching has a super course of teaching or raise course of teaching together with then it's constructor volition hold out executed before your class. Similarly, if you lot conduct maintain to a greater extent than than i constructor inwards your class, you lot tin dismiss telephone telephone them from your constructor. spell calling constructor ever scream back that telephone telephone must hold out the root draw inwards constructor, equally shown inwards next instance :
public OrderProcessor(Queue source, Database target){         this.from = source;         this.to = target;     }          public OrderProcessor(){         this(defaultQueue, defaultDatabase);     }
Here no declaration constructor is calling constructor which convey a Queue together with Database. This is known equally constructor chaining together with you lot use this() together with super() to telephone telephone constructor from same course of teaching together with raise class respectively. You tin dismiss usage public, private, protected access modifier amongst constructor or tin dismiss fifty-fifty acquire out them without whatever parameter inwards that instance it volition usage default access, which is at package-private level. Private constructor are special, because if you lot brand your constructor private, together with then no i tin dismiss telephone telephone it from exterior that class, which agency no external way to do instance of that class. This too prevents a course of teaching from beingness subclasses because yesteryear default root draw of constructor has a telephone telephone to super(), no declaration constructor of raise class, if you lot brand that private, it volition non hold out accessible on nestling course of teaching together with compiler volition throw error. Private constructor has closed to other especial use, inwards singleton blueprint pattern, where destination is to give-up the ghost along only i instance of that class. Singleton creates instance yesteryear itself, caches it together with provides a getInstance() method to brand that instance available to exterior world.
UnLike C++ Java doesn't conduct maintain whatever destructor, instead it has finalize method, which is called only before Garbage collector reclaim an eligible object. Also, you cannot brand constructor abstract, synchronized or final, those are illegal keyword for constructor together with using them at that spot volition hold out fault at compile time.  

Some facts well-nigh Constructor inwards Java

There are lot facts well-nigh constructor you lot equally a Java developer should know, this volition assist you lot to read together with empathize existing Java code inwards your arrangement or from whatever opened upwardly source library.

1. Constructor tin dismiss hold out overloaded
This agency you lot tin dismiss conduct maintain to a greater extent than than i constructor inwards your course of teaching (all amongst the same name) until they conduct maintain dissimilar method signature, which comprises type of declaration together with guild type of argument. Here is an instance of constructor overloading. Here nosotros conduct maintain 3 constructors but all amongst a dissimilar laid of parameters, brand certain you lot follow these overloading best practices to avoid introducing tricky bugs inwards your code.
public OrderProcessor(){         this(defaultQueue, defaultDatabase);     }          public OrderProcessor(Queue source, Database target){         this.from = source;         this.to = target;     }          public OrderProcessor(Queue source, Database target, long timeout){         this.from = source;         this.to = target;         this.timeout = timeout;     }

It's amend to position no declaration constructor at the top together with gradually putting a constructor inwards the increasing guild of declaration equally shown above. This too flows nicely when you lot telephone telephone i constructor from other. You tin dismiss encounter the instance of overloaded constructor inwards JDK also, for example, String course of teaching got a couplet of the overloaded constructors, only await their Java documentation.

 Constructor is a method similar a block of code which is called yesteryear Java runtime during objec Why Constructor is Important inwards Java?
2. Constructor tin dismiss hold out chained
Calling i constructor from other is known equally Constructor chaining. You tin dismiss telephone telephone a constructor from same course of teaching or raise class. By default, every constructor calls their raise class' no-argument constructor inwards the root draw e.g super().

3. Call Constructor using this() together with super()
You tin dismiss invoke raise class' constructor using super() together with same course of teaching constructor using this(). Pay attending to the parameter, if you lot don't move yesteryear whatever parameter they volition telephone telephone default constructor amongst no declaration if you lot conduct maintain defined a constructor which accepts parameter you lot tin dismiss telephone telephone them yesteryear passing a parameter of the same type. You're this() or super() constructor invocation must jibe amongst the corresponding constructor inwards same or raise class. It is i of the popular ways to usage this keyword inwards Java.

4. Constructor is non inherited inwards Java
This is an interesting but non-obvious information well-nigh constructor. When you lot do a nestling course of teaching inwards Java, it inherits fellow member variables, non-final together with non-static methods but non constructors. They belong to the course of teaching they are declared.

5. Constructor should conduct maintain the same advert equally Class they belong to
This is a paramount requirement, inwards fact, this is how you lot recognize a constructor together with how you lot differentiate a constructor amongst a regular method. Any method inwards Java cannot conduct maintain the same advert equally their course of teaching because together with then the compiler volition care for them equally a constructor together with since constructor cannot conduct maintain a render type, but the method must have, they volition throw compile fourth dimension error.

6. Constructor doesn't conduct maintain render type
This is closed to other difference betwixt a regular method together with constructor, it cannot conduct maintain a render type, non fifty-fifty void. Any endeavor to position render type volition lawsuit inwards compile fourth dimension error.

7. Static initializer together with instance initializer block are executed before the constructor.
If you lot don't know how a course of teaching is loaded together with initialize, read this. Apparently static initializer is executed at the fourth dimension of course of teaching loading together with instance initializer block of a course of teaching is executed before the constructor of that class, but entirely subsequently successful execution of constructor from the super class. If your raise course of teaching constructor throws an exception together with then instance initialization block volition non execute.

8. Super course of teaching constructor is executed before subclass
This is true, you lot tin dismiss verify this yesteryear creating a course of teaching hierarchy of manly individual raise together with son, hither is an instance , you lot tin dismiss encounter that message from Father's executed is printed before Son constructor gets executed. This is a natural right, Father comes before Son.
public class Test {      public static void main(String args[]){         Son mySon = new Son();  // telephone telephone Father() root together with then Son()                 } }  class Father {          Father(){         System.out.println("Hello Father");     } }  class Son extends Father {     Son(){         System.out.println("Hello Son");     } }  Output Hello Father Hello Son


9.  Construct invocation must hold out inwards fist line
If  you explicitly called closed to other constructor from same course of teaching or raise course of teaching it must hold out the root draw of calling the constructor. As I said earlier, yesteryear default every constructor telephone telephone super(), no declaration constructor raise class. By the way, this is something compiler volition non allow you lot forget hence non to worry well-nigh it :-)

10. Influenza A virus subtype H5N1 constructor tin dismiss non hold out final, abstract or synchronized.
These modifiers are illegal to hold out used amongst a constructor, hence don't seek them. Understanding why constructor cannot hold out final, abstract or synchronized require learning Java specification. It's something overnice to explore yourself.

11. Consider providing No declaration constructor 
Even if you lot add together a parametric constructor, catch adding a no-argument constructor if your course of teaching is intended to hold out used yesteryear reflection or yesteryear a framework e.g. Hibernate, which requires their entity classes to conduct maintain a no declaration constructor hence that framework tin dismiss do their object, to larn to a greater extent than well-nigh why default constructor is of import for a class, encounter that link.

12. Constructor doesn't render anything
You tin dismiss non usage whatever render type including void amongst the constructor, this volition lawsuit inwards compile fourth dimension error. This is i of the major departure which differentiates a regular method to a constructor inwards Java.


That's all well-nigh Constructor inwards Java. We conduct maintain learned why the constructor is important together with how they piece of work inwards Java. nosotros too conduct maintain learned a lot of especial things well-nigh constructor e.g. they must conduct maintain the same name, they cannot conduct maintain render type or constructor cannot hold out made abstract, final or synchronized. In today's framework globe at that spot is ever fence well-nigh constructor vs setter injection. There is 2 grouping of people, i who likes setter based injection together with other who are purist together with usage a constructor, I am from that bit group. IMHO constructor highlights dependency amend than Setter injection together with it too enforces guild of initialization. In fact using constructor has give-up the ghost easier present because you lot tin dismiss usage dependency injection to initialize your classes. If you lot usage opened upwardly sources IOC containers similar Google Guice or Spring framework, it would hold out really tardily to usage together with evidence course of teaching amongst the proper constructor.  I am ready to give-up the ghost amongst constructor only for the fact that a course of teaching amongst constructor highlighting its dependency is much to a greater extent than readable than the i which is initialized yesteryear setter methods.

Further Learning
SOLID Principles of Object Oriented Design
Absolute Introduction to Object Oriented Programming inwards Java
Java - Object Oriented Programming [For Absolute Beginners]

How To Read, Write Xlsx File Inward Coffee - Apach Poi Example

No thing how Microsoft is doing inwards comparing amongst Google, Microsoft Office is nevertheless the most used application inwards software world. Other alternatives similar OpenOffice in addition to LiberOffice have failed to receive got off to challenge MS Office. What this hateful to a Java application developer? Because of huge popularity of MS purpose products yous oft remove to back upwardly Microsoft purpose format such equally word, Excel, PowerPoint in addition to additionally Adobe PDF. If yous are using JSP Servlet, display tag library automatically provides Excel, Word in addition to PDF support. Since JDK doesn't render direct API to read in addition to write Microsoft Excel in addition to Word document, yous receive got to rely on 3rd political party library to attain your job. Fortunately in that place are couplet of opened upwardly origin library exists to read in addition to write Microsoft Office XLS in addition to XLSX file format, Apache POI is the best one. It is widely used, has rigid community back upwardly in addition to it is characteristic rich.

You tin notice lot of examples of how to attain with Excel using Apache POI online, which agency yous volition never experience lonely in addition to has 2d Google back upwardly if yous stuck there. In this article, nosotros volition larn how to read in addition to write excel files inwards Java. As I said, Excel files has ii pop format .XLS (produced past times Microsoft Officer version prior to 2007 e.g. MS Office 2000 in addition to 2003) in addition to .XLSX (created past times Microsoft Office 2007 onwards e.g. MS Office 2010 in addition to 2013).

Fortunately Apache POI supports both format, in addition to yous tin easily create, read, write in addition to update Excel files using this library. It uses price similar workbook, worksheet, cell, row to kicking the bucket on itself aligned amongst Microsoft Excel in addition to that's why it is rattling slowly to use. Apache POI likewise provides unlike implementation classes to grip both XLS in addition to XLSX file format.




One interesting thing amongst POI is that (I don't know whether it's intentional, accidentally or real) it has got about actually funny names for its workbook implementations e.g.
     No thing how Microsoft is doing inwards comparing amongst Google How to Read, Write XLSX File inwards Java - Apach POI Example
  1. XSSF (XML SpreadSheet Format) – Used to reading in addition to writting Open Office XML (XLSX) format files.    
  2. HSSF (Horrible SpreadSheet Format) – Use to read in addition to write Microsoft Excel (XLS) format files.
  3. HWPF (Horrible Word Processor Format) – to read in addition to write Microsoft Word 97 (DOC) format files.
  4. HSMF (Horrible Stupid Mail Format) – pure Java implementation for Microsoft Outlook MSG files
  5. HDGF (Horrible DiaGram Format) – One of the kickoff pure Java implementation for Microsoft Visio binary files.    
  6. HPSF (Horrible Property Set Format) – For reading “Document Summary” information from Microsoft Office files. 
  7. HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
  8. HPBF (Horrible PuBlisher Format) – Apache's pure Java implementation for Microsoft Publisher files.
  9. DDF (Dreadful Drawing Format) – Apache POI packet for decoding the Microsoft Office Drawing format.
It's rattling of import that yous know amount shape of these acronyms, otherwise it would last hard to kicking the bucket on rail of which implementation is for which format. If yous are exclusively concerned nigh reading Excel files hence at-least shout out upwardly XSSF in addition to HSSF classes e.g. XSSFWorkBook in addition to HSSFWorkBook.


How to Read Excel File (XLSX) inwards Java

In our fist illustration nosotros volition learned nigh reading electrical current pop Excel file format i.e. file amongst extension .XLSX. This is a XML spread canvass format in addition to other spreadsheet software similar OpenOffice in addition to LiberOffice likewise exercise this format. In gild to read Excel file, yous remove to kickoff download Apache POI Jar files, without these your code volition neither compiler nor execute. If yous abhor to keep JARs past times yourself, exercise Maven. In Eclipse IDE, yous tin download M2Eclipse plug-in to setup Maven project. Once yous done that, add together next dependencies inwards your pom.xml (project object model) file.
    <dependency>         <groupId>org.apache.poi</groupId>         <artifactId>poi</artifactId>         <version>3.11-beta2</version>     </dependency>

By the way equally Norbert pointed out, The classes for OOXML format (such equally XSSF for reading .xlsx format) are inwards a unlike Jar file. You remove to include the poi-ooxml jounce inwards your project, along amongst the dependencies for it. When yous add poi-ooxml JAR equally dependency via Maven, it volition likewise add together other required dependencies past times itself. For illustration adding below XML snippet inwards pom.xml will download iv JAR files
<dependency>         <groupId>org.apache.poi</groupId>         <artifactId>poi-ooxml</artifactId>         <version>3.11-beta2</version> </dependency>

poi-ooxml-3.11-beta2.jar
poi-ooxml-schemas-3.11-beta2.jar
xmlbeans-2.6.0.jar
stax-api-1.0.1.jar

If yous are non using Maven hence add together next JAR files inwards your Java program's classpath
poi-3.11-beta2.jar
commons-codec-1.9.jar
poi-ooxml-3.11-beta2.jar
poi-ooxml-schemas-3.11-beta2.jar
xmlbeans-2.6.0.jar
stax-api-1.0.1.jar

Here is how our sample Excel 2013 File await like, shout out upwardly this has saved inwards .xlsx format.
 No thing how Microsoft is doing inwards comparing amongst Google How to Read, Write XLSX File inwards Java - Apach POI Example

add together hither is code to read that Excel file. First ii lines are rattling common, they are to read file from file organisation inwards Java, existent code starts from 3rd line. Here nosotros are passing a binary InputStream to create instance of XSSFWorkBook class, which stand upwardly for a Excel workbook. Next describe gives us a worksheet from book, in addition to from in that place nosotros are only going through each row in addition to hence each column. Cell stand upwardly for a block inwards Excel, likewise known equally cell. This is where nosotros read or write data. Cell tin last whatever type e.g. String, numeric or boolean. Before reading value yous must ascertain right type of cell. After that only telephone phone corresponding value method e.g. getStringValue() or getNumericValue() to read information from cell. This how just yous read rows in addition to columns from Excel file inwards Java. You tin encounter nosotros receive got used ii for loop, i to iterate over all rows in addition to inner loop is to kicking the bucket through each column.
 File myFile = new File("C://temp/Employee.xlsx");             FileInputStream fis = new FileInputStream(myFile);              // Finds the workbook instance for XLSX file             XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);                         // Return kickoff canvass from the XLSX workbook             XSSFSheet mySheet = myWorkBook.getSheetAt(0);                         // Get iterator to all the rows inwards electrical current sheet             Iterator<Row> rowIterator = mySheet.iterator();                         // Traversing over each row of XLSX file             while (rowIterator.hasNext()) {                 Row row = rowIterator.next();                  // For each row, iterate through each columns                 Iterator<Cell> cellIterator = row.cellIterator();                 while (cellIterator.hasNext()) {                      Cell jail cellular telephone = cellIterator.next();                      switch (cell.getCellType()) {                     case Cell.CELL_TYPE_STRING:                         System.out.print(cell.getStringCellValue() + "\t");                         break;                     case Cell.CELL_TYPE_NUMERIC:                         System.out.print(cell.getNumericCellValue() + "\t");                         break;                     case Cell.CELL_TYPE_BOOLEAN:                         System.out.print(cell.getBooleanCellValue() + "\t");                         break;                     default :                                       }                 }                 System.out.println("");             }
Let me know if yous receive got problem to sympathise whatever of line. They are rattling elementary in addition to self-explanatory but if yous remove additional detail, only drib us a comment.

How to write XLSX File inwards Java

Writing  into Excel file is likewise similar to reading, The workbook in addition to worksheet classes volition rest same, all yous volition attain is to create novel rows, columns in addition to cells. Once yous are done creating novel rows inwards your Excel file inwards memory, yous remove to opened upwardly an output current to write that information into your Excel File. This volition salve all update yous made inwards existing file or inwards a novel file which is created past times Java's File class. Here is measuring past times measuring code of updating an existing Excel file inwards Java. In kickoff couplet of lines nosotros are creating rows inwards shape of object array in addition to storing them equally value inwards HashMap amongst key equally row number. After that nosotros loop through HashMap in addition to insert each row at the terminate of final row, inwards other give-and-take nosotros are appending rows inwards our Excel file. Just similar earlier reading nosotros remove to create upwardly one's heed type of cell, nosotros likewise remove to attain the same thing earlier writing information into cell. This is done past times using instanceof keyword of Java. Once yous are done amongst appending all rows shape Map to Excel file, salve the file past times opening a FileOutputStream in addition to saving information into file system.
       
           // Now, let's write about information into our XLSX file
            Map<String, Object[]> information = new HashMap<String, Object[]>();             data.put("7", new Object[] {7d, "Sonya", "75K", "SALES", "Rupert"});             data.put("8", new Object[] {8d, "Kris", "85K", "SALES", "Rupert"});             data.put("9", new Object[] {9d, "Dave", "90K", "SALES", "Rupert"});                       // Set to Iterate in addition to add together rows into XLS file             Set<String> newRows = data.keySet();                       // acquire the final row set out to append novel information                       int rownum = mySheet.getLastRowNum();                                for (String key : newRows) {                               // Creating a novel Row inwards existing XLSX sheet                 Row row = mySheet.createRow(rownum++);                 Object [] objArr = data.get(key);                 int cellnum = 0;                 for (Object obj : objArr) {                     Cell jail cellular telephone = row.createCell(cellnum++);                     if (obj instanceof String) {                         cell.setCellValue((String) obj);                     } else if (obj instanceof Boolean) {                         cell.setCellValue((Boolean) obj);                     } else if (obj instanceof Date) {                         cell.setCellValue((Date) obj);                     } else if (obj instanceof Double) {                         cell.setCellValue((Double) obj);                     }                 }             }                       // opened upwardly an OutputStream to salve written information into XLSX file             FileOutputStream bone = new FileOutputStream(myFile);             myWorkBook.write(os);             System.out.println("Writing on XLSX file Finished ...");   Output Writing on XLSX file Finished ...

Here is how our updated Excel file looks afterwards adding 3 to a greater extent than rows
 No thing how Microsoft is doing inwards comparing amongst Google How to Read, Write XLSX File inwards Java - Apach POI Example



How to read Excel (XLS) file inwards Java

Reading XLS file is no unlike than reading an XLSX format file, all yous remove to attain is to exercise right workbook implementation for XLS format e.g. instead of using XSSFWorkbook in addition to XSSFSheet , yous remove to exercise HSSFWorkbook in addition to HSSFSheet classes from Apache POI library.  As I said before, POI has got about actually funny names for unlike XLS formats e.g. Horrible SpreadSheet Format to stand upwardly for sometime Microsoft Excel file format (.xls). Remembering them tin last hard but yous tin ever refer to their online Javadoc. You tin reuse remainder of code given inwards this example, for illustration yous tin exercise same code snippet to iterate over rows, columns in addition to from reading/writing into a exceptional cell. Given they are ii unlike format, about features volition non last available on XLS file processors but all basic materials rest same.


Error in addition to Exception

If yous tumble out to exercise wrong classes e.g. instead of using XSSFWorkbook  to read XLSX file, if yous use HSSFWorkbook then you volition encounter next mistake :

Exception inwards thread "main" org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied information appears to last inwards the Office 2007+ XML. You are calling the component of POI that deals amongst OLE2 Office Documents. You remove to telephone phone a unlike component of POI to procedure this information (eg XSSF instead of HSSF)  at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:131)  at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104)  at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:128)  at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:361)  at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:342)  at App.main(App.java:25)



Java Program to Read/Write Excel Files using Apache POI

Here is our amount Java programme to read/write from existing Excel file inwards Java. If yous are using Eclipse IDE, only create a Java Project, re-create the code in addition to glue it there. No remove to create proper packet structure in addition to Java origin file amongst same name, Eclipse volition receive got aid of that. If yous receive got Maven in addition to Eclipse plugin installed, instead create a Maven Java project, this volition likewise aid yous to download Apache POI Jar files.

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set;  import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook;  /**  * Sample Java programme to read in addition to write Excel file inwards Java using Apache POI  *  */ public class XLSXReaderWriter {      public static void main(String[] args) {          try {             File excel = new File("C://temp/Employee.xlsx");             FileInputStream fis = new FileInputStream(excel);             XSSFWorkbook mass = new XSSFWorkbook(fis);             XSSFSheet canvass = book.getSheetAt(0);              Iterator<Row> itr = sheet.iterator();              // Iterating over Excel file inwards Java             while (itr.hasNext()) {                 Row row = itr.next();                  // Iterating over each column of Excel file                 Iterator<Cell> cellIterator = row.cellIterator();                 while (cellIterator.hasNext()) {                      Cell jail cellular telephone = cellIterator.next();                      switch (cell.getCellType()) {                     case Cell.CELL_TYPE_STRING:                         System.out.print(cell.getStringCellValue() + "\t");                         break;                     case Cell.CELL_TYPE_NUMERIC:                         System.out.print(cell.getNumericCellValue() + "\t");                         break;                     case Cell.CELL_TYPE_BOOLEAN:                         System.out.print(cell.getBooleanCellValue() + "\t");                         break;                     default:                      }                 }                 System.out.println("");             }              // writing information into XLSX file             Map<String, Object[]> newData = new HashMap<String, Object[]>();             newData.put("7", new Object[] { 7d, "Sonya", "75K", "SALES",                     "Rupert" });             newData.put("8", new Object[] { 8d, "Kris", "85K", "SALES",                     "Rupert" });             newData.put("9", new Object[] { 9d, "Dave", "90K", "SALES",                     "Rupert" });              Set<String> newRows = newData.keySet();             int rownum = sheet.getLastRowNum();              for (String key : newRows) {                 Row row = sheet.createRow(rownum++);                 Object[] objArr = newData.get(key);                 int cellnum = 0;                 for (Object obj : objArr) {                     Cell jail cellular telephone = row.createCell(cellnum++);                     if (obj instanceof String) {                         cell.setCellValue((String) obj);                     } else if (obj instanceof Boolean) {                         cell.setCellValue((Boolean) obj);                     } else if (obj instanceof Date) {                         cell.setCellValue((Date) obj);                     } else if (obj instanceof Double) {                         cell.setCellValue((Double) obj);                     }                 }             }              // opened upwardly an OutputStream to salve written information into Excel file             FileOutputStream bone = new FileOutputStream(excel);             book.write(os);             System.out.println("Writing on Excel file Finished ...");              // Close workbook, OutputStream in addition to Excel file to preclude leak             os.close();             book.close();             fis.close();          } catch (FileNotFoundException fe) {             fe.printStackTrace();         } catch (IOException ie) {             ie.printStackTrace();         }     } } Output ID NAME SALARY DEPARTMENT MANGER  1.0 John 70K information technology Steve  2.0 Graham 80K DATA Carl  3.0 Sodhi 60K information technology Ram  4.0 Ram 100K information technology Alex  5.0 Carl 150K DATA Alex  7.0 Sonya 75K SALES Rupert  9.0 Dave 90K SALES Rupert  8.0 Kris 85K SALES Rupert  Writing on Excel file Finished ...

That's all nigh how to read in addition to write Excel file inwards Java. We receive got learned to read/write both XLS and XLSX format inwards Java, which is key to back upwardly sometime Microsoft Excel files created using Microsoft Office version prior to 2007. Though in that place are couplet of other choice libraries to read Excel files from Java program, but Apache POI is the best i in addition to yous should exercise it whenever possible. Let me know if yous human face upwardly whatever employment land running this programme inwards your Eclipse IDE or from ascendance prompt. Just brand for certain to include right ready of JAR inwards your CLASSPATH, alternatively used Maven to download JAR. 

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!