Java Conversion

By ukmodak | March 31st 2024 10:34:01 AM | viewed 804 times

Java Convert String to int

We can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we can use Integer.valueOf() method which returns instance of Integer class.

Scenario

It is generally used if we have to perform mathematical operations on the string which contains a number. Whenever we receive data from TextField or TextArea, entered data is received as a string. If entered data is in number format, we need to convert the string to an int. To do so, we use Integer.parseInt() method.

Signature

The parseInt() is the static method of Integer class. The signature of parseInt() method is given below:

    public static int parseInt(String s)  

Java String to int Example: Integer.parseInt()

    int i=Integer.parseInt("200");  
    //Java Program to demonstrate the conversion of String into int  
    //using Integer.parseInt() method  
    public class StringToIntExample1{  
    public static void main(String args[]){  
    //Declaring String variable  
    String s="200";  
    //Converting String into int using Integer.parseInt()  
    int i=Integer.parseInt(s);  
    //Printing value of i  
    System.out.println(i);  
    }}  

Test it Now

Output:

200

Understanding String Concatenation Operator

    //Java Program to understand the working of string concatenation operator  
    public class StringToIntExample{  
    public static void main(String args[]){  
    //Declaring String variable  
    String s="200";  
    //Converting String into int using Integer.parseInt()  
    int i=Integer.parseInt(s);  
    System.out.println(s+100);//200100, because "200"+100, here + is a string concatenation operator  
    System.out.println(i+100);//300, because 200+100, here + is a binary plus operator  
    }}  

Test it Now

Output:

200100
300

Java String to Integer Example: Integer.valueOf()

The Integer.valueOf() method converts String into Integer object. Let's see the simple code to convert String to Integer in Java.

    //Java Program to demonstrate the conversion of String into Integer  
    //using Integer.valueOf() method  
    public class StringToIntegerExample2{  
    public static void main(String args[]){  
    //Declaring a string  
    String s="200";  
    //converting String into Integer using Integer.valueOf() method  
    Integer i=Integer.valueOf(s);  
    System.out.println(i);  
    }}  

Test it Now

Output:

300

NumberFormatException Case

If you don't have numbers in string literal, calling Integer.parseInt() or Integer.valueOf() methods throw NumberFormatException.

    //Java Program to demonstrate the case of NumberFormatException  
    public class StringToIntegerExample3{  
    public static void main(String args[]){  
    String s="hello";  
    int i=Integer.parseInt(s);  
    System.out.println(i);  
    }}  

Test it Now

Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "hello"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Integer.parseInt(Integer.java:652)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
	at StringToIntegerExample3.main(StringToIntegerExample3.java:4)


Java Convert int to String

We can convert int to String in java using String.valueOf() and Integer.toString() methods. Alternatively, we can use String.format() method, string concatenation operator etc.

Scenario

It is generally used if we have to display number in textfield because everything is displayed as a string in form

1) String.valueOf()

The String.valueOf() method converts int to String. The valueOf() is the static method of String class. The signature of valueOf() method is given below:

    public static String valueOf(int i)  

Java int to String Example using String.valueOf()

    int i=10;  
    String s=String.valueOf(i);//Now it will return "10" 
        public class IntToStringExample1{  
    public static void main(String args[]){  
    int i=200;  
    String s=String.valueOf(i);  
    System.out.println(i+100);//300 because + is binary plus operator  
    System.out.println(s+100);//200100 because + is string concatenation operator  
    }}  

Test it Now

Output:

300
200100

    

2) Integer.toString()

The Integer.toString() method converts int to String. The toString() is the static method of Integer class. The signature of toString() method is given below:

    public static String toString(int i)  

Java int to String Example using Integer.toString()

int i=10;  
String s=Integer.toString(i);//Now it will return "10" 
    public class IntToStringExample2{  
    public static void main(String args[]){  
    int i=200;  
    String s=Integer.toString(i);  
    System.out.println(i+100);//300 because + is binary plus operator  
    System.out.println(s+100);//200100 because + is string concatenation operator  
    }}  

Test it Now

Output:

300
200100

3) String.format()

    public static String format(String format, Object... args)  

Java int to String Example using String.format()

    public class IntToStringExample3{  
    public static void main(String args[]){  
    int i=200;  
    String s=String.format("%d",i);  
    System.out.println(s);  
    }}  

Test it Now

Output:

200

Java String to long

We can convert String to long in java using Long.parseLong() method.

Scenario

It is generally used if we have to perform mathematical operations on the string that contains long number. Whenever we get data from textfield or textarea, entered data is received as a string. If entered data is long, we need to convert string to long. To do so, we use Long.parseLong() method.

Signature

The parseLong() is the static method of Long class. The signature of parseLong() method is given below:

    public static long parseLong(String s)  

