610 likes | 778 Views
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
E N D
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; //Initialize myValue to 3 • Variable can only store one value of its type at a time.
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
Assignment Statement An 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; x 10 5
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
Primitive Data Types or built-in data types Data type – determines the type of data the variable will store
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 TypeStorage Required int 4 bytes //AP EXAM double 8 bytes //AP EXAM char 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 or32,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 . • Numeric literal – 8 , 9, 427 • 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.
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 statementimport 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
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 OperatorOperation += 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: