Download Variables and Data Types

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript




Just as we use names in the real world to
identify every entity, programmers use names
for the objects they create in programs
Identifiers are special symbols for naming such
program entities as variables, constants, objects,
methods, classes and packages
Descriptive identifiers make programs easy to
read and maintain
Besides making identifiers descriptive, certain
naming conventions apply to different
identifiers






An identifier is a sequence of characters that
consist of letters, digits, underscore (_), and the
dollar sign ($)
An identifier must start with a letter, an
underscore (_), or a dollar symbol ($). It cannot
start with a digit
Identifiers cannot be reserved words (Java
keywords)
An identifier cannot be true, false or null
Identifier names can be of any length
Since Java is case sensitive, AGE, Age and age are
different identifiers



Every entity used within a Java program is part
of a Java class
As we saw in the rules earlier, a Java class can be
declared by using any meaningful identifier
Java class identifiers must be chosen to meet the
following requirements
◦ A class name must begin with any letter of the English
alphabets, or an underscore, or the dollar sign
◦ A class name cannot begin with a numerical digit
◦ A class name can contain only letters, digits,
underscores, or dollar signs or a combination of all of
them
◦ A class name cannot be a Java keyword such as
private, while, true, false or null





By convention Java programmers name Java classes
using upper case letters (though not a strict rule)
This convention improves readability of codes
Some acceptable conventional class names include
TestResults, SalesConsultant, CustomerNumber,
EmployeeStatus
Some uncoventional and not recommended class
names include Temperaturevalues, Accessroad,
Familycomputer
Some unacceptable or illegal class names include class
(class is a reserved word), 2ndYear (class name cannot
begin with a digit), End of Semester Exam ( spaces not
allowed in identifier names), Index# ( # is an illegal
character)



Computer programs are set of instructions that tell the
computer what to do.
Each program instruction is called a statement
◦ System.out.print(“This is a statement”);
A set of instructions can be grouped together to form a
block known as block statements
public static void main( String[ ] args)
{
System.out.println(“Hello ” + lName);
System.out.printf(“I am %d years old”,
age);
}





Some statements are called expressions
A statement is an expression if it has a value
associated with it
Expressions also involve arithmetic operations
float areaOfSquare , side;
areaOfSquare = side * side;
The above code is an expression that sets the
value of the variable name areaOfSquare to the
product of the sides of a square object
All statements in Java are separated by
semicolons ;




Example:
System.out.println(“Ghana Cedis”);
distance = speed * time;
boolean isKeyPressed = false;
There is no value associated with the first
statement in the above examples, thus a statement
The value of the expression is the product of the
variables speed and time
There is a value associated with the statement
isKeyPressed = false





Data items can be categorised as constants or
variables
Constant data items cannot be changed during
program execution
Variable data can be changed during program
execution
Consider the statement System.out.print( 1325);
The number 1325 is a literal or numeric constant
because the value 1325 does not change after
every execution of the statement


In Java, all data items, whether constants or
variables must have a type
In Java, an item’s data type describes
◦ The type of data that item can store
◦ The amount of memory space it occupies
◦ The type of operations that can be performed on the data




In Java, there are eight data types known as
primitive data types
They are primitive because they are simple and
not complicated
The primitive data types serve as building blocks
for more complex data types known as reference
types
Classes are examples of reference types
Data type
Description
byte
Byte-length integer
short
Short integer
int
Integer
long
Long integer
float
Single-precision floating point
double
Double-precision floating point
char
A single character
boolean
A Boolean value ( true or false)






Variables are placeholders for data.
Variables are named memory locations that can
be used to store values
A variable can hold only one value at a time
In Java, all variables must be declared before
they are used in a program
Variables can be assigned values either at
declaration point or later during the program
execution
Their values can be changed at any point in the
course of a program




Rules for naming variables are similar to the rules
for naming classes
By convention, variable names start with lower
cases letters to distinguish them from class names
Variable declaration is a statement that reserves a
named memory location for data storage
Declaring variables involves
1. Specifying a data type that describes the type of data
the variable will store
2. An identifier to name the variable
3. An optional assignment operator and assigned initial
value
4. An ending semicolon

As an example: a variable that stores an integer
representing the highest score in an exam could be
declared as follows:
int
highScore ;
type
name






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;
Note that the expression 21 = age; is illegal
An identifier name cannot be assigned to a literal
The assignment operator (=) has a right-to-left
associativity
Examples of other types of variables:
String studentName;
boolean gameOver;


Two or more variables of the same type can be
declared in a single statement
In such declaration, each variable is separated
from the other by a comma as below
◦ double height = 5.8, weight = 67.5;

Another option is to declare variables of the same
type in a single statement but on different lines
and separated by commas
int myAge = 23,
yourAge = 27,
hisAge = 21;

Variables of different types must be declared in
separate statements on different lines for clarity

Rules for naming variables are the same as those
for naming identifiers as discussed earlier. In
Java the name of a variable can be of any length,
but must start with:
a letter (a – z),
a dollar sign ($),
or, an underscore ( _ ).


The rest of the variable name can include any
character except those used as operators in Java
such as + , - , * /,%. Also spaces are not allowed
In addition, there are certain keywords reserved
(e.g., "class, public, int, etc") in the Java language
which can never be used as names for variables.
Naming (Continued)

Java is a case-sensitive language – the
capitalisation of letters in variables matters.
A shoe is not a Shoe is not a SHOE

It is a good practice to select variable names that
give a good description of the type 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 qqq
would 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:
roadWidth
totalDistance
roomKeyNumber
allTimeRecord

Which of the following are valid variable
names?
1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7)total#

One way is to declare a variable and then assign a
value to it with two statements:
int cost; // declaring a variable
cost = 5; // assigning a value to a
variable