Java String to long Example

    long l=Long.parseLong("200");  
    public class StringToLongExample{  
    public static void main(String args[]){  
    String s="9990449935";  
    long l=Long.parseLong(s);  
    System.out.println(l);  
    }}  

Test it Now

Output:

9990449935

Java long to String

We can convert long to String in java using String.valueOf() and Long.toString() methods.

1) String.valueOf()

The String.valueOf() is an overloaded method. It can be used to convert long to String. The valueOf() is the static method of String class. The signature of valueOf() method is given below:

    public static String valueOf(long i)  

Java long to String Example using String.valueOf()

    long i=9993939399L;//L is the suffix for long  
    String s=String.valueOf(i);//Now it will return "9993939399"


    public class LongToStringExample1{  
    public static void main(String args[]){  
    long i=9993939399L;  
    String s=String.valueOf(i);  
    System.out.println(s);  
    }}  

Test it Now

Output:

9993939399
	

2) Long.toString()

The Long.toString() method converts long to String. The toString() is the static method of Long class. The signature of toString() method is given below:

public static String toString(long i) 

Java long to String Example using Long.toString()

    long i=9993939399L;  
    String s=Long.toString(i);//Now it will return "9993939399"  
	
	
	    public class LongToStringExample2{  
    public static void main(String args[]){  
    long i=9993939399L;  
    String s=Long.toString(i);  
    System.out.println(s);  
    }}  

Test it Now

Output:

9993939399

Java String to float

We can convert String to float in java using Float.parseFloat() method.

Java String to float Example

    float f=Float.parseFloat("23.6");  
	
	    public class StringToFloatExample{  
    public static void main(String args[]){  
    String s="23.6";  
    float f=Float.parseFloat("23.6");  
    System.out.println(f);  
    }}  

Test it Now

Output:

23.6

Java Convert float to String

We can convert float to String in java using String.valueOf() and Float.toString() methods.

1) String.valueOf()

The String.valueOf() is an overloaded method. It can be used to convert float to String. The valueOf() is the static method of String class. The signature of valueOf() method for the float conversion is given below:

public static String valueOf(float f) 

Java float to String Example: String.valueOf()

    float f=12.3F;//F is the suffix for float  
    String s=String.valueOf(f);  
	
	
   public class FloatToStringExample1{  
    public static void main(String args[]){  
    float f=12.3F;//F is the suffix for float  
    String s=String.valueOf(f);  
    System.out.println(s);  
    }}  

Test it Now

Output:

12.3

2) Float.toString()

The Float.toString() method also converts float to String. The toString() is the static method of Float class. The signature of toString() method is given below:

    public static String toString(float f)  

Java float to String Example: Float.toString()

float f=89.7F;  
String s=Float.toString(f);  

    public class FloatToStringExample2{  
    public static void main(String args[]){  
    float f=89.7F;  
    String s=Float.toString(f);  
    System.out.println(s);  
    }}  

Test it Now

Output:

89.7

Java Convert String to double

We can convert String to double in java using Double.parseDouble() method.

Java String to double Example

    public class StringToDoubleExample{  
    public static void main(String args[]){  
    String s="23.6";  
    double d=Double.parseDouble("23.6");  
    System.out.println(d);  
    }}  

Test it Now

Output:

23.6

Java Convert double to String

We can convert double to String in java using String.valueOf() and Double.toString() methods.

Java double to String Example: String.valueOf()

    public class DoubleToStringExample1{  
    public static void main(String args[]){  
    double d=12.3;  
    String s=String.valueOf(d);  
    System.out.println(s);  
    }}  

Test it Now

Output:

12.3

Java double to String Example: Double.toString()

    public class DoubleToStringExample2{  
    public static void main(String args[]){  
    double d=89.7;  
    String s=Double.toString(d);  
    System.out.println(s);  
    }}  

Test it Now

Output:

89.7

Java String to Date

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.

Java String to Date Example

    import java.text.SimpleDateFormat;  
    import java.util.Date;  
    public class StringToDateExample1 {  
    public static void main(String[] args)throws Exception {  
        String sDate1="31/12/1998";  
        Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);  
        System.out.println(sDate1+"\t"+date1);  
    }  
    }  

Test it Now

Output:

