Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.

Similar presentations


Presentation on theme: "CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data."— Presentation transcript:

1 CSci 142 Data and Expressions

2 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data conversions

3 3 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 String class

4 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 4

5 5 Printing Strings println ("Whatever you are, be a good one."); method name information provided to the method (argument) print ("Whatever you are, "); print ("be a good one.");

6 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 6

7 7 The + Operator  The + operator can be used for concatenating Strings or adding numbers  If either or both operands are 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 parentheses can be used to force the order  println(“Hi ” + 2 + 3);  println(“Hi ” + (2 + 3));

8 8 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.");

9 9 Escape Sequences Escape Sequence Character \nNewline \”Double quote \’Single quote \\Backslash \tTab

10 10 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 total; int count, temp, result; Multiple variables can be declared in one statement data type variable name

11 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 11

12 12 Variable Initialization  A variable must be initialized before it can be used  A variable can be initialized in the declaration  A variable can be initialized after it is declared double sum = 0.0; int base = 32, max = 149; double sum; sum = 0.0; int base, max; base = 32; max = 149;

13 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 13 total = 55; int base = 32; println(base); base = 45; println(base);

14 14 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 change the value of a constant  In Java, use the keyword final to declare a constant final int MIN_HEIGHT = 69;

15 15 Why Constants are Cool  Give meaning to 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

16 16 Primitive Data TypesUsed for byte, short, int, long Integers (whole numbers) float, double Decimal (floating point) numbers char A single character boolean Boolean (true or false) values

17 17 Numeric Primitive Data  The difference between the various numeric primitive types is their size 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 10 18 +/- 3.4 x 10 38 with 7 significant digits +/- 1.7 x 10 308 with 15 significant digits Max Value 127 32,767 2,147,483,647 > 9 x 10 18

18 18 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.

19 19 boolean  A boolean value represents true or false  The reserved words true and false are the only valid values for a boolean type boolean done = false;

20 20 Expressions  Arithmetic expressions use arithmetic operators: Addition+ Subtraction- Multiplication* Division/ Remainder%  If either or both operands used by an arithmetic operator are floating point (decimal), then the result is a floating point

21 21 Division and Remainder  If both operands to the division operator ( / ) are integers, the result is an integer  The fractional part is discarded  The remainder operator (%) returns the remainder after dividing the second operand into the first 14 / 3 equals 8 / 12 equals 14 % 3 equals 8 % 12 equals

22 22 Operator Precedence  Operators can be combined into complex expressions result = total + count / max - offset;  Operations have a well-defined precedence 1.Parentheses 2.Multiplication, division, and remainder 3.Addition, subtraction, and string concatenation 4.Assignment  Arithmetic operators with the same precedence are evaluated from left to right

23 23 Example The expression is evaluated and the result is stored in the variable on the left hand side answer = sum / 4 + MAX * lowest; 1432

24 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); 24

25 25 Increment and Decrement  The increment operator ( ++ ) adds one to its operand  The decrement operator ( -- ) subtracts one from its operand  The statement count++; is equivalent to count = count + 1;

26 26 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

27 27 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;

28 28 Assignment Operators  There are many assignment operators in Java, including the following: 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

29 29 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 losing information

30 30 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 widening conversions narrowing conversions

31 31 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 widening conversions can happen via assignment  The value and type of dollars did not change converts the value in dollars to a float

32 32 Data Conversion  Promotion happens automatically in certain expressions  Example double sum = 5.0; int count = 3; double result = sum / count; count is Temporarily converted to a double

33 33 Casting  Casting is the most powerful, and dangerous, technique for conversion  May be used for both widening and narrowing conversions  To cast, the type is put in parentheses in front of the value being converted  Example: int total=3, count=2; result = (double)total / count;

34 34 Practice 1.iResult = num1 / num4; 2.dResult = num1 / num4; 3.iResult = num3 / num4; 4.dResult = num3 / num4; 5.dResult = val1 / num4;  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; 6.dResult = (double)num1 / num2; 7.dResult = num1 / (double)num2; 8.iResult = (int)(val1 / num4); 9.dResult = (int)((double)num1/num2); 10.iResult = num3%num4;


Download ppt "CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data."

Similar presentations


Ads by Google