String Data conversions:
- String variable can accept any type of data.
- Generally input always collect in string format only.
- We need to convert these string type values into corresponding primitive types before processing in application.
- For example, a text box collect input into text(String) type only.
Primitive to String: Following method in Byte class can be used to perform this conversion:
Conversion logic using above method as follows:
/*
class Byte
{
public static byte parseByte(String s) throws NumberFormatException
Parses the string argument as a signed decimal byte.
}
*/
class StringToPrimitive
{
public static void main(String[] args)
{
String s = "100";
byte b = Byte.parseByte(s);
System.out.println("byte value is : " + b);
}
}
Object to String conversion: Byte class is providing following method to convert Object to String
Conversion logic using above method as follows:
/*
class Byte
{
public static Byte valueOf(byte b)
Returns Byte object representing byte value.
public String toString()
Returns a String object representing this Byte's value.
}
*/
class ObjectToString
{
public static void main(String[] args)
{
byte b = 10;
Byte obj = Byte.valueOf(b);
String s = obj.toString();
System.out.println("String value is : " + s);
}
}
String to Primitive conversion:
- An important data conversion used in java application is String to Primitive.
- parseByte() method of Byte class can be used for this conversion.
- Parsing means “conversion”.
Conversion logic using above method as follows:
class StringToPrimitive
{
public static void main(String[] args)
{
String s = "10";
byte b = Byte.parseByte(s);
}
}
Exception: Runtime Error will occur if the input is not valid. How can we avoid exceptions will discuss later in Exception handling concept
class StringToPrimitive
{
public static void main(String[] args)
{
String s = "abc";
byte b = Byte.parseByte(s); // Exception : Invalid input
}
}
String to Object conversion: Byte class is providing class level method for this conversion.
Conversion logic using above method as follows:
/*class Byte
{
public static Byte valueOf(String s) throws NumberFormatException
Returns a Byte object holding the value given by the specified String.
}*/
class StringToObject
{
public static void main(String[] args)
{
String s = "abc";
Byte obj = Byte.valueOf(s);
System.out.println("Byte value is : " + obj);
}
}
Conversion using Byte class constructor:
class StringToObject
{
public static void main(String[] args)
{
String s = "100" ;
Byte b = new Byte(s);
}
}