Variables, Data Types, & Constants. Topics & Objectives Declaring Variables Assignment Statement...

60
Variables, Data Types, & Constants

Transcript of Variables, Data Types, & Constants. Topics & Objectives Declaring Variables Assignment Statement...

Variables, Data Types, &

Constants

Topics & Objectives

• Declaring Variables• Assignment Statement• Reserve Words• Data Types• Constants• Packages & Libraries

• Scanner Class• Math Class• Arithmetic • Compound

Assignment • Flow Charting

Variable

• Is a name for a value stored in memory

• Containers for values

• Is a name for a location in memory used to hold a data value.

Variable Declaration

• Tells the compiler to reserve a portion of main memory space large enough to hold the value.

• All variables must be declared with a name and a type before they can be used.– int myValue = 3; //Declared & Initialized myValue to 3

• Variable can only store one value of its type at a time.

Assignment Statement

• (=) symbol is used as the assignment statement. – (=) - is known as the assignment operator.

• All assignments occurs from right to left. Meaning the right side of the equal sign is evaluated first and then stored to the variable on the left side.– Identifier variable = expression ;– myVariable = myValue + 3;

• myValue + 3 is evaluated first• The result is then stored in myVariable

Assignment StatementAn assignment statement gives a value to a

variable.

Assignment can take several forms:

x = 5; a literal (5) is assigned to x

x = y + 2; the value of an expression (y + 2) is assigned to x

x = z; the value of another variable (z) is assigned to x

Variable Assignment

A variable can store only one value at any time.

int x;x = 5;x = 10;

xx

510

Naming Variables

• 1st letter of a variable name should be lowercase.• Name should consist of letters and numbers and

underscore.• No spaces• No symbols• If using two words join together, the 1st letter of

the second word should be capitalized. – myHouse, totalSum

• Do not use reserve or keywords

Reserve

• Reserve Words – words that have a predefine meaning– boolean, char, byte, int, short, long, float, double,

void, true, false, public, private, protected, static, final, import, class, interface, extends, implements, this, super, abstract, new, if, else, for, while, do, switch, case, default, break, return, try, catch, finally, throw, throws, continue, package, native, volatile, transient, synchronized, instanceof

• All reserved words use only lowercase letter

Java Keywordsabstract double int strictfp

boolean else interface super

break extends long switch

byte final native synchronized

case finally new this

catch float package throw

char for private throws

class goto protected transient

const if public try

continue implements return void

default import short volatile

do instanceof static while

Primitive Data Types or built-in data types

Data type – determines the type of data the variable will store

They are called primitive because data types have no properties.

Eight Primitive Data Types

• 4 kinds of Integers data types

• 2 kinds of floating point data types

• 1 character data type

• 1 boolean data type

Primitive Data Types

Type Storage Requiredint 4 bytes //AP EXAMdouble 8 bytes //AP EXAMchar 2 bytes //Not on AP Exam

boolean 1 bit //AP EXAM

Integer Data Types

• Use for whole numbers

• byte – 1 byte range –27 to 27-1 or –128 to 127

• short – 2 bytes range –215 to 215 – 1 or 32,768 to 32,767

• int – 4 bytes range –231 to 231 - 1

• long – 8 bytes range –263 to 263 – 1

Floating Points Data Types

• Use for real numbers (numbers with decimal).

• float – 4 bytes –3.4 x 1038 to 3.4 x 1038

• double – 8 bytes –1.8 x 10308 to 1.8 x 10308

Character Data Type

• Used for single letters in single quotes

• char – 2 bytes Unicode character set (with ASCII subset)

Boolean Data Type

• Used for true or false

• boolean – 1 byte true or false

Choosing a data type

• It is important to choose the most appropriate type for the quantity being represented.

Constants• Literal – A primitive value used in a program .

o Numeric literal – 8 , 9, 427o String literal – “hello”

• Symbolic - uses the keyword final when declaring variables– final int SUM = 8;– Use all caps the distinguish constant variables from other

