Convert String to int in Java

Convert String to int in Java

There are few ways to convert String to int in Java. Below are few of popular ways for converting String to int

  1. Integer.parseInt()
  2. Integer.valueOf()

1.  Integer.parseInt() Examples

Integer.ParseInt()  will return an int primitive value.If efficiency is your concern and you only need primitive value, then using Integer.ParseInt()  is the best option.

Here is an example to convert “50” to an int value

public class JavaParseInt {
    public static void main(String[] args) {
        String number ="50";
        int result = Integer.parseInt(number);
        System.out.println(result);
    }
}

Here is the output of the above code

50

2.  Integer.valueOf() Examples

You can also use Integer.valueOf() , this method will return Integer object

public class JavaIntegerValueOf {

    public static void main(String[] args) {
        String number ="60";
        Integer result = Integer.valueOf(number);
        System.out.println(result);
    }
}

Output

60

Actually, valueOf uses parseInt internally. If efficiency is your concern do not use this method to convert String to int or Integer.

3.  NumberFormat Exception

Both Integer.parseInt()  and Integer.valueOf()  can throw NumberFormatException if the string cannot be parsed as an integer or int

public class NumberFormatExceptionExample {

    public static void main(String[] args) {
        String invalidNumber = "abc";
        parseIntNFException(invalidNumber);

    }

    public static void parseIntNFException(String number) {
        Integer result = Integer.parseInt(number);
        System.out.println(result);
    }

    public static void valueOfNFException(String number) {
        Integer result = Integer.valueOf(number);
        System.out.println(result);
    }
}

Output

Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at NumberFormatExceptionExample.parseIntNFException(NumberFormatExceptionExample.java:13)
	at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:8)

Note: PraseInt() return a primitive value while valueOf() will always return new Integer object, ideally, if you just want to convert String to an int, it’s always better to avoid creating new Object.

Furthur Reading

It’s always a good habit to read Javadoc for more inside details

  1. JavaDoc valueOf()
  2. JavaDoc parseInt()
  3. NumberFormatException

Download above examples from

  1. GitHub Repository

Java Comparable vs Comparator

Java Comparable vs Comparator

In this articles we will discuss Java Comparable vs Comparator, very often people have  lots of questions when it comes to Java Comparable vs Comparator

  1. What is Comparable and what is Comparator in Java
  2. How do we use them
  3. What is the difference between Comparable and Comparator?
  4. When we should use Comparable vs Comparator

This post does not cover basics about Java’s Comparable and Comparator ( Will cover that in another post ), but this post is more towards getting insight about Comparable vs Comparator.

 

Comparable

public interface Comparable<T>

When a class implement Comparable, the compareTo method of the class defines the “natural” ordering of that object. CompareTo method should follow some general contracts, few of the examples are

  1. Should always be returned 0  for objects when equal ()  comparisons return true.
  2. Comparable is useful when there’s a single natural default comparison.

Comparator

public Interface Comparator<T>

Comparator provides a way to compare 2 objects and can be used to compare objects in a way that might not align with the natural ordering.

One of the common examples is String, String is generally compared alphabetically, ” a”.compareTo(“b”)  would use alphabetical comparisons.If you want to compare based on the String length, writing custom Comparator is a preferred solution.

 

If you do not have control over the source code ( where you can not implement Comparable ), then use Comparator.Comparator is useful when you have multiple ways to compare an object ( e.g you can compare cars by brand and cc etc.).

Both seem to be different, but to summarise, there isn’t much difference.Both ends to similar means.In general implement comparable for natural order, and write a comparator for other sorting or comparison needs.

Please read Java Sorting Example(Comparable and Comparator) to get an understanding of using Comparable and Comparator for sorting objects in Java.

BigDecimal equals versus compareTo

While going through compareTo(T o) method in the Comparable interface, I came across a very interesting finding of BigDecimal equals versus compareTo and though about sharing about it.

Usually, we require that two objects are equal if and only if they are compared as same

For BigDecimal things are really interesting when we check both equals() and compareTo() method
Consider following small program

BigDecimal x = new BigDecimal("2");
BigDecimal y = new BigDecimal("2.00");
System.out.println(x.equals(y));
System.out.println(x.compareTo(y) == 0 ? "true": "false");

We can say that x is equal to y (not object reference), running the above program will show following out

false
true

One of the questions that came to my mind while checking this out is “How compareTo determine that x is equal to y for BigDecimal and what is the difference between compareTo() and equals() methods in BigDecimal”

The answer was in JavaDoc of the equals() method:

Compares this BigDecimal with the specified Object for equality. Unlike compareTo , this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method). equals methods takes scale into consideration

To summarise, equals() check if BigDecimal objects are same is every aspect while compareTo only check for numeric values.

run following code and check the output

BigDecimal x = new BigDecimal(2);                           
BigDecimal y = new BigDecimal(2.00);                        
System.out.println(x.equals(y));                            
System.out.println(x.compareTo(y) == 0 ? "true": "false");

