Java Lectures

Download as pdf or txt
Download as pdf or txt
You are on page 1of 137

Computer Programming III – Java

Dr. Sami AL-MAQTARI


The different types of programming languages
• Machine Code
• Binary representation of instructions and data.
• Machine specific.
• Difficult to read, understand, and maintain.
• Assembly language
• Symbolic English representation of machine code.
• Easier to write than machine code.
• Still not easy to write and maintain.
• High-Level Languages (HLL)
• Closer to human language.
• More portable and easier to understand and maintain.

2
High-Level Languages types
• Compiled languages
• Sources code is translated into machine code (executable file) using
compilers.
• Pros: The final code can be executed directly on the target machine.
• Cons: Low portability, need to be recompiled to be executed on a
different machine.
• Interpreted (script) languages
• Source code is translated on the fly into machine code using
interpreters.
• Pros: High portability, the program can be run on a new machine using
a proper interpreter.
• Cons: Slow to execute compared to compiled code.

3
JAVA programming language
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Compiled & Interpreted language (compile once run everywhere)
• High performance
• Distributed
• Dynamic

4
Java History
• Java 1.0 → Java 17 • J2SE 8 Features
• J2SE 5.0 Features • Lambda expression
• Generics • java.util.stream
• Annotations • java.util.function (functional
• Autoboxing and auto-unboxing interfaces)
• Enumerations • Interface default
implementation for a method
• Enhanced, for-each style for
• JavaFX 8
loop
• Variable-length arguments • …
(varargs)
• Static import
• Formatted I/O
• Concurrency utilities

5
Java Assets
• JDK www.oracle.com - www.java.com
• Java IDE
• Eclipse (2021-12 (4.22.0)) www.eclipse.org
• Netbeans (12.6) netbeans.apache.org/
• Resources
• Java: The Complete Reference, 12th Edition (ISBN: 9781260463422)
• Chapters: 1-9, 12, 14
• www.tutorialspoint.com
• www.javatpoint.com
• www.learnjavaonline.org
• Java tutorial docs.oracle.com/javase/tutorial/
• www.tutorialpoints.com
• www.w3schools.com/java/

6
Java vs C++
• Common: Syntax, Entry points (main function), OOP.
• Platform-independent vs Platform-dependent
• Application programming vs System programming
• Single inheritance only vs Single and multiple inheritance
• Internal pointers support only vs Pointer support
• Compiler & Interpreter vs Compiler only → (slower?)
• No struct nor union
• No operator overloading
• Call by value only
• Built-in thread support
• Auto documentation

7
HelloWorld.java
// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

• Compiling the program


…\>javac HelloWorld.java
Generates HelloWorld.class file
• Running the program
…\>java HelloWorld
• Using eclipse/netbeans

8
Java types and objects:
• Primitive Data types Type Size Default
byte 1-byte 0
short 2-byte 0
int 4-byte 0
long 8-byte 0L
float 4-byte 0.0f
double 8-bye 0.0d
char 2-byte '\u0000' = '\000'
Boolean true/false false
• Reference type:
• Any variable that is not primitive type is considered a reference to an
object.

9
Reference vs. objects
• Objects and references are two separated concepts.
• An object is nameless, reference is used to access it.
• A reference can point to a given object or no object (null).
• An object may have one reference or more or it may have no
reference.
• An object with no reference is deleted by the garbage collector
in the JVM.

10
Naming convention (camel case)
• The following rules of naming make the code more readable
• Classes (types): capital first letter of each word, no underscore for
spaces.
• Variables: same as classes except the first word starts with small letter.
• Names starts with a letter or an underscore, but not with a digit.

11
Primitive Types
Type Keyword Size (bits) default Range
Byte byte 8 0 –128 to 127
Short short 16 0 –32,768 to 32,767
–2,147,483,648 to
Integer int 32 0
2,147,483,647
–9,223,372,036,854,775,808 to
Long long 64 0L
9,223,372,036,854,775,807
Single precision float 32 0.0f 1.4e–045 to 3.4e+038
Double precision double 64 0.0 4.9e–324 to 1.8e+308
Character char 16 '\u0000' Unicode
Boolean boolean false false/true

12
Literal Constants
• Integers 123 // int
01534 // octal
0x2FC6 // hexadecimal
48315L // long
041257L // long octal
0X52F8L // long hexadecimal
0b1101 // binary (Java 7)
123_456_789 // underscore (Java 7)
• Reals 0B1001_0110_1011_1110
2.7181f // float
3.141 // double (default)
-1.6E-19 // scientific notation
0x12.2P2 // hexadecimal (72.5)
• Characters 1_753.4_5_9 // underscore (Java 7)
'a' // character
'\141' // octal 'a'
'\u0061' // hexadecimal 'a'
• Boolean true // true/false
• String "Abc Def" // String

13
Character Escape Sequences
Escape Sequence Description
\ddd Octal character (ddd)
\uxxxx Hexadecimal Unicode character (xxxx)
\' Single quote
\" Double quote
\\ Backslash
\r Carriage return
\n New line (also known as line feed)
\f Form feed
\t Tab
\b Backspace

14
Variables
• Declaring a Variable
𝑡𝑦𝑝𝑒 𝑖𝑑𝑒𝑛𝑡𝑖𝑓𝑖𝑒𝑟 [ = 𝑣𝑎𝑙𝑢𝑒 ][, 𝑖𝑑𝑒𝑛𝑡𝑖𝑓𝑖𝑒𝑟 [= 𝑣𝑎𝑙𝑢𝑒 ] … ];
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

• Dynamic Initialization
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);

