Sei sulla pagina 1di 38

Can I use Java console application to read and write a string

from an Excel file?


Here is the sample for you. Tyr it:
try {

POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));


HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;

int rows; // No of rows


rows = sheet.getPhysicalNumberOfRows();

int cols = 0; // No of columns


int tmp = 0;

// 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;
}
}

for(int r = 0; r < rows; r++) {


row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell((short)c);
if(cell != null) {
// Your code here
}
}
}
}
} catch (Exception ioe) {
ioe.printStackTrace();
}
so you can get value of A1 like following :
cell == sheet.getRow(0).getCell(0);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
}
Difference between Abstraction and Encapsulation in Java - OOP
Both Abstraction and Encapsulation are two of the four basic OOP concepts which allow you
to model real-world things into objects so that you can implement them in your program and
code. Many beginners get confused between Abstraction and Encapsulation because they both
look very similar. If you ask someone what is Abstraction, he will tell that it's an OOP concept
which focuses on relevant information by hiding unnecessary detail, and when you ask about
Encapsulation, many will tell that it's another OOP concept which hides data from outside
world. The definitions are not wrong as both Abstraction and Encapsulation does hide
something, but the key difference is on intent.

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.

Difference between Abstraction vs Encapsulation


Here are some of the key difference between Encapsulation and Abstraction in point format
for your quick revision:

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.

Difference between instance and Object in Java


In Java or other object oriented programming language, we often use Object and instance word
interchangeably, but sometimes it confuses beginners like hell. I have been often asked several
times, whether object and instance are the same thing or different? Why we sometimes use
object and sometimes instance if they are same thing etc? This gives me the idea to write a little
bit about it. I will mostly talk about Java conventions perspective. Just like we use word function
in C or C++ for a block of code, which can be called by its same, but in Java, we refer them as
methods. In Java functions are known as methods, similarly, objects are known as instances in
Java. You have a class, which represent a blueprint of a real world thing e.g. Car, and object
represents a real world car e.g. your car, my car, a red car or a blue car. They are also known
as instances of the car.
One reason of calling instance may be because they are a representation of that class at a
particular instant. In practice, use the instance to say about one particular object, and use an
object to talk about many objects. By the way, it's also worth remembering that Java has a class
named Object, or java.lang.Object, which is the master class and every other class extend it.

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.

public class Test {


public static void main(String args[]) {
Connection connection = new TCP();
connection.connect();
}
}

/**
* Base class to represent a Connection.
*/
public abstract class Connection{
protected String data;

public void connect(){


System.out.println("Connecting ....")
}

public void inputDate(String data){


this.data = data;
}
}

public class TCP extends Connection {

@Override
public void connect() {
System.out.println("Connection reliably but slow ..");
}
}

