Intro to Java Web-Notes_Part41

Intro to Java Web-Notes_Part41 - Java does not like to have...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Java does not like to have mixed types on an operator. If such a situation occurs, Java has a predetermined order for the primitive data types -- if two different types share a binary operator then Java will cast the lower of the two types to the highest type on that operator. The order is: Higher double float mt l—l Lower .For example, the expression 7 / 2.0 has both an int and a double operand. Since double is a higher type than int, the 7 is temporarily converted to the double 7.0 to allow the division to take place, giving 7.0 / 2.0 -- now we have a double divided by a double to yield the double result of 3.5. Changing the type of the lower operand to the type of the higher operand is referred to as promotion. Casting A value can be manually changed to another type via the casting operator. The casting operator is created by placing the name of a type between parenthesis, such as (int) The casting operator is a unary operator which is placed just to the left of its operand, as shown below (int) 5.97 The value of the above expression is 5 (i.e., the integer five). Note that the (int) casting operator does not round the value, it truncates it (i.e., just chops off everything to the right of the decimal point). Here are some more example of the casting operator. Note that the casting operator can be used to perform both promotions (change the type to a higher type) or demotions (change the type to a lower type): Expression int) 6.1 int) 17.888 (double) 45 (double) 2 - (double) 2 2 -- (int) 2.0 (double) 7 / (double) 2 (int) 7.0 / (int) 2.0 Use jGRASP to Help Your Understanding If you are curious about the value of an expression, just enter it in a simple Java program and run the program under jGRASP. For example, to verify the last expression in the above table, paste the following program into jGRASP and look at the output: public class Verifylt { public static void main (String args) { System.out.println( (int) 7.0 / (int) 2.0 ); // Put the expression here } } On a scrap piece of paper write your answers to the following questions - then use jGRASP to verify your answers: : (int) 1.6 + (int) 1.7 |:| (int)(1.6 + 1.7) : Heme - About Us Copyright © 2006 by Kiowok, Ann Arbor, Michigan, USA ...
View Full Document

Page1 / 2

Intro to Java Web-Notes_Part41 - Java does not like to have...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online