Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of...

27
Lesson 3 – Primitive Lesson 3 – Primitive Data Types Data Types Objective: Objective: Students will investigate the definition and Students will investigate the definition and usage of objects and primitive data types in Java usage of objects and primitive data types in Java in order to practice applying the basic tenets of in order to practice applying the basic tenets of Java Programming. Java Programming. Learning Goal: Learning Goal: Java provides several primitive data types to Java provides several primitive data types to store basic information and uses objects to fill store basic information and uses objects to fill in gaps not covered with the primitive data in gaps not covered with the primitive data types. Java gives the programmer a wide variety types. Java gives the programmer a wide variety of data types to use and Primitive data types are of data types to use and Primitive data types are very basic in nature. In this lesson you will very basic in nature. In this lesson you will declare variables, store values in them, learn declare variables, store values in them, learn operations to manipulate and use those values, operations to manipulate and use those values, and print out the values using the System.out and print out the values using the System.out object. object.

Transcript of Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of...

Page 1: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Lesson 3 – Primitive Lesson 3 – Primitive Data TypesData Types

Objective:Objective:Students will investigate the definition and usage of Students will investigate the definition and usage of objects and primitive data types in Java in order to objects and primitive data types in Java in order to practice applying the basic tenets of Java Programming.practice applying the basic tenets of Java Programming.

Learning Goal:Learning Goal:Java provides several primitive data types to store basic Java provides several primitive data types to store basic information and uses objects to fill in gaps not covered information and uses objects to fill in gaps not covered with the primitive data types. Java gives the programmer with the primitive data types. Java gives the programmer a wide variety of data types to use and Primitive data a wide variety of data types to use and Primitive data types are very basic in nature. In this lesson you will types are very basic in nature. In this lesson you will declare variables, store values in them, learn operations declare variables, store values in them, learn operations to manipulate and use those values, and print out the to manipulate and use those values, and print out the values using the System.out object. values using the System.out object.

Page 2: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Primitive Data TypesPrimitive Data Types

When designing a class, one of the When designing a class, one of the programmer’s jobs is to define the programmer’s jobs is to define the attributes of the class. attributes of the class.

Java allows two different types of attributes: Java allows two different types of attributes: objects and primitive data types. objects and primitive data types.

In this lesson you will declare variables, In this lesson you will declare variables, store values in them, learn operations to store values in them, learn operations to manipulate and use those values, and print manipulate and use those values, and print out the values using the System.out object. out the values using the System.out object.

Page 3: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Identifiers in JavaIdentifiers in Java

An identifier is a name that will be used to An identifier is a name that will be used to describe classes, methods, constants, describe classes, methods, constants, variables; anything a programmer is variables; anything a programmer is required to define.required to define.

The rules for naming identifiers in Java are: The rules for naming identifiers in Java are: – Identifiers must begin with a letter. Identifiers must begin with a letter. – Only letters, digits, or an underscore may follow Only letters, digits, or an underscore may follow

the initial letter. the initial letter. – The blank space cannot be used. The blank space cannot be used. – Identifiers cannot be reserved words. Reserved Identifiers cannot be reserved words. Reserved

words or keywords are already defined in Java. words or keywords are already defined in Java. These include words such as These include words such as newnew, , classclass, , intint, etc. , etc. See See Handout A3.1Handout A3.1, Reserved Words in Java, Reserved Words in Java

Page 4: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Java is a case sensitive language. That is, Java will Java is a case sensitive language. That is, Java will distinguish between upper and lower case letters in distinguish between upper and lower case letters in identifiers. identifiers.

Be careful both when naming identifiers and when Be careful both when naming identifiers and when typing them into the code. A good identifier should typing them into the code. A good identifier should help describe the nature or purpose of whatever it is help describe the nature or purpose of whatever it is naming. For a variable name, it is better to use grade naming. For a variable name, it is better to use grade instead of g, number instead of n.instead of g, number instead of n.

However, avoid excessively long or "cute" identifiers However, avoid excessively long or "cute" identifiers such as:such as:

gradePointAverageForStudentsAToZ gradePointAverageForStudentsAToZ or or bigHugeUglyNumberThatIsPrettyPointlessButINeedItAnbigHugeUglyNumberThatIsPrettyPointlessButINeedItAnywayyway

Identifiers in JavaIdentifiers in Java

Page 5: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Remember that the goal is to write code that is professional Remember that the goal is to write code that is professional in nature; other programmers need to understand your code.in nature; other programmers need to understand your code.

Programmers will adopt different styles of using upper and Programmers will adopt different styles of using upper and lower case letters in writing identifiers. The reserved lower case letters in writing identifiers. The reserved keywords in Java must be typed in lower case text, but keywords in Java must be typed in lower case text, but identifiers can be typed using any combination of upper and identifiers can be typed using any combination of upper and lower case letters – “camelCase.”lower case letters – “camelCase.”