15
The Scope and Lifetime of Variables
public static void main(String args[]) {
// System.out.println(x); Error: variable is not defined yet
int x; // known to all code within main
// System.out.println(x); Error: variable is not initialized yet

x = 10;
if (x == 10) { // start new scope
int y = 20; // known only to this block

// x and y both known here.


// int x = 3; Error! x is already defined
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here

// x is still known here.


System.out.println("x is " + x);
}

16
Java’s Type Conversions
• Widening conversion occurs if the following two conditions are
met:
1. The two types are compatible.
2. The destination type is larger than the source type.
• Casting Incompatible Types (Narrowing conversion)
(𝑡𝑎𝑟𝑔𝑒𝑡 − 𝑡𝑦𝑝𝑒) 𝑣𝑎𝑙𝑢𝑒
byte b; int i = 257; double d = 323.142;

System.out.println("\nConversion of int to byte.");


b = (byte) i;
System.out.println("i and b " + i + " " + b);

System.out.println("\nConversion of double to int.");


i = (int) d;
System.out.println("d and i " + d + " " + i);

System.out.println("\nConversion of double to byte.");


b = (byte) d;
System.out.println("d and b " + d + " " + b); 17
Automatic Type Promotion in Expressions
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;

b = b * 2; // Error! Cannot assign an int to a byte!


b = (byte)(b * 2);

• Type Promotion Rules:


1. All byte, short, and char values are promoted to int.
2. If one operand is a long, the whole expression is promoted to long.
3. If one operand is a float, the entire expression is promoted to float.
4. If any of the operands are double, the result is double.

18
Automatic Type Promotion example
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}

238.14 + 515 - 126.3616


result = 626.7784146484375

19
Arrays
• Declaring One-Dimensional Array:
𝑡𝑦𝑝𝑒 𝑎𝑟𝑟𝑎𝑦 − 𝑛𝑎𝑚𝑒[ ];
int monthDays[];
• Creating the array:
𝑎𝑟𝑟𝑎𝑦 − 𝑛𝑎𝑚𝑒 = 𝑛𝑒𝑤 𝑡𝑦𝑝𝑒 [𝑠𝑖𝑧𝑒];
monthDays = new int[12];
• Declaring and creating the array in one step:
𝑡𝑦𝑝𝑒 𝑎𝑟𝑟𝑎𝑦 − 𝑛𝑎𝑚𝑒[ ] = 𝑛𝑒𝑤 𝑡𝑦𝑝𝑒 [𝑠𝑖𝑧𝑒];
int monthDays[] = new int[12];
• Accessing array items:
monthDays[0] = 31;
System.out.println("January has " + monthDays[0] + " days.");

20
Multidimensional Arrays
class TwoDArray { 01234
public static void main(String args[]) { 56789
int twoD[][] = new int[4][5]; 10 11 12 13 14
int i, j, k = 0; 15 16 17 18 19
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twoD[i][j] = k;
k++;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

21
Multidimensional Arrays (cont.)

22
Multidimensional Arrays (cont.)
class TwoDAgain { 0
public static void main(String args[]) { 12
int twoD[][] = new int[4][]; 345
twoD[0] = new int[1]; 6789
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];

int i, j, k = 0;
for (i = 0; i < 4; i++)
for (j = 0; j < i + 1; j++) {
twoD[i][j] = k;
k++;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < i + 1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
23
Multidimensional Arrays (cont.)

24
Initializing 2D array
class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0 * 0, 1 * 0, 2 * 0, 3 * 0 },
{ 0 * 1, 1 * 1, 2 * 1, 3 * 1 },
{ 0 * 2, 1 * 2, 2 * 2, 3 * 2 },
{ 0 * 3, 1 * 3, 2 * 3, 3 * 3 } };
int i, j;

for (i = 0; i < 4; i++) {


for (j = 0; j < 4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}

25
More dimensions?
class ThreeDMatrix { 00000
public static void main(String args[]) { 00000
int threeD[][][] = new int[3][4][5]; 00000
int i, j, k;
00000
for (i = 0; i < 3; i++)
for (j = 0; j < 4; j++) 00000
for (k = 0; k < 5; k++) 01234
threeD[i][j][k] = i * j * k; 02468
0 3 6 9 12
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
for (k = 0; k < 5; k++)
00000
System.out.print(threeD[i][j][k] + " "); 02468
System.out.println(); 0 4 8 12 16
} 0 6 12 18 24
System.out.println();
}
}
}

26
Alternative Array Declaration Syntax
𝑡𝑦𝑝𝑒[ ] 𝑎𝑟𝑟𝑎𝑦 − 𝑛𝑎𝑚𝑒;
int al[] = new int[3];
int[] a2 = new int[3];

char twod1[][] = new char[3][4];


char[][] twod2 = new char[3][4];

int[] nums, nums2, nums3; // create three arrays

int nums[], nums2[], nums3[]; // create three arrays

27
Arithmetic Operators
Operator Result
+ Addition (also unary plus)
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement

28
Arithmetic Operators (examples)
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers // arithmetic using doubles
System.out.println("Integers"); System.out.println("\nReals");
int a = 1 + 1; double da = 1 + 1;
int b = a * 3; double db = da * 3;
int c = b / 4; double dc = db / 4;
int d = c - a; double dd = dc - a;
int e = -d; double de = -dd;
System.out.println("a = " + a); System.out.println("da = " + da);
System.out.println("b = " + b); System.out.println("db = " + db);
System.out.println("c = " + c); System.out.println("dc = " + dc);
System.out.println("d = " + d); System.out.println("dd = " + dd);
System.out.println("e = " + e); System.out.println("de = " + de);
}
}

