How to Convert Double to String to Double in Java Program with Example

Many scenarios come in day to day Java programming when we need to convert a Double value to String or vice versa. In my earlier article we have seen how to convert String to Integer and in this article we will first see how to convert double to String and later opposite of  that from String to double. One important thing to note is Autoboxing which automatically converts primitive type to Object type and only available from Java 5 onwards. These conversion example assumes code is running above Java 5 version and actually tested in JDK 1.6, which makes it enable to pass Double object when method is expecting double primitive value e.g. String.valueOf(double d) which expect a double value.

How to Stop Thread in Java Code Example

Thread is one of important Class in Java and multi-threading is most widely used feature,but there is no clear way to stop Thread in Java. Earlier there was a stop method exists in Thread Class but Java deprecated that method citing some safety reason. By default a Thread stops when execution of run() method finish either normally or due to any Exception.In this article we will How to Stop Thread in Java by using a boolean State variable or flag. Using flag to stop Thread is very popular way  of stopping thread and its also safe, because it doesn't do anything special rather than helping run() method to finish it self.

What is Iterator and ListIterator in Java Program with Example - Tutorial Code Sample

Iterator in Java is nothing but a traversing object, made specifically for Collection objects like List and Set. we have already aware about different kind of traversing methods like for-loop ,while loop,do-while,for each lop etc,they all are  index based traversing but as we know Java is purely object oriented language there is always possible ways of doing things using objects so Iterator is a way to traverse as well as access the data from the collection. Even with traversing with object we have Enumeration, Iterator and ListIterator in Java which we will in this Java Iterator tutorial.

Difference between Truncate and Delete command in SQL - Interview Questions with Example

Delete and truncate command in SQL
Truncate and delete in SQL
are two commands which is used to remove or delete data from table. Though quite basic in nature both sql commands can create lot of trouble until you are familiar with details before using it. Difference between Truncate and delete are not just important to understand perspective but also a very popular SQL interview topic which in my opinion a definite worthy topic. What makes them tricky is amount of data. Since most of Electronic trading system stores large amount of transactional data and some even maintain historical data, good understanding of delete and truncate command is required to effectively work on those environment.I have still seen people firing delete command just to empty a table with millions of records which eventually lock the whole table for doing anything and take ages to complete or Simply blew log segment or hang the machine.

How to convert decimal to binary, octal and hex String in Java Program

This article is about a simple java program which converts decimal number to binary, octal and hexadecimal format. When it was first came into my mind I though I would probably need to write whole code to convert decimal to various other radix or base numbers but when I looked Integer class and saw these two way of converting decimal to binary etc I was simple amazed. It’s indeed extremely easy to do this in java and you can also write this program or use at it is.

Converting decimal to binary in Java Example

convert decimal number to binary in java exampleJava  has many ways to change number system of particular number, you can convert any decimal number into either binary system, hexadecimal system or octal system by following same procedure. here is code example of converting any decimal number into binary number in Java.
//first way      
        //decimal to binary
        String binaryString = Integer.toBinaryString(number);
        System.out.println("decimal to binary: " + binaryString);
        //decimal to octal
        String octalString = Integer.toOctalString(number);
        System.out.println("decimal to octal: " + octalString);
        //decimal to hexadecimal
        String hexString = Integer.toHexString(number);
        System.out.println("decimal to hexadecimal: " + hexString);

//second way
        binaryString = Integer.toString(number,2);
        System.out.println("decimal to binary using Integer.toString: " + binaryString);
        //decimal to octal
        octalString = Integer.toString(number,8);
        System.out.println("decimal to octal using Integer.toString: " + octalString);
        //decimal to hexadecimal
        hexString = Integer.toString(number,16);
        System.out.println("decimal to hexadecimal using Integer.toString: " + hexString);

Nice and little tip to convert decimal to binary or decimal to Octal, hex. This comes very handy many times when we want to do a quick conversion.

Related Java Tutorials

How to write Helloworld in Google Dart with Example - Dart Tutorial

Google Dart  Program Example Tutorial

Google dart is now released and its time to try google dart and see how much it offers to a programmer and whether it is suitable language to replace JavaScript or not. As a language my first impression of Google dart is great it looks so much familiar with Java my favorite programming language and this motivate me to write this hello-world example in Google Dart and execute it , run it and see how it works. Google dart has Class and Object, it has final keyword, String Class , Object class , extends keyword and many more I going to learn but it really look structure because it has google dart compiler which shows warning and error like any other structure programming language.

