Presentation is loading. Please wait.

Presentation is loading. Please wait.

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,

Similar presentations


Presentation on theme: "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,"— Presentation transcript:

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. GasLevel 12 Memory Reference

2 Why use variables?  Variables are used to perform calculations, comparisons, or manipulations of data.  y = x + z; x = 5 and z = 9

3 Declaring Variables  Multiple variables of the same type can be declared in the same statement.,, …, ; int numCars, windows, doors, seats;

4 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. = ;

5 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;

6 Initializing Variables  Some examples of initializing variables (assuming that the variables have been declared) are: numCars = 5; cost = 199.99; carExists = false;

7 Declaring and Initializing  There is a difference between declaring and initializing variables with primitive data types and objects. int usaScore = 89,koreaScore = 57; Car clintsCar = new Car();

8 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 + zebrasinMYZOO;

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

10 Arithmetic Operators  Addition:  var1 = var2 + var3;  Subtraction  var1 = var2 - var3;  Multiplication  var1 = var2 * var3;  Division  var1 = var2 / var3;

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

12 Arithmetic Operators  Modulus (Remainder)  var1 = var2 % var3;  calculates the remainder left after the division of a whole number has been performed.

13 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

14 Arithmetic Operators  Unary operators apply to one variable or constant.  +var1, -var1  Order of evaluation (or associativity) is right to left - - x = -(-x)

15 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

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

17 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

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

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

20 Operator Precedence  Third all additions and subtractions are evaluated from left to right.  X = (1 + (( 2 + 4) * (5 + 2)))  x = (1 + (6 * 7)) = (1 + 42) = 43

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

22 Numeric Promotion  Mixed-mode 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.

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

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

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

26 Casting Conversion  Casting conversion can be used to avoid mixed-mode 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.

27 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

28 Assignment Operators  We have seen Java’s 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.

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

30 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;

31 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

32 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--

33 Increment/Decrement Ops  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?

34 Increment/Decrement Ops  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?

35 Increment/Decrement Ops  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.

36 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 it’s name.

37 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;

38 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).

39 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

40 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);

41 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 it’s 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.

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

43 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);

44 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 “);

45 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);

46 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();

47 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!”);

48 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 + “.”);

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

50 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);

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

52 Output Boxes  The saveToFile method will erase any information that is stored in the file and replace it with the new information.

53 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”);

54 Developing a simple program  Problem statement: Due to the high price of gas, drivers are concerned about the mileage obtained by their cars. Drivers want to know the average miles per gallon of their car.

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

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


Download ppt "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,"

Similar presentations


Ads by Google