Elementary Java Programming
Elementary Java Programming
• The smallest language elements are called lexical tokens and are the building
number
Number
sum_$
bingo
$$_100
mål
grüß
Examples of Illegal Identifiers
• Keywords are reserved identifiers that are predefined in the language and
cannot be used to denote other entities.
• All the keywords are in lowercase.
• Keywords cannot be used as identifiers.
Keywords
const
goto
Literals
Integer 2000 0 -7
• Integer data types are comprised of the following primitive data types: int,
long, byte, and short.
• The default data type of an integer literal is always int, but it can be
specified as long by appending the suffix L (or l) to the integer value.
• There is no direct way to specify a short or a byte literal.
Integer Literals (Contd.)
• Integer literals can also be specified in octal (base 8) and hexadecimal (base
16) number systems.
• Octal and hexadecimal numbers are specified with 0 and 0x (or 0X) prefix
respectively.
• The hexadecimal digits from a to f can also be specified with the
corresponding uppercase forms (A to F).
• Negative integers can be specified by prefixing the minus sign (-) to the
magnitude of the integer regardless of number system
• Java does not support literals in binary notation.
Integer Literals
0.0 0.0d 0D
0.49 .49 .49D
49.0 49. 49D
4.9E+1 4.9E+1D 4.9e1d
4900e-2 .49E2
Examples of float Literals
0.0F 0f
0.49F .49F
49.0F 49.F 49F
4.9E+1F 4900e-2f .49E2F
Boolean Literals
• The primitive data type boolean represents the truth-values true or false that
are denoted by the reserved literals true or false, respectively.
Character Literals
'\141' 'a'
'\46' '&'
'\60' '0'
String Literals
• A white space is a sequence of spaces, tabs, form feed and line terminator
characters in a Java source file.
• Line terminators can be newline, carriage return, or carriage return-newline
sequence.
• A Java program is a free-format sequence of characters that is tokenized by
the compiler.
• White space aids not only in separating tokens, but also in formatting the
program so that it is easy for humans to read.
• The compiler ignores the white spaces once the tokens are identified.
Comments
/* // */
Select the one correct answer.
1. No, the block comment (/* ... */) is not ended since the single-line comment
(// ...) comments out the closing part.
2. It is a completely valid comment. The // part is ignored by the compiler.
3. This combination of comments is illegal and the compiler will reject it.
Primitive Data Types
Primitive Data Types
Data Type Width (bits) True Value Literal False Value Literal
• Variable declarations are used to specify the type and the name of variables.
• This implicitly determines their memory allocation and the values that can
be stored in them.
1. Declaring and Initializing Variables
2. Object Reference Variables
3. Lifetime of Variables
1. Instance variables
2. Static variables
3. Local variables
Default Values for Fields
int a, b;
b = 5;
Select the one correct answer.
1. Local variable a is not declared.
2. Local variable b is not declared.
3. Local variable a is declared but not initialized.
4. Local variable b is declared but not initialized.
5. Local variable b is initialized but not declared.
In which of these variable declarations will the variable
remain uninitialized unless explicitly initialized?
import java.util.*;
package com.acme.toolkit;
public class AClass
{
public Other anInstance;
}
class Other
{
int value;
}
Select the one correct answer.
1. The class will fail to compile, since the class Other has not yet been
declared when referenced in class AClass.
2. The class will fail to compile, since import statements must never be at the
very top of a file.
3. The class will fail to compile, since the package declaration can never
occur after an import statement.
4. The class will fail to compile, since the class Other must be defined in a
file called Other.java.
5. The class will fail to compile, since the class Other must be declared
public.
6. The class will compile without errors.
Is an empty file a valid source file?
• All the binary operators use infix notation, which means that the operator
appears between its operands:
op1 operator op2 //infix notation
• The ternary operator is also infix; each component of the operator appears
between operands:
op1 ? op2 : op3 //infix notation
Operators (Contd.)
• All binary operators, except relational and assignment operators are L-R
associative.
• The relational operators are non-associative.
• Except for unary postfix increment and decrement operators, all unary
operators & all assignment operators are R-L associative.
Operators (Contd.)
• Java guarantees that all operands of an operator are fully evaluated before
the operator is applied. The only exceptions are the short-circuit conditional
operators &&, ||, and ?:.
int b = 10;
System.out.println((b=3) + b);
The value printed will be 6 and not 13
Unary Cast Operator: (type)
(<type>) <expression>
- Casting can be applied to primitive values as well as references.
- Casting between primitive data types and reference types is not permitted.
- Boolean values cannot be cast to other data values, and vice versa.
- The reference literal null can be cast to any reference type.
Narrowing and Widening Conversions
Assignment Operator (=)
e. The program will randomly print either cat or dog when run.
Arithmetic Operators
• When one of the operands is a String object, the other operand is implicitly
converted to its string representation and string concatenation is performed.
Binary String Concatenation Operator (+)
• For a operand of a primitive data type, its value is converted to a String object
with the string representation of the value.
• Values like true, false, and null are represented by string representations of
these literals.
• A reference variable with the value null also has the string representation
"null" in this context.
• For all reference value operands, a string representation is constructed by
calling the toString() method on the referred object.
Binary String Concatenation Operator (+)
• ++i adds 1 to i first, then uses the new value of i as the value of the expression.
i += 1;
result = i;
return result;
• j++ uses the current value of j as the value of the expression first, then adds 1
to j.
result = j;
j += 1;
return result;
Increment and Decrement Operator: ++,--
int i = 10;
int k = ++i + --i;
--i;
long i = 10;
long k = i++ + i--;
// ((i++) + (i--)). k gets the value 21L and i becomes 10L.
i++;
byte b = 10;
int i = ++b;
double x = 4.5;
x = x + ++x;
Relational Operators
int a = 1, b = 7, c = 10;
boolean valid1 = a <= b <= c; // Illegal.
boolean valid2 = a <= b && b <= c; // OK.
Primitive Data Value Equality: ==, !=
a == b a and b are equal? That is, have the same primitive value? (Equality)
a != b a and b are not equal? That is, do not have the same primitive value?
(Inequality)
int a, b, c;
a = b = c = 5;
boolean valid1 = a == b == c; // (1) Illegal.
boolean valid2 = a == b && b == c; // (2) Legal.
boolean valid3 = a == b == true; // (3) Legal.
Object Reference Equality: ==, !=
The equality operator == and the inequality operator != can be applied to
object references to test whether they denote the same object.
a == b a and b are equal? That is, have the same reference value? (Equality)
a != b a and b are not equal? That is, do not have the same reference value?
(Inequality)
These operators always evaluate both the operands, unlike their counterpart
conditional operators && and ||
Truth-values for Boolean Logical Operators
Conditional AND x && y true if both operands are true; otherwise, false.
Conditional OR x || y true if either or both operands are true;
otherwise, false.
Unlike their logical counterparts & and |, which can also be applied to integral
operands for bitwise operations, the conditional operators && and || can only
be applied to boolean operands.
Truth-values for Conditional Operators
x y x && y x || y
true true true true
true false false true
false true false true
false false false false
In evaluation of boolean expressions involving conditional AND & OR, the left-
hand operand is evaluated before the right one, and the evaluation is short-
circuited (i.e., if the result of the boolean expression can be determined from the
left-hand operand, the right-hand operand is not evaluated).
The binary conditional operators have precedence lower than either arithmetic,
relational, or logical operators, but higher than assignment operators.
if (i > 0 && i++ < 10) {/*...*/} // i is not incremented if i > 0 is false.
if (i > 0 || i++ < 10) {/*...*/} // i is not incremented if i > 0 is true.
Integer Bitwise Operators: ~, &, |, ^
int v0 = -42;
char v1 = ')'; // 41 byte
byte v2 = 13;
v0 &= 15; // 1...1101 0110 & 0...0000 1111 => 0...0000 0110 (= 6)
v1 |= v2; // (1) 0...0010 1001 | 0...0000 1101 => 0...0010 1101 (= 45)
Shift Operators: <<, >>, >>>
• The binary shift operators form a new value by shifting bits either left or right a
specified number of times in a given integral value.
• The number of shifts (also called the shift distance) is given by the right-hand
operand, and the value that is to be shifted is given by the left-hand operand.
• Note that unary numeric promotion is applied to each operand individually.
• The shift distance is calculated by AND-ing the value of the right-hand operand
with a mask value of 0x1f (31) if the left-hand has the promoted type int, or
using a mask value of 0x3f (63) if the left-hand has the promoted type long.
Shift Operators
Shift left a << n Shift all bits in a left n times, filling with 0
from the right.
Shift right with sign bit a >> n Shift all bits in a right n times, filling with the
sign bit from the left.
Shift right with zero fill a >>> n Shift all bits in a right n times, filling with 0
from the left.
Given that a contains the value whose bits are to be shifted and n specifies the
number of bits to shift
int i = 12;
int result = i << 4; // 192
i << 4
= 0000 0000 0000 0000 0000 0000 0000 1100 << 4
= 0000 0000 0000 0000 0000 0000 1100 0000
= 0x000000c0
= 192
byte b = -42; // 11010110
short n = 4;
int result = b << n; // -672
byte a = 32, b;
int j;
j = a << 3; // 256
b = (byte) (a << 3); // 0. Cast mandatory.
a << 3
= 0000 0000 0000 0000 0000 0000 0010 0000 << 3
= 0000 0000 0000 0000 0000 0001 0000 0000
= 0x00000100
= 256
int i = 12;
int result = i >> 2; // 3
i >> 2
= 0000 0000 0000 0000 0000 0000 0000 1100 >> 2
= 0000 0000 0000 0000 0000 0000 0000 0011
= 0x00000003
=3
byte b = -42; // 11010110
b >> 4
= 0xfffffffd
= -3
byte b = -42; // 1101 0110
b >>> 4
= 0x0ffffffd
= 268435453
Shift Compound Assignment Operators: <<=, >>=, >>>=
a = (byte) (a << 5)
= (byte) (0000 0000 0000 0000 0000 0000 0000 1100 << 5)
= (byte) 0000 0000 0000 0000 0000 0001 1000 0000
= 1000 0000
= 0x80
= -128
The Conditional Operator: ?
• The new operator is used to create objects, that is, instances of classes and
arrays.
• It is used with a constructor call to instantiate classes, and with the [ ]
notation to create arrays.
• It is also used to instantiate anonymous arrays, and anonymous classes.
Pizza onePizza = new Pizza();
// Create an instance of Pizza class.
Other Operators: new, [ ], instanceof
• The [ ] notation is used to declare and construct arrays and also to access
array elements.
int[ ] anArray = new int[5];
// Declare and construct an int array of 5 elements.
anArray[4] = anArray[3];
// Element at index 4 gets value of element at index 3.
Other Operators: new, [ ], instanceof
• The boolean, binary, and infix operator instanceof is used to test an object's
type.
Pizza myPizza = new Pizza();
boolean test1 = myPizza instanceof Pizza; // True.
boolean test2 = "Pizza" instanceof Pizza;
// Compile error. String is not Pizza.
boolean test3 = null instanceof Pizza;
// Always false. null not an instance.
Control Flow Statements
if (<conditional expression>)
<statement>
• It is used to decide whether an action is to be performed or not, based on a
condition.
• The condition is specified by <conditional expression> and the action to be
performed is specified by <statement>.
• The <conditional expression> is evaluated first. If its value is true, then
<statement> (called the if block) is executed and execution continues with
the rest of the program. If the value is false, then the if block is skipped and
execution continues with the rest of the program.
if(emergency) // emergency is a boolean variable
operate();
if(catIsAway())
{
// Block
getFishingRod();
goFishing();
}
if(emergency); // Empty if block
operate(); // Executed regardless of whether it was
// an emergency or not.
if (<conditional expression>)
<statement1>
else
<statement2>
• The switch statement can be used to choose one among many alternative
actions, based on the value of an expression.
switch (<non-long integral expression>) {
case label1: <statement1>
case label2: <statement2>
...
do{ // (2)
mice.play();
} while (cat.isAway());
for Statement
for(<initialization>; <loop condition>; <increment expression>)
<loop body>
• It is mostly used for counter-controlled loops, that is, when the number of
iterations is known beforehand.
• The <initialization> usually declares and initializes a loop variable that
controls the execution of the <loop body>.
• The <loop condition> is a boolean expression, usually involving the loop
variable, such that if the loop condition is true, the loop body is executed;
otherwise, execution continues with the statement following the for loop.
• After each iteration (i.e., execution of the loop body), the <increment
expression> is executed. This usually modifies the value of the loop variable
to ensure eventual loop termination.
• The loop condition is then tested to determine if the loop body should be
executed again.
• Note that the <initialization> is only executed once on entry to the loop.
int sum = 0;
sum += array[index];
Transfer Statements
• break
• continue
• return
• try-catch-finally
• throw
• assert
• Note that Java does not have a goto statement, although goto is a reserved
word.
Labeled Statements
<label> : <statement>
• A label is any valid identifier and it always immediately proceeds the
statement.
• Label names exist in their own name space, so that they do not conflict with
names of packages, classes, interfaces, methods, fields, and local variables.
• The scope of a label is the statement prefixed by the label, meaning that it
cannot be redeclared as a label inside the labeled statement—analogous to
the scope of local variables.
• A statement can have multiple labels:
• The size of an array is fixed and cannot increase to accommodate more elements.
• In Java, arrays are objects.
• Arrays can be of primitive data types or reference types.
• Each array object has a final field called length, which specifies the array size,
that is, the number of elements the array can accommodate.
Arrays
• The first element is always at index 0 and the last element at index n-1, where n
is the value of the length field in the array.
• Simple arrays are one-dimensional arrays, that is, a simple sequence of values.
• Since arrays can store object references, the objects referenced can also be array
objects. This allows implementation of array of arrays.
Declaring Array Variables
• The minimum value of <array size> is 0 (i.e., arrays with zero elements can be
constructed in Java).
• If the array size is negative, a NegativeArraySizeException is thrown.
The array declaration and construction can be combined.
• The expressions in the <array initialize list> are evaluated from left to right.
• The following array has length two, not three:
• Topping[] pizzaToppings = { new Topping("cheese"), new
Topping("tomato"), };
• // Array with 3 String objects
String[] pets = {"crocodiles", "elephants", "crocophants―};
• // Array of 3 characters
char[] charArray = {'a', 'h', 'a'}; // Not the same as "aha".
Using an Array
• The <array name> can, in fact, be any expression that returns a reference to
an array.
"AHA".toCharArray()[1].
• The array operator [ ] is used to declare array types, specify array size, and
to access array elements.
• This operator is not used when the array reference is manipulated, for
example in an array reference assignment or when the array reference is
passed as an actual parameter in a method call.
Anonymous Arrays
int[ ] daysInMonth;
daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Not ok.
daysInMonth = new int[ ] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // ok.
Multidimensional Array
• Since an array element can be an object reference and arrays are objects,
array elements can themselves reference other arrays.
• In Java, an array of arrays can be defined as follows:
<element type>[][]...[] <array name>;
or
<element type> <array name>[][]...[];
• The following declarations are all equivalent:
int[][] mXnArray; // 2-dimensional array
int[] mXnArray[]; // 2-dimensional array
int mXnArray[][]; // 2-dimensional array
int[][] mXnArray = new int[4][5]; // 4 x 5 matrix of ints
double[ ][ ] identityMatrix = {
{1.0, 0.0, 0.0, 0.0 }, // 1. row
{0.0, 1.0, 0.0, 0.0 }, // 2. row
{0.0, 0.0, 1.0, 0.0 }, // 3. row
{0.0, 0.0, 0.0, 1.0 } // 4. row
}; // 4 x 4 Floating-point matrix
Pizza[ ][ ] pizzaGalore = {
{new Pizza(), null, new Pizza()},
{null, new Pizza()},
new Pizza[1],
{},
null
};