Data and Variables - csc.ncsu.edu · Data Types • Java is a ^strongly typed _language. –Each...

Post on 15-Aug-2019

216 views 0 download

Transcript of Data and Variables - csc.ncsu.edu · Data Types • Java is a ^strongly typed _language. –Each...

Data and Variables

• Data Types

• Expressions– Operators

– Precedence

• String Concatenation

• Variables– Declaration

– Assignment

– Shorthand operators

Review– class

• All code in a java file is written in aclass

• public class <ClassName> { ….. }

– Static methods

• public static void <methodName> () {….. }

• Made up of statements;

• Used in procedural programming– Decompose large tasks into

smaller subtasks

– Create a method for each unique subtask to eliminate redundancy

– Errors

• Syntax (won’t compile)

• Runtime (won’t run)

• Logic (incorrect result)

– Identifiers

• Must begin with a letter,underscore, or $

• Must contain only letters, digits, underscores, or $

• Can not be a Javakeyword/reserved word

Data Types

• Java is a “strongly typed” language.

– Each piece of data has a specific “type”

• Java supports two categories of data types

– Primitive data

– Objects (covered later)

Primitive Data Types• Integer (Whole Number)

• Java keywords for Integer Types

• int (4 bytes)

• byte (1 byte)

• short (2 bytes)

• long (8 bytes)

• We will use the int type

– minimum value -2,147,483,648

– maximum value 2,147,483,647

• Examples: 0, 35, +148, -250

Primitive Data Types (cont.)

• Real (Floating point, Decimal)

• Java keywords for Real Number Types

• double (8 bytes) (double precision)

• float (4 bytes)

• We will use the double type

– minimum value 4.94065645841246544e-324

– maximum value 1.79769313486231570e+308

• Examples: 23. .03 -5.5 10.0583 34e-20

Primitive Data Types (cont.)

• Character (Single Character)

• Java keyword for Character Type

– char (2 bytes)

• Enclosed in single quotes ‘ ’

• Examples: ‘a’ ‘&’ ‘X’ ‘8’

• Use escape sequence for

– Single Quote ‘\’’

– Backslash ‘\\’

Primitive Data Types (cont.)

• boolean (Logical Values)

• Java keyword

– boolean

• Only two different values (Java keywords)

– true

– false

• Covered Later

Practice• Which of the following are legal int

literals?

• 5.

• -1

• 22

• ‘7’

• 1.5

• -6875309

• 10.0

• 2.3

Practice• What primitive data type would you use

to store…

• a person’s middle initial?

• number of people in class?

• cost of lunch?

• distance to class?

• number of siblings a person has?

• your grade in a class?

Expressions

• Expression – A simple value or a set of operations that produces a value.

• Evaluation – The process of obtaining thevalue of an expression.

• Expressions have values, statements do not.

• Two types

– Arithmetic

– Boolean (covered later)

Expressions (cont.)

• A simple value or a set of operations thatproduce a value

– Literal Value• 42 -365 0 +9812

• 28.9 0.24 207. 0.0 -.98

• true false

• ‘a’ ‘m’ ‘X’ ‘!’ ‘\\’ ‘\’’

– Operations: combining values

• (5 * 6) + 32

• Use expressions in print statements– System.out.println(4);

– System.out.println(2 + 2);

Arithmetic Operators and Operands• Operators: indicate the operation to be

performed

– Addition (+) (5 + 2)

– Subtraction (-) (5 - 2)

– Multiplication (*) (5 * 2)

– Division ( / ) (5 / 2) (5.0 / 2.0)

– Remainder (mod) (%) (5 % 2)

• Operands: values used in the expression

– Literal

– Expression (3 + 2) * (6 / 2)

Division

• Integer Division - result is an integer, theremainder is dropped (truncation).

– examples:

• 22 / 4 = 5

• 116 / 5 = 23

• Floating Point Division – “normal division”.

– examples:

• 22.0 / 4. = 5.5

• 116.0 / 5.0 = 23.2

Remainder (Mod)• % - The remainder operator

– Returns the remainder of division

– examples:• 22 % 4 = 2

• 22. % 4.0 = 2.0

