Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » OperatorsRSS Feeds

Conditional operator and type cast operator

Posted By: Leonardo Costa     Category: Java     Views: 77619

This article explains about conditional operator and type cast operator available in java.

Java has a ternary operator that acts as an abbreviated form of an if-then-else statement.

Conditional operator and type cast operator

 Operator

Meaning 

 a = boolean ? b : a

Conditional operator - The first operand - boolean - is a boolean variable or expression. First this boolean operand is evaluated. If it is true then the second operator evaluated and a is set to that value. If the boolean operator is false, then the third operand is evaluated and a is set to that value. 

 (primitive type)

Type cast - To assign a value of one primitive numeric type a more narrow type, e.g. long to int, an explicit cast operation is required, e.g. long a = 5;     int b = (int)a; 



Syntax of Conditional Operator and Type Cast Operator 

expr1 ? expr2 : expr3

expr1 can be any boolean expression. If expr1 is true, then expr2 is evaluated else expr3 is evaluated. Ternary operator returns either the value of expr2 or expr3. 

Note that type of expr2 and expr3 must be same.

varName2 = (typeCastOptr) varName1;

varName2 is a variable of type specified at typeCastOptr.
typeCastOptr is a data type in which varName1 need to convert.
varName1 is a variable which you need to type cast.

Example of Conditional Operator and Type Cast Operator

Example 1 : Program to compare 2 numbers using Conditional Operator i.e ? : and type cast variable from int to float using Type Cast Operator

class CndTyCastOptrDemo
   public static void main(String args[])
   {

      int i = 10;
      float f = 15.0f;

      System.out.println("Greater Number from i and f is " + (f>i)? "f having value " + f: "i having value " + i);

      f = (float)i/2;  

      System.out.println("Value of variable f is " + f);

    }
}


Output

Greater Number from i and f is f having value 15
Value of variable f is 5
  
Share: 


Didn't find what you were looking for? Find more on Conditional operator and type cast operator Or get search suggestion and latest updates.

Leonardo Costa
Leonardo Costa author of Conditional operator and type cast operator is from Salvador, Brazil.
 
View All Articles

 
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!