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 the 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. This conversion example assumes the code is running above Java 5 version and actually tested in JDK 1.6, which makes it unable to pass Double object when the 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

The thread is one of important Class in Java and multithreading is most widely used a 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 a flag to stop Thread is a very popular way  of stopping the thread and it's also safe because it doesn't do anything special rather than helping run() method to finish itself.

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

Truncate and delete in SQL are two commands which are used to remove or delete data from a table. Though quite basic in nature both SQL commands can create a lot of trouble until you are familiar with details before using it. The 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 the amount of data. Since most of Electronic trading system stores large amount of transactional data and some even maintain historical data, a good understanding of delete and the truncate command is required to effectively work in that 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 a simple Java program which converts the decimal number to binary, octal and hexadecimal format. When it 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 simply amazed. It’s indeed extremely easy to do this in java and you can also write this program or use it is.

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 http://www.dartlang.org/ 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}');
}


Output:

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

The Select command in SQL is one of the most powerful and heavily used commands. This is I guess the first command anyone learn in SQL even before CREATE which is used to create a 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 the condition specified in WHERE clause, select all columns using the wild card (*) or only selecting a few columns by explicitly declaring them in a 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?

Java 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.
What is Class in Java Program with Example
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 etc.now 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.

highBetaStock.buy(1000);
highBetaStock.sell();


Summary:

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 the 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 their own market share though Chrome is growing and snatching market share from other browsers.

Top 10 JSP Interview Questions Answers for Java Programmer

This JSP interview questions and answers are asked in the various J2EE interview and focus on view part of MVC framework. JSP or Java Server Pages is a Java technology used to render a 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 the various interview to my friends and colleagues. You can easily find answers to these JSP interview question by google but I have included my version for quick reference. I would love to hear back from you and please share some JSP interview questions asked to you guys on the interview; I can include those in the 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 the path for Java. I have also seen the developer getting confused over path and classpath in java. Though both path and classpath provide run-time settings for any java environment which is required to compile and executes 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 a 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.

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

   @Override
    public int hashCode() {
        int hash = 5;
        hash = 89  hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 89  hash + (int) (this.id ^ (this.id >>> 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;
      
      
       @Override
       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;
       }
       @Override
       public boolean equals(Object obj) {
              if (this == obj) return true;
              if (obj == null || this.getClass() != obj.getClass()){
                     return false;
              }
              Stock other = (Stock) obj;
             
return  
this.tickSize == other.tickSize && this.lotSize == other.lotSize && 
this.isRestricted == other.isRestricted &&
(this.symbol == other.symbol|| (this.symbol != null && this.symbol.equals(other.symbol)))&& 
(this.exchange == other.exchange|| (this.exchange != null && this.exchange.equals(other.exchange))) &&
(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.

    @Override
    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.exchange, other.exchange);
            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;
    }
  
    @Override
    public int hashCode(){
        HashCodeBuilder builder = new HashCodeBuilder();
        builder.append(symbol);
        builder.append(exchange);
        builder.append(lotSize);
        builder.append(tickSize);
        builder.append(isRestricted);
        builder.append(settlementDate);
        builder.append(price);
        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