31/12/1998	Thu Dec 31 00:00:00 IST 1998

    import java.text.SimpleDateFormat;  
    import java.util.Date;  
    public class StringToDateExample2 {  
    public static void main(String[] args)throws Exception {  
        String sDate1="31/12/1998";  
        String sDate2 = "31-Dec-1998";  
        String sDate3 = "12 31, 1998";  
        String sDate4 = "Thu, Dec 31 1998";  
        String sDate5 = "Thu, Dec 31 1998 23:37:50";  
        String sDate6 = "31-Dec-1998 23:37:50";  
        SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");  
        SimpleDateFormat formatter2=new SimpleDateFormat("dd-MMM-yyyy");  
        SimpleDateFormat formatter3=new SimpleDateFormat("MM dd, yyyy");  
        SimpleDateFormat formatter4=new SimpleDateFormat("E, MMM dd yyyy");  
        SimpleDateFormat formatter5=new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss");  
        SimpleDateFormat formatter6=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");  
        Date date1=formatter1.parse(sDate1);  
        Date date2=formatter2.parse(sDate2);  
        Date date3=formatter3.parse(sDate3);  
        Date date4=formatter4.parse(sDate4);  
        Date date5=formatter5.parse(sDate5);  
        Date date6=formatter6.parse(sDate6);  
        System.out.println(sDate1+"\t"+date1);  
        System.out.println(sDate2+"\t"+date2);  
        System.out.println(sDate3+"\t"+date3);  
        System.out.println(sDate4+"\t"+date4);  
        System.out.println(sDate5+"\t"+date5);  
        System.out.println(sDate6+"\t"+date6);  
    }  
    }  

Test it Now

Output:

31/12/1998	Thu Dec 31 00:00:00 IST 1998
31-Dec-1998	Thu Dec 31 00:00:00 IST 1998
12 31, 1998	Thu Dec 31 00:00:00 IST 1998
Thu, Dec 31 1998	Thu Dec 31 00:00:00 IST 1998
Thu, Dec 31 1998 23:37:50	Thu Dec 31 23:37:50 IST 1998
31-Dec-1998 23:37:50	Thu Dec 31 23:37:50 IST 1998

Java Convert Date to String

We can convert Date to String in java using format() method of java.text.DateFormat class.

format() method of DateFormat

The format() method of DateFormat class is used to convert Date into String. DateFormat is an abstract class. The child class of DateFormat is SimpleDateFormat. It is the implementation of DateFormat class. The signature of format() method is given below:

String format(Date d)  

Java Date to String Example

    Date date = Calendar.getInstance().getTime();  
    DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");  
    String strDate = dateFormat.format(date);  
    import java.text.DateFormat;  
    import java.text.SimpleDateFormat;  
    import java.util.Date;  
    import java.util.Calendar;  
     public class DateToStringExample1 {  
           public static void main(String args[]){  
                    Date date = Calendar.getInstance().getTime();  
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");  
                    String strDate = dateFormat.format(date);  
                    System.out.println("Converted String: " + strDate);  
                     
            }  
    }  

Test it Now

Output:

Converted String: 2017-24-28 04:24:27

    import java.text.ParseException;  
    import java.text.SimpleDateFormat;  
    import java.util.Date;  
    import java.util.Locale;  
    public class DateToStringExample2 {  
    public static void main(String[] args) {  
        Date date = new Date();  
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");  
        String strDate = formatter.format(date);  
        System.out.println("Date Format with MM/dd/yyyy : "+strDate);  
      
        formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");  
        strDate = formatter.format(date);  
        System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);  
      
        formatter = new SimpleDateFormat("dd MMMM yyyy");  
        strDate = formatter.format(date);  
        System.out.println("Date Format with dd MMMM yyyy : "+strDate);  
      
        formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");  
        strDate = formatter.format(date);  
        System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);  
      
        formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");  
        strDate = formatter.format(date);  
        System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);  
    }  
    }  

Test it Now

Output:

Date Format with MM/dd/yyyy : 04/13/2015
Date Format with dd-M-yyyy hh:mm:ss : 13-4-2015 10:59:26
Date Format with dd MMMM yyyy : 13 April 2015
Date Format with dd MMMM yyyy zzzz : 13 April 2015 India Standard Time
Date Format with E, dd MMM yyyy HH:mm:ss z : Mon, 13 Apr 2015 22:59:26 IST

Java Convert String to char

We can convert String to char in java using charAt() method of String class.

public char charAt(int index) 

Java String to char Example: charAt() method

String s="hello";  
char c=s.charAt(0);//returns h 
    public class StringToCharExample1{  
    public static void main(String args[]){  
    String s="hello";  
    char c=s.charAt(0);//returns h  
    System.out.println("1st character is: "+c);  
    }}  

Test it Now

Output:

1st character is: h

    public class StringToCharExample2{  
    public static void main(String args[]){  
    String s="hello";    
    for(int i=0; i<s.length();i++){  
            char c = s.charAt(i);  
            System.out.println("char at "+i+" index is: "+c);  
    }   
    }}  

Test it Now

Output:

char at 0 index is: h
char at 1 index is: e
char at 2 index is: l
char at 3 index is: l
char at 4 index is: o