public class UDP extends Connection {

@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.

Difference between State and Strategy Design Pattern in Java


In order to make proper use of State and Strategy design Pattern in Core Java application, its
important for a Java developer to clearly understand difference between them. Though both
State and Strategy design patterns has similar structure, and both of them are based upon
Open closed design principle, represents 'O' from SOLID design principles, they are totally
different on there intent. Strategy design pattern in Java is used to encapsulate related set of
algorithms to provide runtime flexibility to client. Client can choose any algorithm at
runtime, without changing Context class, which uses Strategy object. Some of the
popular example of Strategy pattern is writing code, which uses algorithms e.g. encryption,
compression or sorting algorithm.

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.

Similarities between State and Strategy Pattern


If you look at UML diagram of State and Strategy design Pattern, they both look very similar
to each other. An object that uses State object to change its behaviour is known as Context
object, similarly an Object which uses a Strategy object to alter its behaviour is referred
as Context object. Remember client interact with Context object. In case of state pattern,
context delegates method calls to state object, which is held in form of current object, while
in case of strategy pattern, context uses Strategy object passed as parameter or provided at
the time of creating Context object.

UML Diagram of State Pattern in Java

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

Difference between Static and Dynamic Binding in Java


When you call a method in Java, it is resolved either at compile time or at runtime, depending
upon whether it's a virtual method or a static method. When a method call is resolved at compile
time, it is known as static binding, while if method invocation is resolved at runtime, it is known
as Dynamic binding or Late binding. Since Java is an object-oriented programming language
and by virtue of that it supports Polymorphism. Because of polymorphism, a reference variable
of type Parent can hold an object of type Child, which extends Parent. Now if you call a
virtual method (not private, final or static) on this object, then Compiler can not find actual
method, because it could be the one, which is defined in the Parent class, or the one
which Child has overridden. This call can only be resolved at runtime when the actual object
is available. That's why this is known as runtime or dynamic binding.

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 {

public static void main(String args[]) {

Parent p = new Child();

p.whoAmI(); // static method, resolved at compile time


p.whoAreYou(); // virtual method, runtime resolution
}

class Parent {

private void who(){


System.out.println("Inside private method Parent#who()");
}

public static void whoAmI(){


System.out.println("Inside static method, Parent#whoAmI()");
}

public void whoAreYou(){


who();
System.out.println("Inside virtual method, Parent#whoAreYou()");
}
}
class Child extends Parent{

private void who(){


System.out.println("Child#who()");
}

public static void whoAmI(){


System.out.println("Child#whoAmI()");
}

@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):

"This specification allows an implementation flexibility as to when linking activities


(and, because of recursion, loading) take place[..]."

"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."

How to Read Write Excel file in Java - POI Example


In this Java Excel tutorial, you will learn how to read and write from Excel file in Java . You
will learn steps to read/write both XLS and XLSX file format by using Apache POI library. In
this example, we will particularly focus on reading and writing String and Date values into
Excel file as writing dates are little bit tricky. In our earlier Java Excel tutorial, you have
already learned how to read/write Numeric types from Excel in Java, but we haven't touched
date values, which are also stored as numeric types, we will learn that in this tutorial. There
are two parts of this tutorial, in first part we will write date and String values into XLS file
and in second part we will read them from XLS file. You might aware that Excel file now
comes with two formats, XLS file which is an OLE format and XLSX format, which is also
known as OpenXML format. Apache POI supports both format but you would need different
JAR files to read/write XLS and XLSX files. You need poi-3.12.jar to read XLS file
and poi-ooxml-3.12.jar to read XLSX file in Java.

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.

Apache POI JARs to Read/Write Excel File in Java


Though there are couple of open source library available to read and write from Excel file in
Java e.g. JXL, the most feature rich and most popular one is Apache POI library. You can read
both types of Excel file format using this library. In order to use this library either you need to
download POI JAR files and add into your Eclipse's build path manually or you can use Maven
to download dependency for you.

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.

How to read from Excel File in Java


Suppose you have a cell in your excel file which contains a date e.g. birthdate? how do you
read it? Most of you will say that you will read that cell by first creating a Workbook, then
getting a sheet from that workbook, then getting the cell from that sheet which is containing
date value and finally getting cell value from that cell. Cool, these are the steps to read data
from Excel file in Java, but you forgot one thing you need to find the cell type before getting
cell value, otherwise you will be get error reading that cell. Reading date values are even
more tricky. To your surprise, there is no date cell type in Excel (both XLS and XLSX), instead
Excel stores date as numeric type. So you need to compare the cell type
with HSSFCell.CELL_TYPE_NUMERIC if you are reading XLS file
and XSSFCell.CELL_TYPE_NUMERIC if you reading XLSX file, but story doesn't end here, if
you just print the cell value by using getNumericCellValue(), you will not get any error
but you will see an arbitrary number. In order to print the actual date value you need to use
method getDateCellValue(), which will return an object of java.util.Date, if you
want to display a formatted date, then you need to format date using SimpleDateFormat or
by using Joda Date and Time library.

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.

How to read/write from XLS file in Java


This is our first example to read String and date values from Excel file in Java. In this
example, we are first creating old Excel file format i.e. XLS file birthdays.xls and later
we will read from the same file. Once we run our program, you can see this excel file created
in your Eclipse project directory, as shown below.

Steps to write Data into XLS file in Java


 Include poi-3.12.jar in your Java program's classpath
 Create an object of HSSFWorkBook
 Create a Sheet on that workbook by calling createSheet() method
 Create a Row on that sheet by calling createRow() method
 Create a Cell by calling createCell() method
 Set value to that cell by calling setCellValue() method.
 Write workbook content into File using FileOutputStream object.
 Close the workbook object by calling close() method

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

Step to read data from XLS file in Java


 Include poi-3.12.jar in your Java program's classpath
 Create an object of HSSFWorkBook by opening excel file using FileInputStream
 Get a Sheet from workbook by calling getSheet() method, you can pass name or
sheet index
 Get a Row from that sheet by calling getRow() method, you can pass index
 Get a Cell by calling getCell() method
 Get the Cell type by calling getCellType() method.
 Depending upon Cell type,
call getStringCellValue(), getNumericCellValue()or getDateCellValue()
method to get value.
 Close the workbook object by calling close() method

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 {

public static void main(String[] args) throws FileNotFoundException,


IOException {
writeIntoExcel("birthdays.xls");
readFromExcel("birthdays.xls");
}

/**
* 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");

// first row start with zero


Row row = sheet.createRow(0);

// we will write name and birthdates in two columns


// name will be String and birthday would be Date
// formatted as dd.mm.yyyy
Cell name = row.createCell(0);
name.setCellValue("John");

Cell birthdate = row.createCell(1);

// steps to format a cell to display date value in Excel


// 1. Create a DataFormat
// 2. Create a CellStyle
// 3. Set format into CellStyle
// 4. Set CellStyle into Cell
// 5. Write java.util.Date into Cell
DataFormat format = book.createDataFormat();
CellStyle dateStyle = book.createCellStyle();
dateStyle.setDataFormat(format.getFormat("dd.mm.yyyy"));
birthdate.setCellStyle(dateStyle);

// It's very trick method, deprecated, don't use


// year is from 1900, month starts with zero
birthdate.setCellValue(new Date(110, 10, 10));

// auto-resizing columns
sheet.autoSizeColumn(1);

// Now, its time to write content of Excel into File


book.write(new FileOutputStream(file));
book.close();
}
}
Output
name : John
birthdate :Wed Nov 10 00:00:00 GMT+08:00 2010

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 {

public static void main(String[] args) throws FileNotFoundException,


IOException {
writeIntoExcel("birthdays.xlsx");
readFromExcel("birthdays.xlsx");
}

public static void readFromExcel(String file) throws IOException{


XSSFWorkbook myExcelBook = new XSSFWorkbook(new
FileInputStream(file));
XSSFSheet myExcelSheet = myExcelBook.getSheet("Birthdays");
XSSFRow 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("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);

Cell name = row.createCell(0);


name.setCellValue("Gokul");

Cell birthdate = row.createCell(1);


DataFormat format = book.createDataFormat();
CellStyle dateStyle = book.createCellStyle();
dateStyle.setDataFormat(format.getFormat("dd.mm.yyyy"));
birthdate.setCellStyle(dateStyle);

birthdate.setCellValue(new Date(115, 10, 10));

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.

Difference between Overloading and Overriding in Java

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.

Other Java Fundamentals tutorials :


Difference between HashMap and ConcurrentHashMap in Java
Write Java program to print Fibonacci series upto 100
Write a Java program to find Armstrong number in Java
Difference between Path and Classpath in Java
What is Inheritance in Java and how to use it

What is Polymorphism in Java? Overriding or


Overloading?
Polymorphism vs Overloading vs Overriding

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.

An Example of Polymorphism in Java


An example of Polymorphism in Java

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;

abstract class Pet{


public abstract void makeSound();
}

class Cat extends Pet{

@Override
public void makeSound() {
System.out.println("Meow");
}
}

class Dog extends Pet{

@Override
public void makeSound() {
System.out.println("Woof");
}

Let's test How Polymorphism concept work in Java:

/**
*
* Java program to demonstrate What is Polymorphism
* @author Javin Paul
*/
public class PolymorphismDemo{

public static void main(String args[]) {


//Now Pet will show How Polymorphism work in Java
List<Pet> pets = new ArrayList<Pet>();
pets.add(new Cat());
pets.add(new Dog());

//pet variable which is type of Pet behave different based


//upon whether pet is Cat or Dog
for(Pet pet : pets){
pet.makeSound();
}

}
}

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.

What is the difference between a Class and an Object in


Java?
This article is solely for all beginner programmers, who are learning object oriented
programming language e.g. Java, C++ or C# and aspire to do well on any programming
interview. The difference between class and object is one of the most common questions, you
would like to ask a fresher coming out from college or training institute, but you would be
surprised how many beginner Java programmers struggle with this
question. Class and Object are two pillars of Object Oriented Programming (OOPS) and a
good understanding is a must, but when you ask this question apart from the theoretical and
bookish answer that "class is a blueprint and objects are actual things created out of that
blueprint", you would hardly get anything substantial. Though that answer is correct and works
perfectly, it doesn't differentiate between a programmer, who has just mugged the answer, or
the one who truly understand the difference between class and object.
So, if I receive that answer, I usually ask them to create a class and explain how objects are
created in the program, let's say to represent an Employee, Student or simply a Car. If
programmer truly understand what is a class and what is an object, it will do that in no time, but
if he has just mugged up the answer, then he will be totally confused.

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.

In E-commerce domain Payment, Order, Products are some example of classes.

Class vs Object in Java


Some difference between class and object, which is totally based upon practical experience :

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.

Potrebbero piacerti anche