• 5.2 % 2.4 = 0.4

• 1 % 5 = 1

• 0 % 5 = 0

• 5 % 0 = undefined (runtime error)

• Useful applications– Testing for even/odd (number % 2 = 0 means even)

– Extract final digit (number % 10)

Precedence• Precedence – The order of evaluating

expressions

• Multiplication, Division, and Modulo take precedence over Addition and Subtraction.

• Unary operators (+, -) (pos, neg) takeprecedence over all 5 operators.

• Within same level of precedence, evaluatefrom left to right

• Override precedence with parentheses.

Precedence Examples

• 8 * 4 / 10 + (4 + 2) * 5 % 2

• 46 % 8 * 2 / 7 + 11 / 4 * 3

Mixing TypesPromotion: a copy of a value is converted to a “higher” type.

– Does not lose information about the value

– Integer to a double

– Result of operation between integer and double is a double (integer is promoted to a double to perform the operation)

– 6.4 + 8 = 14.4

Casting: a copy of a value is converted to another type– Double to integer

– Loses the fraction part

– Requires a cast – put the name of the type you want in parentheses in front of the value you want to cast

– (int) 5.62 (result is 5)

– (int) 5.0 / 2.0 (result is 5 / 2.0 = 2.5)

– (int) (5.0 / 2.0) (result is 2)

More Casting• Only casts value immediately following cast For example:

– 23 / 2 = 11

– (double) 23 / 2 = 11.5 (23. / 2, 23 / 2., 23. / 2.)

– (double) (23 / 2) = 11.0

• Example of when we may want to use casting:

– We have some books that are 0.15 feet wide and we want to know how many of them will fit in a bookshelf that is 2.5 feet wide.

– Then, 2.5 / 0.15 = 16.666 books.

• How are we going to put 2/3 of a book on the shelf?

– Instead, we need to see how many whole books can fit on the shelf: (int) (2.5 / 0.15) = 16

String Concatenation• Combining several strings into a single string, or

combining a string with other data into a new, longer string– Addition operator (+)

– Result of adding a String literal and a primitive data type is a String literal (primitive type is promoted to aString literal to perform the operation)

– Examples:• "hello" + 42 is "hello42"

• 1 + "abc" + 2 is "1abc2"

• "abc" + 1 + 2 is "abc12"

• 1 + 2 + "abc" is "3abc"

• "abc" + 9 * 3 is "abc27"

• "12" + 3 is "123"

Expression Practice• Consider the data type in the answers. For example, 5 (an int) is

totally different from 5.0 (a double)

• 5.5 + 2 / 3

• 2 + 3.5 * -2

• 5 * 10 / 5.0 + 3 * (int) 2.5 / 10

• 8 + 4 + "3" + 4 + 10 / 2 + "6" + (7 + 8)

In-Class Exercise1. 2 * 3 - 4 % 2 / 2 + 10 / (double)(10 / 4)

2. 42 % 6 + 35 / 5 % 4 - 16. / (12 % 8)

3. (int) 5.0 / 2.0 + (4 + 6) / 5 * 2

4. 3 * (5 - 3) + 3 - 3 * 2

5. 9 / 2.0 - 2 - 10 / (int) (5 * 0.5)

6. "1" + 2 / 3 + "four" + 5 % 6 + 7 + (8 + 9)

Variables

• Variable – A memory location with a name and a type that stores a value.

• Declaration – A request to set aside a new variable with a given type and name.– <type> <name>;

• Variable names are identifiers– Style guidelines: start with lowercase letter, capitalize each

subsequent word

• Examples

int age;

double weight;

char firstInitial;

Variable Assignment• Assignment – Giving a value to a variable.

• A value is assigned to a variable using an assignment statement:

<variable> = <expression>;

• Equal sign (=) is the operator for assignment

• The value of the expression on the right-hand side of theassignment is stored in the variable on the left-hand side of theassignment and is the result of the assignment operation

• Examples

double height = 70;

double weight = 195;

double bmi = weight / (height * weight) * 703;

char firstInitial = ‘M’;

Initialization

• Giving a variable an initial value is knownas the initialization of the variable

