html5-img
1 / 34

Variables and Expressions

Variables and Expressions. Programming Contests. ACM International Collegiate Programming Contest by IBM: http ://mcicpc.cs.atu.edu Google Code Jam (prize $15,000): http://code.google.com/codejam/ Facebook Hacker Cup ( prize $10,000): https://www.facebook.com/hackercup

etoile
Download Presentation

Variables and Expressions

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. Variables and Expressions

  2. Programming Contests • ACM International Collegiate Programming Contest by IBM: http://mcicpc.cs.atu.edu • Google Code Jam (prize $15,000): http://code.google.com/codejam/ • Facebook Hacker Cup (prize $10,000): https://www.facebook.com/hackercup • TopCoder (prize $25,000): http://community.topcoder.com/tc

  3. Objectives • Describe the Java data types(e.g., “int”, “fload”, “char”, etc) used for simple data. • Write Java statements to declare variables of different types. • Write assignment statements, expressions containing variables and constants.

  4. Variables • Variablesstore data such as numbers and letters. • Think of them as places to store data. • They are implemented as memory locations. • The data stored by a variable is called its value. • The value is stored in the memory location. • The value of a variable can be changed using proper Java statements.

  5. Declaring Variables • When you declare a variable, you provide its type and name: intnumberOfBaskets, eggsPerBasket; • A variable's type determines what kinds of values it can hold (“int”, “double”, “char”, etc.). • Declare a variable just before it is used or at the beginning of your program: public static void main (String[] args) { /* declare variables here */ . . .}

  6. Data Types • A primitive data type is used for simple and nondecomposable values such as an individual number or individual character. • int, double, and char are primitive types • In addition to the 8primitive data types, Java also provides special support for character strings via the java.lang.String class. • String s = “this is a string”

  7. Same kind with different sizes

  8. Examples of Primitive Values • Integer types: 0 -1365 12000 • Floating-point types: 0.99 -22.8 3.14159 5.0 • Character type: ‘a’ ‘A’ ‘#’ ‘ ’ • Boolean type: true false

  9. Java Identifiers • Identifiers are the names of variables, methods, classes, packages and interfaces. They can be arbitrarily long. • The first character cannot be a digit. • Identifiers may contain only • Letters A/a~Z/z, digits 0 ~ 9, underscore _, dollar sign $ • Identifiers may not contain any • Spaces, dots . , asterisks *, or other characters: • Java is case sensitive: “stuff”, “Stuff”, “STUFF” are different.

  10. Keywords and Proper Naming • Words such as if are called keywords or reserved words and have special and predefined meanings: • They cannot be used as identifiers, e.g., int, public. • Primitive types begin with a lowercase letter, e.g., int. • Classes begin with an uppercase letter, e.g., String. • Variables begin with a lowercase letters, e.g., myName. • Choose names that are helpful like count or speed, not cor s. • Multiword names are punctuatedusing uppercase letters.

  11. Assignment Statements • Assignment statement is used to assign a value to a variable: answer = 42; • The equal sign is called the assignment operator. • Say, a variable, named answer, is assigned a value of 42. • Syntax: variable = expression where expression can be another variable, a literal or constant (e.g., a number), or something that combines variables and literals using operators such as + and -. firstInitial = 'W'; amount = 3.99; eggsPerBasket= eggsPerBasket – 2;

  12. Initializing Variables • A variable that has been declared, but no yet given a value is said to be uninitialized. • Uninitialized primitive variables have a default value, e.g., int= 0, boolean = false, String = null. • To protect against an uninitialized variable, assign a value at the time the variable is declared: • Example: intcount = 0; char grade = 'A'; • Syntax: type variable_1 = expression_1;

  13. Assignment Evaluation • The expression on the right-hand side of the assignment operator =is evaluated first. • The result is used to set the value of the variable on the left-hand side of the assignment operator. score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2;

  14. It is a math operation Not a math operation

  15. Sample Screen Output

  16. e Notation & Imprecision • Floating-point constants can be written with digits after a decimal pointor using e notation. • The e notation is also called floating-point notation or scientific notation. • Examples: • 865000000.0can be written as 8.65e8 • 0.000483can be written as 4.83e-4 • Floating-point numbers often are only approximations since they are stored with a finite number of bits. • Hence, 1.0/3.0= 0.33333333333333 is slightly less than 1/3.

  17. Constants & Named Constants • Literal expressions like 2,3.14, or 'y' are called constants. • Constant numbers can be preceded by a + or –sign. • Java provides mechanism to: • Define a variable • Initialize it • Fix the value so it cannot be changed public static final Type Variable = Constant; • Example: public static final double PI = 3.14159;

  18. Assignment Compatibilities • Java is said to be strongly typed. • You can't, for example, assign a floating point value to a variable declared to store an integer. • A value of one type can be assigned to a variable • of any type further to the right byte --> short --> int --> long --> float --> double • but not to a variable of any type further to the left. • You can also assign a value of type char to a variable of type int.

  19. Type Casting • A type cast temporarily changes the value of a variable from the declared type to some other type. • For example: double distance; distance = 9.0; intpoints; points = (int)distance; • Illegal without (int). The value of pointsor (int)distanceis 9but the value of distance, both before & after the cast, is 9.0. • Any nonzero value to the right of the decimal point is truncated rather than rounded.

  20. Arithmetic Operators • Arithmetic expressions can be formed by +, –, *, and /operatorswith variables or numbers, known as operands. • When both operands are of the same type, the result is of that type. • When one of the operands is a floating-point type and the other is an integer, the result is a floating-point type. • Example: if hoursWorked is an intwith a value of 40, and payRate is a double to which 8.25 has been assigned hoursWorked* payRate is a double with a value of 330.0.

  21. Arithmetic Operations • Expressions with two or more operators can be viewed as a series of steps, each involving only two operands. • The result of one step produces one of the operands to be used in the next step: e.g., balance + (balance * rate) • In general, if one of operands is a floating-point type and the rest are integers, the result will be a floating-pointtype. • The result is the rightmost type from the following list that occurs in the expression. byte --> short --> int --> long --> float --> double

  22. Division & Mod Operators • The division operator /behaves as expected if one of the operands is a floating-point type, i.e., the result is a FP type. • However, when both operands are integer types, the result is truncated, not rounded: • Hence, 99/100= 0.99has a value of 0. • The mod operator %is used with operators of integer type to obtain the remainder after integer division. • Example: 14 divided by 4 is 3 with a remainder of 2, i.e., 14 % 4is 2. • The mod operator has many uses, e.g., determining if an integer is odd or even.

  23. Parentheses and Precedence • Parentheses can communicate the order in which arithmetic operations are performed, for examples: (cost + tax) * discount cost + (tax * discount) • Without parentheses, an expressions is evaluated according to the rules of precedence. It is negation like -2 It is subtraction like 4-2

  24. Precedence Rules • Even when ( )are not needed, they can be used to make the code clearer, though * has a higher priority than +, using: balance + (interestRate * balance) rather than balance + interestRate * balance • When unary operators have equal precedence, the operator on the right acts before the operation(s) on the left. • When binary operators have equal precedence, the operator on the left acts before the operator(s) on the right. balance +interestRate – balance

  25. Specialized Assignment Opt. • Assignment operators can be combined with arithmetic operators including –,+,*,/, and %,discussed later: amount = amount + 5; Also, can be written as amount += 5; • Increment and decrement operations, i.e., adding or subtracting by one: count++; ++count; count = count + 1; count--; --count; count = count – 1;

  26. Special Case of Inc. and Dec. • After executing: int m = 4; int result = 3 * (++m) The result has a value of 15 and mhas a value of 5. • After executing: int m = 4; int result = 3 * (m++) The result has a value of 12 and mhas a value of 5.

  27. Case Study • The Vending Machine Change: first we define the requirements of the program: • The user enters an amount between 1 cent and 99 cents. • The program determines a combination of coins equal to that amount. • For example, • 55cents can be 2 quarters and 1 nickel or • 87cents can be 3 quarters, 1 dime, 0 nickels and 2 pennies, i.e., (3 * 25) + (1 * 10) + (0 * 5) + (2 * 1) = 87

  28. Case Study (Cont.) • The initial version of the algorithm: • First read the amount. • Now findmaximum number of quarters in the amount. • Then, subtractthe value of quarters from the amount. • Repeat steps 2 and 3for dimes, nickels, and pennies. • Finally, printthe amount and the quantities of each coin.

  29. Case Study (Cont.) • The algorithm doesn't work properly • The original amount is changed by the intermediate computation and operations. • As a result, the original value of amount is lost. • Therefore, changethe list of variables: intamount, originalAmount; int quarters, dimes,nickles, pennies;

  30. Case Study (Cont.) • The modified version of the algorithm: • First readthe amount. • Make a copy of the amount. • Now findthe maximum number of quarters in amount. • Then subtractthe value of quarters from the amount. • Repeat steps 3 and 4 for dimes, nickels, and pennies. • Finally, printthe amount and the quantities of each coin.

More Related