1 / 37

CSci 142

CSci 142. Data and Expressions. Data and Expressions. Topics Strings Primitive data types 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

neka
Download Presentation

CSci 142

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSci 142 Data and Expressions

  2. Data and Expressions • Topics • Strings • Primitive data types • Variables and constants • Expressions and operator precedence • Data conversions

  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. method name Printing Strings println ("Whatever you are, be a good one."); print ("Whatever you are, "); print ("be a good one."); information provided to the method (argument) • The ConsoleProgram class has two methods for printing: • print - no line break • println - inserts a line break • Both accept String arguments

  5. String Concatenation • Concatenation is appending one string to the end of another • "Peanut butter " + "and jelly" • Concatentation can be used to break up a long line • println ("It was many and many a year ago, " +"in a kingdom by the sea, that a maiden there lived…");

  6. The + Operator • Used for concatenation if either or both operandsare Strings • println(“Good ” + 4 + “U”); • Used for addition if both operands are numeric • println(3+6); • Evaluated left to right, but parenthesescan be used to force the order • println(“Hi ” + 2 + 3); • println(“Hi ” + (2 + 3));

  7. Escape Sequences • How would we print the quote (") character? 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.");

  8. Escape Sequences

  9. Primitive Data Types

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

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

  12. boolean • Abooleanvalue represents true or false • The reserved wordstrue andfalse are the only valid values for a boolean type boolean done = false;

  13. Practice • What data type would you use to store: • A tax rate? • The current year? • Whether or not a customer should receive a discount? • Height?

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

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

  16. Variable Initialization Declare the variable Initialize the variable Use the variable • A variable must be initialized before it can be used • intval; • val = 10; • println(val);

  17. Variable Initialization Declare and initialize the variable Use the variable • A variable can be declared and initialized in one statement • intval = 10; • println(val);

  18. Variable Assignment • An assignment statement changes the value of a variable • Read “=” as gets • The value that was in total is overwritten • Most current value of a variable is used • Values assigned to a variable must be consistent with the variable's declared type total = 55; int base = 32; println(base); base = 45; println(base);

  19. String Variables Declare the variable Initialize the variable Use the variable • Strings can be stored in variables just like primitive data types • String name; • name = "Jose"; • println(name);

  20. String Variables Declare and initialize the variable Use the variable • A variable can be declared and initialized in one statement • String name = "Jose"; • println(name);

  21. Practice • Declare a variable to hold a total price • double price; • In two lines, declare and initialize a variable to hold your age • int age; • age = 21; • Declare and initialize a variable to hold your favorite pet • String pet = "alpaca"; • Declare and initialize a character variable to hold your middle initial • char initial = "J"; • Declare and initialize a boolean variable isMarriedto hold your marital status • booleanisMarried = true;

  22. 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 public static final int MIN_HEIGHT = 62;

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

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

  25. 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 and string concatenation (+), subtraction(-) • Assignment (=) • Arithmetic operators with the same precedence are evaluatedfrom left to right

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

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

  28. 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;

  29. 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;

  30. 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:

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

  32. Practice int a=3, b=5, c=2; int answer; • answer = a += b; • answer = b -= c; • answer = a *= c; • answer = a++;

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

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

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

  36. 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 int total=3, count=2; double result = (double)total / count;

  37. 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? intiResult, 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;

More Related