340 likes | 511 Views
CSci 142. Data and Expressions. Data and Expressions. Topics Strings Primitive data types Using variables and constants Expressions and operator precedence Data conversions. Character Strings. A String consists of zero or more characters Represent a String literal with double quotes
E N D
CSci 142 Data and Expressions
Data and Expressions • Topics • Strings • Primitive data types • Using variables and constants • Expressions and operator precedence • Data conversions
Character Strings • A String consists of zero or more characters • Represent a String literal with double quotes "This is a string literal." "123 Main Street" "X" "" this is called an empty String • Every string is an object in Java, defined by the Stringclass
Printing Strings • The ConsoleProgram class has two methods for printing: • print • println • Both accept String arguments • println inserts a line break, while print does not
method name information provided to the method (argument) Printing Strings println ("Whatever you are, be a good one."); print ("Whatever you are, "); print ("be a good one.");
String Concatenation • Concatenation is appending one string to the end of another • "Peanut butter " + "and jelly" • A string literal cannot be broken across two lines in a program
The + Operator • The + operator can be used for concatenating Strings or adding numbers • If either or both operandsare Strings, String concatenation is performed • println(“Good ” + 4 + “U”); • If both operands are numeric , it adds them • println(3+6); • The + operator is evaluated left to right, but parenthesescan be used to force the order • println(“Hi ” + 2 + 3); • println(“Hi ” + (2 + 3));
Escape Sequences • How would we print the quote (") character? • The following line would confuse the compiler println ("I said "Hi" to you."); • An escape sequence is a series of characters that represents a special character • Begins with a backslash (\) println ("I said \"Hi\" to you.");
data type variable name Variables • A variable is a named memory location • A variable must be declared by specifying the variable's name and the type of information that it will hold int count, temp, result; int total; Multiple variables can be declared in one statement
Variable names • May contain letters or numbers, but may not start with a number • you2 - valid • 2you - not valid • May not contain a space or any special characters, except the underscore (_) • why_not - valid • why not? - not valid • Should use camel case • gpa, numCredits, totalClassCount
Variable Initialization • A variable must be initialized before it can be used • A variable can be initializedin the declaration double sum = 0.0; int base = 32, max = 149; • A variable can be initialized after it is declared double sum; sum = 0.0; int base, max; base = 32; max = 149;
Variable Assignment • An assignment statement changes the value of a variable • Read “=” as gets • total gets 55 • The value that was in total is overwritten • Values assigned to a variable must be consistent with the variable's declared type • Most current value of a variable is used total = 55; int base = 32; println(base); base = 45; println(base);
Constants • A constant is similar to a variable except that its value cannot change during program execution • As the name implies, it is constant, not variable • The compiler will issue an error if you try to changethe value of a constant • In Java, use the keyword final to declare a constant final int MIN_HEIGHT = 69;
Why Constants are Cool • Give meaningto otherwise unclear literal values • MAX_LOAD means more than the literal 250 • They facilitate program maintenance • If a constant is used in multiple places, its value need only be updated once • They formally establish that a value should not change, avoiding inadvertent errors
Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 with 7 significant digits +/- 1.7 x 10308 with 15 significant digits Max Value 127 32,767 2,147,483,647 > 9 x 1018 Numeric Primitive Data • The difference between the various numeric primitive types is their size
char • A char variable stores a single character • Characters are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' • Example declarations: char topGrade = 'A'; char terminator = ';', separator = ' '; Note that a character variable can hold only one character, while a String can hold zero or more characters.
boolean • Abooleanvalue represents true or false • The reserved wordstrue andfalse are the only valid values for a boolean type boolean done = false;
Expressions • Arithmetic expressions use arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder % • If either or both operandsused by an arithmetic operator are floating point (decimal), then the result is a floating point
Division and Remainder • If both operands to the division operator (/) are integers, the result is an integer • The fractional part is discarded 14 / 3equals 8 / 12equals • The remainder operator (%) returns the remainder after dividingthe second operand into the first 14 % 3equals 8 % 12equals
Operator Precedence • Operators can be combined into complex expressions result = total + count / max - offset; • Operations have a well-defined precedence • Parentheses • Multiplication, division, and remainder • Addition, subtraction, and string concatenation • Assignment • Arithmetic operators with the same precedence are evaluatedfrom left to right
Example answer = sum / 4 + MAX * lowest; 4 1 3 2 The expression is evaluated and the result is stored in the variable on the left hand side
Practice int a=3, b=5, c=2; int answer; answer = a * b - c; answer = b + a * c; answer = b / a; answer = a / b; answer = b % a; answer = a % b; answer = b - a * b - c; answer = b - a / c; answer = (b - a) / c; answer = a * (b + c);
Increment and Decrement • The increment operator (++) adds one to its operand • The decrement operator (--) subtracts one from its operand • The statement count++;is equivalent tocount = count + 1;
Increment and Decrement • The increment and decrement operators can be applied in postfix form: count++ • or prefix form: ++count When used as part of a larger expression, the two forms can have different effects
Assignment Operators • Often we perform an operation on a variable, and then store the result back into that variable • Example: • num = num + count; • This can be written using an assignment operator: • num += count;
Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y Assignment Operators • There are many assignment operators in Java, including the following:
Data Conversion • Sometimes it is convenient to convert data from one type to another • These conversions do not change the type of a variable or the value that's stored in it • They only convert a value as part of a computation • Conversions must be handled carefully to avoid losinginformation
Data Conversion • widening conversions • Go from a small data type to a larger one • Example: short to an int • Safe • narrowing conversions • Go from a large data type to a smaller one • Example: int to a short • Can lose information • Types of conversion • Assignment conversion • Data conversion • Casting byte short int long float double narrowing conversions widening conversions
Assignment Conversion • Assignment conversion occurs when a value of one type is assigned to a variable of another double money; int dollars = 5; money = dollars; • Only wideningconversions can happen via assignment • The value and type of dollars did not change converts the value in dollars to a float
Data Conversion • Promotion happens automatically in certain expressions • Example double sum = 5.0; int count = 3; double result = sum / count; countis Temporarilyconverted to a double
Casting • Casting is the most powerful, and dangerous, technique for conversion • May be used for both widening and narrowing conversions • To cast, the typeis put in parentheses in front of the value being converted • Example: int total=3, count=2; result = (double)total / count;
iResult = num1 / num4; dResult = num1 / num4; iResult = num3 / num4; dResult = num3 / num4; dResult = val1 / num4; Practice • Given the following declarations, what result is stored in each of the statements? int iResult, num1=25, num2=40, num3=17, num4=5; double dResult, val1=17.0, val2=12.78; • dResult = (double)num1 / num2; • dResult = num1 / (double)num2; • iResult = (int)(val1 / num4); • dResult = (int)((double)num1/num2); • iResult = num3%num4;