Integers Reals
a = 2 da = 2.0
b = 6 db = 6.0
c = 1 dc = 1.5
d = -1 dd = -0.5
e = 1 de = 0.5
29
Bitwise Operators
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
30
Bitwise Operators (example 1)
class BitLogic {
public static void main(String args[]) {
String binary[] = { "0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111" };
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
a = 0011
int d = a & b;
b = 0110
int e = a ^ b;
a|b = 0111
int f = (~a & b) | (a & ~b);
a&b = 0010
int g = ~a & 0x0f;
a^b = 0101
System.out.println(" a = " + binary[a]);
~a&b|a&~b = 0101
System.out.println(" b = " + binary[b]);
~a = 1100
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
31
}
Bitwise Operators (example 2)
class ByteUShift {
static public void main(String args[]) {
char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
byte b = (byte) 0xf1;
byte c = (byte) (b >> 4);
byte d = (byte) (b >>> 4);
byte e = (byte) ((b & 0xff) >> 4);
System.out.println(" b = 0x"
+ hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
System.out.println(" b >> 4 = 0x"
+ hex[(c >> 4) & 0x0f] + hex[c & 0x0f]);
System.out.println(" b >>> 4 = 0x"
+ hex[(d >> 4) & 0x0f] + hex[d & 0x0f]);
System.out.println("(b & 0xff) >> 4 = 0x"
+ hex[(e >> 4) & 0x0f] + hex[e & 0x0f]); b = 0xf1
} b >> 4 = 0xff
} b >>> 4 = 0xff
(b & 0xff) >> 4 = 0x0f

32
Relational Operators
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

33
Boolean Logical Operators
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
&& Short-circuit OR
|| Short-circuit AND
! Logical unary NOT
?: Ternary if-then-else

34
Ternary if-then-else (example)
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}

Absolute value of 10 is 10
Absolute value of -10 is 10

35
Operator Precedence
(postfix)++ (postfix)--
++(prefix) --(prefix) ~ ! +(unary) -(unary) (type-cast)
* / %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
=
36
Java’s Selection Statements
• The if statement

• The switch statement

37
The if statement
• Syntax
if (condition) statement;

• What if the conditions is false?


if (condition) statement1;
else statement2;
• Nested ifs
if (i == 10) {
if (j < 20) a = b;
if (k > 100) c = d; // this if is
else a = c; // associated with this else
} else a = d;

38
The if-else-if Ladder
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if (month == 12 || month == 1 || month == 2)
season = "Winter";
else if (month == 3 || month == 4 || month == 5)
season = "Spring";
else if (month == 6 || month == 7 || month == 8)
season = "Summer";
else if (month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
April is in the Spring.

39
The switch statement
• Syntax switch(expression) {
case value1:
• expression: // statement sequence
• byte break;
case value2:
• short // statement sequence
• int break;
.
• char .
• Enumeration (later) case valueN:
• String (JDK 7~) // statement sequence
break;
default:
// default statement sequence
}

40
The switch statement (example 1)
class SampleSwitch { i is zero.
public static void main(String args[]) { i is one.
for (int i = 0; i < 6; i++) i is two.
switch (i) {
i is three.
case 0:
System.out.println("i is zero."); i is greater than 3.
break; i is greater than 3.
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
41
The switch statement (example 2)
class MissingBreak { i is less than 5
public static void main(String args[]) { i is less than 5
for (int i = 0; i < 12; i++) i is less than 5
switch (i) {
case 0:
i is less than 5
case 1: i is less than 5
case 2: i is less than 10
case 3: i is less than 10
case 4: i is less than 10
System.out.println("i is less than 5"); i is less than 10
break; i is less than 10
case 5:
case 6:
i is 10 or more
case 7: i is 10 or more
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
42
The switch statement (example 3)
class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12: case 1: case 2:
season = "Winter";
break;
case 3: case 4: case 5:
season = "Spring"; April is in the Spring.
break;
case 6: case 7: case 8:
season = "Summer";
break;
case 9: case 10: case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
}
43
Nested switch Statements
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...

44
Java’s Iteration Statements
• The while statement
• The do-while statement
• The for statement
• The for-each version of for statement (~JDK 5)

45
The while statement
• Syntax
while(condition) {
// body of loop
}

• Condition is evaluated before executing the loop.

46
The while statement (example 1)
class While { tick 10
public static void main(String args[]) { tick 9
int n = 10; tick 8
while (n > 0) { tick 7
System.out.println("tick " + n); tick 6
n--; tick 5
} tick 4
} tick 3
} tick 2
tick 1

47
The while statement (example 2)
class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while (++i < --j)
; // no body in this loop
System.out.println("Midpoint is " + i);
}
}

Midpoint is 150

48
The do-while statement
• Syntax
do {
// body of loop
} while (condition);

• Condition is evaluated after executing the loop.


• The body of the loop is executed at least once.

49
The do-while statement (example 1)
class DoWhile { tick 10
public static void main(String args[]) { tick 9
int n = 10; tick 8
do { tick 7
System.out.println("tick " + n); tick 6
n--; tick 5
} while (n > 0); tick 4
} tick 3
} tick 2
tick 1

do {
System.out.println("tick " + n);
} while (--n > 0);

50
The for statement
• Syntax
for(initialization; condition; iteration) {
// body
}
• At start, the initialization portion is executed,
• Next, condition is evaluated
• The loop body is executed if true,
• The loop finished if false.
• Next, the iteration portion is executed.
• The three portions are optional

51
The for statement (example 1)
class ForTick { tick 10
public static void main(String args[]) { tick 9
for (int n = 10; n > 0; n--) tick 8
System.out.println("tick " + n); tick 7
} tick 6
} tick 5
tick 4
tick 3
tick 2
tick 1

52
The for statement (example 2)
class FindPrime {
public static void main(String args[]) {
int num;
boolean isPrime = true;
num = 14;
if (num < 2)
isPrime = false;
for (int i = 2; i <= num / i; i++) {
if ((num % i) == 0) {
isPrime = false;
break;
}
}
if (isPrime)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}

53
The for statement (example 3)
class Comma {
public static void main(String args[]) {
int a, b;
for (a = 1, b = 4; a < b; a++, b--) {
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}
a = 1
b = 4
a = 2
b = 3

54
The for statement (example 4)
boolean done = false;
for(int i=1; !done; i++) {
// ...
if(interrupted()) done = true;
}

for( ; ; ) {
// ...
}

55
The for-each version of for statement (~JDK 5)
• Syntax
for(type itr-var : collection) statement-block
• type specifies the type and itr-var specifies the name of an iteration
variable that will receive the elements from a collection, one at a time,
from beginning to end.
• The iteration variable is read-only as it relates to the underlying array.
• Various types of collections that can be used with the for, (Arrays
basically).

56
The for-each statement (example 1)
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for (int i = 0; i < 10; i++)
sum += nums[i];
// use for-each style for to display and sum the values
for (int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}

57
The for-each statement (example 2)
class Search {
public static void main(String args[]) {
int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;
boolean found = false;
// use for-each style for to search nums for val
for (int x : nums) {
if (x == val) {
found = true;
break;
}
}
if (found)
System.out.println("Value found!");
}
}

58
Iterating Over Multidimensional Arrays- Nested loops
class ForEach2D { Value is: 1
public static void main(String args[]) { Value is: 2
int sum = 0; Value is: 3
int nums[][] = new int[3][5]; Value is: 4
// give nums some values Value is: 5
for (int i = 0; i < 3; i++) Value is: 2
for (int j = 0; j < 5; j++) Value is: 4
nums[i][j] = (i + 1) * (j + 1); Value is: 6
// use for-each for to display and sum the values Value is: 8
for (int x[] : nums) { Value is: 10
for (int y : x) { Value is: 3
System.out.println("Value is: " + y); Value is: 6
sum += y; Value is: 9
} Value is: 12
} Value is: 15
System.out.println("Summation: " + sum); Summation: 90
}
}

59
Java’s Jump Statements
• The break statement

• The continue statement

• The return statement

60
The break statement
• Three usages
• To terminates a statement sequence in a switch statement.
• To exit a loop (stop the loop completely).
• as a form of goto.

61
The break statement (example 1)
class BreakLoop { i: 0
public static void main(String args[]) { i: 1
for (int i = 0; i < 100; i++) { i: 2
if (i == 10) i: 3
break; // terminate loop if i is 10 i: 4
System.out.println("i: " + i); i: 5
} i: 6
System.out.println("Loop complete."); i: 7
} i: 8
} i: 9
Loop complete.

62
The break statement (example 2)
class BreakLoop2 {
public static void main(String args[]) {
for (int i = 0; i < 3; i++) {
System.out.print("Pass " + i + ": ");
for (int j = 0; j < 100; j++) {
if (j == 10)
break; // terminate loop if j is 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}
}

Pass 0: 0 1 2 3 4 5 6 7 8 9
Pass 1: 0 1 2 3 4 5 6 7 8 9
Pass 2: 0 1 2 3 4 5 6 7 8 9

63
The break statement (example 3)
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if (t)
break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
Before the break.
This is after second block.

64
The break statement (example 4)
class BreakouterLoop {
public static void main(String args[]) {
outer: for (int i = 0; i < 3; i++) {
System.out.print("Pass " + i + ": ");
for (int j = 0; j < 100; j++) {
if (j == 10)
break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}

Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.

65
The break statement (example 5)
class BreakErr {
public static void main(String args[]) {
one: for (int i = 0; i < 3; i++) {
System.out.print("Pass " + i + ": ");
}
for (int j = 0; j < 100; j++) {
if (j == 10)
break one; // WRONG
System.out.print(j + " ");
}
}
}

66
The continue statement
• To force an early iteration of a loop.
• In while and do-while loops, a continue statement causes
control to be transferred directly to the conditional expression
that controls the loop.
• In a for loop, control goes first to the iteration portion of the
for statement and then to the conditional expression.
• Any intermediate code is bypassed.

67
The continue statement (example 1)
class Continue {
public static void main(String args[]) {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
if (i % 2 == 0)
continue;
System.out.println("");
}
}
}
01
23
45
67
89

68
The continue statement (example 2)
class ContinueLabel { 0
public static void main(String args[]) { 01
outer: for (int i = 0; i < 10; i++) { 024
for (int j = 0; j < 10; j++) { 0369
if (j > i) { 0 4 8 12 16
System.out.println(); 0 5 10 15 20 25
continue outer; 0 6 12 18 24 30 36
} 0 7 14 21 28 35 42 49
System.out.print(" " + (i * j)); 0 8 16 24 32 40 48 56 64
} 0 9 18 27 36 45 54 63 72 81
}
System.out.println();
}
}

69
The return statement
• To explicitly return from a method.
• It causes the execution to branch back to the caller of the
method.
• It immediately terminates the method in which it is executed.

70
The return statement (example)
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if (t)
return; // return to caller
System.out.println("This won't execute.");
}
}

Before the return.

71
Classes
• The general form of a class class Box {
double width;
class classname { double height;
type instance-variable1; double depth;
type instance-variable2; }
// ...
type instance-variableN; class BoxDemo {
public static void main(String args[]) {
type methodname1(parameter-list) { Box mybox = new Box();
// body of method double vol;
} mybox.width = 10;
mybox.height = 20;
type methodname2(parameter-list) { mybox.depth = 15;
// body of method // compute volume of box
} vol = mybox.width *
mybox.height * mybox.depth;
// ... System.out.println("Volume is "+vol);
type methodnameN(parameter-list) { }
// body of method }
}
}

72
Classes (example)
class Box {
double width;
double height;
double depth;
}

class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
73
Declaring reference vs. creating object
class-var = new classname();

74
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;

75
Introducing Methods
class Box { type methodname1(parameter-list) {
double width; // body of method
double height; }
double depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
} class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
mybox1.volume();
mybox2.volume();
}
}

76
Returning a Value
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
}

class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.height = 6;
mybox2.depth = 9;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
77
}
Method with parameters
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
void setDim(double w, double h, double d) {
width = w;
height = h; class BoxDemo5 {
depth = d; public static void main(String args[]) {
} Box mybox1 = new Box();
} Box mybox2 = new Box();
double vol;
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

78
Constructors
class BoxDemo6 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
class Box { System.out.println("Volume is " + vol);
double width; }
double height; }
double depth;
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume() {
return width * height * depth;
}
}

79
Parameterized Constructors
class BoxDemo7 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
class Box { }
double width; }
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}

80
this keyword
class BoxDemo7 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
class Box { }
double width; }
double height;
double depth;
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
double volume() {
return width * height * depth;
}
}

81
Instance Variable Hiding
class BoxDemo7 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
class Box { }
double width; }
double height;
double depth;
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
double volume() {
return width * height * depth;
}
}

82
Destructors?
• Java Garbage Collection
• Java handles deallocation for you automatically.
• When no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed.
• No explicit need to destroy objects.
• Garbage collection only occurs sporadically (occasional) during the
execution of your program.
• Different Java run-time implementations will take different approaches for
garbage collection.

• The finalize() Method


protected void finalize() {
// finalization code here
}

83
More practical example? Stack class
class Stack {
int stck[] = new int[10];
int tos;

// Initialize top-of-stack
Stack() {
tos = -1;
}
// Push an item onto the stack
void push(int item) {
if (tos == 9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
int pop() {
if (tos < 0) {
System.out.println("Stack underflow.");
return 0;
} else
return stck[tos--];
}
}
84
Testing Stack class
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
// push some numbers onto the stack
for (int i = 0; i < 10; i++)
mystack1.push(i);
for (int i = 10; i < 20; i++)
mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for (int i = 0; i < 10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for (int i = 0; i < 10; i++)
System.out.println(mystack2.pop());
}
}
85
Overloading Methods
class OverloadDemo {
void test() {
System.out.println("No parameters");
}

// Overload test for one integer parameter.


void test(int a) {
System.out.println("a: " + a);
}

// Overload test for two integer parameters.


void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}

// Overload test for a double parameter


double test(double a) {
System.out.println("double a: " + a);
return a * a;
}
}
86
Overloading Methods (cont.)
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}

