Vous êtes sur la page 1sur 14

STUDENT OUTLINE Lesson 3 - Data Types in Java

INTRODUCTION: As with most high level languages, Java provides standard data types to store information. Java is a richly typed language that gives the programmer a wide variety of data types to use. In this lesson you will declare variables, store values in them, and print out their values using the System.out object. The key topics for this lesson are: A. B. C. D. E. F. VOCABULARY: Identifiers in Java Basic Data Types in Java Declaring and Initializing Variables in Java Printing Variables Using the System.out object ASCII Code Values and Character Data Assignment Statements and Math Operators KEYWORDS
char double String

IDENTIFIER
int boolean float

ESCAPE SEQUENCE TYPE CONVERSION MODULUS DISCUSSION: A. Identifiers in Java

TYPE ASSIGNMENT STATEMENT ASCII

1. An identifier is a name that will be used to describe classes, methods, constants, variables, and other items. 2. The rules for writing identifiers in Java are: a. Identifiers must begin with a letter. b. Only letters, digits, or underscore may follow the initial letter. c. The blank space cannot be used. d. Identifiers cannot be reserved words. Reserved words or keywords are only for system use. 3. Java is a case sensitive language. That is, Java will distinguish between upper and lower case letters in identifiers. Therefore:
grade and Grade are different identifiers

See Handout H.A.3.1, Reserved Words in Java.

4. A good identifier should help describe the nature or purpose of that function or variable. It is better to use
grade instead of g, number instead of n.

APCS - Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

O.A3.1 (Page 1)

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


gradePointAverage or bigHugeUglyNumber

Remember that our goal is to write code that is easy to read and professional in nature. 6. Programmers will adopt different styles of using upper and lower case letters in writing identifiers. The reserved keywords in Java must be typed in lower case text, but identifiers can be typed using any combination of upper and lower case letters. 7. The following conventions will be used throughout the curriculum guide: a. A single word identifier will be written in lower case only. Examples: grade, number, sum. b. If an identifier is made up of several words, the first letter will be lower case. Subsequent words will begin with upper case. Some examples are: stringType, passingScore, largestNum. c. Identifiers used as constants will be fully capitalized. Examples: PI, MAXSTRLEN. B. Basic Data Types in Java 1. Java provides eight primitive data types: byte, short, int, long, float, double, char and a boolean. The data types byte, short, int, and long are for integers, and the data types float and double are for real numbers. 2. Integer type - any positive or negative number without a decimal point. a. Examples: 7 -2 0 2025. 3. Floating Point type - any signed or unsigned number with a decimal point. a. Examples: 7.5 -66.72 0.125 5. b. A floating point value cannot contain a comma or $ symbol. c. A floating point value must have a decimal point. d. Invalid examples: 1,234.56 $66.95 125 7,895 e. Floating point values can be written using scientific notation: 1625. = 1.625e3 .000125 = 1.25e-4

APCS - Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

O.A3.1 (Page 2)

4. The following table summarizes the bytes allocated and the resulting size. Size
byte short int long float double

Minimum Value
-128 -32768 -2147483648 -9223372036854775808 -3.40282347E+38 -1.79769313486231570E+308

Maximum Value
127 32767 2147483647 9223372036854775807 3.40282347E+38 1.79769313486231570E+308

1 byte 2 bytes 4 bytes 8 bytes 4 bytes 8 bytes

See Handout H.A.3.2, ASCII Characters - A Partial List.

