Tampilkan postingan dengan label convert. Tampilkan semua postingan
Tampilkan postingan dengan label convert. Tampilkan semua postingan

Convert String to integer int in Java

Senin, 03 Maret 2014

Java Code Online will discuss the Java Code to convert a String to an int. There is a feature provided in Java, which helps to perform this operation. The conversion is done with the help of a method called parseInt().

Actually any String which could be converted to a primitive can be converted to it, by using the parseXxx() method, where Xxx will replace the type in which it is to be converted, like int, float, etc.

I have provided a sample Java Code which asks the user to enter a number, which is taken as a String by the application. Later it is converted to an integer by using the parseInt() method. Go through the code for a clear understanding on how it is to be used.

  package developer;

  import java.util.Scanner;

  public class StringToInt {

  public static void main(String[] args) {

        System.out.println("Enter a number which would be taken as a String by the application");
        Scanner scanStr = new Scanner(System.in);
        String numStore = null;
        int numConvert = 0;

        // Takes the input as a String
        if (scanStr.hasNext()) {
            numStore = scanStr.next();
        }

        // Convert the String to int by using the Integer.parseInt() method
        numConvert = Integer.parseInt(numStore);

        System.out.println("The number entered by you is: " + numConvert);

     }
  }

The output is something like as shown below.


  Enter a number which would be taken as a String by the application
  22
  The number entered by you is: 22


Some observation points are:-
The String which is to be converted to a number must be a number in the String format. This is required so that the Java parser can parse the String successfully into an int.

If the value entered is not a number, suppose that you entered a String in words in place of a number in String format, then the output is shown below:-

 Enter a number which would be taken as a String by the application
 Conversion from String to int
 Exception in thread "main" java.lang.NumberFormatException: For input string: "Conversion"
     at java.lang.NumberFormatException.forInputString(Unknown Source)
     at java.lang.Integer.parseInt(Unknown Source)
     at java.lang.Integer.parseInt(Unknown Source)
     at developer.StringToInt .main(StringToInt .java:20)

So we see that if a String is entered to be parsed as an int, then the Java Compiler gives a big fat "NumberFormatException".

I hope the Java Code provide to convert an a String to an int was helpful. Do leave a comment if you liked the article. Java Code Online will soon be back with another interesting Java article.

Related Java Codes:-
Convert int to String in Java
Convert int to String in Java using Wrapper Classes
Read More..

How to parse String to Enum in Java Convert Enum to String with Example

Jumat, 07 Februari 2014

Converting Enum into String and parsing String to Enum in Java is becoming a common task with growing use of Enum. Enum is very versatile in Java and preferred choice to represent bounded data and since is almost used everywhere to carry literal value its important to know how to convert Enum to String in Java. In this article we will see both first converting Strings to Enum in Java and than Changing an Enum to String in Java with Example. I thought about this Enum tutorial when I wrote 10 Examples of Enum in Java. I missed String to Enum conversion and one of reader pointed out that. So here we have now.

Enum to String to Enum in Java

This article is in continuation of other conversion related post e.g. how to convert Date to String in Java and How to Convert String to Integer in Java. As these are common needs and having best way to do things in mind saves lot of time while coding.
Read more »
Read More..

How to Convert JSON array to String array in Java GSon example

Selasa, 04 Februari 2014

JSON array is a ordered collection of values, which are enclosed within brackets e.g. [] and separated by comma. In this Java tutorial we will convert JSON Array to String array in Java and subsequently create JSON from Java String Array. This tutorial is similar to our last article in JSON about How to convert JSON object to Java object, instead of JSON object, here we will convert JSON array to String array or List in Java. As I said earlier, there are lot's of open source library out there which can help to parse JSON data format and we have already seen Jackson library in our last example. In this tutorial we will use GSON to parse JSON data format and create Java String array or Listfrom JSON array representation. Given the popularity of JSON as lightweight alternative of XML to transfer data from Server to client in web applications, it's becoming imperative to know about JSON data format and parsing JSON string, much like parsing XML documents and knowing about different XML parsers e.g. DOM or SAX. Since Java application development is more about reusing existing library, then coding yourself, its important to know what is available, and which library other programmers are using. So far we have seen Jackson library, and here we will explore another one called GSon.
Read more »
Read More..

Convert int to String in Java Code

Java Code Online is going to discuss the way to convert an int into a String in Java. It is often required in Java programming, to convert an integer into a String value, and operate on it assuming it to be String.

Converting an integer into a String, provides many powerful features and methods which are inherent to Strings, but not to primitives like integer. That make the operating on the value much more easier when the value is used as a String.

I will discuss the most commonly used, and in fact the most easiest and effective method of converting an int into a String.

Use the + operator to convert int to String

1. Use the "+" operator, for converting an int into a String.

Simple isnt it. The logic is that the "+" operator is overloaded in Java. It performs many functions. When used with two integers, it produces the sum. But when a string is used with an int and the "+" operator in between, the the result is a String. For example:-

The issue with + operator for int
Using the + operator with ints result in their addition. The example demonstrates this:-


   package JavaTest1;

    class TestIntToString {

        public static void main(String[] args)

        {
            int i = 2;
            int j = 3;
          
            System.out.println(i + j);
        }
    }


The above code will result in printing 5. This is not what we wanted, so the solution is to use a string in between.

Solution for converting int to String in Java
If we change the above code such that the variable "j" is a String with some String assigned to it. Then the output will be a String. For example:-

    package JavaTest1;

    class TestIntToString {

        public static void main(String[] args)
        {
            int i = 2;
            String j = "";
            int k = 3;

            System.out.println(i + j + k);
        }
    }

When the above code is executed, the the output is:-
    23

So we see that this time the two numbers do not get added, but they resulted in concatenating to each other. This is because they are converted to String. Thats really cool. Now this String can use all the methods which are available to Strings. So making it really powerful.

So you can see that by using the "+" operator, you can easily convert an int into a String. I hope the post was helpful to you all. Keep buzzing Java Code Online for more info on Java.

Other Links of interest:-
Convert int to String using Wrapper in Java
Reverse a String
Length of String
Number of words in String
Palindrome Java program
Read More..