int age; //uninitialized

age = 35; //now initialized

Declaration/Assignment Variations//declare and assign a value to

//a variable in one statement

<type> <name> = <expression>;

– int value = 10;

– int answer = 5 * 6;

//declare multiple variables of

//the same type in one statement

<type> <name1>, <name2>, …, <name3>;

– int value, answer;

– int number = 5, sum;

– int age1 = 5, age2 = 8;

Practice• Which of the following choices is the

correct syntax for declaring a real number variable named ‘grade’ and initializing its value to 4.0?

1. 4.0 = grade;

2. double grade = 4.0;

3. grade = double 4.0;

4. 4.0 = double grade;

5. int grade = 4.0;

Variables (cont.)Changing the value of a variable using “assignment”:

What will the values of x, y, and z be after the following statements are executed?

int x = 3, y = 7, z;

z = x + y;

x = x + 2;

x = y – 5;

y = z – x;

Variables (cont.)Changing the value of a variable using a “shorthand” method:

– Special Assignment Operators that increment or decrement a value by a set amount

Standard Assignment

x = x + 1;

y = y – 7;

z = z * 2;

a = a / 3;

Shorthand Assignment

x += 1;

y -= 7;

z *= 2;

a /= 3;

Variables (cont.)Changing the value of a variable usingincrement/decrement (++/--) operators

Increment a value by 1

i++; (post increment)

++i; (pre increment)

Decrement a value by 1

i--; (post decrement)

--i; (pre decrement)

Post versions evaluate to the older (original) value

– “evaluate using current value of i, then increment i”

Pre versions evaluate to the new (final) value

– “increment i, then evaluate using new i“

Pre/Post Increment/DecrementExamples

What are the values of age1, age2, age3, and years after the following statements are executed?

int age1 = 21;

int age2 = 50;

int years;

int age3 = age2 – age1++;

years = ++age1 + age2--;

years++;

Common Syntax errors• A variable can't be used until it is assigned a

value.

int x;

System.out.println(x); // ERROR: x has no value

• You may not declare the same variable twice.int x;

int x; // ERROR: x already exists

int x = 3;

int x = 5; // ERROR: x already exists

Printing an expression or variable value• Use + to print a String and an expression value on one line

System.out.println("Grade: " + (95.1 + 71.9) / 2);

• Output: Grade: 83.5

System.out.println("Grade: " + (95.1 + 71.9) + 2);

• Output: Grade: 167.02

• Use + to print a String and a variable's value on one line.double grade = (95.1 + 71.9 + 82.6) / 3.0;

System.out.println("Your grade was " + grade);

• Output: Your grade was 83.2

int students = 11 + 17 + 4 + 19 + 14;

System.out.println("There are " + students +

" students in the course.");

• Output: There are 65 students in the course.

Practice• What does the following program output?public class Variables {

public static void main(String[] args) {

int num1, num2, num3;

num1 = 4;

num2 = 12;

num3 = num1;

num2 /= 3;

num1 = num2++ + 4;

num3 += num1;

int num4 = --num1;

num4++;

System.out.print("num1 = " + --num1 + "\nnum2 = " +

++num2 + "\nnum3 = " + num3++);

System.out.println(" num4 = " + num4--);

}

}

In-Class Assignment• Meadowdale Dairy Farm sells organic brown eggs

to local customers. They charge $3.25 for a dozen eggs, or 45 cents for individual eggs that are not part of a dozen.

• Write a class that includes a variable for the number of eggs in the order and assign the value 27 to this variable.

• Calculate and display the amount owed with a full explanation as follows:

You ordered 27 eggs. That’s 2 dozen at $3.25per dozen and 3 loose eggs at 45 cents each for a total of $7.85.

• Save the class as Eggs.java.

In-Class Assignment• Write a class that calculates and displays the

conversion of an integer variable storing a number of dollars into currency denominations—20s, 10s, 5s, and 1s. Assign the value of 57 to the variable. Print the resulting conversion as shown below (the output values must be calculated, not printed out using literal values).

• Output:

$57 converts to: 2 20s, 1 10s, 1 5s, and 2 1s.

• Save the class as Dollars.java.