School of Computer Science, University of Birmingham. Java Lecture notes. M. D. Ryan. September 2001. A very simple program Week 2: variables & expressions Variables, assignments, expressions, and types. /* a program to print Hello, World on the screen */ public class Hello { public static void main(string[] args) { String greeting; greeting = "Hello, World!\n"; System.out.print(greeting); Declaring variables Variables must be declared before they are used. The general pattern is: type variable ; Examples: int x1 ; double total ; String greeting ; Assignments: examples x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; y = y + 1; total = tenners * 10 + total; total = total * 1.065; area = radius*radius*3.14; a = 'A'; name = "Mark Ryan"; Assignments: pattern General pattern is variable = expression ; Variable names must start with a letter, and can contain numbers, but cannot contain special symbols like +, *. A variable cannot be a Java reserved word, such as public or class. Variables should have meaningful names. Initialising variables It s good practice to initialise variables at the same time as declaring them, as in double radius = 1.0; int total = tenners * 10 + fivers * 5 double area = radius*radius*3.14; char a = 'A'; String name = "Mark Ryan"; 1
Another simple program public class Money1 { public static void main(string[] args) { int pounds = 8; int fivers = 4; int tenners = 3; double total = tenners * 10 + fivers * 5 + pounds * 1; System.out.println(total); // now let s add 6% interest total = total * 1.06; System.out.println(total); Order of evaluation The difference between total = price1 + (price2 * 2) and total = (price1 + price2) * 2 What if we just write total = price1 + price2 * 2? * has higher precedence than + and -. / has higher precedence than + and -. * and / have equal precedence, so 10/5*3 is evaluated left to right. Similarly, + and - have equal precedence. Exercise Answer public class Money2 { public static void main(string[] args) { double invstmt = 1000; System.out.println("Initial investment " + invstmt); invstmt = invstmt * 1.06; System.out.println("Investment after 1 yr " + invstmt); public class Money2 { public static void main(string[] args) { double invstmt = 1000; System.out.println( Initial investment + invstmt); invstmt = invstmt * 1.06 * 1.06; invstmt = invstmt + 10; System.out.println( Investment after 2 yrs (including bonus) + invstmt); Modify this program so that instead of calculating the value of the investment after 1 year. it calculates the value of the investment after 2 years, and adds a bonus of 10, and then prints the result. Some numeric types f type values size range byte integer -128 to 127 short integer -32768 to 32767 int integer -2147483648 to 2147483647 long integer -9223372036854774808 to 9223372036854774808 float real ±3.4 e38 to ±1.4 e-45 9 decimal place precision double real ±1.7 e308 to ±4.9 e-324 18 decimal place precision Respecting types In an expression, we must make sure that we use operations which take values of the type we give them. For example: 2+3 is OK 25.25 - "Mark Ryan" is not OK, because you cannot subtract a string from a double. The compiler will complain. 2.0 + 5 is OK, because the int 5 is converted to a double 2* a is OK, because the character is converted to an integer (its ascii value). 2
Respecting types 2 The variable we assign to must be the right type to take the expression. E.g., if total is an int, then (a) total = 2 + 5; (b) total = 2.45 * 7.63; is OK is not OK If total is a double, then both are OK; in (a), Java will implicitly convert the int to a double. Assignment compatibilities You can assign a value of any type to a variable of a type that appears further down the list: byte short int long float double E.g., you can assign from an int to a double. Finding the unifying type In an expression like 2 * (3.5+7) /1.23 Java will find a type that includes the values it encounters in evaluating the expression. In this case, the result of the expression is a double. Literals A literal whole number (like 34) is considered an int. A literal number with digits after the decimal point (like 53.82) is considered a double. You can make it a float by adding f after it (e.g., 53.82f). Casting To assign from a double to an int, we have to tell Java to get rid of the extra information. We do this by type casting. For example, double price = 2.75; int pounds; pounds = (int) price; results in pounds being 2. Casting precedence Consider what happens if total is 13.75, in each of the following: int pennies = (int) (total * 100) int pennies = ((int) total) * 100 Question: What if we write int pennies = (int) total * 100 Answer: a type cast has highest precedence (i.e. applies to the smallest subexpression possible.) 3
Shortcut operators Operator Example Equivalent += i+=8 i = i+8 -= f-=8.0 f = f-8.0 *= i*=8 i = i*8 /= i/=8 i = i/8 %= i%=8 i = i%8 Increment and decrement operators x = 1; y = 1 + x++; y = 1 + ++x; y = 1 + x--; y = 1 + --x; Increment and decrement operator examples common code int n = 3; int m = 4; int result; What will be the value of m and result after : (a) result = n * ++m; (b) result = n * m++; (c) result = n * --m; (d) result = n * m--; result m 15 5 12 5 9 3 12 3 Program Gotcha: integer division Result int a=6; double t = a/b; System.out.println(t); 0 double a=6.0; double t = a/b; System.out.println(t); 0.75 integer division, again. The boolean data type Program Result boolean switchdown, bulbpresent, lightson; int a=6; double t = (double) (a/b); System.out.println(t); 0 int a=6; double t = ((double)a)/b; System.out.println(t); 0.75 switchdown = true; bulbpresent = false; lightson = switchdown && bulbpresent; // results in false bulbpresent = true; lightson = switchdown && bulbpresent; // results in true daytime = false; cansee = daytime lightson; 4
Some operations on numbers yield values of boolean type. int myvalue = 24; int yourvalue = 32; boolean win = myvalue > yourvalue; boolean draw = myvalue == yourvalue; note: = is the assignment operator; is the comparison relation. boolean lightson = switchdown && (voltage >= 150); Order of evaluation We saw that in total = price1 + price2 * 2; * has higher precedence than +. And in int pennies = (int) total * 100; (type) has higher precedence than *. You can, of course, use brackets to override the precedence: e.g., int pennies = (int) (total * 100); Operator precedence Casting ++, -- *, /, % +, - <, <=, >, => ==,!=; && =, +=, -=, *=, /=, %= Constants static final datatype CONST = value; static final double PI = 3.14159; static final int SIZE = 3; Character data type char letter = 'A'; char letter = '\u000a'; char numchar = '4'; Calling methods In an expression, you can also use function calls, or method calls as they are known in Java. E.g., int n = (int)math.round(100*f); f = Math.sqrt(f); Procedure calls, also called method calls in Java: System.out.println(name5); 5
Naming conventions Variables and method names: Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computearea. Naming conventions, cont. Class names: Capitalize the first letter of each word in the name. For example, the class name PoundsAndPence. Constants: Capitalize all letters in constants. For example, the constant PI. Reading a string from the keyboard Reading an int from the keyboard import java.io.*; //Using the input/output classes import java.io.*; //Using the input/output classes public class Fred { public static void main(string[ ] args) { // `reader' gets characters from the keyboard BufferedReader reader = new BufferedReader( new InputStreamReader(System.in) ); String str=""; System.out.print("Please enter a string: "); try { str = reader.readline(); // read a string catch(ioexception e) { // do nothing on exception System.out.println( "You typed + str + ". ); public class Fred { public static void main(string[ ] args) { // `reader' gets characters from the keyboard BufferedReader reader = new BufferedReader( new InputStreamReader(System.in) ); int x=0; String str=""; System.out.print("Please enter a number: "); try { str = reader.readline(); // read a string x = Integer.parseInt(str); //Convert it to integer catch(ioexception e) { System.out.println( "You typed + x + ". ); Temperature exercise To convert that program into the temperature example, - copy and rename it - instead of System.out.println( "You typed + x + ". ); we put something like double c = (5/9)*(x-32); System.out.println( In Celsius, the temperature is + c + ". ); Random number exercise Let s solve a related problem: obtain a random integer in the range -10 to 10, inclusive. (Is that an even distribution across the range?) What about this problem: in a car simulation program, I want to create cars with random colours in, say, {blue, green, red, yellow with three times as many blue as green, and half as many red/yellow as green. 6