Can I Use Java Console Application To Read and Write A String From An Excel File With Deffrences
Can I Use Java Console Application To Read and Write A String From An Excel File With Deffrences
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
Abstraction hides complexity by giving you a more abstract picture, a sort of 10,000 feet
view, while Encapsulation hides internal working so that you can change it later. In other
words, Abstraction hides details at the design level, while Encapsulation hides details at
the implementation level.
For example, when you first describe an object, you talk in more abstract term e.g. a Vehicle
which can move, you don't tell how Vehicle will move, whether it will move by using tires or
it will fly or it will sell. It just moves. This is called Abstraction. We are talking about a most
essential thing, which is moving, rather than focusing on details like moving in plane, sky, or
water.
There are also the different levels of Abstraction and it's good practice that classes should
interact with other classes with the same level of abstraction or higher level of abstraction.
As you increase the level of Abstraction, things start getting simpler and simpler because you
leave out details.
On the other hand, Encapsulation is all about implementation. Its sole purpose is to hide
internal working of objects from outside world so that you can change it later without
impacting outside clients.
For example, we have a HashMap which allows you to store the object using put() method
and retrieve the object using the get() method. How HashMap implements this method
(see here) is an internal detail of HashMap, the client only cares that put stores the object
and get return it back, they are not concerned whether HashMap is using an array, how it is
resolving the collision, whether it is using linked list or binary tree to store object landing on
same bucket etc.
Because of Encapsulation, you can change the internal implementation of HashMap with ease
without impacting clients who are using HashMap. For example, in Java 8,
the java.util.HashMap changes its implementation to use a binary tree instead of
LinkedList to store objects in the same bucket after a certain threshold (see here).
The client doesn't need to make any change to benefit from this code change because those
details are not exposed to them. Had client knows about that i.e. somehow they can get the
reference of the internal array from HashMap, it would not have been possible to change the
implementation without impacting clients.
There are many design principles which are based on Abstraction e.g. "coding for interfaces
then implementation" which helps you to write flexible code in Java or C++. The idea is that
a class depend upon on an interface, a higher level of abstraction than the class, a lower
level of abstraction. This result in flexible code which can work with any implementation of
the interface.
For example, if you need HashMap, your class should depend upon Map instead of HashMap.
Similarly, if you need ArrayList, make sure you should use the List. Thankfully, Uncle Bob
has shared several such design principles on Clean Code, collectively known as SOLID design
principles, which is something every OOP programmer must learn and understand.
1) The most important difference between Abstraction and Encapsulation is that Abstraction
solves the problem at design level while Encapsulation solves it implementation level.
2) Abstraction is about hiding unwanted details while giving out most essential details, while
Encapsulation means hiding the code and data into a single unit e.g. class or method to
protect inner working of an object from outside world. In other words, Abstraction means
extracting common details or generalizing things.
3) Abstraction lets you focus on what the object does instead of how it does, while
Encapsulation means hiding the internal details of how an object works. When you keep
internal working details private, you can change it later with a better method. The Head First
Object Oriented Analysis and Design has some excellent examples of these OOP concepts, I
suggest you read that book at least once to revisit OOP fundamentals.
4) Abstraction focus on outer lookout e.g. moving of vehicle while Encapsulation focuses on
internal working or inner lookout e.g. how exactly the vehicle moves.
5) In Java, Abstraction is supported using interface and abstract class while Encapsulation is
supported using access modifiers e.g. public, private and protected.
Here is a nice table highlighting key differences between Abstraction and Encapsulation in
Object Oriented Programming:
That's all about the difference between Abstraction and Encapsulation in Java and OOP. I
understand, they both seems very similar but as I said they are a totally different concept.
Just remember that Abstraction solves the problem at design level while Encapsulation solves
at the implementation level. Both are very important for an OOP programmer but sometimes
it can be difficult to explain.
As I have said before, the best way to learn and master Object-Oriented programming is by
writing code and reading code of others. The more you are exposed to code, the more you
realize how these concepts work in practice. There are several design principles which are
based in terms of Abstraction e.g. coding for interface rather than implementation which
allows you to write flexible code.
This is another reason why using instance is better because it will minimize confusion. So use
Object when you want to talk about java.lang.Object and use instance when you want to
talk about the object of OOPS. Let's take a look more closely in next section.
Object vs Instances
The basic concept of Object Oriented Programming (OOP) revolves around two things, Class,
and Object. The class is the blueprint. The Object is an actual thing that is made up using that
'blueprint' (like the car example given above). You cannot see the instances, all you see is
code, which is your class. Object or instance are created at run-time and they are created in a
specific memory area called heap memory.
Each instance consumes some memory depending upon how much and what value you store.
For example "Java" is an instance of String class and holds memory required to represent those
characters and to store some metadata. You might have also heard about class method vs
instance methods, right? look we hardly call object method.
There is no harm calling instance as an object but if you are following rest of Java convention
then why not this one. Do you call Java method function? No right, then there is no point calling
instance as an object, it will just create confusion nothing more.
If you are senior Java developer or a trainer then it's your responsibility to pass right terminology
to junior developers. Whatever they will hear from you, it will go a long way, so make sure you
feed clear and concise information.
That's all about the difference between Object and Instance in Java. In general, it’s better to
treat instance and object as the same thing to avoid confusion, but if you follow Java
convention, better call them instance. By the way no matter, what you do; people will use it as
per their convenience and you can't argue with everyone that, no you are talking about the
instance, please use instance word, or, No, you are talking about an actual object, please use
object word etc. I would derive explanation based upon context. In short, use Object to talk
about java.lang.Object class and use instance to talk about the object of OOP.
Difference between Polymorphism and Inheritance in Java
and OOP
Programmers often confused among different object-oriented concepts e.g. between
Composition and Inheritance, between abstraction and encapsulationand sometime
between Polymorphism and Inheritance. In this article, we will explore third one, Polymorphism
vs Inheritance. Like in the real world, Inheritance is used to define the relationship between two
classes. It's similar to Father-Son relationship. In object-oriented programming, we have a
Parent class (also known as the superclass) and a Child class (also known as the subclass).
Similar to the real world, Child inherits Parents qualities, e.g. it's attribute, methods, and code.
Inheritance is actually meant for code-reuse. A child can reuse all the codes written in Parent
class, and only write code for behavior which is different than the parent. Though it’s possible to
restrict something to parent itself by using the privateand final keyword in Java.On the other
hand, Polymorphism is an ability of Object to behave in multiple forms.
For example, a Parent variable can hold a reference of either a Parent object or a Child object,
so when you call a virtual method on Parent's object, it may go to child's method depending
upon which kind of object it is pointing at runtime. This is known as Polymorphism, and one of
the most popular forms of Polymorphism is method overriding in Java.
By the way, If you look closely they are actually related to each other, because its Inheritance
which makes Polymorphism possible, without any relationship between two class, it's not
possible to write polymorphic code, which can take advantage of runtime binding of different
objects.
You cannot use Polymorphism on something which is not inherited by Child class e.g. private
method can't be overridden in Java. Let's take an example to understand difference between
Polymorphism and Inheritance in Java more closely.
Code of Polymorphism vs Inheritance in Java
Below code is good example of How Inheritance and Polymorphism works. In Java,
polymorphism is type based, in order to write polymorphic code, you need to create a Type
hierarchy, which is achieved using Inheritance. In this example, we have abstract class to
represent a Connection and we have two sub-classes TCP and UDP. All three are related to
each other via Inheritance, Connection is Parent while TCP and UDP are Child classes. Now any
code, which is based upon Connection will be polymorphic and can behave differently based
upon whether actual connection is of type TCP or UDP. This Polymorphism magic is constructed
by method overriding in Java, but its the principle of programming for interfaces than
implementation, which motivates to write polymorphic code. Why you should write Polymorphic
code?Simple to be flexible, to accommodate change and to take advantage of evolution on later
stage of development. A static code is fixed when written, but a Polymorphic code can evolve.
/**
* Base class to represent a Connection.
*/
public abstract class Connection{
protected String data;
@Override
public void connect() {
System.out.println("Connection reliably but slow ..");
}
}
@Override
public void connect(){
System.out.println("Connecting fast but no guarantee of data
delivery");
}
}
Output:
Connection reliably but slow ..
In short here are key difference between Polymorphism and Inheritance in Java :
1) Inheritance defines father-son relationship between two classes, While Polymorphism take
advantage of that relationship to add dynamic behaviour in your code.
2) Inheritance is meant for code reuse, initial idea is to reuse what is written inside Parent class
and only write code for new function or behaviour in Child class. On the other hand
Polymorphism allows Child to redefine already defined behaviour inside parent class. Without
Polymorphism it's not possible for a Child to execute its own behaviour while represented by a
Parent reference variable, but with Polymorphism he can do that.
3) Polymorphism helps tremendously during Maintenance. In fact many object oriented design
principles are based on Polymorphism e.g. programming for interface then implementation,
which advocates to use interface everywhere in your code, to represent variable, in method
parameters, in return type of method etc; so that code can take advantage of polymorphism and
do more than what was expected it to do during writing.
4) Java doesn't allow multiple inheritance of classes, but allows multiple inheritance of Interface,
which is actually require to implement Polymorphism. For example a Class can
be Runnable, Comparatorand Serializable at same time, because all three are
interfaces. This makes them to pass around in code e.g. you can pass instance of this class to a
method which accepts Serializable, or to Collections.sort() which accepts a Comparator.
5) Both Polymorphism and Inheritance allow Object oriented programs to evolve. For example,
by using Inheritance you can define new user types in an Authentication System and by using
Polymorphism you can take advantage of already written authentication code.
Since, Inheritance guarantees minimum base class behaviour, a method depending upon super
class or super interface can still accept object of base class and can authenticate it.
6) In UML diagram, Inheritance is represented using arrows, pointing towards Parent class. For
example in this diagram, AbstractPerson is Parent class
for Employee, Manager and CustomerContact class.
That's all about difference between Inheritance and Polymorphism in Java. Though they are
different thing but not orthogonally, in fact they work together to give Object oriented
programming its true power. Because of Inheritance and Polymorphism, your object oriented
code can do a lot more than what is expected from it initially. It allows your software to grow,
evolve and meet needs of future, an important characteristic of any software.
On the other hand, State design pattern allows an object to behave differently at different
state. Since real world object often has state, and they behave differently at different state,
e.g. a Vending Machine only vend items if it's in hasCoin state, it will not vend until you put
the coin on it.
You can now clearly see the difference between Strategy and State pattern, there intent is
different. State pattern helps object to manage state, while Strategy pattern allows client to
choose different behaviour. Another difference, which is not easily visible is, who drives
change in behaviour.
In case of Strategy pattern, it's client, which provides different strategy to Context, on State
pattern, state transition is managed by Context or State itself. Also, if you are managing
state transition in State object itself, it must hold reference of Context e.g. Vending Machine,
so that it can call setState() method to change current state of Context.
On the other hand, Strategy object never held reference of Context, it's client which passes
Strategy of there choice to Context. As difference between state and strategy pattern is one
of the popular Java design pattern question on Interviews.
In this Java design pattern article, we will take a closer look on this. We will explore some
similarity and difference between Strategy and State design pattern in Java, which will help
to improve your understanding on both of these patterns.
This UML diagram is for state design pattern, drawn for a classic problem of creating object
oriented design of Vending Machine in Java. You can see that State of Vending Machine is
represented using an interface, which further has implementation to represent concrete
state. Each state also holds reference of Context object to make transition to another state
due to action triggered by Context.
UML Diagram of Strategy Pattern in Java
This UML diagram is for strategy design pattern, implementing sorting functionality. Since
there are many sorting algorithm, this design pattern lets client choose the algorithm while
sorting objects. In fact, Java Collection framework make use of this pattern to
implement Collections.sort() method, which is used to sort objects in Java. Only
difference is instead of allowing client to choose sorting algorithm, they allow them to specify
comparison strategy by passing instance of Comparator or Comparable interface in Java.
Let's see couple of more similarities between these two core Java design patterns :
1) Both State and Strategy Pattern makes it easy to add new state and strategy, without
affecting Context object, which uses them.
2) Both of them, makes your code follow open closed design principle, i.e. your design will be
open for extension but closed for modification. In case of State and Strategy pattern,
Context object is closed for modification, introduction of new State or new Strategy, either
you don't need to to modify Context of other state, or minimal changes are required.
3) Just like Context object is started with a initial state in State design Pattern, a Context
object also has a default strategy in case of Strategy pattern in Java.
4) State pattern wraps different behaviour in form of different State object, while Strategy
pattern wraps different behaviour in form of different Strategy object.
5) Both Strategy and State Patterns relies on sub classes to implement behaviour. Every
concrete strategy extends from an Abstract Strategy, each State is sub class of interface or
abstract class used to represent State.
Difference between Strategy and State Pattern in Java
So now we know that State and Strategy are similar in structure and there intent are
different. Let's revisit some of the key difference between these design patterns.
1) Strategy Pattern encapsulate a set of related algorithms, and allow client to use
interchangeable behaviours though composition and delegation at runtime, On the other hand
State pattern helps a class to exhibit different behaviours in different state.
2) Another difference between State and Strategy Patten is that, State encapsulate state of
an Object, while Strategy Pattern encapsulate an algorithm or strategy. Since states are
cohesively associated with object, it can not be reused, but by separating strategy or
algorithm from it's context, we can make them reusable.
3) In State pattern, individual state can contain reference of Context, to implement state
transitions, but Strategies doesn't contain reference of Context, where they are used.
4) Strategy implementations can be passed as parameter to there the Object which uses them
e.g. Collections.sort() accepts a Comparator, which is a strategy. On the other hand
state is part of context object itself, and over time, context object transitions from one State
to other.
5) Though both Strategy and State follows Open closed design principle, Strategy also follow
Single Responsibility principle, Since every Strategy encapsulate individual algorithm,
different strategies are independent to each other. A change in one strategy, doesn't order a
change in another strategy.
6) One more theoretical difference between Strategy and State pattern is that former defines
"How" part of an Object e.g. How a Sorting object sorts data, One the other hand State
Pattern defines "what" and "when" part of Object e.g. What can an object, when it's on
certain state.
7) Order of State transition is well defined in State pattern, there is no such requirement for
Strategy pattern. Client is free to choose any Strategy implementation of his choice.
8) Some of the common example of Strategy Pattern is to encapsulate algorithms e.g. sorting
algorithms, encryption algorithm or compression algorithm. If you see, your code needs to use
different kind of related algorithms, than think of using Strategy pattern. On the other hand,
recognizing use of State design pattern is pretty easy, if you need to manage state and state
transition, without lots of nested conditional statement, state pattern is the pattern to use.
9) Last but one of the most important difference between State and Strategy pattern is that,
change in Strategy is done by Client, but Change in State can be done by Context or State
object itself.
That's all on difference between State and Strategy Pattern in Java. As I said, they both
look similar in there class and UML diagrams, both of them enforces Open Closed design
principle and encapsulate behaviours. Use Strategy design pattern, to encapsulate algorithm
or strategy, which is provided to Context at runtime, may be as parameter or composed
object and use State pattern for managing state transitions in Java.
Further Learning
Design Pattern Library
SOLID Principles of Object Oriented Design
Head First Design Pattern
On the other hand, private, static and final methods are resolved at compile time, because
compiler knows that they can't be overridden and only possible methods are those, which are
defined inside a class, whose reference variable is used to call this method.
This is known as static or compile time binding, all private, static and final methods are
resolved using static binding. This concept is also closely related to method
overloading and method overriding.
As dynamic binding happens when method overriding is possibility and overloaded method calls
are resolved at compile time, because they are always defined in same class.
In this article, we will learn few more difference between Static and Dynamic Binding in
Java, but before this let's see couple of examples of static and dynamic binding :
Static vs Dynamic Binding in Java
Following Java program will help you to understand difference between static and dynamic
binding in Java. In below example, we have two class Parent and Child, where Child is
sub-class of Parent. In superclass we have three methods, one private, one static and one
virtual, similarly on child class we have defined all those three methods, with exact same name
and syntax.
Since private and static method can not be overridden, they simply hide super class
implementation. Only virtual method can be overridden and those will be resolved using
dynamic binding. Test code is written in a test class called, HelloAndroid, where a reference
variable of type Parent is pointing to object of Child class.
This reference variable is then used to call static method whoAmI(), and virtual
method whoAreYou(), defined on both super and sub class, and since we can not call private
method from outside the class, it is internally called inside virtual method. Now let's analyse
output of first call p.whoAmI() , it prints "Inside static method, Parent#whoAmI()" which
means static method from Parent class is invoked and object is not used in method resolution,
only type is used. This is example of static binding in Java.
On the other hand, call to virtual method i.e. p.whoAreYou() prints two
lines Child#who and Child#whoAreYou, which means virtual method from subclass is
invoked, which also invoked private method from sub-class, not from super class, because its
not accessible. This is an example of dynamic binding in Java, and it uses actual object for
method resolution.
/**
* Java program to show difference between static and dynamic binding in
Java.
* Static method are resolved at compile time, by Type of reference variable,
* while Virtual methods are resolved at runtime, depending upon actual
object.
*
* @author WINDOWS 8
*
*/
public class HelloAndroid {
class Parent {
@Override
public void whoAreYou(){
who();
System.out.println("Child#whoAreYou()");
}
}
Output:
Inside static method, Parent#whoAmI()
Child#who()
Child#whoAreYou()
In short following are key differences between Static and Dynamic binding in Java :
1) Static binding is resolved at compile time, while Dynamic binding is resolved at runtime.
2) Static binding only uses Type information, and method resolution is based upon type of
reference variable, while dynamic or late binding resolves method based upon actual object.
3) In Java programming language, private, static and final method are resolved using
static binding, while only virtual methods are resolved using dynamic binding.
4) True Polymorphism is achieved using dynamic binding, and its key of many design principles
e.g. Strategy pattern, Open closed design pattern etc.
That's all about difference between static and dynamic binding in Java. You can play around
this code to try different combination of method calling e.g. calling a sub class method using
Super class object or vice-versa. Let me know if you have question related to understanding
static or dynamic binding in Java.
Everything in this blog post is false. You are only semantically right, kind of. Let me quote the latest
(Java SE 8) Virtual Machine specification (page 367):
"For example, a Java Virtual Machine implementation may choose to resolve each
symbolic reference in a class or interface individually when it is used ('lazy'
or 'late' resolution), or to resolve them all at once when the class is being
verified ('eager' or 'static' resolution). This means that the resolution process may
continue, in some implementations, after a class or interface has been initialized."
You can write different OLE formats using poi-3.12.jar for example you can also use this JAR
to read Microsoft Word files witch .DOC extension and Microsoft PowerPoint files with .PPT
extension in Java. Similarly you can read other OpenXML format e.g. DOCX and PPTX
using poi-ooxml-3.12.jar file. It's very important to understand which JAR files you need
to read which kind of Excel files in Java, because classes used to read different Excel file
format are different e.g. to read old Excel file format i.e. XLS files you
need HSSFWorkbook class, which is inside poi-XX.jar, while class used to read current
Excel file format i.e. XLSX file is XSSFWorkbook, which is inside poi-ooxml.jar library.
If you are using Maven then include following two dependencies to use Apache POI in your
Java program :
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
</dependencies>
Main advantage of using Maven is that it not only downloads direct dependency e.g.
poi.jarand poi-ooxml.jar but also download transitive dependency e.g. JARS on which
POI library is internally dependent. For example, I have just specified Apache POI JAR files
but Maven will also download xmlbeans-2.6.0.jar, stax-api-1.0.1.jar, poi-ooxml-
schemas-3.12.jar and commons-codec-1.9.jar.
JAR Dependencies :
If you are more comfortable by downloading JAR files by yourself, you can download Apache
POI JARS from here . This will download whole bundle so you don't need to worry, but make
sure it contains following JAR files if your application is going to support both XLS and XLSX
format.
poi-3.12.jar
commons-codec-1.9.jar
poi-ooxml-3.12.jar
poi-ooxml-schemas-3.12.jar
xmlbeans-2.6.0.jar
stax-api-1.0.1.jar
POI is for reading OLE format e.g. XLS, DOC and .PPT format, while poi-ooxml.jar is to read
XLSX, DOCX and .PPTX format. Don't download just POI jar, always include transitive
dependency. For example, if you include just poi-3.12.jar then your program will compile fine
because you are not using transitive dependency e.g. xmlbeans directly but it will fail at
runtime with error like java.lang.NoClassDefFoundError:
org/apache/xmlbeans/XmlObjectbecause of missing xmlbeans.jar dependency.
In our example, we will create an excel file which contains one row and two columns. First
column will contain a String type, where we will store name and second column will be of
date type, where we will date of birth. Later, we will read the same excel file in our Java
program to display name and date values in to console. In order to read an excel file in Java,
it must be in classpath. In order to avoid issues, I will use Eclipse IDE to write this program
and it will create excel file in Eclipse's project directly, which always remain in classpath.
These steps are fine for writing String and Numeric values but in order to write date values
into Excel file, you need to follow following more steps :
Create a DataFormat
Create a CellStyle
Set format into CellStyle
Set CellStyle into Cell
Write java.util.Date into Cell
If you are reading date values then just one more thing to remember that there is no cell with
date type and Excel stores date as numeric type. So always compare type of a cell with date
value to a numeric cell type.
In this program, reading and writing logic are encapsulated into two static utility
method readFromExcel() and writeIntoExcel(), so you can also take a look at them
for exact code for reading writing XLS file in Java.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
/**
* Simple Java Program to read and write dates from Excel file in Java.
* This example particularly read Excel file in OLE format i.e.
* Excel file with extension .xls, also known as XLS files.
*
* @author WINDOWS 8
*
*/
public class ExcelDateReader {
/**
* Java method to read dates from Excel file in Java.
* This method read value from .XLS file, which is an OLE
* format.
*
* @param file
* @throws IOException
*/
public static void readFromExcel(String file) throws IOException{
HSSFWorkbook myExcelBook = new HSSFWorkbook(new
FileInputStream(file));
HSSFSheet myExcelSheet = myExcelBook.getSheet("Birthdays");
HSSFRow row = myExcelSheet.getRow(0);
if(row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_STRING){
String name = row.getCell(0).getStringCellValue();
System.out.println("name : " + name);
}
if(row.getCell(1).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
Date birthdate = row.getCell(1).getDateCellValue();
System.out.println("birthdate :" + birthdate);
}
myExcelBook.close();
/**
* Java method to write dates from Excel file in Java.
* This method write value into .XLS file in Java.
* @param file, name of excel file to write.
* @throws IOException
* @throws FileNotFoundException
*/
@SuppressWarnings("deprecation")
public static void writeIntoExcel(String file) throws
FileNotFoundException, IOException{
Workbook book = new HSSFWorkbook();
Sheet sheet = book.createSheet("Birthdays");
// auto-resizing columns
sheet.autoSizeColumn(1);
In our program, we have first created excel file with String and date columns and later read
from the same file and displayed the values into console. Now let's verify output of this
program. It's correctly display the date value, though not formatted, which means excel file
was created successfully and later Java was able to read from it. If you look at your Eclipse
project directory, you will find birthdays.xls file created there, if you open that with
Microsoft Excel or any Open Office editor, you will see following output.
This is because I haven't included sheet.autoSizeColumn(1) method call in first run and
since column width is not enough to display the date in requested format e.g. dd.mm.yyyy it
just displays ######. In order to solve this problem of date not displaying properly, all you
need to do is enable autosizing of columns in Excel by
calling sheet.autoSizeColumn(1)method, where column index is the column you want to
resize automatically. If you run the program again with that code, you can see the date
values properly formatted and fitted in requested column, as shown below
Apache POI Example to read XLSX file in Java
Reading and writing into new excel file format XLSX is also same, all you need to do is
include poi-ooxml.jar and replace all HSFF classes with XSSF classes e.g. instead of
using HSSFWorkbook, use XSSFWorkbook, instead of using HSFFSheet use XSSFSheet,
instead of using HSSFRow use XSSFRow and instead of using HSSFCell just
use XSSFCell class. Rest of the code and steps will be same. In following Java program, I
will show you how to read XLSX file in Java. In this program also we are first creating an excel
file and writing string and date values into it and later reading from same excel file and
displaying data into console, only difference this time would be instead of creating an XLS
file, our program will create an XLSX file. Once you run this program in your Eclipse IDE, you
can see the birthdays.xlsx file created in your Eclipse Project directory, as shown below :
here is our java program to read XLSX files using Apache POI library.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
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.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* This program read date values from XLSX file in Java using Apache POI.
*
* @author WINDOWS 8
*
*/
public class ExcelDateReader {
if(row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_STRING){
String name = row.getCell(0).getStringCellValue();
System.out.println("NAME : " + name);
}
if(row.getCell(1).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
Date birthdate = row.getCell(1).getDateCellValue();
System.out.println("DOB :" + birthdate);
}
myExcelBook.close();
}
@SuppressWarnings("deprecation")
public static void writeIntoExcel(String file) throws
FileNotFoundException, IOException{
Workbook book = new XSSFWorkbook();
Sheet sheet = book.createSheet("Birthdays");
Row row = sheet.createRow(0);
sheet.autoSizeColumn(1);
book.write(new FileOutputStream(file));
book.close();
}
}
NAME : Gokul
DOB :Tue Nov 10 00:00:00 GMT+08:00 2015
That's all about how to read and write from Excel file in Java. You have now learned how
to read and write both String and Date from XLS as well as XLSX file in Java. You can do a lot
more using Apache POI library but this guide will help you learn and quickly use this library.
Once again I suggest to use Maven for including POI dependency and if you are downloading
JAR, make sure you download transitive dependency e.g. xmlbeans.
What is difference between Overloading and Overriding in
Java
Overloading vs Overriding in Java
In last couple of articles we have seen What is method overloading and What is method
overriding in Java and now we will see What is difference between overloading and overriding in
Java. Overloading vs overriding is one of those frequently asked Java interview question which
can not be ignored. Overloading vs Overriding has appeared in almost every Java interview,
mostly at beginner and intermediate level e.g. 2 to 4 years experience. In fact most of
those tricky Java interview Question came from Overloading and Overriding. It's one of the
tricky fundamental to understand. In this article we will some important difference between
Overloading and Overriding which not only help to understand concept better but also serves as
good recap for Java interviews.
Here are some of the most common differences between both of them. If you are
working in Java for more than 1 year, you might be familiar with all of them but any way its good
revision :
1) First and major difference between Overloading and Overriding is that former occur
during compile time while later occur during runtime.
2) Second difference between Overloading and Overriding is that, you can overload method in
same class but you can only override method in sub class.
3) Third difference is that you can overload static method in Java but you can not override static
method in Java. In fact when you declare same method in Sub Class it's known as method
hiding because it hide super class method instead of overriding it.
4) Overloaded methods are bonded using static binding and Type of reference variable is used,
while Overridden method are bonded using dynamic bonding based upon actual Object.
5) Rules of Overloading and Overriding is different in Java. In order to overload a method you
need to change its method signature but that is not required for overriding any method in Java.
6) Another difference between method overloading and overriding is that private and final
method can not be overridden but can be overloaded in Java.
7) Overloaded method are fast as compare to Overridden method in Java.
That's all on Difference between method overloading and overriding in Java. Apart from rules of
overloading and overriding, these are some important differences which is worth remembering
while overloading or overriding any method in Java.
Someone asked me What are the difference between Polymorphism and Overriding in Java and
the similar difference between Polymorphism and Overloading. Well, they are not two different
things, Polymorphismis an object oriented or OOPS concept like Abstraction, Encapsulation or
Inheritance which facilitate the use of the interface and allows Java program to take advantage
of dynamic binding in Java. Polymorphism is also a way through which a Type can behave
differently than expected based upon which kind of Object it is pointing. Overloading and
overriding are two forms of Polymorphism available in Java.
Both overloading and the overriding concept are applied on methods in Java.
Since polymorphismliterally means taking multiple forms, So even though you have the name
of the method same in the case of overloading and overriding, an actual method called can be
any of those multiple methods with the same name. Let's see some more details on method
overloading and overriding to understand how polymorphism relates to overloading and
overriding and How they are different.
Polymorphism vs Overriding
Overriding is a form of polymorphism which is used in Java to dynamically bind method from the
subclass in response to a method call from sub class object referenced by superclass type.
Method overriding is bonded using dynamic binding in Java.
Suppose you have two methods size() in both base class and derived class and Base class
variable is pointing to an object which happens to be subclass object at runtime then method
from subclass will be called, i.e. overridden method will be called.
This allows to program for interface than implementation, a popular OOPS design
principle because Polymorphism guarantees to invoke correct method based upon the object.
Method overriding is key for much flexible design pattern in Java.
See What is method overriding in Java and Rules of method Overriding for examples and more
details.
Polymorphism vs Overloading
Method overloading is another form of Polymorphism though some people argue against that. In
the case of overloading, you also got multiple methods with the same name but different method
signature but a call to correct method is resolved at compile time using static binding in Java.
Overloading is a compile time activity oppose to Overriding which is runtime activity. Because of
this reason overloading is faster than method overriding in Java. Though beware with an
overloaded method which creates conflict e.g. methods with only one parameter e.g. int and
long etc. See What are method overloading in Java for example and complete details.
Let's see a short example of Polymorphism in Java. In this example, Pet variable
behaves polymorphic because it can be either Cat or Dog. this is also an example of method
overriding because makeSound() method is overridden in subclass Dog and Cat.
import java.util.ArrayList;
import java.util.List;
@Override
public void makeSound() {
System.out.println("Meow");
}
}
@Override
public void makeSound() {
System.out.println("Woof");
}
/**
*
* Java program to demonstrate What is Polymorphism
* @author Javin Paul
*/
public class PolymorphismDemo{
}
}
Output:
Meow
Woof
In Summary, you can not compare Polymorphism with method overloading or override.
Polymorphism is the ability of a variable to behave differently based upon which kind of Object it
is referring. They are Java programming language's way to implement polymorphism in
language.
Point is to understand the difference between class and object, not to mug up for an interview,
Why? because if you know your class and object, it would be lot easy for you to work with an
object oriented programming language like Java or C#.
To give you some more example of class and object, if Car is a class
than Merc, Audi and BMW are objects. If Television is class than Sony Bravia, Samsung Smart
tv are its object.
If Smartphone is a class then iPhone, Samsung Galaxy and Nokia Lumia are their object. In an
object oriented application, generally nouns are represented using class, for example in finance
domain Order, Trade, Instruments are classes.
1) A class is what you create while coding, but object is created at runtime by your execution
environment e.g. JVM. Though you write code, which is required to create object during coding
e.g. new Student(), object is not created at that time. They are only created when you run
your program, and when runtime executes that line. Usually constructor of a class is called
when an object is created in Java, but yes there are some anomalies as well e.g. Serialization.
2) Most important difference between class and object is that an Object usually has state
(though stateless object is also possible). This is used to differentiate with another object. For
example, If you have a class to represent Student, then John and Mohan are two object of
that class, which has different name, an attribute which differentiate them. A picture is worth
more than 1000 words, and difference between class and object can be best explained by this
image :
Here Player is a class which is actually the blueprint of creating players and two players
Scooby and Tabby are objects which is created by runtime environment, Java Virtual Machine
in this case. Each Player has different value for their attribute, also known as state of Object.
For example Scooy's position is 5th and has $341, while Tabby's position is 18th and has $87.
If you still doesn't quite get difference between Class and Object then here is one more
example, which you might find more interesting then this one.
Here CookieCutter is a class which is a blueprint to create objects, the cookies. You can see
we have two cookies here, one for you and one for me :)
3) Though Java is not pure Object oriented language, most of things are object in Java, for
example primitive variables and operator are not object. In Java, objects are created on a
special memory area, known as heap memory. No matter on which scope you create them e.g.
locally or globally they are always created in heap space. On the other hand, classes are loaded
into another special area of JVM memory, known as permgen space. From Java 8 onward, this
space is also known as metaspace. You can create as many object from a class as you want,
subject to your heap memory limit, because each object takes some memory. Once all the
memory is exhausted, you can not create any more object and JVM will
throw java.lang.OutOfMemoryError: Java Heap Space if you further try to create object.
4) Object's are also known as instances in Java programming language, and in JVM class is
also represented by an instance of java.lang.Class. On the other hand class is also know
as type. A reference variable which holds reference of an object have a type, which denotes
what kind of object it can reference. For example in following code ConstructorDemo is name
of the class, known as type here, cd is a reference variable of type ConstructorDemo, which
means it can either point a ConstructorDemo object or it's child classes. When you create
Object using new() operator it automatically class the constructor of that class as well.
5) Class is an abstraction to contain code, mostly attributes and methods which operate on
them. On the other hand object are the real thing which operate on them, but there comes static
methods, which belongs to class.
That's all on this question about difference between class and object in Java. As I said,
answers like a class is a blueprint and objects are real things created out of those blueprint is
absolutely correct answer, but you must examine further about practical aspect of class and
object. If a programmer can differentiate between class and object in code, can give you couple
of examples of what class and object are then it's understanding of this important concept is
good enough to consider.