Java String to char Example: toCharArray() method

    public class StringToCharExample3{  
    public static void main(String args[]){  
    String s1="hello";    
    char[] ch=s1.toCharArray();    
    for(int i=0;i<ch.length;i++){    
    System.out.println("char at "+i+" index is: "+ch[i]);   
    }  
    }}  

Test it Now

Output:

char at 0 index is: h
char at 1 index is: e
char at 2 index is: l
char at 3 index is: l
char at 4 index is: o

Java Convert char to String

We can convert char to String in java using String.valueOf(char) method of String class and Character.toString(char) method of Character class.

Java char to String Example: String.valueOf() method

    char c='S';  
    String s=String.valueOf(c);  
    public class CharToStringExample1{  
    public static void main(String args[]){  
    char c='S';  
    String s=String.valueOf(c);  
    System.out.println("String is: "+s);  
    }}  

Test it Now

Output:

String is: S

Java char to String Example: Character.toString() method

    public class CharToStringExample2{  
    public static void main(String args[]){  
    char c='M';    
    String s=Character.toString(c);  
    System.out.println("String is: "+s);    
    }}  

Test it Now

Output:

String is: M

Java Convert String to Object

We can convert String to Object in java with assignment operator. Each class is internally a child class of Object class. So you can assign string to Object directly.

Java String to Object Example

    String s="hello";  
    Object obj=s;  
    public class StringToObjectExample{  
    public static void main(String args[]){  
    String s="hello";  
    Object obj=s;  
    System.out.println(obj);  
    }}  

Test it Now

Output:

hello

Java String to Class object Example

    public class StringToObjectExample2{  
    public static void main(String args[])throws Exception{  
    Class c=Class.forName("java.lang.String");  
    System.out.println("class name: "+c.getName());  
    System.out.println("super class name: "+c.getSuperclass().getName());  
    }}  

Test it Now

Output:

Class name: java.lang.String
Super class name: java.lang.Object

Java Convert Object to String

We can convert Object to String in java using toString() method of Object class or String.valueOf(object) method.

You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else. Here, we are going to see two examples of converting Object into String. In the first example, we are going to convert Emp class object into String which is an user-defined class. In second example, we are going to convert StringBuilder to String.

Java Object to String Example: Converting User-defined class

    class Emp{}  
    public class ObjectToStringExample{  
    public static void main(String args[]){  
    Emp e=new Emp();  
    String s=e.toString();  
    String s2=String.valueOf(e);  
    System.out.println(s);  
    System.out.println(s2);  
    }}  

Test it Now

Output:

Emp@2a139a55
Emp@2a139a55

Java Object to String Example: Converting StringBuilder

    public class ObjectToStringExample2{  
    public static void main(String args[]){  
    String s="hello";  
    StringBuilder sb=new StringBuilder(s);  
    sb.reverse();  
    String rev=sb.toString();//converting StringBuilder to String  
    System.out.println("String is: "+s);  
    System.out.println("Reverse String is: "+rev);  
    }}  

Test it Now

Output:

String is: hello
Reverse String is: olleh

    public class ObjectToStringExample3{  
    public static void main(String args[]){  
    String s="nitin";  
    StringBuilder sb=new StringBuilder(s);  
    sb.reverse();  
    String rev=sb.toString();//converting StringBuilder to String  
    if(s.equals(rev)){  
    System.out.println("Palindrome String");  
    }else{  
    System.out.println("Not Palindrome String");  
    }  
    }}  

Test it Now

Output:

Palindrome String

Java Convert int to long

We can convert int to long in java using assignment operator. There is nothing to do extra because lower type can be converted to higher type implicitly.

It is also known as implicit type casting or type promotion.

Java int to long Example

    public class IntToLongExample1{  
    public static void main(String args[]){  
    int i=200;  
    long l=i;  
    System.out.println(l);  
    }}  

Test it Now

Output:

200

Java int to Long Example

    public class IntToLongExample2{  
    public static void main(String args[]){  
    int i=100;  
    Long l= new Long(i);//first way  
    Long l2=Long.valueOf(i);//second way  
    System.out.println(l);  
    System.out.println(l2);  
    }}  

Test it Now

Output:

100
100

Java Convert long to int

We can convert long to int in java using typecasting. To convert higher data type into lower, we need to perform typecasting.

Typecasting in java is performed through typecast operator (datatype).

Here, we are going to learn how to convert long primitive type into int and Long object into int.

Java long to int Example

    public class LongToIntExample1{  
    public static void main(String args[]){  
    long l=500;  
    int i=(int)l;  
    System.out.println(i);  
    }}  

Test it Now

Output:

500

Java Long to int Example

    public class LongToIntExample2{  
    public static void main(String args[]){  
    Long l= new Long(10);  
    int i=l.intValue();  
    System.out.println(i);  
    }}  

Test it Now

Output:

10

Java Convert int to double