variables.

• Constants are like variables, but they have the same value throughout the program.

• Constant can’t change their value once they are assigned a value.

Named Constants

A named memory location that cannot be changed from its initial value.

The keyword final is used in a constant declaration.

Constant identifiers are typically all uppercase with an underscore (_) separating words within the identifier name.

Example:

final double TAX = 0.08;

Constants Advantages

• Prevent accidental changing during the program run by another source.

• Maintenance - by changing the assignment where it is assigned. It will change throughout the program.

ASCII

• American Standard Code for Information Interchange– Represents the numeric code for each

character– One Byte per character – 0 to 127

• Extended ASCII– 128 to 255

Unicode

• Two bytes per character– ASCII is a subset of Unicode

• Represents 65,000 characters for most world languages

Import, Arithmetic, Casting, Logical Operators, Relational

Operators

Java Packages

Numerous packages are included with JDK

Packages contain classes

Packages can be added to an application with an import statement. For example, the statement

import java.util.Scanner;makes the Scanner class and its methods accessible to the application.

Packages

• Group of related classes by one name.

• Eamples: java.lang – java.util

Class Libraries

• Class Library – is a set of classes that supports the development of programs.

• The Java standard class Library is a useful set of classes that anyone can use when writing Java programs.

• Java APIs – Application Programmer Interfaces. Class library made up of several sets of related classes.

Import Declaration

• import – keyword used to identify packages and classes that will be used by the program.

• import java.util.Random;– Gains access to the Random Class

• import java.util.*;– Gains access to the package that contains class

Random

java.lang.*;• Automatically imported • Classes in java.lang package

– String– System– Double– Integer– Comparable– Math– Object– Etc.

java.util.*;• Random• ArrayList• HashMap• HashSet• Iterator• LinkedList• List• ListIterator• Map• Set• TreeMap• TreeSet

Inputting

Scanner Class

• next()

• nextLine()

• nextInt()

• nextDouble()

• nextBoolean()

• nextFloat()

• nextLong()

• nextShort()

Creating a Scanner object

• Scanner console = new Scanner(System.in);

• console is the object of Scanner

• console has access to all the methods using the dot operator.

Scanner Class Methods• next()

– Returns a string• nextLine()

– Returns a string of the entire sentence• nextInt()

– Returns an integer• nextInt()

– Returns an integer• nextDouble()

– Returns a double value• nextBoolean()

– Returns a Boolean value• nextFloat()

– Returns a float value• nextLong()

– Returns a long value• nextShort()

– Returns a short value

Inputting Char

• No methods for inputting chars

• Scanner console = new console Scanner(System.in);

• char dude = console.next().charAt(0); //return the char at the 0 index

Program

• import java.util.*;• public class Scan{• public static void main(String args[]){• int x=0,y=0, z=0;• String temp = new String();• Scanner console = new Scanner(System.in);• System.out.println("Input 3 values");• x = console.nextInt();• y=console.nextInt();• z=console.nextInt();• System.out.println(x);• System.out.println(y);• System.out.println(z);• }• }

When inputting values, do not use the enter keys between the

values.

The Math Class Part of the java.lang package

The random() methods generates a double between 0 and 1.0. For example,

double rNum;rNum = Math.random();

A random integer in a range is generated by using the expression:(highNum – lowNum + 1) * Math.random() + lowNum

Math Class• abs(int) or abs(double) - absolute value• acos(double) – arc cos• asin(double) – arc sin• atan(double) – arc tan• cos(double) – cosine• sin(double) - sine• tan(double) - tangent• ceil(double) – smallest whole number greater than or equal to

num• exp(double) - power• floor(double) – largest whole number less than or equal to num.• pow(double, double) – return num raised to a power• random() – 0.0 to < 1.0• sqrt(double) – square root

Built-in arithmetic operators

• * - multiplication

• % - modulus division

• / - division

• + - addition

• - - subtraction

Modulus Division

