www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons Type Conversion in Java Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Java is much stronger than C++ in the type conversions that are allowed.

In this lesson we will discuss conversions among different primitive types i.e. char, byte, short, int, long, float, and double.

Booleans cannot be converted to other types. For the other primitive types (char, byte, short, int, long, float, and double), there are two kinds of conversion: implicit and explicit.

Implicit conversions:
An implicit conversion means that a value of one type is changed to a value of another type without any special directive from the programmer. A char can be implicitly converted to an int, a long, a float, or a double. For example, the following will compile without error:

char c = 'a';
int k = c;
long x = c;
float y = c;
double d = c;

For the other (numeric) primitive types, the basic rule is that implicit conversions can be done from one type to another if the range of values of the first type is a subset of the range of values of the second type. For example, a byte can be converted to a short, int, long or float; a short can be converted to an int, long, float, or double, etc.

Explicit conversions:
Explicit conversions are done via casting. The name of the type to which you want a value converted is given, in parentheses, in front of the value. For example, the following code casts a value of type double to a value of type int, and a value of type double to a value of type short:

double d = 5.6;
int k = (int)d;
short s = (short)(d * 2.0);

Casting can be used to convert among any of the primitive types except boolean. Please note that casting can lose information; for example, floating-point values are truncated when they are cast to integers (e.g. the value of k in the code fragment given above is 5).
Next >>> Lesson No. 14: Useful Java Classes

Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.