CSC 2014 Java Bootcamp Lecture 2 Variables, Expressions, I/O & Control VARIABLES & EXPRESSIONS 2 Variables Variable Initialization A variable is a name for a location in memory A variable can be given an initial value in the declaration A variable must be declared by specifying the int sum = 0; variable's name and the type of information that it will int base = 32, max = 149; hold variable name data type • When a variable is referenced in a program, its current value is used int total; int count, temp, result; Multiple variables can be created in one declara ration 3 4 Primitive Data Numeric Primitive Data The difference between the various numeric primitive There are eight primitive data types in Java types is their size, and therefore the values they can Four of them represent integers: store: – byte , short , int , long Two of them represent floating point numbers: Type Storage Min Value Max Value – float , double One of them represents characters: 8 bits -128 128 127 127 byte – char 16 bits -32,768 32,767 short 32 bits -2,147,483,648 2,147,483,647 int And one of them represents boolean values: long 64 bits < -9 x 10 18 < 18 > 9 x 10 18 18 – boolean 38 with 7 significant digits 32 bits +/ +/- 3.4 x 10 38 float 308 with 15 significant digits 64 bits +/ +/- 1.7 x 10 308 double 5 6 1
Characters Boolean A char variable stores a single character A boolean value represents a true or false condition Character literals are delimited by single quotes: The reserved words true and false are the only 'a' 'X' '7' '$' ',' '\n' valid values for a boolean type Example declarations: boolean done = false; char topGrade = 'A'; A boolean variable can also be used to represent any char terminator = ';', separator = ' '; two states, such as a light bulb being on or off Note the distinction between a primitive character variable, which holds only one character, and a String object, which can hold multiple characters 7 8 Constants Assignment A constant is an identifier that is similar to a variable An assignment statement changes the value of a except that it holds the same value during its entire variable existence The assignment operator is the = sign As the name implies, it is constant, not variable total = 55; The compiler will issue an error if you try to change the • The expression on the right is evaluated and the value of a constant result is stored in the variable on the left In Java, we use the final modifier to declare a • The value that was in total is overwritten constant • You can only assign a value to a variable that is final int MIN_HEIGHT = 69; consistent with the variable's declared type 9 10 Expressions Division and Remainder If both operands to the division operator ( / ) are An expression is a combination of one or more operators and operands integers, the result is an integer (the fractional part is discarded) Arithmetic expressions compute numeric results and make use of the arithmetic operators: equals equals 14 / 3 4 Addition + equals equals 8 / 12 0 Subtraction - Multiplication * • The remainder operator (%) returns the remainder Division / after dividing the second operand into the first Remainder % • If either or both operands used by an arithmetic equals equals 14 % 3 2 operator are floating point, then the result is a equals equals 8 % 12 8 floating point 11 12 2
Operator Precedence Operator Precedence Operators can be combined into complex expressions What is the order of evaluation in the following expressions? result = total + count / max - offset; a + b + c + d + e a + b * c - d / e Operators have a well-defined precedence which 1 2 3 4 3 1 4 2 determines the order in which they are evaluated Multiplication, division, and remainder are evaluated a / (b + c) - d % e prior to addition, subtraction, and string concatenation 2 1 4 3 Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be a / (b * (c + (d - e))) used to force the evaluation order 4 3 2 1 13 14 Increment and Decrement Increment and Decrement The increment and decrement operators use only one The increment and decrement operators can be applied operand in postfix form : The increment operator ( ++ ) adds one to its operand count++ The decrement operator ( -- ) subtracts one from its or prefix form : operand ++count The statement When used as part of a larger expression, the two forms count++; can have different effects is functionally equivalent to Because of their subtleties, the increment and count = count + 1; decrement operators should be used with care 15 16 Shortcut Assignment Operators Shortcut Assignment Operators Often we perform an operation on a variable, and then There are many assignment operators in Java, including store the result back into that variable the following: Java provides assignment operators to simplify that process Operator Example Equiva valent To += x += y x = x + y For example, the statement -= x -= y x = x - y *= x *= y x = x * y num += count; /= x /= y x = x / y %= x %= y x = x % y is equivalent to num = num + count; 17 18 3
Shortcut Assignment Operators The right hand side of an assignment operator can be a complex expression The entire right-hand expression is evaluated first, then the result is combined with the original variable Therefore result /= (total-MIN) % num; is equivalent to INPUT & OUTPUT result = result / ((total-MIN) % num); 19 20 Interactive Programs Reading Input Programs generally need input on which to operate The following line creates a Scanner object that reads from the keyboard: The Scanner class provides convenient methods for Scanner scan = new Scanner (System.in); reading input values of various types The new operator creates the Scanner object A Scanner object can be set up to read input from various sources, including the user typing values on the Once created, the Scanner object can be used to keyboard invoke various input methods, such as: Keyboard input is represented by the System.in object answer = scan.nextLine(); 21 22 Reading Input Input Tokens The Scanner class is part of the java.util class Unless specified otherwise, white space is used to library, and must be imported into a program to be used separate the elements (called tokens ) of the input The nextLine method reads all of the input until the White space includes space characters, tabs, new line end of the line is found characters The next method of the Scanner class reads the next input token and returns it as a string Methods such as nextInt and nextDouble read data of particular types 23 24 4
Example: The High-Low Game The printf Method The System.out.printf method can be used to print formatted output to the console window System.out is a PrintStream object double height = 24.56832; System.out.printf("The height is %.2f%n", height); The height is 24.57 25 26 The printf Method The printf Method The printf method takes a format string followed by series A format specifier starts with the % sign and ends with a of values that are "plugged" into the format string conversion code The format string may contain format specifiers (such as %.2f and %n) Format Specifier Output %d decimal integer format string %f floating-point %e scientific notation System.out.printf("The height is %.2f%n", height); %c character %b boolean %s character string %.2f - print this floating-point value to two decimal places %% percent sign %n newline %n - new line (move to the next line of output) 27 28 The printf Method The printf method accepts any number of parameters The values must match up to the format specifiers in the format string int a = 32; double b = 123.45; System.out.printf("The sum of %d and %.3f is %.3f%n", a, b, a + b); CONTROL STRUCTURES The sum of 32 and 123.450 is 155.450 29 30 5
Recommend
More recommend