Upload
dinhhuong
View
216
Download
1
Embed Size (px)
Citation preview
Lecture 2Variables and Primitive Data Types
MIT AITI - 2004
What is a Variable?
• Variables are places where information can be stored while a program is running.
• Their values can be changed at any pointover the course of a program
Creating Variables
• To create a variable, declare its name and the type of information that it will store.
• The type is listed first, followed by the name.• Example: a variable that stores an integer
representing the highest score on an exam could be declared as follows:
int highScore ;
type name
Creating Variables (continued)
• Now you have the variable (highScore), you will want to assign a value to it.
• Example: the highest score in the class exam is 98.
highScore = 98;
• Examples of other types of variables:
String studentName;boolean gameOver;
Naming Variables• The name that you choose for a variable is
called an identifier. In Java, an identifier can be of any length, but must start with:
a letter (a – z), a dollar sign ($),or, an underscore ( _ ).
• The rest of the identifier can include any character except those used as operators in Java such as + , - , * .
• In addition, there are certain keywords reserved (e.g., "class") in the Java language which can never be used as identifiers.
we'll learn what operators are later
Naming (Continued)
• Java is a case-sensitive language – the capitalization of letters in identifiers matters. A rose is not a Rose is not a ROSE
• It is good practice to select variable names that give a good indication of the sort of data they hold– For example, if you want to record the size of a hat, hatSize is a good choice for a name whereas qqqwould be a bad choice
• When naming a variable, the following convention is commonly used:
– The first letter of a variable name is lowercase– Each successive word in the variable name begins
with a capital letter – All other letters are lowercase
• Here are some examples:
pageCountloadFileanyStringthreeWordVariable
POP QUIZ
• Which of the following are valid variable names?
1)$amount2)6tally3)my*Name4)salary5)_score6)first Name7)total#
Statements
• A statement is a command that causes something to happen.
• All statements in Java are separated by semicolons ;
• Example: System.out.println(“Hello, World”);
• You have already used statements to create a variable and assign it a value.
Variables and Statements
• One way is to declare a variable and then assign a value to it with two statements:
int e; // declaring a variable
e = 5; // assigning a value to a variable
• Another way is to write a single initialization statement:
int e = 5; // declaring AND assigning
Java is a Strongly-Typed Language
• All variables must be declared with a data type before they are used.
• Each variable's declared type does not change over the course of the program.
• Certain operations are only allowed with certain data types.
• If you try to perform an operation on an illegal data type (like multiplying Strings), the compiler will report an error.
Primitive Data Types
• There are eight built-in (primitive) data types in the Java language
– 4 integer types (byte, short, int, long)– 2 floating point types (float, double)– Boolean (boolean)– Character (char)
**see Appendix II: Summary of Primitive Data Types for a complete table of sizes and formats**
Integer Data Types• There are four data types that can be used
to store integers.
• The one you choose to use depends on the size of the number that we want to store.
• In this course, we will always use int when dealing with integers.
Data Type Value Rangebyte -128 to +127short -32768 to +32767int -2147483648 to +2147483647long -9223372036854775808 to +9223372036854775807
• Here are some examples of when you would want to use integer types:
- byte smallValue;smallValue = -55;
- int pageCount = 1250;- long bigValue = 1823337144562L;
Note: By adding an L to the end of the value in the last example, the program is “forced” to consider the value to be of a type long even if it was small enough to be an int
Floating Point Data Types• There are two data types that can be used
to store decimal values (real numbers).
• The one you choose to use depends on the size of the number that we want to store.
• In this course, we will always use doublewhen dealing with decimal values.
Data Type Value Range
float 1.4×10-45 to 3.4×1038
double 4.9×10-324 to 1.7×10308
• Here are some examples of when you would want to use floating point types:
– double g = 7.7e100 ;– double tinyNumber = 5.82e-203;– float costOfBook = 49.99F;
• Note: In the last example we added an Fto the end of the value. Without the F, it would have automatically been considered a double instead.
Boolean Data Type
• Boolean is a data type that can be used in situations where there are two options, either true or false.
• Example:boolean monsterHungry = true;boolean fileOpen = false;
Character Data Types
• Character is a data type that can be used to store a single characters such as a letter, number, punctuation mark, or other symbol.
• Example:– char firstLetterOfName = 'e' ;– char myQuestion = '?' ;
• Note that you need to use singular quotation marks when assigning char data types.
Introduction to Strings
• Strings consist of a series of characters inside double quotation marks.
• Examples statements assign String variables:String coAuthor = "John Smith";String password = "swordfish786";
• Strings are not one of the primitive data types, although they are very commonly used.
• Strings are constant; their values cannot be changed after they are created.
POP QUIZ
• What data types would you use to store the following types of information?:
1)Population of Ethiopia
2)Approximation of π3)Open/closed status of a file4)Your name5)First letter of your name6)$237.66
intdoublebooleanStringchardouble
Appendix I: Reserved Words
The following keywords are reserved in the Java language. They can never be used as identifiers:
abstract assert boolean break byte
case catch char class const
continue default do double else
extends final finally float for
goto if implements import instanceof
int interface long native new
package private protected public return
short static strictfp super switch
synchronized this throw throws transient
try void violate while
Appendix II: Primitive Data Types
The following tables show all of the primitive data types along with their sizes and formats:
IntegersData Type Descriptionbyte Variables of this kind can have a value from:
-128 to +127 and occupy 8 bits in memoryshort Variables of this kind can have a value from:
-32768 to +32767 and occupy 16 bits in memoryint Variables of this kind can have a value from:
-2147483648 to +2147483647 and occupy 32 bits in memorylong Variables of this kind can have a value from:
-9223372036854775808 to +9223372036854775807 and occupy 64 bits in memory
Appendix II: Primitive Data Types (cont)
Real NumbersData Type Description
float Variables of this kind can have a value from:1.4e(-45) to 3.4e(+38)
double Variables of this kind can have a value from:4.9e(-324) to 1.7e(+308)
Other Primitive Data Typeschar Variables of this kind can have a value from:
A single characterboolean Variables of this kind can have a value from:
True or False