We can convert int to double in java using assignment operator. There is nothing to do extra because lower type can be converted to higher type implicitly.

Java int to double Example

    public class IntToDoubleExample1{  
    public static void main(String args[]){  
    int i=200;  
    double d=i;  
    System.out.println(d);  
    }}  

Test it Now

Output:

200.0

Java int to Double Example

    public class IntToDoubleExample2{  
    public static void main(String args[]){  
    int i=100;  
    Double d= new Double(i);//first way  
    Double d2=Double.valueOf(i);//second way  
    System.out.println(d);  
    System.out.println(d2);  
    }}  

Test it Now

Output:

100.0
100.0

Java Convert double to int

We can convert double to int in java using typecasting. To convert double data type into int, we need to perform typecasting.

Java double to int Example: Typecasting

    public class DoubleToIntExample1{  
    public static void main(String args[]){  
    double d=10.5;  
    int i=(int)d;  
    System.out.println(i);  
    }}  

Test it Now

Output:

10

Java Double to int Example: intValue() method

    public class DoubleToIntExample2{  
    public static void main(String args[]){  
    Double d=new Double(10.5);  
    int i=d.intValue();  
    System.out.println(i);  
    }}  

Test it Now

Output:

10

Java Convert char to int

We can convert char to int in java using various ways. If we direct assign char variable to int, it will return ASCII value of given character.

1) Java char to int Example: Get ASCII value

    public class CharToIntExample1{  
    public static void main(String args[]){  
    char c='a';  
    char c2='1';  
    int a=c;  
    int b=c2;  
    System.out.println(a);  
    System.out.println(b);  
    }}  

Test it Now

Output:

97
49

2) Java char to int Example: Character.getNumericValue()

    public class CharToIntExample2{  
    public static void main(String args[]){  
    char c='1';  
    int a=Character.getNumericValue(c);  
    System.out.println(a);  
    }}  

Test it Now

Output:

1

3) Java char to int Example: String.valueOf()

    public class CharToIntExample3{  
    public static void main(String args[]){  
    char c='1';  
    int a=Integer.parseInt(String.valueOf(c));  
    System.out.println(a);  
    }}  

Test it Now

Output:

1

Java Convert int to char

We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable.

Java int to char Example: Typecasting

    public class IntToCharExample1{  
    public static void main(String args[]){  
    int a=65;  
    char c=(char)a;  
    System.out.println(a);  
    }}  

Test it Now

Output:

A

    public class IntToCharExample2{  
    public static void main(String args[]){  
    int a=1;    
    char c=(char)a;    
    System.out.println(c);  
    }}  

Test it Now

Output:



If you add '0' with int variable, it will return actual value in the char variable. The ASCII value of '0' is 48. So, if you add 1 with 48, it becomes 49 which is equal to 1. The ASCII character of 49 is 1.

    public class IntToCharExample3{  
    public static void main(String args[]){  
    int a=1;    
    char c=(char)(a+'0');    
    System.out.println(c);   
    }}  

Test it Now

Output:

1

If you store integer value in a single quote, it will store actual character in char variable.

    public class IntToCharExample4{  
    public static void main(String args[]){  
    int a='1';    
    char c=(char)a;    
    System.out.println(c);  
    }}  

Test it Now

Output:

1

Java int to char Example: Character.forDigit()

To get the actual value, you can also use Character.forDigit() method.

    public class IntToCharExample5{  
    public static void main(String args[]){  
    int REDIX=10;//redix 10 is for decimal number, for hexa use redix 16  
    int a=1;    
    char c=Character.forDigit(a,REDIX);    
    System.out.println(c);   
    }}  

Test it Now

Output:

1

To get the hexa value, use redix 16 in Character.forDigit() method.

    public class IntToCharExample6{  
    public static void main(String args[]){  
    int REDIX=16;//redix 16 is for Hexadecimal value  
    int a=10;    
    char c=Character.forDigit(a,REDIX);    
    System.out.println(c);   
    }}  

Test it Now

Output:

a

Java Convert String to boolean

We can convert String to boolean in java using Boolean.parseBoolean(string) method.

To convert String into Boolean object, we can use Boolean.valueOf(string) method which returns instance of Boolean class.

To get boolean true, string must contain "true". Here, case is ignored. So, "true" or "TRUE" will return boolean true. Any other string value except "true" returns boolean false.

Java String to boolean Example: Boolean.parseBoolean()

    public static int parseBoolean(String s)  
    public class StringToBooleanExample{  
    public static void main(String args[]){  
    String s1="true";  
    String s2="TRue";  
    String s3="ok";  
    boolean b1=Boolean.parseBoolean(s1);  
    boolean b2=Boolean.parseBoolean(s2);  
    boolean b3=Boolean.parseBoolean(s3);  
    System.out.println(b1);  
    System.out.println(b2);  
    System.out.println(b3);  
    }}  