Modulus division (%) returns the remainder of a division operation:

Compound Assignment Operators

Operator Operation+= addition and then assignment-= subtraction and then assignment*= multiplication and then

assignment/= division and then assignment%= modulus division and then

assignment

Order of Precedence

• !, (unary) -, Cast, ++, --• *, /, %• +, -• <, >, <=, >=, ==, !=• &&• ||• In the absence of parentheses, binary operators of

the same rank are performed left to right, and unary operators right to left. If in doubt use parentheses!

Parentheses

• Operations inside of parentheses are evaluated first.

• The order in which operators are evaluated can be changed by using parentheses. For example, addition is performed first, then multiplication, and finally division:

• Example:– 6 + 4 * 2 – 1 // 13– (6 + 4) * (2 – 1) // 10– (5 + 6) * 4 / 2 // 22

Type promotion (implicit conversion)

• Occurs when using a math expression of different data types.

• Example: int + double will return a double and the int will be promoted to a double by the compiler automatically.

• You will need to have a double data type to store the result.

• If you try to store it in an int memory location, you will get a loss of precision error.

+, -, *, %

• Will return the data type of the operand if they of same data type.

• Mixed mode operands will use type promotion to determine the data type that will be return.

• Can’t % by a 0– 5 % 0;

• Can 0%8 = 0

Mixed Mode Operands• int + int int• int + double double• double + double double• int * int int• int *double double• double * double double• int / int int• int / double double• double / double double• Just as long as one of the operand is a double, the other

operand will be promoted up and result will be a double.

/ division

• Must be careful when working with division.

• int/int will return an int and the remainder is dropped.

• One or both of the sides of the division must be a double to return a double

• Can’t divide by 0 example 5/0;• Can 0/5 = 0;

Real Division

Real division (/) is performed when one or both operands are type double. The entire quotient, including the decimal portion is returned:

double result;result = 20.0/7.0; //result is 2.857

Integer Division

Integer division (/) is performed when both operands are integers. Only the integer portion of the quotient is returned:

Division & Modulus

• Can use if statement to eliminate errors

if(x != 0)8 / x

• Eliminates any errors if x = 0;

Casting or Type Casting

• Converts a value Data Type temporary to another type.

• Examples:int x, i = 2;double d = 3.7;x = i * (int) d; // d is explicitly cast

• Type casting is necessary in this case because one of the operands has less precision than the variable that will store the result.

• Explicit casting also makes it clear that the programmer intended for the calculation result to be an int.

Type Casting

Type Casting converts a number of one type to a number of a different, but compatible type. Type casting is used to:

1. make the operand types in an expression match. For example, wholeNum = (int)y * 2

2. truncate the decimal portion of a double. For example, wholeNum = (int)z

3. change the way in which a division (/) operation will be performed. For example, realDivision = (double)a / (double)b

Casting real division

• Casting is useful when real division with integers is preferred

• result = (double) 8/ (double) 5; //explicitly• result = (double) 8/ 5; // explicitly & implicitly• Java will implicitly type cast operands in a mixed

expression to match the precision of the variable storing the value. Although explicitly type casting is not necessary, it is better programming style to include casts.

• Casting makes the programmer’s intentions clear and makes bugs easier to find.

Truncate

• Casting a double to an int truncates the decimal portion of the number.

Rounding

• Rounding can be simulated when casting a double to an int by adding .5 to the number before the casting.

• x = i * (int)(d + 0.5);

Abstract Data Types

A variable declared with a class is called an object. For example, the object spot is type Circle:

Circle spot = new Circle(4);spotspot

getRadius()area()

Programming Errors

Syntax errors violate the rules of Java.

Logic errors, also called semantic errors, occur in statements that are syntactically correct, but produce undesired or unexpected results.

Run-time errors, also called exceptions, halt program execution at the statement that cannot be executed. One type of exception is called InputMismatchException.

Flowchart Symbols

processprocess

The BirthdayGame Flowchart