In this Google Dart tutorial we will see How to write Helloworld in Google Dart and How to run Google dart program using Google Dartboard Application which is a browser based application, allow you to write and run Google Dart Programs. This is the easiest and quickest way to get a feel of Google Dart language itself before trying it with HTML code. Google Dart also has compiler and html converter which allow you to convert Dart code into JavaScript and use it. We will see about how to convert Google Dart Code into JavaScript in next article. For now let's start with this step by step guide of writing Google Dart HelloWorld Example and running it.

Step by Step Guide to Write and Run Google Dart Example

I. Open in your browser.

Make sure you use Mozilla Firefox, Google Chrome or Apple Safari. Google Dartboard application won’t work on Microsoft Internet Explorer, though support is coming in may be few days or week.also if you are using Mozilla please use latest version, Google Dartboard was not working on my Mozilla Firefox 3.6 versions. Once you open this link Google Dartboard Application will be open on your browser and first example which it has is "Hello Dart" as shown in below screen.

google dart example tutorial

II. Important points about Google Dart structured programming language

Now you have two options either edit the existing program or write a new program.
Before writing new program let’s see few points about google dart language.

1. Like Java google dart program will start with main () method.

2. You can declare Variable using "var" a JavaScript style or using correct type like String or int using Java Style , for example below two code  are same.

String text = "NYSE is biggest Stock Market in world";
var text = "NYSE is biggest Stock Market in world";

It depends upon your choice whether you want to adopt javascript style or Java Style. Since I am a Java programmer I found Java Style more intuitive and easy to use.

3. You can assign incorrect type to variable e.g. in this example assigning "text" as int, your programe will run but Dart compiler will show warning related to incorrect type.

int text ="google dart compler will show warning but programme will run".

4. Instead of var or a formal type, you can use final keyword and your program will run successfully.

5. Each statement ends with semicolon ";" otherwise compiler will throw error "Unexpected token "IDENTIFIER expected" or "; expected"

6. For displaying value of variable we need to use interpolation or jsp expression language style "${var}" or else it will complain as "cannot resolve text".

7. We can display string as literal, exactly same as in Java. print() method is similar to Perl, java or any other language. For example

print("This is String literal");

III. Our first google dart program

main() {
  String tradingSecrets = "High Frequency Trading requires extremely fast computers";
  int latency = 10;
  String message = "Google Dart language";
  print('Hello world in ${message }');
  print("This is String literal just like Java");
  print( '${tradingSecrets}');


Hello world in Google Dart language
This is String literal just like Java
High Frequency Trading requires extremely fast computers

IV. Running your Google Dart program

Just press the Run button as shown in the above image, it will contact darn server and run your program, sometime you may get error as "The darn server failed to respond." but mostly you see out of your google dart program.

This is the first Google Dart tutorial there are more to come but this is good to start and get feeling of Google dart language. Google Dartboard application is easy to use and execute google dart program which reduce learning curve but converting google dart program to JavaScript and than running into HTML file like JavaScript requires little effort which we will see in next article.

10 Example Queries of SQL Select Command

Select command in SQL is one of the most powerful and heavily used commands. This is I guess the first command any one learn in SQL even before CREATE which is used to create table in SQL. SELECT is used in SQL to fetch records from database tables and you can do a lot many things using Select. For example you can select all records, you can select few records based on condition specified in WHERE clause, select all columns using wild card (*) or only selecting few columns by explicitly declaring them in query.

Dennis Ritchie, Creator of C language and Unix has passed away

I just come to know about this sad news that Dennis Ritchie passed away, It is second blow to technology world after Steve jobs who has recently passed away. Dennis Ritchie is the first programming figure I come to know when I started my programming classes in C and C++ and that's why when I heard this news I feel sad about it and suddenly I remember my programming days and I thought about this post to pay my tribute and remember him.

Dennis Ritchie creator of C and Unix passed away
There is lot of Great information available on Dennis Ritchie in web and Wikipedia but two of its main contribution is:

1) C Programming language, which is still number one after Java.
2) His Contribution in UNIX Operating System which is best Server Operating system available.
3) Author of book

Let’s remember this programming genius and pay 2 minute tribute to him, without his C language and immense contribution to programming language, community will never forget him.

May god rest his soul in piece.

What is Class in Java Programming with General Example