87
Overloading Constructors
class Box {
double width; double height; double depth;

// constructor used when all dimensions specified


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}

// compute and return volume


double volume() {
return width * height * depth;
}
88
}
Overloading Constructors (cont.)
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}

89
Passing Objects as Parameters
class Test {
int a, b;

Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equalTo(Test o) {
if (o.a == a && o.b == b)
return true;
else
return false;
}
}

class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
}
90
}
Passing Objects as Parameters to Constructors
class Box {
double width;
double height;
double depth;

// Notice this constructor. It takes an object of type Box.


Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}

Box(double w, double h, double d) {


width = w;
height = h;
depth = d;
}

Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
...
91
}
Call-by-value vs. Call-by-reference
• Call-by-value
• Copies the value of an argument into the formal parameter of the
subroutine.
• Changes made to the parameter of the subroutine have no effect on the
argument.
• Call-by-reference
• A reference to an argument (not the value of the argument) is passed to
the parameter.
• Inside the subroutine, this reference is used to access the actual
argument specified in the call.
Java use call-by-value ONLY

92
Returning Objects
class Test {
int a;

Test(int i) {
a = i;
}

Test incrByTen() {
Test temp = new Test(a + 10);
return temp;
}
}

class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: " + ob2.a);
}
}
93
Recursion (example 1)
class Factorial {
// this is a recursive method
int fact(int n) {
int result;
if (n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
}

class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
} 94
Recursion (example 2)
class Recursion2 {
int values[];

Recursion2(int i) { [0] 0
values = new int[i];
} [1] 1
[2] 2
// display array -- recursively [3] 3
void printArray(int i) {
[4] 4
if (i == 0)
return; [5] 5
else [6] 6
printArray(i - 1); [7] 7
System.out.println("[" + (i - 1) + "] " + values[i - 1]);
} [8] 8
[9] 9
public static void main(String args[]) {
Recursion2 ob = new Recursion2(10);
int i;
for (i = 0; i < 10; i++)
ob.values[i] = i;
ob.printArray(10);
}
}
95
Introducing Access Control
class Test {
int a; // default/package access
public int b; // public access
private int c; // private access
public void setC(int i) { // set c's value
c = i;
}
public int getC() { // get c's value
return c;
}
}

class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setC(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getC());
}
96
}
Return to Stack class
class Stack {
private int stck[] = new int[10];
private int tos;

Stack() {
tos = -1;
}

public void push(int item) {


if (tos == 9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}

public int pop() {


if (tos < 0) {
System.out.println("Stack underflow.");
return 0;
} else
return stck[tos--];
}
}
97
Testing the new Stack class
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
// push some numbers onto the stack
for (int i = 0; i < 10; i++)
mystack1.push(i);
for (int i = 10; i < 20; i++)
mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for (int i = 0; i < 10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for (int i = 0; i < 10; i++)
System.out.println(mystack2.pop());
// these statements are not legal
// mystack1.tos = -2;
// mystack2.stck[3] = 100;
}
}

