Variables and Assignments CSC 121 Spring 2015 Howard Rosenthal

Lesson Goals  Understand variables  Understand how to declare and use variables in Java    

Programs Learn Assignment statements for variables Learn how to read in data from a terminal Compatibility and casting Using the Scanner object for interactive input

2

What is a Variable • A variable is a named memory location capable of storing data of a specified type • Variables indicate logical, not physical addresses – Those are taking care of in the JVM and the OS • Variables always have a specific data type • Variables must always be declared before they can be used • Remember that a data type is a scheme for using bit patterns to represent a value. Think of a variable as a little box made of one or more bytes that can hold a value using a particular data type. Cost_of_Home $128,695.22

• A declaration of a variable is where a program says that it needs a variable • The value of a variable is always its last declared or assigned value in a program public class Example { public static void main ( String [] args ) { long payAmount = 123; //the declaration of the variable System.out.println("The variable payAmount contains: " + payAmount ); } }

3

Declaring Variables  Variables must be declared before the are used  Basic syntax: Type name1, name2, name3 …;  Example: double dinner_bill, credit_balance, money_in_bank;  Variables can be explicitly initialized when they are used long rent = 75; double milkprice_half = 1.99; boolean testimony = true;  Can’t do multiple assignments at once when declaring variables int x=y=z=0; // Incorrect syntax int x,y,z=60; // only z is initialized int x=60, y=60, z=60; //all three are initialized  Don’t try to assign a value that that is illegal short big_number = 250000;  This gives an error – why? 4

Naming Variables  Use only the characters 'a' through 'z', 'A' through 'Z',

'0' through '9', character '_', and character '$'. A variable name cannot contain the space character.  Do not start with a digit. An identifier can be any length. Upper and lower case count as different characters. SUM and Sum are different identifiers.  A variable name can not be a reserved word. An identifier must not already be in use in this part of the program  Don’t use the same name twice, even as different types

5

Assigning Variables  Assignment statements look like this: variableName = expression ; //The equal sign = is the assignment operator.  variableName is the name of a variable that has been declared previously in the program.  Remember: An expression is a combination of literals, operators, variable names, and parentheses used to calculate a value – must be syntactically correct  Assignment is accomplished in two steps:  Evaluate the expression  Store the value in the variable  Examples: total = 3 + 5; // total =8 price = 34.56; tax = price*0.05; //tax = 1.728  While you can’t do multiple initializations at once, you can do multiple assignments: x=y=z=0; // works as an assignment statement provided the variables have been declared previously – these work right to left int x=y=z=3; // This will generate a syntax error because you are first declaring the variables here x=y=z=14+5; // First calculate the value of the expression, then do the assignments

6

Assigning Variables (2)  What does the following program fragment write?

value = 5; System.out.println("value is: " + value ); value = value + 10; System.out.println("value is: " + value );

7

Final Variables  Final variables are really constants  They are assigned a value that doesn’t change

final double PI = 3.14159; final int PERFECT = 100;  Final variables are by convention written with all

capitals

8

An Example public class Fibonacci { // Print out the Fibonacci sequence for values < 50 public static void main(String[] args) { int lo = 1; int hi = 1; System.out.println(lo); while (hi < 50) { System.out.println(hi); hi = lo + hi; // new hi lo = hi - lo; /* new lo is (sum - old lo) i.e., the old hi */ } } }

9

Obtaining Input Data Using Scanner  A Scanner is an object.  You must include the following statement to use the

object: import java.util.*  Declare a Scanner object: Scanner ScannerName = new Scanner (System.in)  Then you can access seven types of input: byte, short, int, long, double, float and boolean  A Scanner object doesn’t read characters

10

There are 7 Input Methods Available ScannerName.nextByte() ScannerName.nextShort() ScannerName.nextInt() ScannerName.nextLong() ScannerName.nextDouble() ScannerName.nextFloat() ScannerName.nextBoolean() What you are looking at above is the standard way objects access methods: objectname.method(par1, par2, …)

11

An Example Using Scanner import java.util.*; // Make the Scanner class available. public class Interest2WithScanner { public static void main(String[] args) { Scanner stdin = new Scanner( System.in ); // Create the Scanner. double principal; // The value of the investment. double rate; // The annual interest rate. double interest; // The interest earned during the year. System.out.print("Enter the initial investment: "); principal = stdin.nextDouble(); System.out.print("Enter the annual interest rate (decimal, not percent!): "); rate = stdin.nextDouble(); interest = principal * rate; // Compute this year's interest. principal = principal + interest; // Add it to principal. System.out.print("The value of the investment after one year is $"); System.out.println(principal); // } } // end of class Interest2With Scanner

12

Casting (1)  The value of a smaller numerical type may be assigned to a higher numerical data type automatically  Do you know the order?  Casting down must be done explicitly Example: int Natural, Bigger; double ODDS, OtherNumber; ODDS = 20.3; Natural = 5; OtherNumber = int(ODDS)*Natural; Bigger = (int)OtherNumber; System.out.println(OtherNumber); //100.0 System.out.println(Bigger); //100 OtherNumber = ODDS*Natural; Bigger = (int)OtherNumber; System.out.println(OtherNumber); //101.5 System.out.println(Bigger); //101

13

Casting (2)  Character data may be assigned to any of the types

short, int, long, double or float

 When this happens the ASCII/Unicode value is assigned

to the numerical value

double x = ‘A’; System.out.print(x); The output is 65.0 – Why?

14

Shortcuts Operator

Shortcut

For

+=

x+=10

x=x+10

-=

x-=10

x=x-10

*=

x*=10

x=x*10

/=

x/=10

x=x/10

%=

x%=10

x=x%10

15

Prefix and Postfix for Incrementing and Decrementing  There are two mechanisms for adding or subtracting 1

from a variable

 ++number; //prefix form for adding 1 to a number  --number; //prefix form for subtracting 1 from a number  number++; //postfix form for adding 1 to a number  number--; //postfix form for subtracting 1 from a number

 What’s the difference? 



In assignment statements prefix action take effect before the assignment In assignment statements postfix action take effect after the assignment

16

Prefix and Postfix for Incrementing and Decrementing (2) Prefix Incrementing

Postfix Incrementing

int number =5,result; result = 3*(++number); System.out.println(result); 18 System.out.println(number); 6

int number =5,result; result = 3*(number++); System.out.println(result); 15 System.out.println(number); 6

Use postscript incrementing carefully, it can be confusing It is very useful when dealing with loops

17

Programming Exercise – Class (1) Exercise 9. Baseball Serious baseball fans know that the batting average is a misleading statistic. A better predictor of a player’s run productivity is the OBAS: on-base average times slugging percentage. On-base percentage is defined to be: (hits+walks+hit by pitch)/ (atBats+walks+hit by pitch + sacrifice flies). Slugging percentage is defined to be totalBases/atBats. Write a program that prompts for six integers: a player’s atBats, walks, singles, doubles, triples, home runs, and calculates the player’s OBAS. Note that a single is a one-base hit, a double is a two-base hit, a triple is a three-base hit, and a home run is a four-base hit. Walks do not count in totalBases. Assume that the number of hits by pitch and sacrifice flies are both zero. Look at the essence of the problem: On-base average slugging percentage (OBAS) = on-base average times slugging percentage. On-base average = (hits+walks+hit by pitch)/(atBats+walks + hit by pitch + sacrifice flies) Slugging percentage = totalBases/atBats Write a program that prompts for six integers: atBats, walks, singles, doubles, triples, homeruns and calculates OBAS. Assume that that sacrifice flies and hit by pitch are 0.

18

Programming Exercise – Lab(1) 10. Larger or Smaller Write a program that accepts 5 integers, and for each integer following the first, prints true or false depending on whether or not that integer is greater than the previous one. This program can be written more simply after reading chapter 4.

19