When I first about Class in Java I just thought what is this Class in Java and from that date to now Whenever we talk about java its really incomplete without classes, every one who are little bit familiar with java knows it’s purely object oriented language means every thing we discuss in java as object .so its very important for learner or anyone who is keen to know about java should know about java class then only they can move forward on java world.
In this article we will see what Java Class, Example of Class in Java is and what makes a Java Class including members, field and method.If you have just started programming in Java or learning Please check my article How to Set Path for Java and How to set ClassPath for Java covering two important concept PATH and CLASSPATH.

Class in Java Programming Example

What is Java Class?

What is Class in Java Program with ExampleJava class is nothing but a template for object you are going to create or it’s a blue print by using this we create an object. In simple word we can say it’s a specification or a pattern which we define and every object we define will follow that pattern.

What does Java Class Consist

§          When we create class in java the first step is keyword class and then name of the class or identifier we can say.
§          Next is class body which starts with curly braces {} and between this all things related with that class means their property and method will come here.

Template is:

Class (name of the class) {

(Here define member of class)


Access level of class:

Java class has mainly two type of access level:

Default: class objects are accessible only inside the package.

Public: class objects are accessible in code in any package.

What are members of Class?

When we create a class its totally incomplete without defining any member of this class same like we can understand one family is incomplete if they have no members.

Field: field is nothing but the property of the class or object which we are going to create .for example if we are creating a class called computer then they have property like model, mem_size, hd_size, os_type etc

Method: method is nothing but the operation that an object can perform it define the behavior of object how an object can interact with outside world .startMethod (), shutdownMethod ().

Access Level of members: Access level is nothing but where we can use that members of the class.
Each field and method has an access level:
  • private: accessible only in this class
  • package or default: accessible only in this package
  • protected: accessible only in this package and in all subclasses of this class
  • public: accessible everywhere this class is available

Real world example of Class in Java Programming:

In real world if we want to understand about the class everything of same quality  can be visualize as a class e.g. men,women,birds ,bicycles ,cars or  we can say vehicle .
The entire vehicle will make one class they have the property like no_of_wheels, color, model, brand we can think changeGear () and speedOfvehicle (), applyBreak () etc as a method on that class. Similarly all human being also can be one class now their member will be a men ,women ,child.,isAlive() ,isDeath() can be their method or behavior of that class .again we can make Men or women a separate class and define their property and method accordingly,
In short in java every problem we get solution can be think in terms of class and object.

One Java class example:

Class Stock {
Public commodity;
Public price;
Public void buy (int no_of commodity) {}
Public boolean sale () {}

In this example Stock is called Class and commodity, price are field and buy() and sale() are two methods defined inside class. To access elements of Class you need to create an instance of class Stock. You can create instance of Class using keyword new as shown below

Stock highBetaStock = new Stock();

For calling method of Stock just call by using instance.;


In short in java everything must be thinking in terms of java class its nothing but a template they have their own members and methods for accessing those members. The entire member has their own visibility which is decided by the developer where they want to use those objects.
Related Java Tutorials

Google Dart: New Programming language to replace JavaScript

Google Dart: Structured Web Programming language

Google has launched its much awaited mysterious DART web programming language. Ahh another programming language…, why does google launched a new language Google DART? What I read from web is that google is trying to replace JavaScript as main web scripting language. Over the years from Netscape Era JavaScript has evolved, formed a large based of Developers and has existing codes, framework and utilities, so I am not sure how far Google DART can go but this is a serious attempt to replace JavaScript much in the line of Chrome which was launched to replace Internet Explorer and What we see now is they are living happily with there own market share though Chrome is growing and snatching market share form other browsers.

Now let’s get back to Google Dart, according to leaked Memo, Google perceives that Security Problems of JavaScript cannot be solved by modifying or evolving language and it has tried to solve that on Google Dart: A structured web programming language on its own way.

Example of Google Dart Code
Let's see an example Hello World program in Google Dart, I bet you will see and understand it in one second if you written code in Java or C#.

  print("Hello World from Google Dart");
  print("My Name is Google Dart and I am going to replace JavaScript");

Nothing fancy simple and familiar syntax and that's what Google reiterate as one of design goal.
You can execute Dart Code in two ways either in native Dart Virtual Machine; Google is planning Dart support in Chrome and push other vendors to do the same.

Salient feature of Google Dart

Familiar Syntax: if you look Google Dart code you will easily able to understand what's going on because its syntax is quite similar to Java,Which is undoubted world famous programming language.Its is also similar to C# on same line.

High Performance: Dart is promising high performance from web browser to hand held devices to Server Side Execution.

Runs in Virtual Machine: Similar to Java Google Dart also run on Virtual Machine.
Google Dart is semi typed language where you can switch from typed to untype based on your need.

Open Source: Google Dart is open source project and it comes with set of tools for compiling and executing Dart Code. You can check for further details.

How Google Dart will get Popular

Google is doing its hard work to get Dart accepted by web developers and community and arranging support, tools and execution environment for Google Dart.

1. Google will provide support of Dart in Google Chrome by integrating native virtual Machine and it will encourage to Microsoft and Mozilla to do the same.

2. Google will provide a Cross Compiler which will convert Dart to ECMAScript 3 , so that it can run on Non Dart Browser. This will be the major step as getting Dart Virtual Machine integrated on all popular brower might take some time.
What is positive for Google Dart

Though Google Dart is a new programming language and anything new takes it time to get adopted and supported by community and that's the most difficult phase for language. Google Dart is not an exception but there are some positive facts which suggest that it can go a long way:

Technologically advanced: Dart is technological advanced than JavaScript and since it aims to fix security and other problems of JavaScript it will definitely have an appeal.

Google: Since language is developed and launched by Google, expect future support, marketing and strong backup from Google.

Familiar Syntax: Google Dart doesn't reinvent the wheel at least on language syntax it's quite familiar to Java and C# which gives it easy access of large community of Java and C# web developer.

Google Dart Cross Compiler: Cross compiler will make Dart running on browsers which doesn't have native Google Dart Virtual Machine, if google gets it right this would be the biggest point and can provide language an initial thrust.

High Performance: Google Dart Promises high performance from web browser, web Server to hand held devices
If you want to know more about Google Dart I suggest reading References

Top 10 JSP Interview Questions Answers for Java Programmer

This JSP interview questions and answers are asked in various J2EE interview and focus on view part of MVC framework. JSP or Java Server Pages is a Java technology used to render dynamic view. Whenever you go for any Java web developer interview there is always some interview questions on JSP. This article is a collection of some JSP interview questions which has asked in various interview to my friends and colleagues. You can easily find answers of these JSP interview question by google but I have included my version for quick reference. I would love to here back from you and please share some JSP interview questions asked to you guys on interview; I can include those in main post for everybody’s benefit.

How SubString method works in Java - Memory Leak Fixed in JDK 1.7

Substring method from String class is one of most used method in Java, and it's also part of an interesting String interview question  e.g. How substring works in Java or sometime asked as how does substring creates memory leak in Java. In order to answer these questions, you knowledge of  implementation details is required. Recently one of my friend was drilled on substring method in Java during a Java interview, he was using substring() method from long time, and of course all of us has used this, but what surprises him was interviewer's obsession on Java substring, and deep dive till the implementation level. Though String is a special class in Java, and subject of many interview questions e.g. Why char array is better than String for storing password . In this case it was, substring method, which took center stage. Most of us rather just use substring(..), and than forgot. Not every Java programmer go into code, and see how exactly it's working. To get a feel of how his interview was let's start .

How to Set Path for Java Unix Linux and Windows

PATH is one of fundamental Environment variable on shell or DOS but it’s commonly associated with Java mainly because if we try to run a java program which doesn't include Java executable in PATH then we say PATH is not set for Java and we need to set path for Java. I have also seen developer getting confused over path and classpath in java. Though both path and classpath provides run-time settings for any java environment which is required to compile and execute Java program they are completely different to each other. Classpath is usually used to find out classes and mostly associated with lib part while PATH is used to find the executable or command to be executed. In order to compile and run java program from command line your PATH environment variable must have "javac" and "java" on it. In this Java PATH tutorial we will see what is PATH for Java, How to Set Path for Java and how to troubleshoot PATH related issues.

What is Path in Java

First of all PATH is not specific to java it’s a shell concept and also available in Windows and DOS. It’s represented by Environment variable called "PATH" and that's why it’s known as path. Whenever you type a command in shell in UNIX or Linux or in command prompt in windows machine, command will be looked on PATH and if shell is not able to find the command in PATH it says "not recognized" or wrong command. Now for compiling and running we use two java commands "javac" and "java" and these commands doesn't come by default with windows or Unix instead they comes when you install JDK in your machine. Now to successfully compile and run a java program in either windows or Linux you must have these two commands or executable in your PATH environment variable and that is called Setting Path for Java.

Setting Path for Java in Unix/Linux and Windows

How to check if "java" or "javac" is in PATH

Javac and Java command resides under /bin directory or your Java installation directory. In my machine its "C:\Program Files\Java\jdk1.6.0_26\bin"

If you have this bin directory in path it means java and javac will be in path and Path is set to run Java Program. There are two ways you verify whether java is in path or not.

1) Simple and easy way
Open a command prompt window by pressing start -->run-->cmd and then typing "java" or "javac" in command prompt as shown in below example

C:\Documents and Settings>java
Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)

