#Topic-7
Previous topic (6) we have discussed about Wrapper class, auto-boxing, UN-boxing and other related topics. If you have not gone through that topic, click this link Wrapper class, auto-boxing, UN-boxing in Java?
In this section we will discuss about How to convert String into primitive data types and primitive data types into String.
Note: value should be compatible to destination type (we can’t convert “java” into int)
//1st way
Example of convert String to Integer:
String
str1 = "5";
int result = Integer.parseInt(str1); // Using Integer.parsrInt()
System.out.println(result);
int result = Integer.parseInt(str1); // Using Integer.parsrInt()
System.out.println(result);
Example of convert String to Double:
String
str=”125”;
double a1=Double.parseDouble(str);
double a1=Double.parseDouble(str);
System.out.println(a1);
Example of convert String to Boolean:
String
a=”true”;
boolean a=Boolean.parseBoolean(a);
boolean a=Boolean.parseBoolean(a);
System.out.println(a);
Example of convert String to Char array:
String a=”java”;
char[] ch=a.toCharArray();
char[] ch=a.toCharArray();
//2nd way
Example of convert String to Integer:
String str2 = "5";
Integer result2 = Integer.valueOf(str2); // Using Integer.valueOf()
System.out.println(result2);
Example of convert String to Double:
String
str=”125”;
double a1=Double.valueOf(a1);
double a1=Double.valueOf(a1);
System.out.println(a1);
Example of convert String to Boolean:
String
a=”true”;
boolean a=Boolean.valueOf(a);
boolean a=Boolean.valueOf(a);
System.out.println(a);
//1st way
Example of convert Integer to String:
int x = 5;
int x = 5;
String str =
Integer.toString(x); // using Integer.toString()
System.out.println(str);
System.out.println(str);
Example of convert Double to String:
double d=150.25;
String s1=Double.toString(d);
double d=150.25;
String s1=Double.toString(d);
System.out.println(s1);
//2nd way
Example of convert Integer to String:
int x = 5;
int x = 5;
String str2 =
String.valueOf(x); // using String.valueOf()
System.out.println(str2);
System.out.println(str2);
Example of convert Double to String:
double d=150.25;
String s1=String.valueOf(d);
double d=150.25;
String s1=String.valueOf(d);
System.out.println(s1);
What is Next?
In the next section, we will be going through Class , constructor ans this keyword in Java
If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Twitter or Facebook. Thank you! - Shivananda Rai
In the next section, we will be going through Class , constructor ans this keyword in Java
If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Twitter or Facebook. Thank you! - Shivananda Rai
Very informative
ReplyDeleteThank you for spreading knowledge...tat so structured ...
ReplyDelete