Java Conversion

Java String to Int

By using Integer.parsrInt() method we can convert a string type data to a integer type. This method returns instance of integer class. When a string is made up of any digits and we need to do arithmetic operation then we need to concert the string to integer.

Example:

public class StringToInt {


    public static void main(String[] args) {


        String s="646";


        int num1=900;


        int num2=Integer.parseInt(s);


        int sum=num1-num2;


        System.out.println("Result is: "+sum);


    }


}

Output:

Result is: 14

Let’s explain the code:

Explanation:

Inside the main method, there are three variables declared and initialized:

String s = “646”;: A String variable s is initialized with the value “646”. This is the string that we want to convert to an integer later in the code.

int num1 = 900;: An integer variable num1 is initialized with the value 900.

int num2 = Integer.parseInt(s);: Another integer variable num2 is declared and initialized by converting the string s to an integer using the Integer.parseInt() method. The parseInt() method takes a String as input and returns an int representation of the provided string.

The code then calculates the difference between num1 and num2 and stores it in the variable sum: int sum = num1 – num2;.

Finally, the result of the subtraction is printed to the console using System.out.println(): System.out.println(“Result is: ” + sum);.

Overall, the code takes a String representation of a number (s) and an integer (num1), converts the String to an int using Integer.parseInt(), and then performs a subtraction between num1 and the converted value. The result of the subtraction is then printed to the console. In this specific example, the result will be 254, which is the difference between 900 and the converted value of 646.

In the above example, the variable s is a string. If we want to calculate s-num2.it will give an error. Make sure that the String contains a valid integer representation; otherwise, parseInt() will throw a NumberFormatException. It’s important to handle this exception to avoid program crashes when dealing with invalid inputs.

Example:

public class StringToInt {

    public static void main(String[] args) {
       String s="Hello World";
       int i=Integer.parseInt(s);
       System.out.println("Result is: "+i);
    }

}

Output:

Also, keep in mind that the parseInt() method only works for converting String representations of integers, and it won’t work for floating-point numbers or other non-integer formats. For such cases, you’d need to use different conversion methods like parseFloat() or Double.parseDouble().

Java Int to String

To convert a int type data to String type we need to use String.valueOf() method or integer.toString() method.

These methods are generally used when we need to display number in textfield because everything is displayed as a string form.

Example:

public class IntToString {


    public static void main(String[] args) {


        int i1=111;


        int i2=123;


        String s=String.valueOf(i1);


        System.out.println("Before Conversion");


        System.out.println("i2+i1: "+ " "+(i2+i1));


        System.out.println("After Conversion");


        System.out.println("i2+s: "+i2+s);


    }


}

Output:

Before Conversion

i2+i1: 234

After Conversion

i2+s: 123111

Explanation:

Two integer variables, i1 and i2, are declared and initialized with values 111 and 123, respectively.

The integer variable i1 is converted to a String and stored in the variable s.

The code prints “Before Conversion” to the console.

The code performs an addition operation between i2 and i1, and the result is printed to the console.

The code prints “After Conversion” to the console.

The code concatenates i2 (an integer) with s (a String), and the resulting string is printed to the console.

It’s important to remember that the behavior of the + operator in Java can change depending on the types of the operands. When used with String and another data type, it performs string concatenation, while with numeric data types, it performs arithmetic operations.

Java String to Char

We use charAt() methods  to convert String to char. But this method returns the characters according the index number. So we need to use loop to display the all characters of a string.

Example:

public class IntToString {


    public static void main(String[] args) {


        String s="Java world";


        for(int i=0;i<s.length();i++) {


            char c=s.charAt(i);


            System.out.println("characters are "+c);


        }


    }


}

Output:

characters are J

characters are a

characters are v

characters are a

characters are

characters are w

characters are o

characters are r

characters are l

characters are d

We can also use ‘tocharArray()” method to convert a ‘String’ to ‘char’.

This method returns a new character array that represents the contents of the String. Each character in the array corresponds to a character in the String.

Example:

public class StringToCharArrayExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        char[] charArray = str.toCharArray();

        // Printing the characters one by one
        System.out.println("String to CharArray:");
        for (char c : charArray) {
            System.out.print(c + " ");
        }
        System.out.println();

        // Accessing a specific character from the array
        char firstChar = charArray[0];
        System.out.println("First character: " + firstChar);
    }
}

Output:

String to CharArray:

H e l l o , W o r l d !

First character: H

In this example, the str variable contains the String “Hello, World!”. This String can be transformed into an array of characters (charArray) using the toCharArray() method. We then print the characters one by one to the console and access a specific character from the array using array indexing.  As you can see, the String “Hello, World!” is successfully converted into an array of characters, and we can access individual characters from the array using their respective indices.

Visited 1 times, 1 visit(s) today

Comments are closed.

Close