where options include:
    -client       to select the "client" VM
    -server       to select the "server" VM
    -hotspot      is a synonym for the "client" VM [deprecated]

How to set Path for Java in Unix, windows and Linux
If it displays lot of output means Java is in your path and similarly you can check for "javac”, on the other hand if java is not in your system's path you will get below output in UNIX

stock_trader$ javac
javac: not found

and in windows
C:\Documents and Settings>javac
'javac' is not recognized as an internal or external command,
operable program or batch file.

If Java or Javac is not in your path then you can add them into path by adding "bin" directory or your JDK installation directory into environment variable "PATH". Both windows and UNIX use same name.

How to set PATH for Java in windows

I say pretty easy just add bin directory of your JDK installation directory into PATH environment variable. You can do this either from command prompt or by using windows advanced environment editor

1) Setting Java PATH using command prompt in windows

Use "set" command to set value of PATH environment variable as shown in below example:

C:\Documents and Settings>set PATH=%PATH%; C:\Program Files\Java\jdk1.6.0_26\bin

%PATH% is actually representing current path and we are appending java bin directory into PATH. Note that every path in windows is comma (;) separated while in UNIX it would be colon (:) separated

2) Setting Java PATH using windows environment variable editor

Use short cut "window key + pause/break" --> Advanced --> Environment Variables -->PATH