Test it Now

Output:

true
true
false

Java String to Boolean Example: Boolean.valueOf()

The Boolean.valueOf() method converts string into Boolean object. Let's see the simple code to convert String to Boolean in java.

    public class StringToBooleanExample2{  
    public static void main(String args[]){  
    String s1="true";    
    String s2="TRue";    
    String s3="ok";    
    Boolean b1=Boolean.valueOf(s1);    
    Boolean b2=Boolean.valueOf(s2);    
    Boolean b3=Boolean.valueOf(s3);    
    System.out.println(b1);    
    System.out.println(b2);    
    System.out.println(b3);  
    }}  

Test it Now

Output:

true
true
false

Java Convert boolean to String

We can convert boolean to String in java using String.valueOf(boolean) method.

Alternatively, we can use Boolean.toString(boolean) method which also converts boolean into String.

1) String.valueOf()

The String.valueOf() method converts boolean to String. The valueOf() is the static method of String class. The signature of valueOf() method is given below:

    public static String valueOf(boolean b)  

Java boolean to String Example using String.valueOf()

    public class BooleanToStringExample1{  
    public static void main(String args[]){  
    boolean b1=true;  
    boolean b2=false;  
    String s1=String.valueOf(b1);  
    String s2=String.valueOf(b2);  
    System.out.println(s1);  
    System.out.println(s2);  
    }}  

Test it Now

Output:

true
false

2) Boolean.toString()

The Boolean.toString() method converts boolean to String. The toString() is the static method of Boolean class. The signature of toString() method is given below:

    public static String toString(boolean b)  

Java boolean to String Example using Boolean.toString()

 
public class BooleanToStringExample2{  
    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);  
    }}  

Test it Now

Output:

true
false

Java Convert Date to Timestamp

We can convert Date to Timestamp in java using constructor of java.sql.Timestamp class.

The constructor of Timestamp class receives long value as an argument. So you need to convert date into long value using getTime() method of java.util.Date class.

You can also format the output of Timestamp using java.text.SimpleDateFormat class.

    Timestamp(long l)  
	public long getTime()  

Java Date to Timestamp Example

    import java.sql.Timestamp;    
    import java.util.Date;    
     public class DateToTimestampExample1 {    
           public static void main(String args[]){    
                    Date date = new Date();  
                    Timestamp ts=new Timestamp(date.getTime());  
                    System.out.println(ts);                     
            }    
    }    

Test it Now

Output:

2017-11-02 01:59:30.274

    import java.sql.Timestamp;    
    import java.util.Date;    
    import java.text.SimpleDateFormat;  
     public class DateToTimestampExample2 {    
           public static void main(String args[]){    
                    Date date = new Date();  
                    Timestamp ts=new Timestamp(date.getTime());  
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
                    System.out.println(formatter.format(ts));                     
            }    
    }    

Test it Now

Output:

2017-11-02 02:04:03

Java Convert Timestamp to Date

We can convert Timestamp to Date in java using constructor of java.util.Date class.

The constructor of Date class receives long value as an argument. So, you need to convert Timestamp object into long value using getTime() method of java.sql.Timestamp class.

Constructor of Date class

    Date(long l)  

getTime() method of Timestamp class:

    public long getTime()  

Java Timestamp to Date Example

    import java.sql.Timestamp;    
    import java.util.Date;    
     public class TimestampToDateExample1 {    
           public static void main(String args[]){    
                    Timestamp ts=new Timestamp(System.currentTimeMillis());  
                    Date date=new Date(ts.getTime());  
                    System.out.println(date);                     
            }    
    }    

Test it Now

Output:

Thu Nov 02 02:29:07 IST 2017

The Timestamp class extends Date class. So, you can directly assign instance of Timestamp class into Date. In such case, output of Date object will be like Timestamp. But, it is not suggested by Java Doc because you may loose the milliseconds or nanoseconds of data.

    import java.sql.Timestamp;    
    import java.util.Date;    
     public class TimestampToDateExample2 {    
           public static void main(String args[]){    
                    Timestamp ts=new Timestamp(System.currentTimeMillis());  
                    Date date=ts;  
                    System.out.println(date);                     
            }    
    }    

Test it Now

Output:

2017-11-02 02:36:57.204

Java Convert Binary to Decimal

Java Convert Binary to Decimal

Java Binary to Decimal conversion: Integer.parseInt()

The Integer.parseInt() method converts string to int with given redix. The signature of parseInt() method is given below:

    public static int parseInt(String s,int redix)  
    public class BinaryToDecimalExample1{  
    public static void main(String args[]){  
    String binaryString="1010";  
    int decimal=Integer.parseInt(binaryString,2);  
    System.out.println(decimal);  
    }}  

