|
|
|
|
Type casting ints and floatsJava Changing Sign ArithmeticQuick review of how to cast an int as a floatint myInt= 11; float myIntCastAsAFloat = (float)myInt;
The java code below will yeild a result of 1 becuase both are ints!7
public static void main(String[] args) {
int intOne= 2;
int intTwo= 3;
System.out.println("myResult "+ (intOne/intTwo));
}
Run the Java code below and you will see what happens to the datatype
whenever a single operation involves an int and float. What datatype conversion happens?
public static void main(String[] args) {
double myDouble= 2;
int inta= 3;
System.out.println("myResult "+ (inta/myDouble));
}
Run the Java code below andyou wll see that myResult evaluates to 3.
public static void main(String[] args) {
int myInt= 11;
int myIntegerDivisor = 3;
double myResult = myInt/myIntegerDivisor;
System.out.println("myResult "+ myResult );
}
Now let's cast some ints to floats! What does myResult evaluate to now?
#1
public static void main(String[] args) {
int myInt= 11;
int myIntegerDivisor = 3;
double myResult = (double)myInt/myIntegerDivisor;
System.out.println("myResult "+ myResult );
}
#2Let's add some parenthesis and see what happens
public static void main(String[] args) {
int myInt= 11;
int myIntegerDivisor = 3;
double myResult = (double)(myInt/myIntegerDivisor);
System.out.println("myResult "+ myResult );
}
Top |