Just append the path of java installation directory here and you are done. Open a command prompt and type java or javac and you can see the output.

How to set Java PATH in UNIX or Linux

Setting PATH for java in UNIX is similar to the way we did for it on windows using command prompt. In UNIX just open any shell and execute below command

set PATH=${PATH}:/home/opt/jdk1.6.0_26/bin

Remember here each element in PATH is colon separated.

Related Java tutorials

How to override hashcode in Java example - Tutorial

Equals and hashcode methods are two primary but yet one of most important methods for java developers to be aware of. Java intends to provide equals and hashcode for every class to test the equality and to provide a hash or digest based on content of class. Importance of hashcode increases when we use the object in different collection classes which works on hashing principle e.g. hashtable and hashmap. A well written hashcode method can improve performance drastically by distributing objects uniformly and avoiding collision. In this article we will see how to correctly override hashcode() method in java with a simple example. We will also examine important aspect of hashcode contracts in java. This is in continuation of my earlier post on overriding equals method in Java, if you haven’t read already I would suggest go through it.

General Contracts for hashCode() in Java

1) If two objects are equal by equals() method then there hashcode returned by hashCode() method must be same.

2) Whenever hashCode() mehtod is invoked on the same object more than once within single execution of application, hashCode() must return same integer provided no information or fields used in equals and hashcode is modified. This integer is not required to be same during multiple execution of application though.

3) If two objects are not equals by equals() method it is not require that there hashcode must be different. Though it’s always good practice to return different hashCode for unequal object. Different hashCode for distinct object can improve performance of hashmap or hashtable by reducing collision.

To better understand concept of equals and hashcode and what happens if you don’t override them properly I would recommend understanding of How HashMap works in Java

Overriding hashCode method in Java

Override java hashcode exampleWe will follow step by step approach for overriding hashCode method. This will enable us to understand the concept and process better.

