variables, data types, & constants

60
Variables, Data Types, & Constants

Upload: mercia

Post on 11-Jan-2016

81 views

Category:

Documents


3 download

DESCRIPTION

Variables, Data Types, & Constants. 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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Variables, Data Types, & Constants

Variables, Data Types, & Constants

Page 2: Variables, Data Types, & Constants

Objectives

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

• Math Class• Arithmetic • Compound

Assignment • Flow Charting

Page 3: Variables, Data Types, & Constants

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.

Page 4: Variables, Data Types, & Constants

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; //Initialize myValue to 3

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

Page 5: Variables, Data Types, & Constants

Assignment Statement

• (=) symbol is used for 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

Page 6: Variables, Data Types, & Constants

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

Page 7: Variables, Data Types, & Constants

Variable Assignment

A variable can store only one value at any time.

int x;x = 5;x = 10;

xx

510

Page 8: Variables, Data Types, & Constants

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

Page 9: Variables, Data Types, & Constants

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

Page 10: Variables, Data Types, & Constants

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

Page 11: Variables, Data Types, & Constants

Primitive Data Types or built-in data types

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

Page 12: Variables, Data Types, & Constants

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

Page 13: Variables, Data Types, & Constants

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

Page 14: Variables, Data Types, & Constants

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

Page 15: Variables, Data Types, & Constants

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

Page 16: Variables, Data Types, & Constants

Character Data Type

• Used for single letters in single quotes

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

Page 17: Variables, Data Types, & Constants

Boolean Data Type

• Used for true or false

• boolean – 1 byte true or false

Page 18: Variables, Data Types, & Constants

Choosing a data type

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

Page 19: Variables, Data Types, & Constants

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.

Page 20: Variables, Data Types, & Constants

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.

Page 21: Variables, Data Types, & Constants

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.

Page 22: Variables, Data Types, & Constants

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

Page 23: Variables, Data Types, & Constants

Unicode

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

• Represents 65,000 characters for most world languages

Page 24: Variables, Data Types, & Constants

Import, Arithmetic, Casting, Logical Operators, Relational

Operators

Page 25: Variables, Data Types, & Constants

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.

Page 26: Variables, Data Types, & Constants

Packages

• Group of related classes by one name.

• Eamples: java.lang – java.util

Page 27: Variables, Data Types, & Constants

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.

Page 28: Variables, Data Types, & Constants

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

Page 29: Variables, Data Types, & Constants

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

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

Page 30: Variables, Data Types, & Constants

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

Page 31: Variables, Data Types, & Constants

Inputting

Page 32: Variables, Data Types, & Constants

Scanner Class

• next()

• nextLine()

• nextInt()

• nextDouble()

• nextBoolean()

• nextFloat()

• nextLong()

• nextShort()

Page 33: Variables, Data Types, & Constants

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.

Page 34: Variables, Data Types, & Constants

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

Page 35: Variables, Data Types, & Constants

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

Page 36: Variables, Data Types, & Constants

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

Page 37: Variables, Data Types, & Constants

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

values.

Page 38: Variables, Data Types, & Constants

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

Page 39: Variables, Data Types, & Constants

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

Page 40: Variables, Data Types, & Constants

Built-in arithmetic operators

• * - multiplication

• % - modulus division

• / - division

• + - addition

• - - subtraction

Page 41: Variables, Data Types, & Constants

Modulus Division

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

Page 42: Variables, Data Types, & Constants

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

Page 43: Variables, Data Types, & Constants

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!

Page 44: Variables, Data Types, & Constants

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

Page 45: Variables, Data Types, & Constants

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.

Page 46: Variables, Data Types, & Constants

+, -, *, %

• 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

Page 47: Variables, Data Types, & Constants

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.

Page 48: Variables, Data Types, & Constants

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

Page 49: Variables, Data Types, & Constants

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

Page 50: Variables, Data Types, & Constants

Integer Division

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

Page 51: Variables, Data Types, & Constants

Division & Modulus

• Can use if statement to eliminate errors

if(x != 0)8 / x

• Eliminates any errors if x = 0;

Page 52: Variables, Data Types, & Constants

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.

Page 53: Variables, Data Types, & Constants

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

Page 54: Variables, Data Types, & Constants

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.

Page 55: Variables, Data Types, & Constants

Truncate

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

Page 56: Variables, Data Types, & Constants

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

Page 57: Variables, Data Types, & Constants

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

Page 58: Variables, Data Types, & Constants

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.

Page 59: Variables, Data Types, & Constants

Flowchart Symbols

processprocess

Page 60: Variables, Data Types, & Constants

The BirthdayGame Flowchart