Professional Documents
Culture Documents
UNIT 2
BASIC JAVA & OBJECT ORIENTED
Faculty of Computer Science 2007
Universitas Indonesia
Objectives
Introduction to Class
Statement Control in java
Initialization
Object creation and lifetime
Constructor
1
9/15/2010
2
9/15/2010
Example
3
9/15/2010
Control Structures
Two basic types of control structures:
Selection: Given one or more possible choices: choose which section (if
any) of an algorithm to execute.
Iteration: Repeat a section of an algorithm provided required conditions
are met. Also known as looping.
Selection Control:
The If−Then_Else statement. Provides up to two possible alternatives.
The Case statement. Provides any number of possible alternatives.
Repetition Control:
while
do…while
for
4
9/15/2010
Exercise
What is the output of the following :
int k = 100;
for (int i = 1; i <3; i++)
{
System.out.println("This is set " +i);
for(int k = 10; k>5; k--)
{
System.out.println(k);
}
System.out.println(k + "\n");
}
Exercise
Consider the following commission scheme:
5
9/15/2010
Exercise
for(int m = 10; m>5; m--)
{
for(int i=0; i<m; i+=2)
{
k = m + i;
}
}
System.out.println(―k =‖ + k);
6
9/15/2010
Conditional Operator (? : )
Java’s only ternary operator (takes three operands)
? : and its three operands form a conditional
expression
Entire conditional expression evaluates to the second
operand if the first operand is true
Entire conditional expression evaluates to the third
operand if the first operand is false
Conditional Operator (? : )
int ternary(int i) {
return i < 10 ? i * 100 : i * 10;
}
int alternative(int i) {
if (i < 10)
return i * 100;
else
return i * 10;
}
7
9/15/2010
switch(c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': System.out.println("vowel"); break;
case 'y':
case 'w':
System.out.println("Sometimes a vowel");
break;
default: System.out.println("consonant");
}
8
9/15/2010
Corrected Version
The correct version should be:
switch ( choice)
{
case ’Y’: case ’y’:
repeatAgain = true;
break;
case ’N’: case ’n’:
repeatAgain = false;
}
9
9/15/2010
break/continue
Alter flow of control
break statement
Causes immediate exit from control structure
Used in while, for, do…while or switch statements
continue statement
Skips remaining statements in loop body
Proceeds to next iteration
Used in while, for or do…while statements
break Statement
1 // Fig. 5.12: BreakTest.java
2 // break statement exiting a for statement.
3 public class BreakTest
4 {
5 public static void main( String args[] )
6 {
7 int count; // control variable also used after loop terminates
8
9 for ( count = 1; count <= 10; count++ ) // loop 10 times
10 {
11 if ( count == 5 ) // if count is 5,
12 break; // terminate loop
13
14 System.out.printf( "%d ", count );
15 } // end for
16
17 System.out.printf( "\nBroke out of loop at count = %d\n", count );
18 } // end main
19 } // end class BreakTest
1 2 3 4
Broke out of loop at count = 5
10
9/15/2010
continue Statement
1 // Fig. 5.13: ContinueTest.java
2 // continue statement terminating an iteration of a for statement.
3 public class ContinueTest
4 {
5 public static void main( String args[] )
6 {
7 for ( int count = 1; count <= 10; count++ ) // loop 10 times
8 {
9 if ( count == 5 ) // if count is 5,
10 continue ; // skip remaining code in loop
11
12 System.out.printf( "%d " , count );
13 } // end for
14
15 System.out.println ( "\nUsed continue to skip printing 5" );
16 } // end main
17 } // end class ContinueTest
1 2 3 4 6 7 8 9 10
Used continue to skip printing 5
Object Creation
To create an object you must:
Declare a variable to be of the desired class
Use the new operator to create an instance of the class
Froggclass froggie;
froggie = new Froggclass(“Kermit”);
11
9/15/2010
Primitive variables:
Directaccess to the data
Modification of the data involves modification to the
contents of the variable
Reference variables:
Indirectaccess to the data
Modification of the data within an object must be done
via object method
Example:
frogName = froggie.getName();
froggie.setName(“Kermit”);
Initialization
What is stored in a variable when it is created?
Java auto-initializes variables
Primitive variables:
Numeric set to zero
char set to blank
boolean set to false
Object variables:
Set to null
null represents an invalid memory address
Not all programming languages auto-initialize so it is extremely bad
programming practice to rely on auto-initialization
You should always explicitly initialize variables
12
9/15/2010
Order of Initialization
Within a class, the order of initialization is
determined by the order that the variables are
defined within the class.
The variable definitions may be scattered
13
9/15/2010
Example:
class Counter {
int i;
Counter() { i = 7; }
// . . .
The variable i will be first initialized to 0, then to 7.
This is true with all the primitive types and with object
references, including those that are given explicit
initialization at the point of definition.
Constructors
Used to perform any initialization required.
The name of the constructors must be identical to the name of the
class.
Even though the constructor is returning a value to the calling module,
we do not specify a return type for the method (as it must be a
pointer to the object).
When an object is instantiated, storage is allocated and the
constructor is called
It is guaranteed that an object is initialized before you can use it.
The object reference returned by the new operator is essentially returned
by the constructor
After we have used a constructor to create an object, we call the
object an instance of a class.
14
9/15/2010
The Constructor
//: c04:SimpleConstructor.java
// Demonstration of a simple constructor.
class Rock {
Rock() { // This is the constructor
System.out.println("Creating Rock");
}
}
public class SimpleConstructor {
public static void main(String[] args) {
for(int i = 0; i < 10; i++)
new Rock();
}
}
15
9/15/2010
//: c04:SimpleConstructor2.java
// Constructors can have arguments.
class Rock {
int myNumber;
Rock(int i) { // This is the constructor
myNumber = i;
System.out.println("Creating Rock No: " + myNumber);
}
}
public class SimpleConstructor {
public static void main(String[] args) {
for(int i = 0; i < 10; i++)
new Rock(i);
}
}
16
9/15/2010
The Constructor
// Constructors can be overloaded.
class Rock {
int myNumber;
// myNumber is left at 0
}
Rock(int i) { // This is the constructor
myNumber = i;
}
} // end class Rock
17
9/15/2010
Default Constructor
//: c04:DefaultConstructor.java
class Bird {
int i;
}
Default Constructor
// Oops! NoDefaultConstructor.java
class Bird {
int wingspan;
Bird(int i) {
wingspan = i;
} // end constructor
}
18
9/15/2010
Default Constructor
A constructor which has no parameters is called a
default constructor.
If a class definition does not include any constructors
then a default constructor is assumed.
If a class has not explicitly been defined to inherit
from a specified super class then it is assumed to
inherit from the predefined class java.lang.Object.
The default constructor for the super class is always
called prior to executing the constructor for the sub
class.
19
9/15/2010
Exercise
Create a class with a no-args constructor that
prints a message.
Include a main method that instantiates an
20
9/15/2010
quitButton.addActionListener( this);
21
9/15/2010
22
9/15/2010
other constructor!
23
9/15/2010
24
9/15/2010
25
9/15/2010
Specifying Initialization
You can specify an initialization expression at the
point you define a variable.
class Measurement {
boolean b = true;
char c = 'x';
short s = 0xff;
int i = 999;
}
You can initialize non-primitives in the same way.
String s = new String("Hello");
Specifying Initialization
You can even call a method:
String s = getDefaultString();
The method can have arguments, but the arguments
cannot be other class members that haven't been
initialized yet.
Order is important!
26
9/15/2010
Order of Initialization
Order of Initialization
Explicit static initialization
Java allows you to group static initializations inside
a static block:
static int i;
static {
i = 999;
}
This block is executed the first time you instantiate
an object of the class type, or the first time you
access a static member of the class.
27
9/15/2010
Order of Initialization
28
9/15/2010
29
9/15/2010
30
9/15/2010
31