Java Language Basics
Java Language Basics
Expectations:
The student will:
1. be able to define the term: variable
2. explain the primitive variable types
3. declare a primitive variable
4. assign a value to a primitive variable
5. know the various comparison operators
6. know the various types of math operations
7. know the shortcut assignment operators
8. know how to define constants
9. explain casting
10. be familiar with methods of the Math class
11. know the general pattern for coding a class
1 byte
short
2 bytes
int
4 bytes
long
8 bytes
4 bytes
double
8 bytes
Declaring Variables
General Format:
Java-Variable-Type-Name Variable-Name Semi Colon
Variable Naming Convention
Examples :
boolean happy;
char gender;
double robsPay;
Assignment Statement
Examples:
int age;
age = 16;
long age;
age = 197L; (L indicates a long value)
double robsPay;
robsPay = 13.50;
float robsPay;
robsPay = 13.50f; (f indicates a float value)
char gender;
gender = m; (Note: single quotes around the character value)
boolean happy;
happy = false;
Primitive Variable Type Comparative Operators
Operator
Symbol Example
equals
==
if (x = = y)
not equals
!=
if (x != y)
less than
<
if (x < y)
greater than
>
if (x > y)
<=
if (x <= y)
if (x >= y)
Math Operations
Java follows BEDMAS and left-to-right evaluation when two or more operations of same
precedent occur without brackets
Operation
Symbol Example
addition
a = b + 2;
subtraction
a = b - 2;
multiplication
a = b * 2;
division
a = b / 2;
Note: if b is integer, then the answer has all decimals
truncated, even if a is a float or double
integer division
remainder (mod)
a = b % 2;
++
a++;
adds 1 to a, after operations involving a are completed eg.
if (a++ < 2) -> a is incremented after the comparison is
performed
pre increment
++
++a;
adds 1 to a, before operations involving a are completed
eg. if (++a < 2) -> a is incremented before the comparison
is performed
post decrement
--
a--;
same comment as a++
pre decrement
--
--a;
same comment as ++a
post increment
answer is 3.5
because 7.0 is a double
ShortCut Assignment Operators
Operator
Symbol Example
assign addition
+=
a += 2;
means: a = a + 2;
assign subtraction
-=
a -= 2;
means: a = a - 2;
assign multiplication *=
a *= 2;
means: a = a * 2;
assign division
/=
a /= 2;
means: a = a / 2;
assign mod
%=
a %= 2;
means: a = a % 2;
Constants in Java
Example
private final double GST = 0.07;
private final double MINIMUM_WAGE=6.75;
Coding Standards - Constant names have all letters capitalized
Notes:
* 2 variables declared
** mutator method
Unless it is a helper methods that other public methods will use, but never need
to be used by outside classes, in which case it is private
Example : A simple calculation used by a number of other methods