98
Understanding static members
• A static member belongs to the class, not to the object of that
class type.
• can be accessed before any objects of its class are created, and
without reference to any object.
• Static data members:
• Similar to global variables.
• Shared by all instances of the class.
• Static Methods:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.

99
Understanding static members (example 1)
class UseStatic {
static int a = 3;
static int b;

static void meth(int x) {


System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}

public static void main(String args[]) {


meth(42);
}
}

100
Understanding static members (example 2)
class StaticDemo {
static int a = 42;
static int b = 99;

static void callme() {


System.out.println("a = " + a);
}
}

class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}

101
Initialization blocks
• Non-static initialization block
• Used to as a part of constructors.
• They are added to the beginning of each constructor (unless it is started
with this() constructor call).

• Static initialization block


• Executed once when the class is loaded
• Can only access static data/method members.

102
Initialization blocks (example)
class InitBlockDemo{
public static void main(String[] args) {
System.out.println("Starting the main() method");
InitBlock ib1; // declare an InitBlock variable
InitBlock ib2; // declare another InitBlock variable
InitBlock ib3; // declare another InitBlock variable
System.out.println("After declaring the reference");
ib1 = new InitBlock();
ib2 = new InitBlock(17);
ib3 = new InitBlock(ib2);
System.out.println("After creating the objects");
ib1.displayValues();
ib2.displayValues();
ib3.displayValues();
}
}