Another way is to write a single initialization
statement:
int price = 5; // declaring AND
assigning

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.

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)



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 almost always use int
when dealing with integers.
Data Type
Value Range
byte
-128 to +127
short
-32768 to +32767
int
-2147483648 to +2147483647
long
-9223372036854775808 to +9223372036854775807

Here are some examples of when you would
want to use integer types:
- byte smallValue;
smallValue = -55;
- int daysCounted = 1250;
- short roomNumber = 125;
- long hugeValue = 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

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.

Data Type
Value Range
float
1.4×10-45 to 3.4×1038
double
4.9×10-324 to 1.7×10308
In this course, we will almost always use
double when dealing with floating point
values.

Here are some examples of when you would
want to use floating point types:
◦ double metalWeight = 9.8e10 ;
◦ double tinyNumber = 5.82e-203;
◦ float
costOfBook = 49.99F;

Note: In the last example we added an F to the
end of the value. Without the F, it would have
automatically been considered a double
instead.

Boolean is a data type that can be used in
situations where there are two options, either
true or false.

Example:
boolean firstTimePlayer = false;
boolean imageDisplayed = false;

Character is a data type that can be used to
store a single character such as a letter,
number, punctuation mark, or other symbol.

Example:
◦ char firstInitial = ‘F' ;
◦ char myQuestion = '?' ;

Note that you need to use singular quotation
marks when assigning char data types.
import java.util.Scanner; // import the Scanner class
class MyCalculator // declare a class
{
// program execution begins in method main
public static void main( String[ ] arg )
{
// create a Scanner object for keyboard input
Scanner dataInput = new Scanner( System.in );
// declare my variables
int firstNumber, secondNumber, numbersTotal;
// obtain input with Scanner object
System.out.print( "Please enter the first number : “ );
firstNumber = dataInput.nextInt();
// obtain input with Scanner object
System.out.print("Please enter the second number : ");
secondNumber = dataInput.nextInt();
// sum the two numbers
numbersTotal = firstNumber + secondNumber;
// format the output
System.out.printf( "%d + %d = %d \n" ,
firstNumber, secondNumber,numbersTotal );
}
}

Strings consist of a series of characters inside
double quotation marks.

Examples statements assign String variables:
String firstName = “Patrick”;
String lastName = “Thompson”;

Strings are not one of the primitive data types,
they are class type.

Strings are constant; their values cannot be
changed after they are created.


As noted earlier, a string is a sequence of characters treated
as a single item in quotes
The following statement declares a string variable called
course
String course;

The following statement assigns a value (a string constant )
to the String variable course
course = “The Programming Course II”;

The following statement displays the value of the string
variable course
System.out.println(course);

The above statement will display the string
The Programming Course II

A string with no (zero) characters “”, is an empty string



Strings can be joined or connected together to
form a larger string
This is achieved by using the plus (+) operator
called the concatenation operator
Consider the following codes
String firstName, secondName, fullName;
firstName = “Julius”;
secondName = “Agyei”;


The statement fullName = firstName + secondName;
produces JuliusAgyei
To produce a space between Julius and Agyei, a
string with a single character space “ ” is needed


String concatenation gets interesting when Strings
are combined with numbers
Consider the following:
String a = “Track”;
int b = 4;
int c = 9;
System.out.println( a + b + c );




Will the + operator act as a plus sign when adding
the int variables b + c ?
Or will the + operator treat 4 and 9 as characters,
and concatenate them individually?
Will the result be Track13 or Track49?
You have enough time to think about it







The int values are simply treated as characters and attached
to the right side of the String Track
Start with String a, “Track”, and add the character 4 (the
value of b) to it, to produce a new String Track4
Add the character 9 (the value of c) to that, to produce
another String Track49, and print it out
However if parenthesis are put around the int variables as in
System.out.println( a + ( b + c ) );
The resulting output is Track13
The parenthesis causes the ( b + c ) to be evaluated first, so
the + functions as the addition operator since both operands
are int values
Key rule to remember is that if either operand is a String, the
+ operator becomes String concatenation. If both operands
are numbers the + operator becomes addition operator



A String variable is a class type of variable that names
String objects
An object has both data and methods of its class
Consider the string “Good morning”
“Good morning”.length(); returns the total number of characters 12

Similarly the String variable salute in the statement
String salute = “Good morning”; can be used on the string method
length as follows
int numberOfCharacters = salute.length() and the result is the same
integer value 12



Most of the class String methods depend on counting
positions
Position in strings begin with 0, instead of 1
A position is known as index, thus index 0, index 1, etc.



The value of a variable may change during the
execution of a program
A constant represents permanent data that never
changes
The syntax for declaring constants is as follows
final datatype CONSTANT_NAME = value;



The word final is a keyword which indicates that
the constant cannot be changed
By convention constants are named in uppercase:
RATE, not rate or Rate
A constant must be declared and initialised before
it can be used in a program

What data types would you use to store the
following types of information?:
1)Population of Ghana
2)Approximation of π
3)Open/closed status of a file
4)Your name
5)First letter of your name
6)$237.66
int
double
boolean
String
char
double
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
The following tables show all of the primitive
data types along with their sizes and formats:
Integers
Data Type
Description
byte
Variables of this kind can have a value from:
-128 to +127 and occupy 8 bits in memory
short
Variables of this kind can have a value from:
-32768 to +32767 and occupy 16 bits in memory
int
Variables of this kind can have a value from:
-2147483648 to +2147483647 and occupy 32 bits in memory
long
Variables of this kind can have a value from:
-9223372036854775808 to +9223372036854775807 and occupy
64 bits in memory
Real Numbers
Data 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 Types
char
Variables of this kind can have a value from:
A single character
boolean
Variables of this kind can have a value from:
True or False