The following conventions will be used throughout this The following conventions will be used throughout this curriculum guide: curriculum guide: – A single word identifier will be written in lower case only. A single word identifier will be written in lower case only.

Examples: grade, number, sum. Examples: grade, number, sum. – Class names will begin with upper case. Examples: String, Class names will begin with upper case. Examples: String,

DrawingTool, SketchPad, Benzene. DrawingTool, SketchPad, Benzene. – If an identifier is made up of several words, all words beyond the If an identifier is made up of several words, all words beyond the

first will begin with upper case. Examples: stringType, first will begin with upper case. Examples: stringType, passingScore, largestNum, DrawHouse, SketchPad. passingScore, largestNum, DrawHouse, SketchPad.

– Identifiers used as constants will be fully capitalized. Examples: Identifiers used as constants will be fully capitalized. Examples: PI, MAXSTRLEN.PI, MAXSTRLEN.

Conventions for Using Conventions for Using Identifiers in JavaIdentifiers in Java

Page 6: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Primitive Data TypesPrimitive Data Types

Java provides eight primitive data types: Java provides eight primitive data types: bytebyte, , shortshort, , intint, , longlong, , floatfloat, , doubledouble, , charchar, and , and booleanboolean. The data types . The data types bytebyte, , shortshort, , intint, and , and longlong are for integers, and the data types are for integers, and the data types floatfloat and and doubledouble are for real numbers (numbers with decimal places). are for real numbers (numbers with decimal places).

The College Board Advanced Placement (AP) Examinations The College Board Advanced Placement (AP) Examinations require you to know about the require you to know about the intint, , doubledouble, and , and booleanboolean data data types. This curriculum will, from time to time, also use the types. This curriculum will, from time to time, also use the charchar type when appropriate.type when appropriate.

An integer is any positive or negative number without a decimal An integer is any positive or negative number without a decimal point.point.

A double is any signed or unsigned number with a decimal point. A double is any signed or unsigned number with a decimal point. Doubles cannot contain a comma or any symbols. A double value Doubles cannot contain a comma or any symbols. A double value can be written using scientific notation.can be written using scientific notation.

– Valid numbers: 7.5 -66.72 0.125 5 Valid numbers: 7.5 -66.72 0.125 5 – Invalid numbers: $37,582.00 #5.0 10.72% Invalid numbers: $37,582.00 #5.0 10.72% – Scientific notation: 1625. = 1.625e3 .00125 = 1.25e-4 Scientific notation: 1625. = 1.625e3 .00125 = 1.25e-4

(Note: When applying 5 to a double variable, Java will (Note: When applying 5 to a double variable, Java will automatically add the decimal point for you.)automatically add the decimal point for you.)

Page 7: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Primitive Data TypesPrimitive Data Types

The following table summarizes the bytes allocated and the resulting size. The following table summarizes the bytes allocated and the resulting size. Size Minimum Value Size Minimum Value Maximum ValueMaximum Value

ByteByte 1 byte1 byte -128 -128 127 127ShortShort 2 bytes2 bytes -32768 -32768 32767 32767IntInt 4 bytes4 bytes -2147483648 -2147483648 2147483647 2147483647LongLong 8 bytes8 bytes -9223372036854775808 -9223372036854775808 9223372036854775807 9223372036854775807FloatFloat 4 bytes4 bytes -3.40282347E+38-3.40282347E+38 3.40282347E+383.40282347E+38DoubleDouble 8 bytes8 bytes -.79769313486231570E+3081.79769313486231570E+308-.79769313486231570E+3081.79769313486231570E+308

Character type consists of letters, digits 0 through 9, and punctuation symbols. Character type consists of letters, digits 0 through 9, and punctuation symbols. A character must be enclosed within single quotes. Examples: 'A', 'a', '8', '*'A character must be enclosed within single quotes. Examples: 'A', 'a', '8', '*'

Java characters are stored using 2 bytes according to the ASCII code. ASCII Java characters are stored using 2 bytes according to the ASCII code. ASCII stands for American Standard Code for Information Interchange. stands for American Standard Code for Information Interchange. See Handout See Handout A3.2, ASCII Characters - A Partial ListA3.2, ASCII Characters - A Partial List

Using ASCII, the character value 'A' is actually stored as the integer value 65. Using ASCII, the character value 'A' is actually stored as the integer value 65. Because a capital 'A' and the integer 65 are physically stored in the same Because a capital 'A' and the integer 65 are physically stored in the same fashion, this will allow us to easily convert from character to integer types, and fashion, this will allow us to easily convert from character to integer types, and vice versa. vice versa.

