Introduction To Java Programming: Week 2
Introduction To Java Programming: Week 2
Chapter 2
Week 2
Variables and Literals
• A variable is a named storage location in the computer’s memory.
• A literal is a value that is written into the code of a program.
• Programmers determine the number and type of variables a program
will need.
• See example:Variable.java
2-2
Variable.java
Variables and Literals
This line is called The following line is known
a variable declaration. as an assignment statement.
int value; value = 5;
2-4
The + Operator
• The + operator can be used in two ways.
• as a concatenation operator
• as an addition operator
• If either side of the + operator is a string, the result
will be a string.
System.out.println("Hello " + "World");
System.out.println("The value is: " + 5);
System.out.println("The value is: " + value);
System.out.println("The value is: " + ‘/n’ + 5);
2-5
String Concatenation
• Java commands that have string literals must be treated with care.
• A string literal value cannot span lines in a Java source code file.
System.out.println("This line is too long and now it has spanned more
than one line, which will cause a syntax error to be generated by the
compiler. ");
2-6
String Concatenation
• The String concatenation operator can be used to fix this problem.
System.out.println("These lines are " +
"are now ok and will not " +
"cause the error as before.");
2-7
String Concatenation
• The Concatenation operator can be used to format
complex String objects.
2-9
Identifiers
• Identifiers must follow certain rules:
• An identifier may only contain:
• letters a–z or A–Z,
• the digits 0–9,
• underscores (_), or
• the dollar sign ($)
• The first character may not be a digit.
• Identifiers are case sensitive.
• itemsOrdered is not the same as itemsordered.
• Identifiers cannot include spaces.
2-10
Java Reserved Keywords
abstract double instanceof static
assert else int strictfp
boolean enum interface super
break extends long switch
byte false native synchronized
case for new this
catch final null throw
char finally package throws
class float private transient
const goto protected true
continue if public try
default implements return void
do import short volatile
while
2-11
Variable Names
• Variable names should be descriptive.
• Descriptive names allow the code to be more readable; therefore, the
code is more maintainable.
• Which of the following is more descriptive?
double tr = 0.0725;
double salesTaxRate = 0.0725;
2-12
Java Naming Conventions
• Variable names should begin with a lower case letter and then switch
to title case thereafter:
Ex: int caTaxRate
• Class names should be all title case.
Ex: public class BigLittle
• More Java naming conventions can be found at:
http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html
• A general rule of thumb about naming variables and classes are that,
with some exceptions, their names tend to be nouns or noun phrases.
2-13
Primitive Data Types
• Primitive data types are built into the Java language
and are not derived from classes.
• There are 8 Java primitive data types.
• byte • float
• short • double
• int • boolean
• long • char
2-14
Numeric Data Types
byte 1 byte Integers in the range
-128 to +127
2-15
Variable Declarations
• Variable Declarations take the following form:
• DataType VariableName;
• byte inches;
• short month;
• int speed;
• long timeStamp;
• float salesCommission;
• double distance;
2-16
Integer Data Types
• byte, short, int, and long are all integer data types.
• They can hold whole numbers such as 5, 10, 23, 89, etc.
• Integer data types cannot hold numbers that have a decimal point in
them.
• Integers embedded into Java source code are called integer literals.
• See Example: IntegerVariables.java
2-17
Floating Point Data Types
• Data types that allow fractional values are called
floating-point numbers.
• 1.7 and -45.316 are floating-point numbers.
• In Java there are two data types that can represent
floating-point numbers.
• float - also called single precision (7 decimal points).
• double - also called double precision (15 decimal points).
2-19
Floating Point Literals
• When floating point numbers are embedded into Java source code
they are called floating point literals.
• The default type for floating point literals is double.
• 29.75, 1.76, and 31.51 are double data types.
• Java is a strongly-typed language.
• See example: Sale.java
2-20
Floating Point Literals
• A double value is not compatible with a float variable because of
its size and precision.
• float number;
• number = 23.5; // Error!
• A double can be forced into a float by appending the letter F or f
to the literal.
• float number;
• number = 23.5F; // This will work.
2-22
Floating Point Literals
• Literals cannot contain embedded currency symbols or commas.
• grossPay = $1,257.00; // ERROR!
• grossPay = 1257.00; // Correct.
• Floating-point literals can be represented in scientific notation.
• 47,281.97 == 4.728197 x 104.
• Java uses E notation to represent values in scientific notation.
• 4.728197X104 == 4.728197E4.
2-23
Scientific and E Notation
2-24
The boolean Data Type
• The Java boolean data type can have two possible values.
• true
• false
• The value of a boolean variable may only be copied into a
boolean variable.
See example: TrueFalse.java
2-25
The char Data Type
• The Java char data type provides access to single characters.
• char literals are enclosed in single quote marks.
• ‘a’, ‘Z’, ‘\n’, ‘1’
• Don’t confuse char literals with string literals.
• char literals are enclosed in single quotes.
• String literals are enclosed in double quotes.
2-27
Unicode
• Internally, characters are stored as numbers.
• Character data in Java is stored as Unicode characters.
• The Unicode character set can consist of 65536 (216) individual
characters.
• This means that each character takes up 2 bytes in memory.
• The first 256 characters in the Unicode character set are compatible
with the ASCII* character set.
See example: Letters2.java
*American Standard Code for Information Interchange
2-29
Unicode
A B
00 65 00 66
0000000001000001 0000000001000011
2-31
Unicode
Characters are
A stored in memory
as binary numbers.
B
00 65 00 66
0000000001000001 0000000001000011
2-32
Unicode
The binary numbers
A represent these
decimal values.
B
00 65 00 66
0000000001000001 0000000001000011
2-33
Unicode
A B
0000000001000001 0000000001000011
2-34
Variable Assignment and Initialization
• In order to store a value in a variable, an assignment statement must
be used.
• The assignment operator is the equal (=) sign.
• The operand on the left side of the assignment operator must be a
variable name.
• The operand on the right side must be either a literal or expression
that evaluates to a type that is compatible with the type of the
variable.
2-35
Variable Assignment and Initialization
// This program shows variable assignment.
public class Initialize
{
public static void main(String[] args)
{
int month, days;
month = 2;
days = 28;
System.out.println("Month " + month + " has " +
days + " Days.");
}
}
2-36
Variable Assignment and Initialization
// This program shows variable assignment.
public class Initialize
{
public static void main(String[] args)
{
int month, days;
month = 2;
days = 28;
System.out.println("Month " + month + " has " +
days + " Days.");
}
}
2-37
Variable Assignment and Initialization
// This program shows variable assignment.
public class Initialize
{
public static void main(String[] args)
{
int month, days;
month = 2;
days = 28;
System.out.println("Month " + month + " has " +
days + " Days.");
}
}
2-38
Variable Assignment and Initialization
// This program shows variable initialization.
2-39
Variable Assignment and Initialization
• Variables can only hold one value at a time.
• Local variables do not receive a default value.
• Local variables must have a valid type in order to be used.
public static void main(String [] args)
{
int month, days; //No value given…
System.out.println("Month " + month + " has " +
days + " Days.");
}
Trying to use uninitialized variables will generate a Syntax Error when the code
is compiled.
2-40
Arithmetic Operators
• Java has five (5) arithmetic operators.
2-41
Arithmetic Operators
• The operators are called binary operators because they must have
two operands.
• Each operator must have a left and right operator.
See example: Wages.java
• The arithmetic operators work as one would expect.
• It is an error to try to divide any number by zero.
• When working with two integer operands, the division operator
requires special attention.
2-42
Integer Division
• Division can be tricky.
In a Java program, what is the value of 1/2?
• You might think the answer is 0.5…
• But, that’s wrong.
• The answer is simply 0.
• Integer division will truncate any decimal remainder.
2-43
Operator Precedence
• Mathematical expressions can be very complex.
• There is a set order in which arithmetic operations will be carried out.
2-44
Grouping with Parenthesis
• When parenthesis are used in an expression, the inner
most parenthesis are processed first.
• If two sets of parenthesis are at the same level, they
are processed left to right.
3
• x = ((4*5) / (5-2) ) – 25; // result = -19
1 2
4
2-45
Home Task
• The Java API provides a class named Math
• Write a code in Java that uses the two methods (pow and sqrt) of
Math class
Combined Assignment Operators
• Java has some combined assignment operators.
• These operators allow the programmer to perform an arithmetic
operation and assignment with a single operator.
• Although not required, these operators are popular since they
shorten simple equations.
2-47
Combined Assignment Operators
Operator Example Equivalent Value of variable after operation
2-48
Conversion b/w Primitive Data Types
• Value’s data type must be compatible with variable’s data type
• Java performs some conversions between data types automatically
• Java does not automatically perform any conversion that can result in
the loss of data
int x;
double y = 2.5;
x = y;
• Java compiler gives an error message “possible loss of precision” as
we are trying to store double value in an int variable
Conversion b/w Primitive Data Types
• Java allows the following assignment:
int x;
short y = 2;
x = y;
• Why?
Conversion b/w Primitive Data Types
2-54
Creating Constants
• Constants keep the program organized and easier to maintain.
• Constants are identifiers that can hold only a single value.
• Constants are declared using the keyword final.
• Constants need not be initialized when declared; however, they must
be initialized before they are used or a compiler error will be
generated.
2-55
Creating Constants
• Once initialized with a value, constants cannot be changed
programmatically.
• By convention, constants are all upper case and words are separated
by the underscore character.
final int CAL_SALES_TAX = 0.725;
2-56