590 likes | 609 Views
Java Programming: From The Ground Up. Chapter 3 Variables and Assignment. Variable and Assignments. Three questions: 1. How does a program obtain storage for data? 2. How does a program store data? | 3. How does a program use stored data?. Variables.
E N D
Java Programming:From The Ground Up • Chapter 3 Variables and Assignment
Variable and Assignments Three questions: 1. How does a program obtain storage for data? 2. How does a program store data?| 3. How does a program use stored data?
Variables • A variable is a named memory location capable of storing data of a specified type. • Visualize a variable as a labeled box, container, or memory cell capable of holding a single value of a specific data type:
Variables You can • store a value in a variable, • change the contents of a variable, and also • retrieve and use a stored value.
Variables Problem statement Write a program that calculates the number of people, sacks, cats, and kits that the narrator of the following encountered on his/her journey. As I was going to St. Ives, I met a man with seven wives, Each wife had seven sacks, Each sack had seven cats, Each cat had seven kits: Kits, cats, sacks, and wives, How many were there going to St. Ives?
Solution 1. // How many people, sacks, cats and // kits were encountered on the road to St. Ives 2. public class StIves 3. { 4. public static void main (String[] args) 5. { 6. int wives = 7; //a variable named wives that holds the value 7 7. int sacks; //holds the number of sacks 8. int cats; // holds the number of cats 9. int kits; // number of kits 10. int total; // sum of man, wives, sacks, cats and kits 11. sacks = 7*wives; // each wife had seven sacks 12. cats = 7*sacks; // each sack had seven cats 13. kits = 7*cats; //each cat had seven kits 14. total = 1+wives+sacks+cats+kits; // “1” counts the man
Solution 15. System.out.println("Wives: "+ wives); 16. System.out.println("Sacks: "+ sacks); 17. System.out.println("Cats: "+ cats); 18. System.out.println("Kits: "+ kits); 19. System.out.println("Man, wives, sack, cats and kits: "+ total); 20. } 21. }
Discussion Line 6 (int wives = 7; ) is a variable declaration. The declaration accomplishes three tasks: 1. It instructs the compiler to set aside or allocate enough memory to hold one integer (int). 2. It labels the allocated memory location with the name wives. 3. It stores the number 7 in this memory location.
Discussion • Lines 7 – 10: int sacks; int cats; int kits; int total; Each variable can hold one integer (int). No values are assigned to these variables. The variables are uninitialized. The uninitialized variables hold no meaningful values at this point
Discussion Line 11: sacks = 7 * wives; The value stored in the variable wives (7) is used to compute the number of sacks. The result (49) is stored in the variable sacks.
Discussion Line 12: cats = 7 * sacks; The value of sacks (49) is used to compute the number of cats. This product (343) is saved in the variable cats
Discussion Line 13: kits = 7 * cats; The value 343 stored in cats is used to calculate the number of kits. The number of kits is 2401 and that is the value placed in variable kits.
Discussion Line 14: total = 1 + wives + sacks+ cats + kits; The sum of the values stored in wives, sacks, cats, and kits plus 1 (for the narrator) is computed and stored in total.
Discussion • Lines 15 – 19: • System.out.println("Wives: "+ wives); System.out.println("Sacks: "+ sacks); System.out.println("Cats: "+ cats) System.out.println("Kits: "+ kits); System.out.println("Man, wives, sack, cats and kits: "+ total); • The numbers stored in wives, sacks, cats, kits, and total are displayed.
Variable Declarations: How a Program Obtains Storage for Data • A variable must be declared before it can be used: • A variable declaration specifies: the type of data that the variable can hold the name of the variable. • The syntax of a variable declaration is: Typename1, name2, name3,…; where Type is a data type (int, double, char, boolean) and nameX is a valid Java identifier.
Variable Declarations: How a Program Obtains Storage for Data • int cats; • // cats can store a single integer (int) • double radius, area, circumference; // commas separating the names are mandatory • // the three variables are all double • boolean done; • // done can hold the values true or false When naming a variable, choose a name that is meaningful.
Integers • The declaration: int total; instructs the compiler to allocate enough memory to store one number of type int. • A value of type int requires 32 bits or four bytes of memory. • With 32 bits of storage, a variable of type int can hold a value in the range -2,147,483,468 to 2,147,483,467.
Integers In addition to type int, Java provides three additional integer data types: • byte, • short, and • long.
The storage requirements and the range of values for all integer types are as follows: • byte: 8 bits ( 1 byte) 27 to 27-1 (-128 to 127) • short: 16 bits (2 bytes) 215 to 215-1 (-32,768 to 32,767) • int 32: bits (4 bytes) 231 to 231-1 (-2,147,483,468 to 2,147,483,467) • long 64 bits (8 bytes) 263 to 263-1 (-922,337,203,685,475,808 to 922,337,203,685,475,807)
Floating Point Numbers Floating Point Numbers: float 32 bits (4 bytes) -3.4e38 to 3.4e38 (with 6 to 7 significant digits) double 64 bits (8 bytes) -1.7e308 to 1.7e308 (with 14 to 15 significant digits)
Characters and Booleans Characters Variables of type char require 16 bits or 2 bytes of memory. A character is stored as a 16-bit Unicode integer. Boolean values: • The boolean type has just two values: true and false.
How a Program Stores Data: Initialization and Assignment • A variable can be given a value via an initialization statement or an assignment statement • Initialization: A variable may be declared and given an initial value, with a single initialization statement: double pi = 3.14159; int number = 10, sum = 0, total = 125; boolean done = true; char firstLetter = ‘A’, lastLetter = ‘Z’;
Assignment • Values may be stored in a previously declared variable using an assignment statement. • An assignment statement has the following format: Variable = Expression where Variable is a declared variable and Expression is a valid Java expression. The symbol = is the assignment operator.
Assignment • The left-hand side of an assignment statement consists of a single variable. • Assignment is accomplished in two steps: 1. Expression is evaluated. 2. The value of Expression is stored in Variable. int sum; // a variable declaration: sum is type int sum = 1+2+3+4+5; //assignment: sum gets the value 15 • Assignments can be chained: int number1,number2, number3; number1 = number2 = number3 = 2+4+6+8;
Variables • Assignments can be chained, but initializations cannot: int x = y = z = 3; // ERROR! • Correct initialization can be accomplished with: int z = 3, y = 3, x = 3; or int z = 3, y = z, x = y;
How a Program Uses Stored Data • Once a variable has been assigned a value, you can use the variable’s name in an expression, provided that the data type of the variable makes sense in the expression. int number1 = 10; int number2 = 20; int sum; sum = 5*number1 + 2*number2; • The value stored in a variable may be changed.
Example • Problem Statement • Write a program that exchanges the values in two variables.
Solution • 1. //switches the values stored in two variables • 2. public class Swap • 3. { • 4. public static void main (String[] args) • 5. { • 6. int a = 7; • 7. int b = 100; • 8. int temp; // uninitialized • 9. System.out.print("Before -- "); • 10. System.out.print("a: "+ a); • 11. System.out.println(", b: "+ b); • 12. temp = a; //store the current value of a in temp • 13. a = b; // store the value of b in a • 14. b = temp; // store the original value of a in b • 15. System.out.print("After -- "); • 16. System.out.print("a: "+ a); • 17. System.out.println(", b: "+ b); • 18. } • 19. }
Output • Before -- a: 7, b: 100 • After -- a: 100, b: 7
Discussion • int a = 7 • Int b = 100; • Int temp; //uninitialized • temp = a • a = b • b = temp
Obtaining Data from Outside a Program A very simple mechanism available for interactive input, a Scanner object.
Example According to the Farmer’s Almanac, you can estimate air temperature by counting the number of times per minute that a cricket chirps. To compute the air temperature (Celsius), divide the number of chirps/minute by 6.6 and add 4. Problem Statement Write an application that calculates the air temperature given the number of cricket chirps per minute. A user supplies the number of chirps per minute.
Solution • 1. //calculates the air temperature (Celsius) from the number of cricket chirps/minute • 2. import java.util.*; • 3. public class Cricket • 4. { • 5. public static void main (String[] args) • 6. { • 7. int chirps; //chirps per minute • 8. double temperature; // Celsius • 9. Scanner input = new Scanner(System.in); • 10. System.out.print("Enter the number of chirps/minute: "); • 11. chirps = input.nextInt(); • 12. temperature = chirps/6.6 + 4; • 13. System.out.println("The temperature is "+temperature+"C"); • 14. } • 15. }
Output • Enter the number of chirps/minute: 99 • The temperature is 19.0C
Discussion • Line 7: int chirps; • Declare an integer variable, chirps. • Line 8: double temperature; • The variable temperature holds the air temperature. Because the computation of the temperature requires division by 6.6, temperature is declared as double. • Line 9: Scanner input = new Scanner(System.in) ; • The name input refers to a “Scanner object.”
Discussion • Line 10: System.out.print("Enter the number of chirps/minute: "); • An output statement that prompts the user for data. • Line 11: chirps = input.nextInt(); • The Scanner object, input, accepts or reads one integer from the keyboard Once the user supplies an integer, that number is assigned to the variable chirps. The Scanner object, input, expects an integer (input.nextInt()). A Scanner object skips leading whitespace’
Discussion • Line 12: temperature = chirps/6.6 + 4; • The value stored in chirps is used to compute the air temperature. The result of the computation is assigned to the variable temperature. • Line 13: System.out.println("The temperature is "+temperature+"C"); • The program displays the value stored in temperature along with some explanatory text.
A Scanner Object for Interactive Input • Before using a Scanner object for input you must: • Include the import statement: import java.util.*; • Declare a Scanner object as Scanner name = new Scanner(System.in) where name is a valid Java identifier such as input or keyboardReader. .
A Scanner Object for Interactive Input Once a Scanner has been declared you can use the following methods to read data: • name.nextInt() • name.nextShort() • name.nextLong() • name.nextDouble() • name.nextFloat() • name.nextBoolean() where name is the declared name of the Scanner
Example • Do you get more bite for your buck with a fourteen inch pizza or a ten inch pizza? • Problem Statement • Write a program that calculates the price per square inch of a round pizza, given the diameter and price.
Solution • 1. //Calculates the price/sq.in. of a round pizza using area = л r2 • 2. //Uses the diameter and the price • 3. import java.util.*; // to use Scanner • 4. public class Pizza • 5. { • 6. public static void main (String[] args) • 7. { • 8. Scanner input = new Scanner(System.in); //declare a Scanner • 9. double diameter, area, radius; • 10. double price; • 11. double pricePerSquareInch;
Solution • 12. System.out.print("Enter the diameter of the pizza in inches: "); • 13. diameter = input.nextDouble(); // use Scanner object, read a double • 14. radius = diameter/2.0; • 15. area = 3.14159*radius*radius; //area = л r2 • 16. System.out.print("Enter the price of the pizza: "); • 17. price = input.nextDouble(); // use Scanner object, read a double • 18. pricePerSquareInch = price/area; • 19. System.out.println("The price per square inch of a "+ diameter + " inch pizza is $" + pricePerSquareInch); • 20. } • 21. }
Output • Enter the diameter of the pizza in inches: 10.00 • Enter the price of the pizza: 6.50 • The price per square inch of a 10.0 inch pizza is $0.0827606403127079 • Enter the diameter of the pizza in inches: 12.00 • Enter the price of the pizza: 10.50 • The price per square inch of a 12.0 inch pizza is $0.09284046188925567 • Enter the diameter of the pizza in inches: 14.00 • Enter the price of the pizza: 12.50 • The price per square inch of a 14.0 inch pizza is $0.08120157016552973
Discussion: • Lines • 3: import java.util.*; • 8: Scanner input = new Scanner(System.in); • 13: diameter = input.nextDouble(); and • 17: price = input.nextDouble(); • contain the necessary statements for interactive user input with a Scanner object.
Final Variables • A final variable is a variable that is assigned a permanent value. • A final variable may be assigned a value just once in any program, and once assigned, the value cannot be altered: 1. final double PI = 3.14159; // PI cannot be changed 2. double radius = 13.6567, area; ……………. 3. area = PI*radius*radius;
Type Compatibility and Casting • Before evaluating a binary expression with operands of different data types, Java promotes or casts the operand of the "smaller" data type to the data type of the other operand. • The value of the expression 2 + 3 is 5 (int) but the expression 2 + 3.0 evaluates to 5.0 (double) • Assignment is no different. • The value of a smaller numerical data type may be assigned to a variable of a larger numerical data type.
Type Compatibility and Casting • The pecking order of the numeric data types from smallest to largest is: • byte • short • int • long • float • double double decimalNumber; decimalNumber = 100; // a value of type int is assigned to a variable of type double System.out.println( decimalNumber); prints 100.0.
Type Compatibility and Casting The following assignment is illegal: int wholeNumber; wholeNumber = 37.2; //cannot assign 37.2 (double) to an integer variable Java does not automatically cast 37.2 to the integer 37 because the cast results in a loss of precision. However, such an assignment can be accomplished with an explicit cast.
Explicit Casts • If value is a number or variable of a numeric data type, then the expression (X)value, where X is a numeric data type, explicitly casts value to type X. • (int)3.1459.2 casts a floating point number to an integer. • The value of the expression is the integer 3. • (float)3.14159 casts 3.14159 from double to float.
Explicit Casts Assign a value of type double to variable of type int: 1. int wholeNumber; 2. double decimalNumber = 37.2; 3. wholeNumber = (int)decimalNumber; // decimalNumber is explicitly cast to int