Finding Minimum number between 2 number is quite quite quite easy in any Programming Language. We just have to use comparison operator (<,>,<=,>=,==). In this case we gonna make use of < operator.
class Minof2{
public static void main(String args[]){
//taking value as command line argument.
//Converting String format to Integer value
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int result = (i<j)?i:j;
System.out.println(result+" is a minimum value");
}
}
In this program ternary operator (? : ) is used which basic idea is:
(condition)?true:false;
if condition is true then true statement will be excuted or it's value will be assigned to another variable or value will be returned as per program designed .
and same for false;
In this Example,
int result = (i<j)?i:j;
Here lets say i = 5, j=20;
ok
so we have int result = (5 < 20)?5:20;
(I am just replacing the value and checking for your ease)
From the above statement we can analyze that 5 < 20 so, it's true then after question mark condition we have is true so we got 5 , which will be stored inside integer result..and it will be printed out.
It's that's so easy.
No comments:
Post a Comment