103
Initialization blocks (example)
class InitBlock {
private int a;
private static int b = 2;
// Static initialization block
static {
System.out.println("Inside the static initialization block");
b = 5;
}
// Non-static initialization block
{
System.out.println("Inside the non-static initialization block");
a = 2;
}
InitBlock() {
System.out.println("Inside the InitBlock() constructor");
}
InitBlock(int v) {
System.out.println("Inside the InitBlock(int) constructor");
a = v;
}
InitBlock(InitBlock v) {
System.out.println("Inside the InitBlock(InitBlock) constructor");
a = v.a;
}
public void displayValues() {
System.out.println("a = " + a);
System.out.println("b = " + b);
}
} 104
Constants, the final variables
• Final variables are declared with final keyword. They cannot
be changes later.
• They should be initialized:
• When they are declared
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5
• Before the first use (like in constructors), This allows values to be
determined during the execution time.
final int FILE_NEW;
...
FILE_NEW = 1;

105
Arrays revisited, array length
class Length {
public static void main(String args[]) {
int[] a1 = new int[5];
int[] a2 = { 3, 5, 7, 1, 8, 99, 44, -10 };
int[] a3 = { 4, 3, 2, 1 };

printArray(a1);
printArray(a2);
printArray(a3);
}

public static void printArray(int[] a) {


System.out.println("length of the array is " + a.length);
for (int i = 0; i < a.length; i++) {
System.out.println("array[ " + i + " ] = " + a[i]);
}
System.out.println();
}
} 106
Improved Stack class
class Stack { class TestStack2 {
private int stck[]; public static void main(String args[]) {
private int tos; Stack mystack1 = new Stack(5);
Stack mystack2 = new Stack(8);
Stack(int size) { // push some numbers onto the stack
stck = new int[size]; for (int i = 0; i < mystack1.size(); i++)
tos = -1; mystack1.push(i);
} for (int i = 0; i < mystack2.size(); i++)
mystack2.push(i);
public void push(int item) { // pop those numbers off the stack
if (tos == stck.length - 1) // use length member System.out.println("Stack in mystack1:");
System.out.println("Stack is full."); for (int i = 0; i < mystack1.size(); i++)
else System.out.println(mystack1.pop());
stck[++tos] = item; System.out.println("Stack in mystack2:");
} for (int i = 0; i < mystack2.size(); i++)
System.out.println(mystack2.pop());
public int pop() { }
if (tos < 0) { }
System.out.println("Stack underflow.");
return 0;
} else
return stck[tos--];
}

public int size() {


return stck.length;
}
}
107
Nested and Inner Classes
• A class defined within another class.
• The scope of a nested class is bounded by the scope of its enclosing
class. if class B is defined within class A, then B does not exist
independently of A.
• A nested class has access to the members, including private
members, of the class in which it is nested.
• The enclosing class does not have access to the members of the
nested class.
• A nested class that is declared directly within its enclosing class
scope is a member of its enclosing class.
• It is also possible to declare a nested class that is local to a block.
• There are two types of nested classes:
• static classes,
• non-static classes (inner classes).

108
Inner Classes (example 1)
class Outer {
int outer_x = 100;

void test() {
Inner inner = new Inner();
inner.display();
}

// this is an inner class


class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}

class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
109
}
Inner Classes (example 2)
class Outer {
int outer_x = 100;

void test() {
for (int i = 0; i < 5; i++) {
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
Inner inner = new Inner();
inner.display();
}
}
}

class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
110
}
The String class
• Every string you create is actually an object of type String.
• Even string constants are actually String objects.
System.out.println("This is a String, too");

• Objects of type String are immutable; once a String object is


created, its contents cannot be altered.
• If you need to change a string, you can always create a new one that
contains the modifications.
• Java defines peer classes of String, called StringBuffer and StringBuilder,
which allow strings to be altered, so all of the normal string
manipulations are still available in Java.

111
The String class (example 1)

class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}

