Chapter 2: Variables and Types
PROGRAMMING 1
COS 011
More Printing
2
Remember our first code from the previous class
Can we put as many statements as we want in main?
Yes, we can
3
Output
4
What is the difference here?
5
No Different
6
Gives the same output.
But coding this way make program harder and
harder to read. Newlines and spaces are useful for
organizing your program visually, making it easier to
read the program and locate errors.
Variables
7
A variable is a named location that stores a value.
Form: TYPE NAME;
Example: String FirstName;
This statement is a declaration, because it declares that the
variable named FirstName has the type String.
Can we declaring multiple variables with the same type?
String FirstName, LastName;
You should take care to get it right. There is no such type
as Int or string, and the compiler will object if you mistype
the syntax int , String
Identifiers
8
Identifier: The name of a variable or other item
(class, method, object, etc.) defined in a program
A Java identifier must not start with a digit, and all the
characters must be letters, digits, or the underscore
symbol
Java identifiers can theoretically be of any length
Java is a case-sensitive language: Rate, rate, and RATE
are the names of three different variables
Variable Declarations
9
Every variable in a Java program must be declared before it
is used
A variable declaration tells the compiler what kind of data (type) will
be stored in the variable
The type of the variable is followed by one or more variable names
separated by commas, and terminated with a semicolon
Variables are typically declared just before they are used or at the
start of a block (indicated by an opening brace { )
Basic types in Java are called primitive types
int numberOfBeans;
double oneWeight, totalWeight;
Variable names
10
Variable names must be one character from the first
set and 0 or more characters from the second set.
[a..z,A..Z,_,$][a..z,A..Z,0..9,_,$]*
a, Xx, fred0, X, x1_y, birds2
2birds, a$b, a+b, a&b2
“The $ character should be used only in mechanically generated source code
or, rarely, to access preexisting names on legacy systems.” - http://java.sun.
com/docs/books/jls/third_edition/html/lexical.html#3.8
Naming Conventions
11
Start the names of variables, methods, and objects
with a lowercase letter, indicate "word" boundaries
with an uppercase letter, and restrict the remaining
characters to digits and lowercase letters
topSpeed bankRate1 timeOfArrival
Start the names of classes with an uppercase
letter and, otherwise, adhere to the rules above
FirstProgram MyClass String
Valid variable names
12
Starts with: a letter (a-z or A-Z), dollar sign($), or
underscore(_)
Followed by: zero or more letters, dollar signs,
underscores, or digits(0-9)
Case-sensitive! Uppercase and lowercase are
different. Rate, rate, and RATE are the names of
three different variable
Cannot be any of the reserved names
Can theoretically be of any length
Variable names (valid or invalid?)
13
$$1_1
numberOfBeans
public (reserved word)
1day
peanutbutter&jelly
aZ_b
INT
Good variable names
14
Do not use $
Avoid names that are identical other than
differences in case
Use meaningful names
Avoid excessive length
Using +
15
In Java, the plus sign (+) can be used to denote
addition (as above) or concatenation
Using +, two strings can be connected together
System.out.println("2 plus 2 is " + answer);
Keywords and Reserved words
16
Keywords and Reserved words: Identifiers that
have a predefined meaning in Java
Do not use them to name anything else
public class void static
import for while if else
Predefined identifiers: Identifiers that are defined
in libraries required by the Java language standard
Although they can be redefined, this could be confusing
and dangerous if doing so would change their standard
meaning
System String println
The complete list of Keywords
17
Available at:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html.
18
Composition
19
It is the ability to combine variables, expressions,
and statements.
Example:
int percentage, minute=30;
percentage = (minute * 100) / 60;
Primitive Types
20
Assignment
21
We do assignment with an assignment statement to
store value for the variable.
The equal sign (=) is used as the assignment operator
Example:
FirstName=“Abdullah”;
Age=30;
To sum up, the concept beyond this process is:
When you declare a variable, you create a named storage location.
When you make an assignment to a variable, you give it a value.
22
What do you see here?
Age=Thirty;
Not legal Assignment.
FirstName=“7366”
It is Legal, since numbers stored as text.
Assignment Statements With Primitive Types
23
In Java, the assignment statement is used to
change the value of a variable
An assignment statement consists of a variable
on the left side of the operator, and an expression
on the right side of the operator
Variable = Expression;
An expression consists of a variable, number, or
mix of variables, numbers, operators, and/or
method invocations
temperature = 98.6;
count = numberOfBeans;
Assignment Statements With Primitive Types
24
When an assignment statement is executed, the
expression is first evaluated, and then the variable on the
left-hand side of the equal sign is set equal to the value
of the expression
distance = rate * time;
Note that a variable can occur on both sides of the
assignment operator
count = count + 2;
The assignment operator is automatically executed from
right-to-left, so assignment statements can be chained
number2 = number1 = 3;
Tip: Initialize Variables
25
A variable that has been declared but that has not
yet been given a value by some means is said to
be uninitialized
In certain cases an uninitialized variable is given a
default value
It is best not to rely on this
Explicitly initialized variables have the added benefit of
improving program clarity
Tip: Initialize Variables
26
The declaration of a variable can be combined with
its initialization via an assignment statement
int count = 0;
double distance = 55 * .5;
char grade = 'A';
Note that some variables can be initialized and others
can remain uninitialized in the same declaration
int initialCount = 50, finalCount;
Shorthand Assignment Statements
27
Shorthand assignment notation combines the assignment
operator (=) and an arithmetic operator
It is used to change the value of a variable by adding,
subtracting, multiplying, or dividing by a specified value
The general form is
Variable Op = Expression
which is equivalent to
Variable = Variable Op (Expression)
The Expression can be another variable, a constant, or a more
complicated expression
Some examples of what Op can be are +, -, *, /, or %
Shorthand Assignment Statements
28
Example: Equivalent To:
count += 2; count = count + 2;
sum -= discount; sum = sum – discount;
bonus *= 2; bonus = bonus * 2;
time /= time =
rushFactor; time / rushFactor;
change %= 100; change = change % 100;
amount *= amount = amount * (count1 +
count1 + count2; count2);
Assignment Compatibility
29
In general, the value of one type cannot be stored
in a variable of another type
int intVariable = 2.99; //Illegal
The above example results in a type mismatch because a
double value cannot be stored in an int variable
However, there are exceptions to this
double doubleVariable = 2;
For example, an int value can be stored in a double type
Assignment Compatibility
30
More generally, a value of any type in the following list can
be assigned to a variable of any type that appears to the
right of it
byteshortintlongfloatdouble
char
Note that as your move down the list from left to right, the range of
allowed values for the types becomes larger
An explicit type cast is required to assign a value of one
type to a variable whose type appears to the left of it on the
above list (e.g., double to int)
Note that in Java an int cannot be assigned to a variable of
type boolean, nor can a boolean be assigned to a variable
of type int
Enum Types
31
An enum type is a special data type that enables for a
variable to be a set of predefined constants.
The variable must be equal to one of the values that have
been predefined for it.
Example:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
}
Because they are constants, the names of an enum
type's fields are in uppercase letters.
Constants
32
Constant (or literal): An item in Java which has
one specific value that cannot change
Constants of an integer type may not be written with a
decimal point (e.g., 10)
Constants of a floating-point type can be written in
ordinary decimal fraction form (e.g., 367000.0 or
0.000589)
Constant of a floating-point type can also be written in
scientific (or floating-point) notation (e.g., 3.67e5 or
5.89e-4)
Note that the number before the e may contain a decimal point,
but the number after the e may not
Constants
33
Constants of type char are expressed by placing a
single character in single quotes (e.g., 'Z')
Constants for strings of characters are enclosed by
double quotes (e.g., "Welcome to Java")
There are only two boolean type constants, true
and false
Note that they must be spelled with all lowercase letters
Differences between int and double
34
int (integer) and double (real numbers) are different.
int is a subset of double but ints are much faster to calculate
than doubles
So use ints whenever you can but be aware of the following:
int n = 5/2;
int k = 9/10;
Differences between int and double
35
5 is an int.
5.1 is a double.
5.0 is a double.
5.7f is a float
Range of values:
int -2 billion to+2 billion
double 4.9x10-324 to1.8x10308
float 1.4x10-45 to3.4x1038
Float vs. double
36
Recall range of values:
double 4.9x10-324 to1.8x10308
float 1.4x10-45 to3.4x1038
Recall that we used a cast to convert a double to an int:
double d = 12.9;
int i = (int) d;
This is because a double won’t fit into an int. Will a double fit into
a float?
Converting doubles to ints
37
When we convert, we will typically lose something.
Consider converting 12.9 to an int. There is no int 12.9.
So the compiler will issue a message. To inform the compiler
that we really wish to do this, we can use a cast.
int i;
double d = 12.9;
i = (int) d; //What do you think is in i now?
Converting doubles to ints
38
int i;
double d = 12.9;
i = (int) d; //What do you think is in i now?
//how can we round instead?
Pitfall: Round-Off Errors in Floating-Point Numbers
39
Floating point numbers are only approximate
quantities
Mathematically, the floating-point number 1.0/3.0 is
equal to 0.3333333 . . .
A computer has a finite amount of storage space
It may store 1.0/3.0 as something like 0.3333333333, which is
slightly smaller than one-third
Computers actually store numbers in binary notation, but
the consequences are the same: floating-point numbers
may lose accuracy
Integer and Floating-Point Division
40
When one or both operands are a floating-point type,
division results in a floating-point type
15.0/2 evaluates to 7.5
When both operands are integer types, division results in an
integer type
Any fractional part is discarded
The number is not rounded
15/2 evaluates to 7
Be careful to make at least one of the operands a floating-
point type if the fractional portion is needed
Type Casting
41
A type cast takes a value of one type and produces a value
of another type with an "equivalent" value
If n and m are integers to be divided, and the fractional portion of the
result must be preserved, at least one of the two must be type cast
to a floating-point type before the division operation is performed
double ans = n / (double)m;
Note that the desired type is placed inside parentheses immediately
in front of the variable to be cast
Note also that the type and value of the variable to be cast does not
change
More Details About Type Casting
42
When type casting from a floating-point to an integer type,
the number is truncated, not rounded
(int)2.9 evaluates to 2, not 3
When the value of an integer type is assigned to a variable
of a floating-point type, Java performs an automatic type
cast called a type coercion
double d = 5;
In contrast, it is illegal to place a double value into an int
variable without an explicit type cast
int i = 5.5; // Illegal
int i = (int)5.5 // Correct
The Class String
43
There is no primitive type for strings in Java
The class String is a predefined class in Java that is used
to store and process strings
Objects of type String are made up of strings of characters
that are written within double quotes
Any quoted string is a constant of type String
"Live long and prosper."
A variable of type String can be given the value of a String
object
String blessing = "Live long and prosper.";
Concatenation of Strings
44
Concatenation: Using the + operator on two strings in
order to connect them to form one longer string
If greeting is equal to "Hello ", and javaClass is equal to "class", then
greeting + javaClass is equal to "Hello class"
Any number of strings can be concatenated together
When a string is combined with almost any other type of
item, the result is a string
"The answer is " + 42 evaluates to
"The answer is 42"
Some Methods in the Class String
45
Glossary
46
1. variable
2. value
3. type
4. keyword
5. declaration
6. assignment
7. expression
8. operator
9. composition
Exercise
47
In a piece of paper, write a simple code to store your
first name, last name, and age on suitable variables
and print them on separate lines.
You can use your book.
Write your own code.
More
48
Write a Java program to print the result of
5 + 15 / 3 * 2 – 8
Write a Java program that takes 4 even numbers as
input to calculate and print the average.
Write a Java program to convert a m to cm.
Knowledge Check
49
Write a program that creates variables named day,
date, month and year. Assign values to those variables
that represent today’s date and print them.
Modify the program so that it prints the date in
standard American
form: Saturday, July 16, 2011.
50
Questions ?!