Page 8: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Primitive Data TypesPrimitive Data Types

In Java, you can make a direct In Java, you can make a direct assignment of a character value to assignment of a character value to an integer variable, and vice versa. an integer variable, and vice versa. This is possible because both an This is possible because both an integer and a character variable are integer and a character variable are ultimately stored in binary. However, ultimately stored in binary. However, it is better to be more explicit about it is better to be more explicit about such conversions by using type such conversions by using type conversions. conversions.

Page 9: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Escape Code UsageEscape Code Usage

Programmers use the single quote to represent Programmers use the single quote to represent char data and double quotes to denote String char data and double quotes to denote String types. To use either of those characters in a types. To use either of those characters in a String literal, such as in a System.out.println String literal, such as in a System.out.println statement, you must use an escape sequence. statement, you must use an escape sequence. Here is a partial list:Here is a partial list:

CharacterCharacter Java Escape Sequence Java Escape Sequence NewlineNewline '\n‘'\n‘ Horizontal tabHorizontal tab '\t‘'\t‘ BackslashBackslash '\\‘'\\‘ Single quoteSingle quote '\‘‘'\‘‘ Double quoteDouble quote '\“'\“ 'Null character'Null character '\0' '\0'

Page 10: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Primitive Data TypesPrimitive Data Types

Data types are provided by high-level Data types are provided by high-level languages to minimize memory usage and languages to minimize memory usage and processing time. Integers and characters processing time. Integers and characters require less memory and are easier to process. require less memory and are easier to process. Floating-point values require more memory Floating-point values require more memory and time to process.and time to process.

The last primitive data type is the type The last primitive data type is the type booleanboolean. It is used to represent a single . It is used to represent a single truetrue//falsefalse value. A value. A booleanboolean value can have value can have only one of two values: only one of two values: truetrue false false

In a Java program, the reserved words In a Java program, the reserved words truetrue and and falsefalse always refer to these always refer to these booleanboolean values.values.

Page 11: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Declaring and Declaring and Initializing VariablesInitializing Variables A variable must be declared A variable must be declared

before it can be initialized with a before it can be initialized with a value. The general syntax of value. The general syntax of variable declarations is:variable declarations is:data_type variableName;data_type variableName;

for example:for example:intint number; number;charchar ch; ch;

Page 12: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Declaring and Declaring and Initializing VariablesInitializing Variables Variables can be declared in a Variables can be declared in a

class outside of any methods or class outside of any methods or inside of a method. Variables can inside of a method. Variables can also be declared and initialized in also be declared and initialized in one line. The following example one line. The following example code illustrates these aspects of code illustrates these aspects of variable declaration and variable declaration and initialization. initialization.

Page 13: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Example of Example of Declaration:Declaration:

Page 14: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Printing Variables Printing Variables Using the System.out Using the System.out ObjectObject The System.out object is automatically The System.out object is automatically

created in every Java program. It has created in every Java program. It has methods for displaying text strings and methods for displaying text strings and numbers in plain text format on the system numbers in plain text format on the system display, which is sometimes referred to as display, which is sometimes referred to as the “console.” the “console.”

Method System.out.println displays (or Method System.out.println displays (or prints) a line of text in the console window. prints) a line of text in the console window. When System.out.println completes its task, When System.out.println completes its task, it automatically positions the output cursor it automatically positions the output cursor (the location where the next character will be (the location where the next character will be displayed) to the beginning of the next line in displayed) to the beginning of the next line in the console window. the console window.

Page 15: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Assignment Assignment StatementsStatements An assignment statement has An assignment statement has

the following basic syntax:the following basic syntax:

variable = expression;variable = expression; The assignment operator (=) The assignment operator (=)

assigns the value of the assigns the value of the expression on the right to the expression on the right to the variable. a = 5; variable. a = 5;

Page 16: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Variables contain either primitive data or object references. Variables contain either primitive data or object references. Notice that there is a difference between the two Notice that there is a difference between the two statements: primitiveValue = 18234; and myPencil = new statements: primitiveValue = 18234; and myPencil = new DrawingTool();DrawingTool();

A variable will A variable will never never actually contain an object, only a actually contain an object, only a reference to an object.reference to an object. In the first statement, In the first statement, primitiveValue is a primitive type, so the assignment primitiveValue is a primitive type, so the assignment statement puts the data directly into it. In the second statement puts the data directly into it. In the second statement, myPencil is an object reference variable (the statement, myPencil is an object reference variable (the only other possibility) so a reference to the object is put only other possibility) so a reference to the object is put into that variable. into that variable.