112
The String class (example 2)
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " + strOb1.length());
System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3));
if (strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if (strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
}

113
The String class (example 3)

class StringDemo3 {
public static void main(String[] args) {
String[] str = { "one", "two", "three" };
for (int i = 0; i < str.length; i++)
System.out.println("str[" + i + "]: " + str[i]);
}
}

114
The String class (example 4)

class CommandLine {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
java CommandLine this is a test 100 -1

args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1

115
The String class (example 5)
class StringDemo4 { str1.equals(str2) ? true
public static void main(String[] args) { str1.equals(str3) ? false
String str1 = "ABC"; str4.equals(str5) ? true
String str2 = "ABC"; str4.equals(str6) ? true
String str3 = "DEF"; str4.equals(str7) ? true
String str4 = "ABCDEF"; str4.equals(str8) ? true
String str5 = "ABC" + "DEF"; str4.equals(str9) ? true
String str6 = "AB" + "CD" + "EF";
String str7 = "ABCDE"; str1 == str2 ? true
str7 = str7 + "F"; str1 == str3 ? false
String str8 = "ABC" + str3; str4 == str5 ? true
String str9 = str1 + str3; str4 == str6 ? true
str4 == str7 ? false
System.out.println("str1.equals(str2) ? " + str1.equals(str2)); str4 == str8 ? false
System.out.println("str1.equals(str3) ? " + str1.equals(str3)); str4 == str9 ? false
System.out.println("str4.equals(str5) ? " + str4.equals(str5));
System.out.println("str4.equals(str6) ? " + str4.equals(str6));
System.out.println("str4.equals(str7) ? " + str4.equals(str7));
System.out.println("str4.equals(str8) ? " + str4.equals(str8));
System.out.println("str4.equals(str9) ? " + str4.equals(str9));
System.out.println();
System.out.println("str1 == str2 ? " + (str1 == str2));
System.out.println("str1 == str3 ? " + (str1 == str3));
System.out.println("str4 == str5 ? " + (str4 == str5));
System.out.println("str4 == str6 ? " + (str4 == str6));
System.out.println("str4 == str7 ? " + (str4 == str7));
System.out.println("str4 == str8 ? " + (str4 == str8));
System.out.println("str4 == str9 ? " + (str4 == str9));
} 116
}
Varargs: Variable-Length Arguments (JDK5)
class PassArray {

static void vaTest(int[] v) {


System.out.print("Number of args: " + v.length + " Contents: ");
for (int x : v)
System.out.print(x + " ");
System.out.println();
}

public static void main(String[] args) {


// Notice how an array must be created to
// hold the arguments.
int[] n1 = { 10 };
int[] n2 = { 1, 2, 3 };
int[] n3 = {};
vaTest(n1); // 1 arg
vaTest(n2); // 3 args
vaTest(n3); // no args
}
}
117
Varargs (example 1)
class VarArgs {
// vaTest() now uses a vararg.
static void vaTest(int... v) {
System.out.print("Number of args: " + v.length + " Contents: ");
for (int x : v)
System.out.print(x + " ");
System.out.println();
}

public static void main(String args[]) {


// Notice how vaTest() can be called with a
// variable number of arguments.

vaTest(10); // 1 arg
vaTest(1, 2, 3); // 3 args
vaTest(); // no args
}
}
118
Varargs (example 2)
class VarArgs2 {
// Here, msg is a normal parameter and v is a varargs parameter.
static void vaTest(String msg, int... v) {
System.out.print(msg + v.length + " Contents: ");
for (int x : v)
System.out.print(x + " ");
System.out.println();
}

public static void main(String args[]) {


vaTest("One vararg: ", 10);
vaTest("Three varargs: ", 1, 2, 3);
vaTest("No varargs: ");
}
}

119
Overloading Varargs Methods
class VarArgs3 {
static void vaTest(int... v) {
System.out.print("vaTest(int ...): " + "Number of args: " + v.length + " Contents: ");
for (int x : v)
System.out.print(x + " ");
System.out.println();
}

static void vaTest(boolean... v) {


System.out.print("vaTest(boolean ...) " + "Number of args: " + v.length + " Contents: ");
for (boolean x : v)
System.out.print(x + " ");
System.out.println();
}

static void vaTest(String msg, int... v) {


System.out.print("vaTest(String, int ...): " + msg + v.length + " Contents: ");
for (int x : v)
System.out.print(x + " ");
System.out.println();
}

public static void main(String args[]) {


vaTest(1, 2, 3);
vaTest("Testing: ", 10, 20);
vaTest(true, false, false);
}
}
120
Overloading Varargs Methods ambiguity
class VarArgs4 {
static void vaTest(int... v) {
System.out.print("vaTest(int ...): " + "Number of args: " + v.length + " Contents: ");
for (int x : v)
System.out.print(x + " ");
System.out.println();
}

static void vaTest(boolean... v) {


System.out.print("vaTest(boolean ...) " + "Number of args: " + v.length + " Contents: ");
for (boolean x : v)
System.out.print(x + " ");
System.out.println();
}

public static void main(String args[]) {


vaTest(1, 2, 3); // OK
vaTest(true, false, false); // OK
vaTest(); // Error: Ambiguous!
}
}

121
Inheritance
• Inheritance is one of the cornerstones of object-oriented programming
because it allows the creation of hierarchical classifications.
• You can create a general class that defines traits common to a set of related
items.
• The new class can then be inherited by other, more specific classes, each
adding those things that are unique to it.
• A class that is inherited is called a superclass. The class that does the
inheriting is called a subclass.
• A subclass is a specialized version of a superclass. It inherits all of the
members defined by the superclass and adds its own, unique elements.
• The general form of a class declaration that inherits a superclass is:
class subclass-name extends superclass-name {
// body of class
}

122
Inheritance Basics
class A { class B extends A {
int i, j; int k;

void showij() { void showk() {


System.out.println("i and j: "+i+" "+j); System.out.println("k: " + k);
} }
}
void sum() {
System.out.println("i+j+k: “ + (i+j+k));
class SimpleInheritance {
}
public static void main(String args[]) {
}
A superOb = new A();
B subOb = new B();
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
} 123
Member Access and Inheritance
/*
In a class hierarchy, private members remain private to their class.
This program contains an error and will not compile.
*/

// Create a superclass.
class A {
int i; // public by default
private int j; // private to A

void setij(int x, int y) {


i = x;
class Access {
j = y;
public static void main(String args[]) {
}
B subOb = new B();
}
subOb.setij(10, 12);
subOb.sum();
// A's j is not accessible here.
System.out.println("Total is "+subOb.total);
class B extends A {
}
int total;
}
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
124
Extending the Box class
class Box { class BoxWeight extends Box {
double width; double weight; // weight of box
double height;
double depth; BoxWeight(double w, double h, double d, double m) {
width = w;
Box(Box ob) { // pass object to constructor height = h;
width = ob.width; depth = d;
height = ob.height; weight = m;
depth = ob.depth; }
} }
Box(double w, double h, double d) {
width = w;
height = h; class ColorBox extends Box {
class DemoBoxWeight {
depth = d; int color; // colorargs[])
of box {
public static void main(String
}
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
Box() { ColorBox(double w, double h,3,
double d, int c) {
BoxWeight mybox2 = new BoxWeight(2, 4, 0.076);
width = -1; // use -1 to indicate width = w;
double vol;
height = -1; // an uninitialized height = h;
vol = mybox1.volume();
depth = -1; // box depth = d;
System.out.println("Volume of mybox1 is " + vol);
} color = c;
System.out.println("Weight of mybox1 is " + mybox1.weight);
Box(double len) { }
System.out.println();
width = height = depth = len; } mybox2.volume();
vol =
}
System.out.println("Volume of mybox2 is " + vol);
double volume() {
System.out.println("Weight of mybox2 is " + mybox2.weight);
return width * height * depth;
}
}
}
}

125
A Superclass Variable Can Reference a Subclass Object
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println();
// assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
// The following statement is invalid because plainbox
// does not define a weight member.
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}

126
The super keyword
• The super has two general forms:
• The first calls the superclass’ constructor.
super(arg-list);
• The second is used to access a member of the superclass that has been
hidden by a member of a subclass.
super.member

127
Calling superclass constructor
class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()

BoxWeight(double w, double h, double d, double m) {


super(w, h, d); // call superclass constructor
weight = m;
}
}

128
A complete implementation of BoxWeight
class Box { class BoxWeight extends Box {
private double width; double weight;
private double height;
private double depth; BoxWeight(BoxWeight ob) {
super(ob);
Box(Box ob) { weight = ob.weight;
width = ob.width; }
height = ob.height;
depth = ob.depth; BoxWeight(double w, double h, double d, double m) {
} super(w, h, d);
Box(double w, double h, double d) { weight = m;
width = w; }
height = h;
depth = d; BoxWeight() {
} super();
Box() { weight = -1;
width = -1; }
height = -1;
depth = -1; BoxWeight(double len, double m) {
} super(len);
Box(double len) { weight = m;
width = height = depth = len; }
} }
double volume() {
return width * height * depth;
}
}

129
BoxWeight demo
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}
}
130
The Second Use for super
class A {
int i;
}

class B extends A {
int i; // this i hides the i in A

B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}

void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}

class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
131
Multilevel Hierarchy
class Box { class BoxWeight extends Box {
private double width; double weight;
private double height;
private double depth; BoxWeight(BoxWeight ob) {
super(ob);
Box(Box ob) { weight = ob.weight;
width = ob.width; }
height = ob.height;
depth = ob.depth; BoxWeight(double w, double h, double d, double m) {
} super(w, h, d);
Box(double w, double h, double d) { weight = m;
width = w; }
height = h;
depth = d; BoxWeight() {
} super();
Box() { weight = -1;
width = -1; }
height = -1;
depth = -1; BoxWeight(double len, double m) {
} super(len);
Box(double len) { weight = m;
width = height = depth = len; }
} }
double volume() {
return width * height * depth;
}
}

132
Multilevel Hierarchy (cont.)
class Shipment extends BoxWeight {
double cost;

Shipment(Shipment ob) {
super(ob);
cost = ob.cost;
}
Shipment(double w, double h, double d, double m, double c) {
super(w, h, d, m);
cost = c;
}
Shipment() {
super();
cost = -1;
}
Shipment(double len, double m, double c) {
super(len, m);
cost = c;
}
}
133
Multilevel Hierarchy (cont.)
class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is " + shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is " + shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}

