Convert int to String in Java Code

Selasa, 04 Februari 2014

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

Related Posts by Categories

0 komentar:

Posting Komentar