The object reference tells the program where to find an The object reference tells the program where to find an object.object. The two types of variables are distinguished by how The two types of variables are distinguished by how they are declared. Unless it was declared to be of a they are declared. Unless it was declared to be of a primitive type, it is an object reference variable. A variable primitive type, it is an object reference variable. A variable will not change its declared type.will not change its declared type.

Assignment Assignment StatementsStatements

Page 17: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Math OperatorsMath Operators

Java provides 5 math operators:Java provides 5 math operators:

+ Addition, as well as unary ++ Addition, as well as unary +

- Subtraction, as well as unary – - Subtraction, as well as unary –

* Multiplication* Multiplication

/ Floating point and integer division/ Floating point and integer division

% Modulus, remainder of integer or % Modulus, remainder of integer or floating point divisionfloating point division

Page 18: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Precedence of Math Precedence of Math OperatorsOperators Precedence rules govern the order in which Precedence rules govern the order in which

an expression is solved. For example: an expression is solved. For example: 2 + 3 * 6 -> 20 the * operator has priority 2 + 3 * 6 -> 20 the * operator has priority

over +.over +. Associativity refers to the order in which Associativity refers to the order in which

operators are applied if they have the same operators are applied if they have the same precedence level. The two possibilities are precedence level. The two possibilities are from left-to-right or right-to-left.from left-to-right or right-to-left.

A unary operator is used on only one A unary operator is used on only one number. An example of a unary operator is number. An example of a unary operator is the negative sign in the expression the negative sign in the expression -a-a, , meaning the negative of meaning the negative of aa..

Page 19: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Precedence of Math Precedence of Math OperatorsOperatorsThe following table summarizes The following table summarizes

precedence of math operators:precedence of math operators:

Level of Precedence Level of Precedence Operator Operator AssociativityAssociativity

HighestHighest unary -unary - right to leftright to left

* / %* / % left to rightleft to right

LowestLowest + - + - left to rightleft to right

Parentheses take priority over all the Parentheses take priority over all the math operators. math operators.

Page 20: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Assignment OperatorsAssignment Operators

The statement number = number + The statement number = number + 5; is an example of an accumulation 5; is an example of an accumulation statement. The old value of number statement. The old value of number is incremented by 5 and the new is incremented by 5 and the new value is stored in number.value is stored in number.

The above statement can be The above statement can be simplified as follows: number += simplified as follows: number += 5;5;

Page 21: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Assignment OperatorsAssignment Operators

Java provides the following Java provides the following assignment operators:assignment operators:

+=   -=   *=   /=   %=+=   -=   *=   /=   %=

Page 22: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Assignment OperatorsAssignment Operators

The precedence of the The precedence of the assignment operators is the assignment operators is the lowest of all operators. lowest of all operators.

Page 23: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Increment/Decrement Increment/Decrement OperatorsOperators Incrementing or decrementing by Incrementing or decrementing by

one is a common task in one is a common task in programs. This task can be programs. This task can be accomplished by the statements:accomplished by the statements:

n = n + 1;    or   n += 1;n = n + 1;    or   n += 1;

Page 24: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Increment/Decrement Increment/Decrement OperatorsOperators The increment and decrement operators The increment and decrement operators

can be written as either a prefix or can be written as either a prefix or postfix unary operator. If the ++ is postfix unary operator. If the ++ is placed before the variable it is called a placed before the variable it is called a pre-increment operator (++number), pre-increment operator (++number), but it can follow after the variable but it can follow after the variable (number++), which is called a post-(number++), which is called a post-increment operator. The following three increment operator. The following three statements have the same effect: +statements have the same effect: ++number;    number++;  +number;    number++;  

number = number + 1;number = number + 1;

Page 25: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

SummarySummary

This lesson has covered a large amount This lesson has covered a large amount of detail regarding the Java language. At of detail regarding the Java language. At first, it will be necessary to memorize first, it will be necessary to memorize the syntax of data types and their the syntax of data types and their operations, but with time and practice, operations, but with time and practice, fluency will come. You will find as fluency will come. You will find as classes are designed and code is written classes are designed and code is written to solve problems, a primitive data type to solve problems, a primitive data type will often be chosen to store basic will often be chosen to store basic information. information.

Page 26: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Wrap - UpWrap - Up

What are the two different types What are the two different types of attributes allowed in Java?of attributes allowed in Java?

Is Java case sensitive?Is Java case sensitive? What are the rules for naming What are the rules for naming

identifiers?identifiers?

Page 27: Lesson 3 – Primitive Data Types Objective: Students will investigate the definition and usage of objects and primitive data types in Java in order to practice.

Assignments – Assignments –

Vocabulary – record in your notes Vocabulary – record in your notes with definitions.with definitions.

Do Lab – calculating date for Do Lab – calculating date for Easter.Easter.