Type conversion to string in java

Data conversion in Java

Sometimes we need to convert data types from e.g. a number to a string or vice versa. We explain the basics behind it in this tutorial.
Go on reading to get the full explanation of all conversion and casts between types. All code snippets will work in your preferred IDE.

Table of Contents

  1. Data type conversion in Java
    1. Widening or Automatic Conversion
    2. Narrowing or Explicit Conversion
    1. Converting Java int to String
    2. Converting Java byte to String
    3. Converting Java short to String
    4. Converting Java long to String
    5. Converting Java double to String
    6. Converting Java float to String
    7. Converting Java boolean to String
    1. Converting Java Character to Int
    2. Converting Java Double to Int
    3. Converting Java long to int
    4. Converting Java Int to Char

    In the tutorial What are data types in Java we have explained the Java data types. But using them will result quickly into the need to convert between them.

    That process is called Java Type Casting or Java Type Cast , and we use type cast in Java when we want to convert an object or variable of one type into another.

    1. Data type conversion in Java

    Changing a value from one data type to another type is known as data type conversion. There are 2 types of conversions:

    1.1. Widening or Automatic Conversion

    This is also named a lower to higher precision conversion and therefore done automatically by the compiler for us. Widening or Automatic conversion takes place when two data types are automatically converted. It can occur when

    • The two data types are compatible
    • When we assign value of a smaller data type to a bigger data type

    So a conversion in this direction will work out of the box:

    byte ➡ short ➡ int ➡ long ➡ float ➡ double

    class Low2High public static void main(String[] args) int i = 100; 
    long l = i;
    float f = l;
    System.out.println("Int value " +i);
    System.out.println("Long value " +l);
    System.out.println("Float value " +f);
    >
    >

    The output for this example will be :

    Int value 100

    Long value 100

    Float value 100.0

    Here is the screenshot from the Eclipse:

    dataConversion-low-2-high

    1.2. Narrowing or Explicit Conversion

    This is also called a higher to lower precision conversion often by developers named as cast or casting.
    So a conversion in this direction will need special handling:

    double ➡ float ➡ long ➡ int ➡ short ➡ byte

    Since this direction is losing information or precision the machine or compiler cannot decide for the human. Here we have to tell the compiler what he needs to do for us.

    class High2Low public static void main(String[] args) double d = 100.05; 
    long l = (long)d;
    int i = (int)l;
    System.out.println("Double value " +d);
    System.out.println("Long value " +l);
    System.out.println("Int value " +i);
    >
    >

    The output for this example will be:

    Double value 100.05

    Long value 100

    Int value 100

    Here is the screenshot from the Eclipse:

    dataConversion-high-2-low

    2. How to convert values to Strings?

    In any programming language we have to handle conversion from a human input (string) to a specific value mostly a number or a different specific type.

    2.1. Converting Java int to String

    Converting int to String is very common in Java, here is the most popular way to do it:

    The integer class has a static method that returns a String object representing the specified int parameter.

    public class Int2String public static void main(String[] args) int number = -125; 
    String numberAsString = Integer.toString(number);
    System.out.println(numberAsString);
    >
    >

    dataConversion-int-to-string

    We can reduce the above code to

    public class Int2String public static void main(String[] args) System.out.println(Integer.toString(-125)); 
    >
    >

    dataConversion-int-to-string

    There are other ways to do it, but this is the most popular way is:

    public class Int2String public static void main(String[] args) int number = -125; 
    System.out.println("anything to note" + number);
    >
    >

    dataConversion-int-to-string

    2.2. Converting Java byte to String

    This is similar method to integer to string, and it is used when you need to convert byte to String in Java, you can use this method of Byte class.

    Here is an example how to do it:

    public class Byte2String public static void main(String[] args) byte b = 20; 
    System.out.println(Byte.toString(b));
    >
    >

    The output of this example will be

    Here is the screenshot from the Eclipse:

    dataConversion-byte-to-string

    2.3. Converting Java short to String

    Using Short.toString(short d)

    Similar method as using byte to String, when you need to convert short to String in Java, you can use this method.

    public class Short2String public static void main(String[] args) short s = 25; 
    System.out.println(Short.toString(s));
    >
    >

    The output of converting to String will be

    Here is the screenshot from the Eclipse:

    dataConversion-short-to-string

    The output of converting to String will be

    2.4. Converting Java long to String

    This is an overloaded method, it can be used convert long to String. The method is static method of String class.

    Here is an example how to use this method:

    public class Long2String public static void main(String[] args) long l = 14861584l; 
    String s = String.valueOf(l);
    System.out.println(s);
    >
    >

    The output for this example will be

    Here is the screenshot from the Eclipse:

    dataConversion-long-to-string

    2.5. Converting Java double to String

    This is an overloaded method used for converting double to String. The valueOf() is the static method of String class.

    public class Double2String public static void main(String[] args) double d = 24.5; 
    String s = String.valueOf(d);
    System.out.println(s);
    >
    >

    Here is the screenshot from the Eclipse:

    dataConversion-double-to-string

    2.6. Converting Java float to String

    This method converts float to String. The toString() is the static method of float class.

    Here is an example of this method:

    public class Float2String public static void main(String[] args) float f = 45.7f; 
    String s = Float.toString(f);
    System.out.println(s);
    >
    >

    The output for this example will be

    Here is the screenshot from the Eclipse:

    dataConversion-float-to-string

    2.7. Converting Java boolean to String

    This method converts boolean to String. The toString() is the static method of boolean class.

    Here is an example of this method:

    public class Boolean2String public static void main(String[] args) boolean b1 = true; 
    boolean b2 = false;
    String s1 = Boolean.toString(b1);
    String s2 = Boolean.toString(b2);
    System.out.println(s1);
    System.out.println(s2);
    >
    >

    The outputs for this example will be

    Here is the screenshot from the Eclipse:

    dataConversion-boolean-to-string

    3. Now we have shown conversion to String, now we can show some conversion to Int

    3.1. Converting Java Character to Int

    We use char to int Java when we want to convert a char value in int, we define a char (for example char c = ‘a’;) and than convert it into int. There are few ways to convert it but the simplest way is to just take the char value and initialize it, here is an example;

    public class Char2Int public static void main(String[] args ) char c = 'a'; 
    int i = c;
    System.out.println(i);
    >
    >

    but let’s explain how it works, basically every character has its ASCII value, and when we convert it into int, the int will return its ASCII value.

    Here is the screenshot from the Eclipse:

    dataConversion-char-to-int

    Note: if we put in char number (example char = ‘1’;) when we convert it to int the return value will not be 1, the int will return its ASCII value (in this case 49)

    3.2. Converting Java Double to Int

    We use double to int Java in cases where we need double value converted in int. It is similar to previous conversion, and this type also has multiple ways of conversion, but we will show you the simplest one:

    public class Double2Int public static void main(String[] args ) double d = 4.255; 
    int i = (int) d;
    System.out.println(i);
    >
    >

    As a result, but even if we put really high decimal value (example 4.9999) the int value will return 4, this method will not round the value.

    Here is the screenshot from the Eclipse:

    dataConversion-double-to-int

    3.3. Converting Java long to int

    This conversion is similar to previous one, it is used when we want to convert long value to int, so here is an example:

    public class Long2Int public static void main(String[] args ) long l = 4245; 
    int i = (int) l;
    System.out.println(i);
    >
    >

    We have already explained how to convert char to int, but what about int to char?

    Here is the screenshot from the Eclipse:

    dataConversion-long-to-int

    3.4. Converting Java Int to Char

    Converting int to char java is made by typecasting. Similar to char to int, when int returned ASCII value of char, now we will have ASCII value of int, and char will return its value, here is an example:

    public class Int2Char public static void main(String[] args ) int i = 38; 
    char c = (char) i;
    System.out.println(c);
    >
    >

    If we put any other number and convert it, we would get different characters, because of the ASCII code

    Here is the screenshot from the Eclipse:

    Источник

    Converting Between Numbers and Strings

    Frequently, a program ends up with numeric data in a string object—a value entered by the user, for example.

    The Number subclasses that wrap primitive numeric types ( Byte , Integer , Double , Float , Long , and Short ) each provide a class method named valueOf that converts a string to an object of that type. Here is an example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:

    public class ValueOfDemo < public static void main(String[] args) < // this program requires two // arguments on the command line if (args.length == 2) < // convert strings to numbers float a = (Float.valueOf(args[0])).floatValue(); float b = (Float.valueOf(args[1])).floatValue(); // do some arithmetic System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); >else < System.out.println("This program " + "requires two command-line arguments."); >> >

    The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:

    a + b = 91.7 a - b = -82.7 a * b = 392.4 a / b = 0.0516055 a % b = 4.5

    Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat() ) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we could use:

    float a = Float.parseFloat(args[0]); float b = Float.parseFloat(args[1]);

    Converting Numbers to Strings

    Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:

    int i; // Concatenate "i" with an empty string; conversion is handled for you. String s1 = "" + i;
    // The valueOf class method. String s2 = String.valueOf(i);

    Each of the Number subclasses includes a class method, toString() , that will convert its primitive type to a string. For example:

    int i; double d; String s3 = Integer.toString(i); String s4 = Double.toString(d);

    The ToStringDemo example uses the toString method to convert a number to a string. The program then uses some string methods to compute the number of digits before and after the decimal point:

    public class ToStringDemo < public static void main(String[] args) < double d = 858.48; String s = Double.toString(d); int dot = s.indexOf('.'); System.out.println(dot + " digits " + "before decimal point."); System.out.println( (s.length() - dot - 1) + " digits after decimal point."); >>

    The output of this program is:

    3 digits before decimal point. 2 digits after decimal point.

    Источник

    Читайте также:  Boilerplate code in java
Оцените статью