Test it Now

Output:

10

    public class BinaryToDecimalExample2{  
    public static void main(String args[]){  
    System.out.println(Integer.parseInt("1010",2));  
    System.out.println(Integer.parseInt("10101",2));  
    System.out.println(Integer.parseInt("11111",2));  
    }}  

Test it Now

Output:

10
21
31

Java Binary to Decimal conversion: Custom Logic

    public class BinaryToDecimalExample3{    
    public static int getDecimal(int binary){  
        int decimal = 0;  
        int n = 0;  
        while(true){  
          if(binary == 0){  
            break;  
          } else {  
              int temp = binary%10;  
              decimal += temp*Math.pow(2, n);  
              binary = binary/10;  
              n++;  
           }  
        }  
        return decimal;  
    }  
    public static void main(String args[]){    
    System.out.println("Decimal of 1010 is: "+getDecimal(1010));  
    System.out.println("Decimal of 10101 is: "+getDecimal(10101));  
    System.out.println("Decimal of 11111 is: "+getDecimal(11111));  
    }}    

Test it Now

Output:

Decimal of 1010 is: 10
Decimal of 10101 is: 21
Decimal of 11111 is: 31

Java Convert Decimal to Binary

Java Decimal to Binary conversion: Integer.toBinaryString()

    public static String toBinaryString(int decimal)  
    public class DecimalToBinaryExample1{  
    public static void main(String args[]){  
    System.out.println(Integer.toBinaryString(10));  
    System.out.println(Integer.toBinaryString(21));  
    System.out.println(Integer.toBinaryString(31));  
    }}  

Test it Now

Output:

1010
10101
11111

Java Decimal to Binary conversion: Custom Logic

    public class DecimalToBinaryExample2{    
    public static void toBinary(int decimal){    
         int binary[] = new int[40];    
         int index = 0;    
         while(decimal > 0){    
           binary[index++] = decimal%2;    
           decimal = decimal/2;    
         }    
         for(int i = index-1;i >= 0;i--){    
           System.out.print(binary[i]);    
         }    
    System.out.println();//new line  
    }    
    public static void main(String args[]){      
    System.out.println("Decimal of 10 is: ");  
    toBinary(10);    
    System.out.println("Decimal of 21 is: ");  
    toBinary(21);    
    System.out.println("Decimal of 31 is: ");    
    toBinary(31);  
    }}      

Test it Now

Output:

Decimal of 10 is: 
1010
Decimal of 21 is: 
10101
Decimal of 31 is: 
11111

Java Convert Hexadecimal to Decimal

We can convert hexadecimal to decimal in java using Integer.parseInt() method or custom logic.

Java Hexadecimal to Decimal conversion: Integer.parseInt()

    public static int parseInt(String s,int redix)  
    public class HexToDecimalExample1{  
    public static void main(String args[]){  
    String hex="a";  
    int decimal=Integer.parseInt(hex,16);  
    System.out.println(decimal);  
    }}  

Test it Now

Output:

10
    public class HexToDecimalExample2{  
    public static void main(String args[]){  
    System.out.println(Integer.parseInt("a",16));  
    System.out.println(Integer.parseInt("f",16));  
    System.out.println(Integer.parseInt("121",16));  
    }}  

Test it Now

Output:

10
15
289

Java Hexadecimal to Decimal conversion: Custom Logic

    public class HexToDecimalExample3{    
    public static int getDecimal(String hex){  
        String digits = "0123456789ABCDEF";  
                 hex = hex.toUpperCase();  
                 int val = 0;  
                 for (int i = 0; i < hex.length(); i++)  
                 {  
                     char c = hex.charAt(i);  
                     int d = digits.indexOf(c);  
                     val = 16*val + d;  
                 }  
                 return val;  
    }  
    public static void main(String args[]){    
    System.out.println("Decimal of a is: "+getDecimal("a"));  
    System.out.println("Decimal of f is: "+getDecimal("f"));  
    System.out.println("Decimal of 121 is: "+getDecimal("121"));  
    }}    

Test it Now

Output:

Decimal of a is: 10
Decimal of f is: 15
Decimal of 121 is: 289

Java Convert Decimal to Hexadecimal

We can convert decimal to hexadecimal in java using Integer.toHexString() method or custom logic

public static String toHexString(int decimal)

    public class DecimalToHexExample1{  
    public static void main(String args[]){  
    System.out.println(Integer.toHexString(10));  
    System.out.println(Integer.toHexString(15));  
    System.out.println(Integer.toHexString(289));  
    }}  

Test it Now

Output:

a
f
121