134
Constructors calling order
class A {
A() {
System.out.println("Inside A's constructor.");
}
}

class B extends A {
B() {
System.out.println("Inside B's constructor."); Inside A's constructor.
} Inside B's constructor.
} Inside C's constructor.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}

class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
135
Constructors calling order (2)
class A { class CallingCons {
A() { public static void main(String args[]) {
System.out.println("Inside A() constructor."); A a1 = new A(); System.out.println();
} A a2 = new A(5); System.out.println();
A(int a) { B b1 = new B(); System.out.println();
this(); B b2 = new B(5); System.out.println();
System.out.println("Inside A(int) constructor."); C c1 = new C(); System.out.println();
} C c2 = new C(5); System.out.println();
} }
class B extends A { } Inside A() constructor.
B() {
System.out.println("Inside B() constructor."); Inside A() constructor.
} Inside A(int) constructor.
B(int a) {
System.out.println("Inside B(int) constructor.");
} Inside A() constructor.
} Inside B() constructor.
class C extends B {
{ Inside A() constructor.
System.out.println("Inside C initialization block."); Inside B(int) constructor.
}
C() { Inside A() constructor.
super(2); Inside B(int) constructor.
System.out.println("Inside C() constructor."); Inside C initialization block.
}
Inside C() constructor.
C(int a) {
this();
System.out.println("Inside C(int) constructor."); Inside A() constructor.
} Inside B(int) constructor.
} Inside C initialization block.
Inside C() constructor.
Inside C(int) constructor.

136
Method Overriding
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j); i and j: 1 2
}
}
k: 3
class B extends A {
int k;
B(int a, int b, int c) { i and j: 1 2
super(a, b);
k = c;
k: 3
}
void show() {
super.show();
System.out.println("k: " + k);
}
}

class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show();
}
} 137

You might also like