Operations Casting Operators and Symbols Casting Variables can
Operations Casting, Operators, and Symbols
Casting • Variables can only hold the type of data they were designed to hold. • Since int and double variables are both number types, sometimes you want to move data between them. • Let’s say that you had: int i = 5; and double d = 7. 2; • If you tried to write: d = i; the value of 5 would be changed into a double 5. 0 and d would be set to 5. 0
Casting cont. • If, however you tried i = d; the decimal part (. 2) would not have anywhere to go and there would be an error. • To fix the problem, you must tell the computer that you want to assign the int approximation of the value to i. (Cast) • i = (int) d; -> now i = 7;
Basic Operators • The five basic operators are: + , - , / , * , % • The only unfamiliar one should be % (mod). • Mod is the remainder when doing int division.
Operators With Assignments • You may use operators in assignment. • int num = 6; int num 2 = num + 5; • num 2 now equals 11; • If I wrote: int num 3 = num 2 % 3; What would the value of num 3 be?
Shortcut Operators • Many times in programming you want to increment a variable. • int x = 5; x = x + 2; • x would now have the value of 7. • This can be done with the shortcut: • x += 2; • This can be done with all 5 of the basic operators (+ , - , / , * , %).
Shortcuts cont. • Write each of these expressions in the shortcut manner: • x = x + 5; • x = x - 6; • x = x / 11; • x = x * (-2); • x = x % 7; • x = 3 - x;
More Shortcuts • Incrementing and decrementing by 1 are so common that there also even shorter cuts for them. • x++, x--, ++x, --x; • -- subtracts 1 and ++ adds 1. • There is a difference between ++x and x++ • If int x = 5; and int y; • After y = ++x; x = 6 and y = 6. • After y = x++; x = 6 and y = 5.
Relational Operators • There are 6 relational operators: = = is equal to? ! = is not equal to? > is greater than? < is less than? > = is greater than or equal to? < = is less than or equal to?
Boolean Operators • • The 3 boolean operators are ! , && , and || These are not, and or respectively. boolean b, c, d, e; b = !(false); c = !(false) && !(true); d = false || true; e = false || !(false && true) && true;
Shortcut Decision • It is an Aritmetic. Exception(error) to divide by 0. • Thus int x = 5 / 0; is an error. • If int x = 10; • boolean b = (x = = 5/2) && (x = = 5/0); does not cause an error. • Neither does: b = (x = = 20/2) || (x = = 5/0);
- Slides: 11