Java Decimal to Hex conversion: Custom Logic

    public class DecimalToHexExample2{    
    public static String toHex(int decimal){    
         int rem;  
         String hex="";   
         char hexchars[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};  
        while(decimal>0)  
         {  
           rem=decimal%16;   
           hex=hexchars[rem]+hex;   
           decimal=decimal/16;  
         }  
        return hex;  
    }    
    public static void main(String args[]){      
         System.out.println("Hexadecimal of 10 is: "+toHex(10));  
         System.out.println("Hexadecimal of 15 is: "+toHex(15));  
         System.out.println("Hexadecimal of 289 is: "+toHex(289));  
    }}      

Test it Now

Output:

Hexadecimal of 10 is: A
Hexadecimal of 15 is: F
Hexadecimal of 289 is: 121

Java Convert Octal to Decimal

We can convert octal to decimal in java using Integer.parseInt() method or custom logic.

Java Octal to Decimal conversion: Integer.parseInt()

The Integer.parseInt() method converts a string to an int with the given radix. If you pass 8 as a radix, it converts an octal string into decimal. Let us see the signature of parseInt() method:

    public static int parseInt(String s,int radix)  
    //Java Program to demonstrate the use of Integer.parseInt() method  
    //for converting Octal to Decimal number  
    public class OctalToDecimalExample1{  
    public static void main(String args[]){  
    //Declaring an octal number  
    String octalString="121";  
    //Converting octal number into decimal  
    int decimal=Integer.parseInt(octalString,8);  
    //Printing converted decimal number  
    System.out.println(decimal);  
    }}  

Test it Now

Output:

81

    //Shorthand example of Integer.parseInt() method  
    public class OctalToDecimalExample2{  
    public static void main(String args[]){  
    System.out.println(Integer.parseInt("121",8));  
    System.out.println(Integer.parseInt("23",8));  
    System.out.println(Integer.parseInt("10",8));  
    }}  

Test it Now

Output:

81
19
8

Java Octal to Decimal conversion: Custom Logic

    //Java Program to demonstrate the conversion of Octal to Decimal  
    //using custom code  
    public class OctalToDecimalExample3{  
    //Declaring method  
    public static int getDecimal(int octal){    
        //Declaring variable to store decimal number  
        int decimal = 0;    
        //Declaring variable to use in power  
        int n = 0;    
        //writing logic   
        while(true){    
          if(octal == 0){    
            break;    
          } else {    
              int temp = octal%10;    
              decimal += temp*Math.pow(8, n);    
              octal = octal/10;    
              n++;    
           }    
        }    
        return decimal;    
    }    
    public static void main(String args[]){      
    //Printing the result of conversion  
    System.out.println("Decimal of 121 octal is: "+getDecimal(121));    
    System.out.println("Decimal of 23 octal is: "+getDecimal(23));    
    System.out.println("Decimal of 10 octal is: "+getDecimal(10));    
    }}  

Test it Now

Output:

Decimal of 121 is: 81
Decimal of 23: 19
Decimal of 10 is: 8

Java Convert Decimal to Octal

We can convert decimal to octal in java using Integer.toOctalString() method or custom logic.

Java Decimal to Octal conversion: Integer.toOctalString()

    public static String toOctalString(int decimal)  
    //Java Program to demonstrate the use of Integer.toOctalString() method  
    public class DecimalToOctalExample1{  
    public static void main(String args[]){  
    //Using the predefined Integer.toOctalString() method  
    //to convert decimal value into octal  
    System.out.println(Integer.toOctalString(8));  
    System.out.println(Integer.toOctalString(19));  
    System.out.println(Integer.toOctalString(81));  
    }}  

Test it Now

Output:

10
23
121


Java Decimal to Octal conversion: Custom Logic

    //Java Program to demonstrate the decimal to octal conversion  
    //using custom code  
    public class DecimalToOctalExample2{    
    //creating method for conversion so that we can use it many times  
    public static String toOctal(int decimal){    
        int rem; //declaring variable to store remainder  
        String octal=""; //declareing variable to store octal  
        //declaring array of octal numbers  
        char octalchars[]={'0','1','2','3','4','5','6','7'};  
        //writing logic of decimal to octal conversion   
        while(decimal>0)  
        {  
           rem=decimal%8;   
           octal=octalchars[rem]+octal;   
           decimal=decimal/8;  
        }  
        return octal;  
    }    
    public static void main(String args[]){      
    //Calling custom method to get the octal number of given decimal value  
    System.out.println("Decimal to octal of 8 is: "+toOctal(8));  
    System.out.println("Decimal to octal of 19 is: "+toOctal(19));  
    System.out.println("Decimal to octal of 81 is: "+toOctal(81));  
    }}      

Test it Now

Output:

Decimal to octal of 8 is: 10
Decimal to octal of 19 is: 23
Decimal to octal of 81 is: 121

bONEandALL
Visitor

Total : 46847

Today :39

Today Visit Country :