This is a tricky part of BigDecimal, if you do not have clarity of this and implement it incorrectly, it can lead to many strange bug/issues in your code.

Bottom line is

Use compareTo() instead of equals() to compare numeric values since equals() takes scale into consideration

Remote debug spring boot application with maven and IntelliJ

I run in to an issue some time back where I was required to  debug a remote spring boot web application using IntelliJ and was not sure what is the best way to do it.

IntelliJ has still some issue to run Spring-boot powered web applications with Tiles and I faced same one while working on Shopizer.

We used command line to run Spring boot application using maven plugin. In this post I will try to outline how I configured IntelliJ to debug remote application.

To debug remote spring boot application make sure you have  “Spring Boot Maven Plugin” plugin configured in your pom.xml file

        org.springframework.boot
        spring-boot-maven-plugin
        1.5.2.RELEASE

You have 2 way to configure debug option using spring boot maven plugin

  1. configure debug option using <jvmArguments> option
  2. use command line argument
        org.springframework.boot
        spring-boot-maven-plugin
        1.5.2.RELEASE&
        
          
            -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
         
        
        ...

 

Alternatively we will can pass these parameters using command line and we will go with this option in this post.

mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005"

By default, the run goal runs in the same process unless jvm arguments or an agent have been specified, above configuration will ensure that you are forking the process and able to debug it.

Next step is to configure IntelliJ to enable debug points, use below steps to configure it

  1. Open run/debug configuration dialogue box and click on the new iconRemote
  2. Create remote configuration , see screen shot belowJVM
  3. Click on the debug button and you are all set to debug remote spring boot applicationDebug

Make sure that you have same port number as used while starting spring boot application using Maven.

 

Build and Run Shopizer 2.0.5

With the latest 2.0.5 release, Shopizer team has done a number of changes including migrating to Spring Boot ( 2.0.5 is based on Spring Boot 1.3.5 ). Please read Shopizer 2.0.5 for more details.

In this post, I will try to give you an overview of downloading Shopizer 2.0.5, build and run it on your local machine. Shopizer comes with a predefined demo DB which can be used out of the box to run demo application.

I am assuming that you have basic understanding of following terms

  1. JAVA ( we will be using JDK 1.8)
  2. Spring
  3. Maven
  4. Build
  5. Elastic Search ( 2.4.1 )

I have following configurations for this post

JAVA

java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode

Maven

Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T08:41:47-08:00)
Java version: 1.8.0_101, vendor: Oracle Corporation
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.12.3", arch: "x86_64", family: "mac"

 

I will start by cloning Shopizer from GitHub ( You can use UI client ), for this post I am using Git command line tool

clone shopizer

 

Elastic Search

Shopizer uses Elastic Search for its front end search before we build Shopizer, we need to start Elastic Search server and make sure to update configuration with the correct port number and host information. Please update

configs.properties

file under

sm-core/resources

with the correct value for Elastic Search

Once clone is completed, move to the root folder and run following command to build Shopizer

mvn:clean install

This will make sure that you have your build and packet created by Maven

build

 

Spring boot provides embedded support for Tomcat 8, which mean you don’t need standalone Tomcat to run your application.

Run the following command to start embedded Tomcat 8 for Shopizer 2.0.5

mvn spring-boot:run

application-started

When you run your application, Spring Boot will detect that you have a Spring MVC controller and start up an embedded Apache Tomcat 8 instance, by default.

You are all set to run your shop and admin panel. Go ahead and use following URL to open shop and back-end system for Shopizer

Back-end / Admin : localhost:8080/admin/logon.html

backend-login

use following details to log in to the backend

username : admin
password: password

backend

 

Web shop : http://localhost:8080/shop

shop-frontend

I hope this will help you to setup and run default OOTB Shopizer 2.0.5. Let me know in case you have any questions or comments.

In our next post, we will cover how to setup development environment for Shopizer using IntelliJ IDEA’s

 

 

 

Shopizer 2.0.5 Released

Shopizer team has released version 2.0.5 with a lots of improvements and bug fixes. below are some of the major up-gradations and changes in 2.0.5

  1. We have upgraded code base to 1.8.
  2. QSDL has been replaced completely with JPA.
  3. 2.0.5 is based on Spring Boot and provide all the powers and flexibility of Spring boot.
  4. Spring data JPA
  5. Build issues has been fixed which was preventing deployment in some of the cases

For more details and download, please refer to Shopizer GitHub repository.

 

How to setup shopizer

How to setup Shopizer

The first step for working on OSS is to setup your development environment. In order to work with Shopizer, we need to setup development environment so as we can work/customise it as per our preference.

Setting up Shopizer is really easy, all we need is IDE and Apache Maven to work with. In this post, I will try to explain as of how we can setup Shopizer in Eclipse. We will need following for setting up our development environment.

  1. JDK ( I will use 1.8)
  2. Apache Maven.
  3. IDE ( Eclipse for our case )
  4. Git client to clone Shopizer in your local repository.

This tutorial assumes that you have a basic understanding of Maven and how to use git.