5. Character type - letters, digits 0..9, and punctuation symbols. a. Examples: 'A', 'a', '8', '*' b. Note that a character type must be enclosed within single quotes. c. Java character types are stored using 2 bytes, usually according to the ASCII code. ASCII stands for American Standard Code for Information Interchange. d. 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 fashion, this will allow us to easily convert from character to integer types, and vice versa. e. Using the single quote as a delimiter leads to the question about how to assign the single quote (') character to a variable. Java provides escape sequences for unusual keystrokes on the keyboard. Here is a partial list: Character Newline Horizontal tab Backslash Single quote Double quote Null character Java Escape Sequence
'\n' '\t' '\\' '\'' '\"' '\0'

6. Data types are provided by high level languages to minimize memory usage and processing time. Integers and characters require less memory and are easier to process. Floating-point values require more memory and time to process. 7. The final primitive data type is the type boolean. It is used to represent a single true/false value. A boolean value can have only one of two values:
true false

In a Java program, the words true and false always mean these boolean values.

APCS - Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

O.A3.1 (Page 3)

C. Declaring and Initializing Variables in Java 1. A variable must be declared before it can be initialized with a value. The general syntax of variable declarations is:
data_type variableName;

for example
int number; char ch;

2. Variables can be declared near the top of the method or in the midst of writing code. Variables can also be declared and initialized in one line. The following example program illustrates these aspects of variable declaration and initialization. Program 3-1
public class DeclareVar { public static void main(String[] args) { // first is declared and initialized // second is just initialized int first = 5, second; double x; char ch; boolean done; second = 7; x = 2.5; ch = 'T'; done = false; } int sum = first + second;

a. Multiple variables can be declared on one line. b. Initialization is accomplished with an equal (=) sign. c. Initialization can occur at declaration time or later in the program. The variable sum was declared and used in the same line. 3. Where the variables are declared is a matter of programming style. Your instructor will probably have some preferences regarding this matter. D. Printing Variables Using the System.out Object 1. The System.out object is defined in each Java program. It has methods for displaying text strings and numbers in plain text format on the system display, which is sometimes referred to as the console. For example:

APCS - Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

O.A3.1 (Page 4)

Program 3-2
public class PrintVar { public static void main(String[] args) { int number = 5; char letter = 'E'; double average = 3.95; boolean done = false; System.out.println("number = " + number); System.out.println("letter = " + letter); System.out.println("average = " + average); System.out.println("done = " + done); System.out.print("The "); System.out.println("End!");

Run output:
number = 5 letter = E average = 3.95 done = false The End!

2. Method System.out.println displays (or prints) a line of text in the console window. When System.out.println completes its task, it automatically positions the output cursor (the location where the next character will be displayed) to the beginning of the next line in the console window (this is similar to pressing the Enter key when typing in a text editorthe cursor is repositioned at the beginning of the next line in your file). 3. The expression
"number = " + number

from the statement


System.out.println("number = " + number);

uses the + operator to add a string (the literal "number = ") and number (the int variable containing the number 5). Java has a version of the + operator for String concatenation that enables a string and a value of another data type to be concatenated (added). The result of this operation is a new (and normally longer) string. String concatenation is discussed in more detail in the next lesson.

APCS - Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

O.A3.1 (Page 5)

4. The lines
System.out.print("The "); System.out.println("End!");

of Program 3-2 display one line in the console window. The first statement uses System.outs method, print, to display a string. Unlike println, print does not position the output cursor at the beginning of the next line in the console window after displaying its argument. The next character displayed in the console window appears immediately after the last character displayed with print. 5. Note the distinction between sending a text constant, "number = ", versus a variable, number, to the System.out object. A boolean variable will be printed out as its representation of true or false. E. ASCII Code Values and Character Data 1. As mentioned earlier in section B.5, a character value can easily be converted to its corresponding ASCII integer value. 2. A character value is stored using two byte of memory, which consists of 16 bits of binary (0 or 1) values. 3. The letter 'A' has the ASCII value of 65, which is stored as the binary value 0000000001000001. This is illustrated in the following program fragment:
char letter = 'A'; System.out.println("letter = " + letter); System.out.print("its ASCII value = "); System.out.print((int)letter);

Run output:
letter = A its ASCII value = 65

The statement (int)letter is called a type conversion. The data type of the variable is converted to the outer type inside of the parentheses, if possible. 4. In Java, you can make a direct assignment of a character value to an integer variable, and vice versa. This is possible because both an integer and a character variable are ultimately stored in binary. However, it is better to be more explicit about such conversions by using type conversions. For example, the two lines of code below assign to position the ASCII value of letter.

APCS - Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

O.A3.1 (Page 6)

char letter = 'C'; int position; position = letter;

// ASCII value = 67 // This is legal, position now equals 67

vs.
position = (int)letter; // This is easier to understand.

More detail about type conversions follows in section F. 9. F. Assignment Statements and Math Operators 1. An assignment statement has the following basic syntax:
variable = expression;

a. The expression can be a literal constant value such as 2, 12.25, 't'. b. The expression can also be a numeric expression involving operands (values) and operators. c. The = operator returns the value of the expression. This means that the statement
a = 5;

assigns 5 to the variable and returns the value 5. This allows for chaining of assignment operators.
a = b = 5;

The assignment operator (=) is right-associative. This means that the above statement is really solved in this order:
a = (b = 5);// solved from right to left.

Since (b = 5) returns the integer 5, the value 5 is also assigned to variable a. 2. Java provides 5 math operators as listed below:
+ * / %

Addition, as well as unary + Subtraction, as well as unary Multiplication Real and integer division Modulus, remainder of integer or floating point division

3. The numerical result and data type of the answer depends on the type of operands used in a problem.

APCS - Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

O.A3.1 (Page 7)

4. For all the operators, if both operands are integers, the result is an integer. Examples:
2 + 3 = 5 (integer) 4 * 8 = 32 (integer) 9 - 3 = 6 (integer) 11/2 = 5 (integer Note!)

5. If either of the operands is a float type, the result is a float type. Examples:
2 + 3.000 = 5.000 (float) 25 / 6.75 = 3.7037 (float) 11.0 / 2.0 = 5.5 (float)

a. When an integer and a float are used in a binary math expression, the integer is promoted to a float value, and then the math is executed. b. In the example 2 + 3.000 = 5.000, the integer value 2 is promoted to a float (2.000) and then added to the 3.000. 6. The modulus operator (%) returns the remainder of dividing the first operand by the second. For example:
10 % 3 = 1 2 % 4 = 2 16 % 2 = 0 27.475 % 7.22 = 5.815

7. Changing the sign of a value can be accomplished with the negation operator (-), often called the unary (-) operator. A unary operator works with only one value. Applying the negation operator to an integer returns an integer, while applying it to a float returns a float value. For example:
-(67) = -67 -(-2.345) = 2.345

8. To obtain the fractional answer to a question like 11/2 = 5.5, a type conversion must be applied to one of the operands.
(double)11/2 11.000/2 5.5

results in 5.5 then we do division

The type conversion operators are unary operators with the following syntax:
(type) operand

9. There is more to cover regarding operators in Java. Topics such as math precedence and assignment operators will be covered in a later lesson. SUMMARY/ REVIEW: This lesson has covered a great amount of detail regarding the Java language. At first you will have to memorize the syntax of data types, but with time and practice, fluency will come. Lab Exercise, L.A.3.1, MathFun Lab Exercise, L.A.3.2, Easter
O.A3.1 (Page 8)

ASSIGNMENT:

APCS - Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

LAB EXERCISE MathFun


Background: 1. For each primitive data type (such as int or double) there is a corresponding class (such as Integer or Double) in package java.lang. These classes (commonly known as wrapper classes) provide methods and constants for dealing with primitive data type values. Primitive data types do not have methods. Therefore, methods related to a primitive data type are located in the corresponding wrapper class. 2. Some of the information provided by the wrapper classes are constants to indicate the largest and smallest values for a given data type. For example, the largest integer is 2147483647. 3. Here are the names of the some of the constants associated with the wrapper classes for each data type:
Byte.MAX_VALUE Byte.MIN_VALUE Short.MAX_VALUE Short.MIN_VALUE Character.MAX_VALUE Character.MIN_VALUE Integer.MAX_VALUE Integer.MIN_VALUE Long.MAX_VALUE Long.MIN_VALUE Float.MAX_VALUE Float.MIN_VALUE Double.MAX_VALUE Double.MIN_VALUE // // // // // // // // // // // // // // the the the the the the the the the the the the the the largest value of type byte smallest value of type byte largest value of type short smallest value of type short largest value of type char smallest value of type char largest value of type int smallest value of type int largest value of type long smallest value of type long largest positive value of type float smallest positive value of type float largest positive value of type double smallest positive value of type double

Assignment: 1. Write a program to solve the math expressions shown below. 2. The program must store each calculated result in an appropriate variable. 3. The program must print out the math expression and result as follows:
2 + 3 = 5 17 % 4 = 1

4. The program will display and solve the following problems:


4 + 9 46 / 7 46 % 7 2 * 3.0 (double)25 / 4 (int) 7.75 + 2 (int) 'P' (char)105

APCS Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

L.A.3.1 (Page 1)

5. The code will look something like this:


intAnswer = 4 + 9; System.out.println("4 + 9 = " + intAnswer);

6. Print out all the constants listed in Background: section 3. For example:
System.out.println("The largest value of type int = " + Integer.MAX_VALUE );

Instructions: 1. After completing the program, print your source code and a run output to the printer. 2. Make sure your name is documented near the top of your source code.

APCS Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

L.A.3.1 (Page 2)

LAB EXERCISE Easter


Background: A convenient algorithm for determining the date of Easter in a given year was devised in 1876 and first appeared in Butchers Ecclesiastical Handbook. This algorithm holds for any year in the Gregorian calendar, which means years including and after 1583. Subject to minor adaptations, the algorithm is as follows: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. Let y be the year (such as 1583 or 2003). Divide y by 19 and call the remainder a. Ignore the quotient. Divide y by 100 and get a quotient b and a remainder c. Divide b by 4 and get a quotient d and a remainder e. Divide b + 8 by 25 and get a quotient f. Ignore the remainder. Divide b f + 1 by 3 and get a quotient g. Ignore the remainder. Divide 19 * a + b d g + 15 by 30 and get a remainder h. Ignore the quotient. Divide c by 4 and get a quotient i and a remainder k. Divide 32 + 2 * e + 2 * i - h - k by 7 and get a remainder r. Ignore the quotient. Divide a + 11 * h + 22 * r by 451 and get a quotient m. Ignore the remainder. Divide h + r - 7 * m + 114 by 31 and get a quotient n and a remainder p.

The value of n gives the month (3 for March and 4 for April) and the value of p + 1 gives the day of the month. For example, if y is 2003: a b c d e f g h i k r m n p = = = = = = = = = = = = = = 8 20 3 5 0 1 6 26 0 3 3 0 4 19

Therefore, in 2003, Easter fell on April 20 (month = n = 4 and day = p + 1 = 20).

APCS Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

L.A.3.2 (Page 1)

Assignment: 1. Write a program to solve for the day that Easter falls on for a given year. 2. The program should display the values for all of the variables and the date for Easter. A Sample run output for the year 2003 would be: a b c d e f g h i k r m n p = = = = = = = = = = = = = = 8 20 3 5 0 1 6 26 0 3 3 0 4 19

Easter in 2003 falls on 4/20 3. Verify that the program gives the correct date of Easter for the current year. Instructions: 1. After completing the program, print your source code and a run output to the printer. 2. Make sure your name is documented near the top of your source code.

APCS Java, Lesson 3

ICT 2003, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

L.A.3.2 (Page 2)

RESERVED WORDS IN JAVA


Keyword abstract boolean break byte case catch char class continue default do double else extends final finally float for if implements import instanceof int interface long new package private protected public return short static super switch synchronized this throw throws try void while Contextual Description Used in a class definition to specify that a class is not to be instantiated, but rather inherited by other classes Refers to an expression or variable that can have only a true or false value Terminates processing of a switch statement or loop A sequence of eight bits Used in a switch statement to specify a match for the statement's expression Used to specify the actions to be taken when an exception occurs (see throw, try) Declares objects whose values are characters Construct new types to describe data and operations Used in a loop statement to transfer control to the beginning of the loop Used in a switch statement to handle expression values not specified using case Marks the beginning of a do-while statement Declares objects whose values are double precision real numbers Used as the alternative action of an if statement Used to specify that a subclass inherits the methods of a superclass An entity that is defined once and cannot be changed or derived from later Executes a block of statements regardless of whether a Java Exception, or run time error, occurred in a block defined previously by the "try" keyword Declares a primitive data type whose values are single precision real numbers Marks the beginning of a for statement Marks the beginning of an if statement Optionally included in the class declaration to specify any interfaces that are implemented by the current class Used at the beginning of a source file that can specify classes or entire packages to be referred to later without including their package names in the reference tests whether the run-time type of its first argument is assignment compatible with its second argument Declares objects whose values are integer numbers used to define a collection of method definitions and constant values Used to declare a primitive data type with values that range from Allocates memory dynamically at run-time A group of types Declares class members that are inaccessible from outside of the class Declares class members that are private, except to derived classes Declares class members that can be accessed outside of the class Terminates a function, usually returning the value of some expression Used to declare 16-bit integer numbers Declares objects whose lifetime is the duration of the program Used to access members of a class inherited by the class in which it appears Marks the beginning of a switch statement When applied to a method or code block, guarantees that at most one thread at a time executes that code Used with a class member to unambiguously access other members of the class Used to generate an exception (see catch, try) Used in method declarations that specify which exceptions are not handled within the method but rather passed to the next higher level of the program Used to mark the beginning of a block containing exception handlers (see catch) Used to indicate the absence of any type (for a function or parameter list) Marks the beginning of a while statement, as well as the end of a do-while statement

APCS - Java, Lesson 3

2003, ICT

H.A.3.1

ASCII CHARACTERS - A PARTIAL LIST


Ordinal Position 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 Character Ordinal Position 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 Character Ordinal Position 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 Character

space ! " # $ % & ' ( ) * + , . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?

@ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ -

' a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~

APCS - Java, Lesson 3

2003, ICT

H.A.3.2

Vous aimerez peut-être aussi