Type Casting in Java

By: Saravanan Viewed: 176 times  Printer Friendly Format    


In this tutorial we are going to see how to typecast in java. Now we are going to see the syntax and sample code to convert each and every data type into other type.

//Integer code1
public class CastExample
{
public static void main(String arg[])
{
String s=”27”;
int i=Integer.parseInt(s);
System.out.println(i);
Float f=99.7f;
int i1=Integer.parseInt(f);
}
}

//Integer code2
public class CastExample
{
public static void main(String arg[])
{
String s=”27”;
int i=(int)s;
System.out.println(i);
}
}


//Integer to String
int a=97;
String s=Integer.toString(a);

(or)
String s=””+a;


//Double to String
String s=Double.toString(doublevalue);

//Long to String
String s=Long.toString(longvalue);

//Float to String
String s=Float.toString(floatvalue);

//String to Integer
String s=”7”;
int i=Integer.valueOf(s).intValue();

(or)
int i = Integer.parseInt(s);

//String to Double
double a=Double.valueOf(s).doubleValue();

//String to Long
long lng=Long.valueOf(s).longValue();

(or)
long lng=Long.parseLong(s);

//String to Float
float f=Float.valueOf(s).floatValue();

//Character to Integer
char c=’9’;
int i=(char)c;

//String to Character
String s=”welcome”;
char c=(char)s;


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. your second last example in above code (Character
View Tutorial          By: jyoti at 2011-11-06 17:01:19

2. program is very long
View Tutorial          By: ajit kumar at 2012-04-21 03:57:13

3. your last comment String to character is wrong....
View Tutorial          By: anurag at 2012-05-04 01:45:37

4. Float f=99.7f;
int i1=Integer.parseInt(f);<

View Tutorial          By: Ashwin at 2012-12-23 05:14:04

5. Looks good. This is going to be a good resource.
View Tutorial          By: Brainpower at 2013-03-02 02:45:11

6. Class TypeCasting
{
public static v

View Tutorial          By: kishoree koli at 2013-03-14 03:00:31

7. A narrowing primitive conversion may lose informat
View Tutorial          By: Java Training at 2013-04-13 13:05:16

8. your second last example in above code (Character
View Tutorial          By: rupam shaw at 2013-04-24 08:36:05

9. Design program with given algorithm---


View Tutorial          By: siddhant at 2014-10-11 13:19:25

10. for the topic :
http://java.meritcampus.com

View Tutorial          By: meritcampus at 2016-02-12 05:07:12

11. EXAMPLES FOR TYPE CASTING :
http://java.mer

View Tutorial          By: meritcampus at 2016-02-15 09:52:22

12. Hi to every one, the contents present at this web
View Tutorial          By: push up bra bathing suits at 2017-06-01 13:31:14

13. I see you don't monetize your page, don't waste yo
View Tutorial          By: 86Micheal at 2017-07-25 07:19:49