Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Type conversion in expression

Posted By: Alex Evans     Category: Java     Views: 3906

This article explains about how type conversion is happen for expression in java.

Type conversion in Expressions

Java allows you to perform operation with different types of data used in one expression. For Example, 

Example

char c;
int i;
float f;

c = '1';
i = 1;
f = 1.1f;

f  = c + i - f;

Java allows different types of variable in one expression because it has a strict set of conversion rules, that resolves type differences.    

Note that if a variable of type char, byte or short is used in an expression, its value is automatically converted to int while evaluating that expression.

Portion of java conversion rule is called integral promotion. The integral promotion is only in effect during the evaluation of an expression. The variable memory size does not become larger.    

Automatic integral promotions are applied the java complier converts all operands 'up' to the type of the largest operand in an expression is called type promotion

Examples of Type conversion in expression 

Example 1:

int i;
float f;

i = 10;
f = 10.5f;

f = f - i;

In the above code i is converted to a float during the evaluation of the expression f - i;. So the final result will be 0.5.

Example 2 :

int i1, i2;
float f1;

i1 = 11;
i2 = 2;
f1 = 50f;

f1 = f1 / (i1 / i2);

Note that the above expression will evaluate it on operation by operation basis. That means Even though the final result of an expression will be of the largest type, the type conversion rules are applied on an operation by operation basis. Firstly the division of i1 by i2 will produce an integer result, since both are integer variables. Then then this value is converted to float to divide float variable f1.

  
Share: 


Didn't find what you were looking for? Find more on Type conversion in expression Or get search suggestion and latest updates.

Alex Evans
Alex Evans author of Type conversion in expression is from London, United Kingdom.
 
View All Articles

Related Articles and Code:


 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!