1) Take a prime hash e.g. 5, 7, 17 or 31 (prime number as hash, results in distinct hashcode for distinct object)
2) Take another prime as multiplier different than hash is good.
3) Compute hashcode for each member and add them into final hash. Repeat this for all members which participated in equals.
4) Return hash

  Here is an example of hashCode() method

    public int hashCode() {
        int hash = 5;
        hash = 89  hash + ( != null ? : 0);
        hash = 89  hash + (int) ( ^ ( >>> 32));
        hash = 89  hash + this.age;
        return hash;

It’s always good to check null before calling hashCode() method on members or fields to avoid NullPointerException, if member is null than return zero. Different data types has different way to compute hashCode.Integer members are simplest we just add there value into hash, for other numeric data-type are converted into int and then added into hash. Joshua bloach has full tables on this. I mostly relied on IDE for this.

Better way to override equals and hashCode

hashcode in Java exampleIn my opinion better way to override both equals and hashcode method should be left to IDE. I have seen Netbeans and Eclipse and found that both has excellent support of generating code for equals and hashcode and there implementations seems to follow all best practice and requirement e.g. null check , instanceof check etc and also frees you to remember how to compute hashcode for different data-types.

Let’s see how we can override hashcode method in Netbeans and Eclipse.

In Netbeans
1) Write your Class.
2) Right click + insert code + Generate equals() and hashCode().

How to override java hashcode
In Eclipse
1) Write your Class.
2) Go to Source Menu + Generate hashCode() and equals()

Things to remember while overriding hashcode in Java

1. Whenever you override equals method, hashcode should be overridden to be in compliant of equals hashcode contract.
2. hashCode() is declared in Object class and return type of hashcode method is int and not long.
3. For immutable object you can cache the hashcode once generated for improved performance.
4. Test your hashcode method for equals hashcode compliance.
5. If you don't override hashCode() method properly your Object may not function correctly on hash based collection e.g. HashMap, Hashtable or HashSet.

Complete example of equals and hashCode

public class Stock {
       private String symbol;
       private String exchange;
       private long lotSize;
       private int tickSize;
       private boolean isRestricted;
       private Date settlementDate;
       private BigDecimal price;
       public int hashCode() {
              final int prime = 31;
              int result = 1;
              result = prime * result
                           + ((exchange == null) ? 0 : exchange.hashCode());
              result = prime * result + (isRestricted ? 1231 : 1237);
              result = prime * result + (int) (lotSize ^ (lotSize >>> 32));
              result = prime * result + ((price == null) ? 0 : price.hashCode());
              result = prime * result
                           + ((settlementDate == null) ? 0 : settlementDate.hashCode());
              result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
              result = prime * result + tickSize;
              return result;
       public boolean equals(Object obj) {
              if (this == obj) return true;
              if (obj == null || this.getClass() != obj.getClass()){
                     return false;
              Stock other = (Stock) obj;
this.tickSize == other.tickSize && this.lotSize == other.lotSize && 
this.isRestricted == other.isRestricted &&
(this.symbol == other.symbol|| (this.symbol != null && this.symbol.equals(other.symbol)))&& 
( ==|| ( != null && &&
(this.settlementDate == other.settlementDate|| (this.settlementDate != null && this.settlementDate.equals(other.settlementDate))) &&
(this.price == other.price|| (this.price != null && this.price.equals(other.price)));


Writing equals and hashcode using Apache Commons EqualsBuilder and HashCodeBuilder

EqualsBuilder and HashCodeBuilder from Apache commons are much better way to override equals and hashcode method, at least much better than ugly equals, hashcode generated by Eclipse. I have written same example by using HashCodebuilder and EqualsBuilder and now you can see how clear and concise they are.

    public boolean equals(Object obj){
        if (obj instanceof Stock) {
            Stock other = (Stock) obj;
            EqualsBuilder builder = new EqualsBuilder();
            builder.append(this.symbol, other.symbol);
            builder.append(this.lotSize, other.lotSize);
            builder.append(this.tickSize, other.tickSize);
            builder.append(this.isRestricted, other.isRestricted);
            builder.append(this.settlementDate, other.settlementDate);
            builder.append(this.price, other.price);
            return builder.isEquals();
        return false;
    public int hashCode(){
        HashCodeBuilder builder = new HashCodeBuilder();
        return builder.toHashCode();
    public static void main(String args[]){
        Stock sony = new Stock("6758.T", "Tkyo Stock Exchange", 1000, 10, false, new Date(), BigDecimal.valueOf(2200));
        Stock sony2 = new Stock("6758.T", "Tokyo Stock Exchange", 1000, 10, false, new Date(), BigDecimal.valueOf(2200));

        System.out.println("Equals result: " + sony.equals(sony2));
        System.out.println("HashCode result: " + (sony.hashCode()== sony2.hashCode()));

Only thing to concern is that it adds dependency on apache commons jar, most people use it but if you are not using than you need to include it for writing equals and hashcode method.

Related Java tutorials