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

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

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

Page 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,

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.

Page 2: 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,

Why use variables?

• Variables are used to perform calculations, comparisons, or manipulations of data.– y = x + z; x = 5 and z = 9

Page 3: 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,

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.

<data type> <variables>;

Page 4: 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,

Declaring Variables

• Some example declarations are:int numCars;

double cost; // the cost of a new stereo

boolean carExists;

Page 5: 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,

Declaring Variables

• Multiple variables of the same type can be declared in the same statement.<data type> <variable name>, <variable

name>, …, <variable name>;

int numCars, windows, doors, seats;

Page 6: 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,

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.

<variable name> = <value>;

Page 7: 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,

Initializing Variables

• Some examples of initializing variables (assuming that the variables have been declared) are:numCars = 5;

cost = 199.99;

carExists = false;

Page 8: 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,

Declaring and Initializing

• You can declare and initialize a variable all in the same line.<data type> <variable name> = <value>;

int numCars = 5;

double cost = 199.99;

boolean carExists = false;

Page 9: 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,

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

Page 10: 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,

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;

Page 11: 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,

Assignment Statements• The basic syntax of an assignment statement

is:– <variable name> = <expression>;– 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.

Page 12: 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,

Arithmetic Operators

• Addition:– var1 = var2 + var3;

• Subtraction– var1 = var2 - var3;

• Multiplication– var1 = var2 * var3;

• Division– var1 = var2 / var3;

Page 13: 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,

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.

Page 14: 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,

Arithmetic Operators

• Modulus (Remainder)– var1 = var2 % var3;– calculates the remainder left after the

division of a whole number has been performed.

Page 15: 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,

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

Page 16: 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,

Arithmetic Operators

• Unary operators apply to one variable or constant.– +var1, -var1– Order of evaluation (or associativity) is

right to left• - - x = -(-x)

Page 17: 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,

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

Page 18: 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,

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.

Page 19: 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,

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

Page 20: 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,

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.

Page 21: 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,

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.

Page 22: 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,

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

Page 23: 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,

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.

Page 24: 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,

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.

Page 25: 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,

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.

Page 26: 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,

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.

Page 27: 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,

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.

Page 28: 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,

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.

Page 29: 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,

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

Page 30: 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,

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.

Page 31: 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,

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;

Page 32: 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,

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;

Page 33: 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,

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

Page 34: 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,

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

Page 35: 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,

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?

Page 36: 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,

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?

Page 37: 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,

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.

Page 38: 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,

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.

Page 39: 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,

Constant Data Values

• Constant data values are defined using:

final <data type> <variable name> = <value>;

– Constant names are always all Capital letters.

final double PI = 3.14159;

final double CM_PER_INCH = 2.54;

Page 40: 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,

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

Page 41: 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,

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

Page 42: 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,

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

Page 43: 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,

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.

Page 44: 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,

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.

Page 45: 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,

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

Page 46: 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,

Input Boxes

• The methods that can be used to read input values are:<variable name>.getInteger();

<variable name>.getInteger(“ Some text “);

<variable name>.getDouble();

<variable name>.getDouble(“ Some text “);

<variable name>.getFloat();

<variable name>.getFloat(“ Some text “);

Page 47: 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,

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

Page 48: 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,

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

Page 49: 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,

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

Page 50: 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,

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

Page 51: 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,

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.

Page 52: 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,

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

Page 53: 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,

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.

Page 54: 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,

Output Boxes

• The saveToFile method will erase any information that is stored in the file and replace it with the new information.

Page 55: 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,

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

Page 56: 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,

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.

Page 57: 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,

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.

Page 58: 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,

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.