What is a variable? A variable holds data in memory so the program may use that data, or store...

Author
shawnmiles 
Category
Documents

view
217 
download
1
Embed Size (px)
Transcript of What is a variable? A variable holds data in memory so the program may use that data, or store...
 Slide 1
What is a variable? A variable holds data in memory so the program may use that data, or store results. Variables have a data type. int, boolean, char, double, etc. Variables have a name that is used to reference the information stored in memory. Slide 2 Why use variables? Variables are used to perform calculations, comparisons, or manipulations of data. y = x + z; x = 5 and z = 9 Slide 3 Declaring Variables When a program declares a variable with a primitive data type, the required memory is allocated. Note this is different from declaring objects. Memory to store objects is not created until the object is instantiated. ; Slide 4 Declaring Variables Some example declarations are: int numCars; double cost; // the cost of a new stereo boolean carExists; Slide 5 Declaring Variables Multiple variables of the same type can be declared in the same statement.,, , ; int numCars, windows, doors, seats; Slide 6 Initializing Variables When a variable is declared, it does not contain data. Data has to be placed into the variable before they can be used in a program. Putting a default value or an initial value into a variable is called initialization. = ; Slide 7 Initializing Variables Some examples of initializing variables (assuming that the variables have been declared) are: numCars = 5; cost = 199.99; carExists = false; Slide 8 Declaring and Initializing You can declare and initialize a variable all in the same line. = ; int numCars = 5; double cost = 199.99; boolean carExists = false; Slide 9 Declaring and Initializing There is a difference between declaring and initializing variables with primitive data types and objects. int usaScore = 89,koreaScore = 57; Car clintsProsche = new Car(); Slide 10 Assignment Statements An assignment statement can be used to put values into a variable both by simple assignment or by an expression. zebraCount = 5; zebraCount = zebraCount + numInHerd * 0.3; Slide 11 Assignment Statements The basic syntax of an assignment statement is: = ; The expression is evaluated and the result is assigned to the variable name on the left of the equals sign. In this case = means assigned and is called an assignment operator. The expression is any valid combination of constants, variables, parenthesis, and arithmetic or boolean operators. Slide 12 Arithmetic Operators Addition: var1 = var2 + var3; Subtraction var1 = var2  var3; Multiplication var1 = var2 * var3; Division var1 = var2 / var3; Slide 13 Arithmetic Operators Division Division between two integer values results in an integer result, any fractional part is lost. This is called integer division. If either or both of the numbers are float or double, then the result is a real number. Slide 14 Arithmetic Operators Modulus (Remainder) var1 = var2 % var3; calculates the remainder left after the division of a whole number has been performed. Slide 15 Arithmetic Operators Binary operators occur between or apply to two variables or constants. Addition, subtraction, multiplication, division, and modulus. Order of evaluation (or associativity) is generally left to right x = 1 + 3 * 8 / 4 x = 7 x = (1 + 3) * 8 / 4 x = 8 Slide 16 Arithmetic Operators Unary operators apply to one variable or constant. +var1, var1 Order of evaluation (or associativity) is right to left   x = (x) Slide 17 Integer Arithmetic Integer arithmetic occurs when all variables and constants are of type integer and the result is always an integer. If division of two integers does not result in an integer the decimal place information is lost. The result can only be an integer. int x = 4 / 3; x = 1 the.333333 is discarded Slide 18 Integer Arithmetic Due to the fact that information can be lost in calculations using integers, integers should only be used for values that are guaranteed to have integer results. The real data types should be used for values that may not be an integer. Slide 19 Floating Point Arithmetic Floating point arithmetic occurs when all variables and constants are of a real type and the result is always a real. The float data type has a limited range and precision and may not be an accurate representation of a value. float x = 4/3; x = 1.3333333 double x = 4 / 3; x = 1.333333333333333 Slide 20 Floating Point Arithmetic The double data type also has a limited range and precision but it is much larger than that of type float and therefore provides a more accurate representation. double x = 4 / 3; x = 1.333333333333333 the double data type should be used for calculations but you should remember that double results may not be equal even though they theoretically should be because there are still rounding issues with doubles. Slide 21 Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions, and modulus operations are calculated from left to right. Slide 22 Operator Precedence Third all additions and subtractions are evaluated from left to right. X = (1 + (( 2 + 4) * (5 + 2))) x = (1 + (6 * 7)) = (1 + 48) = 49 Slide 23 Numeric Promotion When an arithmetic operation is performed between operators of the same data type, the result is the defined data type. For instance, if two integers are added together the result is an integer. Slide 24 Numeric Promotion Mixedmode arithmetic occurs in expressions that contain integer and real numbers. In such a situation, numeric promotion must occur. Meaning that the smaller data type is automatically converted into the larger data type. Numeric promotion occurs only when there are two values of different data types in the expression. Slide 25 Numeric Promotion The rules for numeric promotion If one of the operands is a double then the other operand is converted to a double. Otherwise, if one of the operands is a float then the other operand is converted to a float. Otherwise, if one of the operands is a long, the other operand is converted to a long. Otherwise, both operands are converted to int. Slide 26 Assignment Conversion Assignment conversion occurs when the result of the expression is a different data type than the data type of the result. Widening conversion occurs when the result is promoted to a larger data type. For instance, an integer result is promoted to a double data type because the result is stored into a double data type variable. Slide 27 Assignment Conversion Narrowing conversion occurs when the result is demoted to a smaller data type. For instance, a double result is to be stored in an integer result. This is not allowed to automatically occur in Java and will result in a compile time error. This is allowed in Java if a cast operator is used. Slide 28 Casting Conversion Casting conversion can be used to avoid mixedmode arithmetic and to guarantee the resultant data type. double x = x + (double) y; where y is of type int. the (double) is called the cast operator. Allows the programmer to make numeric conversions explicit while avoiding confusion about what data type is used in the mixed mode arithmetic. Slide 29 Casting Conversion Widening conversion using type casting is legal in Java and can remove any ambiguities as to the resultant value. Narrowing conversion using type casting is legal in Java but is discouraged because you are loosing value precision when this is done. int x = (int) 89.99; x = 89 int x = (int) 50235645642L; x = 2147483648 Slide 30 Assignment Operators We have seen Javas basic assignment operator, but Java also has some special assignment operators that combine the assignment operator with a binary operator in a single statement. Such operators can be used to create short cuts in your code. Slide 31 Assignment Operators The += operator allows you to represent: a = a + 1 as a += 1. The 1 is added to the value of a and stored back into a. a += c; a += 984; Slide 32 Assignment Operators In addition to the += operator there are: a = 5; which is the same as a = a  5; a *= c; which is the same as a = a * c; a /= 2; which is the same as a = a / 2; a %= 4; which is the same as a = a % 4; Slide 33 Increment/Decrement Operators Java contains two unary operators the increment ++ and decrement  operators. When these operators are combined with an integer variable, they increment or decrement that variable by 1. a++ == a = a + 1 == a +=1 a == a = a  1 == a =1 Slide 34 Increment/Decrement Operators There are two types of increment and decrement operators called preincrement/decrement and postincrement/decrement. A preincrement looks like: ++a and a predecrement looks like: a A postincrement looks like: a++ and a postdecrement looks like: a Slide 35 Increment/Decrement Operators The Preincrement/decrement operators place the ++ or  before the variable name and cause the variable to be incremented or decremented before it is used in an expression. Assume a = 5, what is: b given b = ++a + 6? What is b given b = a + 7? Slide 36 Increment/Decrement Operators The Postincrement/decrement operators place the ++ or  after the variable name and cause the variable to be incremented or decremented after it is used in an expression. Assume a = 5, what is b given b = a++ + 6? What is b given b = a + 7? Slide 37 Increment/Decrement Operators It is legal to combine increment and decrement operators but can become very confusing. Assume a = 7, What is the result of: ++a++++ (++( (a++)))++ It is best to avoid combining multiple increment and decrement operators. Slide 38 Constant Data Values A constant is a value in a program that is assigned an initial value but can not be changed while the program runs. If a program attempts to change a constant the result is a syntax error. The keyword final is used to signify that a value is a constant. The data value can be referenced in the program using its name. Slide 39 Constant Data Values Constant data values are defined using: final = ; Constant names are always all Capital letters. final double PI = 3.14159; final double CM_PER_INCH = 2.54; Slide 40 Mathematical Methods Java provides a Math library (class file) that implements many common mathematical functions. The Math class contains mathematical constants such as PI (Math.PI). Slide 41 Mathematical Methods The Math methods provided by Java are listed in Table 3.5 on page 101 Absolute value  Math.abs(x); Maximum value of x and y  Math.max(x,y); Random numbers between 0 and 1  Math.random() Sine  Math.sin(x) Note that x must be in radians not degrees Slide 42 Mathematical Methods Assume that we want to calculate the following: y = sin(x *3.14159) Assume y is a double and that x is an int. final double DEG_2_RAD = Math.PI / 180; int x = 8; double y = Math.sin(x * DEG_2_RAD); Slide 43 Overloaded Math Methods If you look at the table for the absolute value function you will notice that it can take float, double, int, or long as its input parameter. The abs method is said to be overloaded because there are three separate definitions or versions. The versions of abs differ only in the type of the input parameter. The methods have the same name, the same functionality, but have different parameter types. Java knows which version to call based upon the data type of the parameter passed to the method. The result is a;ways the same parameter data type. Slide 44 Math Methods using Coercion Some Math methods only work with a specific data type but they still accept parameters of other data types. Java will automatically convert the other data type into the preferred data type before executing the method, this is call coercion of arguments. For instance the square root method, Math.sqrt(x) requires a parameter of type double. If x is of type byte, short, int, long, or float, Java will automatically convert x to type double. This method only returns a double. Slide 45 Input Boxes An Input Box is a dialog box that allows the user to input values for a program. To create an Input Box: MainWindow mainWindow = new MainWindow(); InputBox inputBox = new InputBox(mainWindow); Slide 46 Input Boxes The methods that can be used to read input values are:.getInteger();.getInteger( Some text );.getDouble();.getDouble( Some text );.getFloat();.getFloat( Some text ); Slide 47 Output Boxes An output box is used to display textual data to a user. To create an Output Box: MainWindow mainWindow = new MainWindow(); OutputBox outputBox = new OutputBox(mainWindow); Slide 48 Output Boxes The program needs to display both the main window and output box to the user before the user can see any textual information. This is done using a show method. mainWindow.show(); outputBox.show(); Slide 49 Output Boxes The program must specifically request that data is displayed in the output box. This is done using the print method. outputBox.print(hello world!); Slide 50 Output Boxes To display a variable to the box: int cost = 199.99; outputBox.print(The cost is $); outputBox.print(cost); outputBox.print(.); The above can be replaced with: outputBox.print(The cost is $ + cost + .); Slide 51 Output Boxes The print method will display the text of multiple print statements on the same line. The printLine method will display the text of each print statement on a new line. Slide 52 Output Boxes If a program needs to display blank lines between statements then the skipLine method can be used. The skipLine method requires an integer value that indicates how many lines should be skipped. outputBox.skipLine(5); Slide 53 Output Boxes The information displayed in an output box can be saved to a text file using the saveToFile method. The saveToFile method requires the name of a valid file as a parameter. outputBox.saveToFile(output.txt); Note the . These are required around the file name. Slide 54 Output Boxes The saveToFile method will erase any information that is stored in the file and replace it with the new information. Slide 55 Output Boxes The appendToFile method allows a file to be opened and write new information to the end of the file without erasing the original information. outputBox.appendToFile(output.txt); Slide 56 Developing a simple program Problem statement: Due to the high price of gas, drives are concerned with the mileage obtained by their automobiles. Drivers want to know based upon how many miles they have driven and how much gas has been used, how many miles per gallon their automobile averages. Slide 57 Developing a Simple Program First, we need to develop a plan for implementing the program. What tasks does our program need to complete? Next we need to determine what classes we need to implement our program. Slide 58 Developing a simple program Third, we need to develop our steps to implement the program. Fourth, we complete each implementation step. Finally, we test the program to ensure it works properly.