Module 1 - Java Basics
Module 1 - Java Basics
Example declarations:
int testGrade;
int numPlayers, highScore, diceRoll;
short xCoordinate, yCoordinate;
byte ageInYears;
long cityPopulation;
Floating-Point Data Types
• Numbers with fractional parts
Type Size Minimum Value Maximum Value
in Bytes
float 4 1.4E-45 3.4028235E38
double 8 4.9E-324 1.7976931348623157E308
Example declarations:
float salesTax;
double interestRate;
double paycheck, sumSalaries;
char Data Type
• One Unicode character (16 bits - 2 bytes)
Type Size Minimum Value Maximum Value
in Bytes
char 2 character character
encoded as 0 encoded as FFFF
Example declarations:
char finalGrade;
char newline, tab, doubleQuotes;
boolean Data Type
• Two values only:
true
false
• Used for decision making or as "flag"
variables
• Example declarations:
boolean isEmpty;
boolean passed, failed;
Assigning Values to Variables
• Assignment operator =
– Value on the right of the operator is assigned to
the variable on the left
– Value on the right can be a literal (text
representing a specific value), another variable,
or an expression (explained later)
• Syntax:
dataType variableName = initialValue;
Or
dataType variable1 = initialValue1,
variable2 = initialValue2, …;
Literals
• int, short, byte
Optional initial sign (+ or -) followed by
digits 0 – 9 in any combination.
• long
Optional initial sign (+ or -) followed by
digits 0–9 in any combination, terminated
with an L or l.
***Use the capital L because the lowercase l
can be confused with the number 1.
Floating-Point Literals
• float
Optional initial sign (+ or -) followed by a
floating-point number in fixed or scientific
format, terminated by an F or f.
• double
Optional initial sign (+ or -) followed by a
floating-point number in fixed or scientific
format.
• Commas, dollar signs, and percent signs
(%) cannot be used in integer or floating-
point literals
char and boolean Literals
• char
– Any printable character enclosed in single
quotes
– A decimal value from 0 – 65535
– \ is an escape sequence. For example, '\n'
represents a newline, and '\t' represents a tab
character.
• boolean
true or false
Assigning the Values of Other
Variables
• Syntax:
dataType variable2 = variable1;
• Rules:
1. variable1 needs to be defined before this
statement appears in the source code
2. variable1 and variable2 need to be compatible
data types; in other words, the precision of
variable1 must be lower than or equal to that of
variable2.
Compatible Data Types
Any type in right column can be assigned to type in left
column:
• Example:
String hello = "Hello";
String there = "there";
String greeting = hello + ' ' + there;
System.out.println( greeting );
Output is:
Hello there
Common Error Trap
• String literals must start and end on the
same line. This statement:
System.out.println( "Never pass a water fountain
without taking a drink" );
generates these compiler errors:
unclosed string literal
')' expected
• Break long Strings into shorter Strings and use the
concatenation operator:
System.out.println( "Never pass a water fountain"
+ " without taking a drink" );
Escape Sequences
• To include a special character in a String, use
an escape sequence
Character Escape Sequence
Newline \n
Tab \t
Double quotes \"
Single quote \'
Backslash \\
Backspace \b
Carriage return \r
Form feed \f
• Declare a variable only once
• Once a variable is declared, its data type
cannot be changed.
These statements:
double twoCents;
double twoCents = .02;
generate this compiler error:
twoCents is already defined
• Commas, dollar signs, and percent signs
(%) cannot be used in integer or floating-
point literals
• Once a variable is declared, its data type
cannot be changed.
These statements:
double cashInHand;
int cashInHand;
generate this compiler error:
cashInHand is already defined
Constants
• Value cannot change during program
execution
• Syntax:
final dataType constantIdentifier =
assignedValue;
Note: assigning a value when the constant is
declared is optional. But a value must be assigned
before the constant is used.
• Use all capital letters for constants and
separate words with an underscore:
Example:
final double TAX_RATE = .05;
• Declare constants at the top of the program
so their values can easily be seen
• Declare as a constant any data that should
not change during program execution
EXPRESSIONS AND
ARITHMETIC OPERATORS
int pennies = 2 * 25 + 3 * 10 + 2 * 5;
= 50 + 30 + 10
= 90
Another Example
Translate x into Java:
2y
// incorrect!
double result = x / 2 * y;
=> x * y
2
// correct
double result = x / ( 2 * y );
Integer Division & Modulus
• When dividing two integers:
– the quotient is an integer
– the remainder is truncated (discarded)
• To get the remainder, use the modulus
operator with the same operands
Division by Zero
• Integer division by 0:
Example: int result = 4 / 0;
• No compiler error, but at run time, JVM
generates ArithmeticException and program
stops executing
• Floating-point division by 0:
– If dividend is not 0, the result is Infinity
– If dividend and divisor are both 0, the result is
NaN (not a number)
Mixed-Type Arithmetic
• When performing calculations with operands
of different data types:
– Lower-precision operands are promoted to
higher-precision data types, then the operation is
performed
– Promotion is effective only for expression
evaluation; not a permanent change
– Called "implicit type casting"
• Bottom line: any expression involving a
floating-point operand will have a floating-
point result.
Rules of Promotion
Applies the first of these rules that fits:
1. If either operand is a double, the other operand is
converted to a double.
2. If either operand is a float, the other operand is
converted to a float.
3. If either operand is a long, the other operand is
converted to a long.
4. If either operand is an int, the other operand is promoted
to an int
5. If neither operand is a double, float, long, or an int, both
operands are promoted to int.
Explicit Type Casting
• Syntax:
(dataType)( expression )
Note: parentheses around expression are
optional if expression consists of 1 variable
+= a += 3; a = a + 3;
-= a -= 10; a = a - 10;
*= a *= 4; a = a * 4;
/= a /= 7; a = a / 7;
%= a %= 10; a = a % 10;
Common Error Trap
• No spaces are allowed between the
arithmetic operator and the equals sign
• Note that the correct sequence is +=, not =+
Example: add 2 to a
// incorrect
a =+ 2; // a = +2; assigns 2 to 2
// correct
a += 2; // a = a + 2;
Operator Precedence
Operator Order of Operation
evaluation
( ) left - right parenthesis for explicit
grouping
++ -- right - left preincrement, predecrement
++ -- right - left postincrement, postdecrement
* / % left - right multiplication, division,
modulus
+ - left - right addition or String
concatenation, subtraction
= += -= right - left assignment
*= /= %=