Java Programming
Identifiers
Identifiers
Are tokens that represent name of variables, methods, classes, etc.
Examples of identifiers are: Hello, main, System, println.
Java Identifiers are case sensitive
This means that the identifier Hello is not the same as hello.
2
Identifiers (cont…)
Naming convention
Identifiers must begin with a letter (A to Z or a to z), currency character
($), underscore character (_)
Identifiers can have any combination of characters after the first
character.
A keyword cannot be used as an identifier like class, public, void
Examples of legal identifier: age, $salary, _count
Examples of illegal identifier: 123abc, -salary
3
Identifiers (cont…)
Coding Guidelines
1. For names of classes, capitalize the first letter of the class name.
- ThisIsAnExampleOfClassName
2. For names of methods and variables, the first letter of the word should
start with a small letter.
- thisIsAnExampleOfMethodName
4
Identifiers (cont…)
Coding Guidelines
3. In case of multi-word identifiers, use capital letters to indicate the start of
the word except the first word.
- charArray, fileNumber, ClassName
4. Avoid using underscores at the start such as _read or _write
5
Keywords
Java Keywords
Keywords are predefined identifiers reserved by Java for a specific
purpose.
You cannot use keywords as names for your variables, classes, methods
…etc
6
Keywords (cont…)
7
Java Program
Components
Literals
Java Literals
Literals are tokens that do not change or are constant.
The different types of literals in Java are:
- Integer Literals
- Floating-Point Literals
- Boolean Literals
- Character Literals
- String Literals 9
Literals (cont…)
Java Literals: Integer
Integer literals come in different formats:
- decimal (base 10)
- hexadecimal (base 16)
- octal (base 8)
10
Literals (cont…)
Java Literals: Integer
Special Notations in using integer literals in our programs:
- Decimal
• No special notation
• Example: 12
- Hexadecimal
• Precede by 0x or 0X
• Example: 0xC
11
Literals (cont…)
Java Literals: Integer
Special Notations in using integer literals in our programs:
- Octal
• Precede by 0
• Example: 014
12
Literals (cont…)
Java Literals: Floating Point
Represents decimal with fractional parts
- Example: 3.1416
Can be expressed in standard or scientific notation
- Example: 583.45 (standard)
- Example: 5.8345e2 (scientific)
13
Literals (cont…)
Java Literals: Boolean
Boolean literals have only two values:
- true
- false
14
Literals (cont…)
Java Literals: Character
Character literals represent single Unicode characters.
Unicode character
- A 16-bit character set that replaces the 8-bit ASCII character set.
- Unicode allows the inclusion of symbols and special characters from
other languages
15
Literals (cont…)
Java Literals: Character
To use a character literal, enclose the character in single qoute delimiters.
For example
- The letter a, is represented ‘a’
- Special characters such as a newline character, a backslash is used
followed by the character code. For example, ‘\n’ for the newline
character, ‘\r’ for the carriage return, ‘\b’ for backspace.
16
Literals (cont…)
Java Literals: String
String literals represent multiple characters and are enclosed by double
qoutes.
An example of a string literal is, “Hello World”
17
Primitive Data Types
Java Programming language defines eight primitive data types:
- boolean (for logical) - int
- char (for textual) - long (integral)
- byte - double
- short - float (floating point)
18
Primitive Data Types (cont...)
Logical-boolean
A boolean data type represents two states: true and false
An example is:
boolean result = true;
The example shown above, declares a variable named result as boolean
type and assigns it a value of true.
19
Primitive Data Types (cont...)
Textual-char
A character data type (char), represents a single Unicode character
It must have its literal enclosed in single qoutes (‘ ‘);
For example,
To represent special characters like ‘ (single qoutes) or “ (double qoutes),
use the escape character \. For example,
‘\’’ //for single qoutes
‘\”’ //for double qoutes
20
Primitive Data Types (cont...)
Textual-char
String is a class and not a data type.
String represents a data type that contains multiple characters.
It has its literal enclosed in double qoutes (“ ”)
For example:
String message = “Hello World”;
21
Primitive Data Types (cont...)
Integral – byte, short, int & long
Integral data types in Java uses three forms – decimal, octal, or
hexadecimal
Examples are:
2 //The decimal value 2
077 //The leading 0 indicates an octal value
0xBACC //The leading 0x indicates a hex value
22
Primitive Data Types (cont...)
Integral – byte, short, int & long
Integral types has int as default data type.
You can define its long value by appending the letter l or L
For example:
10L
23
Primitive Data Types (cont...)
Integral – byte, short, int & long
Integral data type have the following ranges:
24
Primitive Data Types (cont...)
Floating Point – float and double
Floating point types has double as default data type
Floating point literal includes either a decimal point or one of the
following:
E or e //add exponential value
F or f //float
D or d //double
25
Primitive Data Types (cont...)
Floating Point – float and double
Floating point examples:
3.14 //A simple floating-point value (a double)
6.02E23 //A large floating-point value
2.718F //A simple float size value
123.4E+306D //A large double
26
Primitive Data Types (cont...)
Floating Point – float and double
Floating point data types have the following ranges:
27
Variables
Variable
A variable is an item of data used to store the state of objects.
A variable has a:
- data type
The data type indicates the type of value that the variable can hold
- name
The variable name must follow rules of identifiers
28
Variables (cont...)
Declare a variable follows:
<data type> <name> [=initial value]
Note: Values enclosed in <> are required values, while those
values in [ ] are optional
29
Variables (cont...)
1 public class VariableSamples {
2 public static void main( String[] args ){
3 //declare a data type with variable name
4 // result and boolean data type
5 boolean result;
6 //declare a data type with variable name
7 // option and char data type
8 char option;
9 option = 'C'; //assign 'C' to option
10 //declare a data type with variable name
11 //grade, double data type and initialized
12 //to 0.0
13 double grade = 0.0;
14 } 30
15 }
Variables (cont...)
Coding Guidelines
1. It always good to initialize you variables as you declare
them.
2. Use descriptive name for your variables. Like for example, if
you want to have a variable that contains a grade for a
student, name it as, grade and not just some random letters
you choose.
31
Variables (cont...)
Coding Guidelines
3. Declare one variable per line of code. For example, the
variable declarations,
double exam = 0;
double quiz = 10;
double grade = 0;
Is preferred over the declaration,
double exam = 0, quiz = 10, grade = 0;
32
Outputting Variable
In order to ouput the value of a certain variable, we can use
the following commands:
System.out.println();
System.out.print();
33
Outputting Variable (cont...)
1 public class OutputVariable {
2 public static void main( String[] args ){
3 int value = 10;
4 char x;
5 x = ‘A’;
6 System.out.println( value );
7 System.out.println( “The value of x=“ + x );
8 }
9 }
The program will output the following text on screen:
10
The value of x=A 34
Outputting Variable (cont...)
System.out.println() vs System.out.print()
System.out.println()
- Appends a newline at the end of the data output
System.out.print()
- Does not append newline at the end of the data output
35
Outputting Variable (cont...)
System.out.print()
System.out.print(“Hello”);
System.out.print(“World!”);
Output:
HelloWorld!
36
Outputting Variable (cont...)
System.out.print()
System.out.println(“Hello”);
System.out.println(“World!”);
Output:
Hello
World!
37
Operators
Different types of operators:
- Arithmetic operator
- Relational operator
- Logical operator
- Conditional operator
These operators follow a certain kind of precedence so that
the compiler will know which operator to evaluate first in case
multiple operators are used in one statement
38
Operators (cont...)
Arithmetic Operator
39
Operators (cont...)
Arithmetic Operator
1. public class ArithmeticDemo {
2. public static void main(String[] args){
3. //a few numbers
4. int i = 37;
5. int j = 42;
6. double x = 27.475;
7. double y = 7.22;
8. System.out.println("Variable values...");
9. System.out.println(" i = " + i);
10. System.out.println(" j = " + j);
11. System.out.println(" x = " + x);
12. System.out.println(" y = " + y); 40
Operators (cont...)
Arithmetic Operator
13. System.out.println("Adding...");
14. System.out.println(" i + j = " + (i + j));
15. System.out.println(" x + y = " + (x + y));
16. //subtracting numbers
17. System.out.println("Subtracting...");
18. System.out.println(" i - j = " + (i – j));
19. System.out.println(" x - y = " + (x – y));
20. //multiplying numbers
21. System.out.println("Multiplying...");
22. System.out.println(" i * j = " + (i * j));
23. System.out.println(" x * y = " + (x * y));
41
Operators (cont...)
Arithmetic Operator
24. //dividing numbers
25. System.out.println("Dividing...");
26. System.out.println(" i / j = " + (i / j));
27. System.out.println(" x / y = " + (x / y));
28. //computing the remainder
29. System.out.println("Computing the remainder...");
30. System.out.println(" i % j = " + (i % j));
31. System.out.println(" x % y = " + (x % y));
42
Operators (cont...)
Arithmetic Operator
32. //mixing types
33. System.out.println("Mixing types...");
34. System.out.println(" j + y = " + (j + y));
35. System.out.println(" i * x = " + (i * x));
36. }
37.}
43
Operators (cont...)
Arithmetic Operator
Variable values... Dividing...
i = 37 i / j = 0
j = 42 x / y = 3.8054
x = 27.475
Computing the remainder...
y = 7.22
i % j = 37
Adding...
x % y = 5.815
i + j = 79
Mixing types...
x + y = 34.695
j + y = 49.22
Subtracting...
i * x = 1016.58
i - j = -5
x - y = 20.255
Multiplying...
i * j = 1554
x * y = 198.37 44
Operators (cont...)
Arithmetic Operator
Note:
When an integer and a floating-point number are used as
operands to a single arithmetic operation, the result is a
floating point. The integer is implicitly converted to a floating-
point number before the operation takes place.
45
Operators (cont...)
Increment and Decrement Operators
Unary increment operator (++)
Unary increment operator (--)
Increment and decrement operators increase and decrease a
value stored in a number variable by 1
For example, the expression,
count = count + 1;
Is equivalent to
count++; 46
Operators (cont...)
Increment and Decrement Operators
47
Operators (cont...)
Increment and Decrement Operators
The increment and decrement operators can be placed before
or after an operand
When used before an operand, it causes the variable to be
incremented or decremented by 1, and then the new value is
used in the expression in which it appears.
48
Operators (cont...)
Increment and Decrement Operators
For example:
int i = 10;
int j = 3;
int k = 0;
k = ++j + i; //will result to
//k = 4+10 = 14
49
Operators (cont...)
Increment and Decrement Operators
When the increment and decrement operators are placed after
the operand, the old value of the variable will be used in the
expression where it appears
For example,
int i = 10;
int j = 3;
int k = 0;
k = j++ + i; //will result to k = 3+10 = 13 50
Operators (cont...)
Relational Operators
Relational operators compare two values and determines the
relationship between those values.
The output of evaluation are the boolean values true or false
51
Operators (cont...)
Relational Operators
52
Operators (cont...)
Relational Operators
1. public class RelationalDemo{
2. public static void main(String[] args){
3. //a few numbers
4. int i = 37;
5. int j = 42;
6. int k = 42;
7. System.out.println("Variable values...");
8. System.out.println(" i = " +i);
9. System.out.println(" j = " +j);
10. System.out.println(" k = " +k);
53
Operators (cont...)
Relational Operators
11. //greater than
12. System.out.println("Greater than...");
13. System.out.println(" i > j = "+(i>j));//false
14. System.out.println(" j > i = "+(j>i));//true
15. System.out.println(" k > j = "+(k>j));//false
16. //greater than or equal to
17. System.out.println("Greater than or equal to...");
18. System.out.println(" i >= j = "+(i>=j));//false
19. System.out.println(" j >= i = "+(j>=i));//true
20. System.out.println(" k >= j = "+(k>=j));//true
54
Operators (cont...)
Relational Operators
21. //less than
22. System.out.println("Less than...");
23. System.out.println(" i < j = "+(i<j));//true
24. System.out.println(" j < i = "+(j<i));//false
25. System.out.println(" k < j = "+(k<j));//false
26. //less than or equal to
27. System.out.println("Less than or equal to...");
28. System.out.println(" i <= j = "+(i<=j));//true
29. System.out.println(" j <= i = "+(j<=i));//false
30. System.out.println(" k <= j = "+(k<=j));//true
55
Operators (cont...)
Relational Operators
31. //equal to
32. System.out.println("Equal to...");
33. System.out.println(" i == j = " + (i==j));//false
34. System.out.println(" k == j = " + (k==j));//true
35. //not equal to
36. System.out.println("Not equal to...");
37. System.out.println(" i != j = " + (i!=j));//true
38. System.out.println(" k != j = " + (k!=j));//false
39. }
40. }
56
Operators (cont...)
Variable values... Less than or equal to...
i = 37
i <= j = true
j = 42
k = 42 j <= i = false
Greater than... k <= j = true
i > j = false
j > i = true Equal to...
k > j = false i == j = false
Greater than or equal to... k == j = true
i >= j = false
j >= i = true Not equal to...
k >= j = true i != j = true
Less than... k != j = false
i < j = true
j < i = false
k < j = false 57
Operators (cont...)
Logical Operators
Logical operators have one or two boolean operands that yield a
boolean result
There are six logical operators:
- && (logical AND) - ^ (boolean logical exclusive OR)
- & (boolean logical AND) - ! (logical NOT)
- || (logical OR)
- | (boolean logical inclusive OR)
58
Operators (cont...)
Logical Operators
The basic operation for a logical operation is
x1 op x2
where,
x1, x2 –can be Boolean expressions, variables or constants
op – is either &&, &, ||, | or ^ operator
The truth tables that will be shown next, summarize the result of each
operation for a possible combinations of x1 and x2.
59
Operators (cont...)
&& (logical) and & (boolean logical) AND
Here is the truth table for && and &,
60
Operators (cont...)
&& (logical) and & (boolean logical) AND
The basic difference between && and & operators:
- && supports short-circuit evaluations (or partial evaluations), while &
doesn’t.
Given an expression
exp1 && exp2
- && will evaluate the expression exp1, and immediately return a false
value if exp1 is false
61
Operators (cont...)
&& (logical) and & (boolean logical) AND
- If exp1 is false, the operator never evaluates exp2 because
the result of the operator will be false regardless of the value
of exp2.
In contrast, the & operator always evaluates both exp1 and exp2
before returning an answer.
62
Operators (cont...)
1 public class TestAND {
2 public static void main( String[] args ){
3 int i = 0;
4 int j = 10;
5 boolean test= false;
6 //demonstrate &&
7 test = (i > 10) && (j++ > 9);
8 System.out.println(i);
9 System.out.println(j);
10 System.out.println(test);
11 //demonstrate &
12 test = (i > 10) & (j++ > 9);
13 System.out.println(i);
14 System.out.println(j);
15 System.out.println(test);
16 } 63
17 }
Operators (cont...)
&& (logical) and & (boolean logical) AND
The output of the program is ,
0
10
false
0
11
false
64
Operators (cont...)
&& (logical) and & (boolean logical) AND
Note, that the j++ on the line containing && operator is not
evaluated since the first expression (i>10) is already equal to
false
65
Operators (cont...)
|| (logical) and | (boolean logical) inclusive OR
Here is the truth table for || and |,
66
Operators (cont...)
1 public class TestOR {
2 public static void main( String[] args ){
3 int i = 0;
4 int j = 10;
5 boolean test= false;
6 //demonstrate ||
7 test = (i < 10) || (j++ > 9);
8 System.out.println(i);
9 System.out.println(j);
10 System.out.println(test);
11 //demonstrate |
12 test = (i < 10) | (j++ > 9);
13 System.out.println(i);
14 System.out.println(j);
15 System.out.println(test);
16 }
67
17 }
Operators (cont...)
|| (logical) and | (boolean logical) inclusive OR
The output of the program is ,
0
10
true
0
11
true
68
Operators (cont...)
|| (logical) and | (boolean logical) inclusive OR
Note, that the j++ on the line containing || operator is not
evaluated since the first expression (i<10) is already equal to
true.
69
Operators (cont...)
|| (logical) and | (boolean logical) inclusive OR
Note, that the j++ on the line containing || operator is not
evaluated since the first expression (i<10) is already equal to
true.
70
Operators (cont...)
^ (boolean logical exclusive OR)
Here is the truth table for ^,
71
Operators (cont...)
^ (boolean logical exclusive OR)
The result of an exclusive OR operation is TRUE, if and only if
one operand is true and the other is false.
Note that both operands must always be evaluated in order to
calculate the result of an exclusive OR.
72
Operators (cont...)
1 public class TestXOR {
2 public static void main( String[] args ){
3 boolean val1 = true;
4 boolean val2 = true;
5 System.out.println(val1 ^ val2);
6 val1 = false; val2 = true;
7 System.out.println(val1 ^ val2);
8 val1 = false; val2 = false;
9 System.out.println(val1 ^ val2);
10 val1 = true; val2 = false;
11 System.out.println(val1 ^ val2);
12 }
13 }
73
Operators (cont...)
^ (boolean logical exclusive OR)
The output of the program is,
false
true
false
true
74
Operators (cont...)
! (logical NOT)
The logical NOT takes in one argument, wherein that argument
can be an expression, variable or constant
Here is the truth table for !,
75
Operators (cont...)
1 public class TestNOT {
2 public static void main( String[] args ){
3 boolean val1 = true;
4 boolean val2 = false;
5 System.out.println(!val1);
6 System.out.println(!val2);
7 }
8 }
The output of the program is,
false
true
76
Operators (cont...)
Conditional Operator ( ?: )
The conditional operator ?:
- Is a ternary operator
This means that it takes in three arguments that together form a
conditional expression
- The structure of an expression using a conditional operator
is exp1?:exp2:exp3
wherein exp1 – is a Boolean expression whose result must either
true or false
77
Operators (cont...)
Conditional Operator ( ?: )
The conditional operator ?:
- Result
if exp1 is true, exp2 is the value returned
if it is false, then exp3 is returned
78
Operators (cont...)
1 public class ConditionalOperator {
2 public static void main( String[] args ){
3 String status = "";
4 int grade = 80;
5 //get status of the student
6 status = (grade >= 60)?"Passed":"Fail";
7 //print status
8 System.out.println( status );
9 }
10 }
The output of the program is,
Passed
79
Operators (cont...)
Conditional Operator ( ?: )
80
Operators (cont...)
Operator Precedence
81
Operators (cont...)
Operator Precedence
For example, multiplication have higher precedence than
addition. In the expression 2+3*4, the multiplication is done
before the addition, producing a result of 14.
So if we want to prioritize addition over multiplication we can
use ( ) parenthesis because parenthesis have higher precedence
than multiplication. In the expression (2+3)*4, the addition is
done before the addition, producing a result of 20.
82
Operators (cont...)
Operator Precedence
Given a complicated expression,
6%2*5+4/2+88-10
we can rewrite the expression and place some parenthesis
base on operator precedence.
((6%2)*5)+(4/2)+88-10
83
Operators (cont...)
Coding Guidelines
To avoid confusion in evaluating mathematical operations, keep
your expressions simple and use parenthesis.
84