You are on page 1of 31

9/15/2010

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

Introduction to Class Diagram


 A class diagram shows the existence of classes and
their relationships in the logical view of a system

2
9/15/2010

Example

3
9/15/2010

Java’s Control Statement


 Java'ssyntax is made to mimic C
 Control Statements in Java is similar with C.

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:

 Create the control statement to determine the


correct monthly income

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);

 What is the output of the above code?


 Re-write both blocks above using while loops.

If-Then-Else: Java Implementation

public class IfElse


{
static int test(int testval, int target) {
if(testval > target)
return +1;
else if(testval < target)
return -1;
else
return 0;
}
public static void main(String[] args) {
System.out.println(test(10, 5));
System.out.println(test(5, 10));
System.out.println(test(5, 5));
}
}

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 Multiple Selection Statement

 When the expression matches a case, the statements


in the case are executed until:
 A break statement is encountered or
 The end of the switch statement is encountered

 The default clause is optional


 If the default clause is supplied then it is executed if
the switch expression does not match any of the case
constants

switch Multiple Selection Statement

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

Mistakes are easy with switch

 Care must be taken to ensure that the break statements are


placed where they are required. The compiler cannot check
this for you because the break statement is not required to
follow each case.
switch ( choice)
{
case ’Y’: case ’y’:
repeatAgain = true;
case ’N’: case ’n’:
repeatAgain = false;
}
 What is the error in the above statement?

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 and continue Statement

 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

 The variable is set to the memory location of the


object
 It becomes a reference to the object
 Example:

Froggclass froggie;
froggie = new Froggclass(“Kermit”);

11
9/15/2010

Primitive vs Reference Variables

 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

Initialization and Clean Up


 Many C bugs occur when the programmer forgets to
initialize a variable. This is especially true with
libraries when users don’t know how to initialize a
library component, or even that they must.
 Cleanup is a special problem because it’s easy to
forget about an element when you’re done with it,
since it no longer concerns you.
 Thus, the resources used by that element are
retained and you can easily end up running out of
resources (most notably, memory).

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

throughout and in between method definitions,


but the variables are initialized before any
methods can be called—even the constructor

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();
}
}

 Like any method, the constructor can have


arguments.
 The constructor arguments allow you to provide
initialization parameters when instantiating an
object

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);
}
}

 There may be a variety of ways in which the object


can be created.
 A constructor should be defined for each case.
 Method overloading is used to select the correct
constructor for each instantiation.

16
9/15/2010

The Constructor
// Constructors can be overloaded.
class Rock {
int myNumber;

Rock() { // This is the constructor

// myNumber is left at 0
}
Rock(int i) { // This is the constructor
myNumber = i;
}
} // end class Rock

 The new operator must call a constructor


 The constructor must both exist and be exposed
(remember access control?) or the compiler will give
an error
 If you don't code a constructor in the class definition,
the compiler supplies a default constructor with no
arguments
 also called the "no args" constructor
 If you define any constructors, the compiler will not
provide a default!

17
9/15/2010

Default Constructor
//: c04:DefaultConstructor.java
class Bird {
int i;
}

public class DefaultConstructor {


public static void main(String[] args) {
Bird nc = new Bird(); // default!
}
}

Default Constructor
// Oops! NoDefaultConstructor.java
class Bird {
int wingspan;
Bird(int i) {
wingspan = i;
} // end constructor
}

public class NoDefaultConstructor {


public static void main(String[] args) {
Bird nc = new Bird(); // Compiler error!
}
}

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.

The Java String Class


 Generally a string is a collection of 1 or more characters
 The Java String class provide us with the facility to
handle strings
 String variables are objects but they can be used as if
they were primitive variables
String unitName = “Design and Programming”;
 Can also be treated as an object
String unitName = new String(“Design and Programming”);
 String can also be concatenated using the plus operator
 Example: int x=42;
String message;
message = “x = “ + x;

19
9/15/2010

Exercise
 Create a class with a no-args constructor that
prints a message.
 Include a main method that instantiates an

instance of the class.


 Add a constructor that takes a String as an
argument and prints that.

Referring to a Object from Within Itself:this

 It is sometimes necessary to for an object to refer to


itself.
 This is a problem for a Java programmer because
they need to express this self−reference in the class
design. i.e. They cannot write the object!
 In the class design, whenever the self−reference is
required the reserved word this is used.
 When an object is created from the class design then
this will be replaced by the actual address of that
object.

20
9/15/2010

The Two Uses of this


 The two situations where self−referencing is required are:
 When the address of this object needs to be passed as a parameter to
a method which resides outside of the class specification for the object.
 When a Java programmer wishes to name a local method IMPORT
parameter with the same name as its corresponding class field.
 Example of when the address of this object needs to be
passed on to some other part of the program:
 An object which will display a GUI has a close button object declared
within in it.
 The close button needs a reference to this object so that it can inform it
when the button has been pressed.

quitButton.addActionListener( this);

The ―this‖ Keyword


// Simple use of the "this" keyword
public class Leaf {
int i = 0;
Leaf increment() {
i++;
return this;
} // end method increment
void print() {System.out.println("i="+i);
public static void main(String[] args) {
Leaf l = new Leaf();
l.increment().increment().print();
} // end method main
} // end class Leaf

21
9/15/2010

The ―this‖ Keyword


// Another use of the "this" keyword
public class Leaf {
int i = 0; // i is part of the object
void increment(int i) { // i as local, too
this.i = this.i + i; // The compiler knows!
} // end method increment
} // end class Leaf

Constructor Calling Constructor


 When you define a class with several
constructors, you'd often like to call one
constructor from another to avoid duplicating
code.
 A constructor is called using: this

 You can, using this with an argument list:

this(); // calls no-args constructor


this(27); // constructor with numeric arg
 But there are rules!

22
9/15/2010

Constructor Calling Constructor


 A constructor can call another constructor only
in the first statement of the constructor.
 This implies that a constructor can only call one

other constructor!

Constructor Calling Constructor


 Modify your class so that the no-args
constructor, instead of printing a specified
value, calls the other constructor

23
9/15/2010

The Meaning of Static


 Now that we've seen the this keyword, we're more
able to deal with static .
 Members that are part of a particular object can
be referenced only with an object reference
(including this ).
 Members that are part of a class - and shared by
all objects of that type - are not referred to by
object reference.
 Java: Static method and static variable
→ C: Global function and global variable

Static Data Initialization


 When you say something is static, it means that data
or method is not tied to any particular object instance
of that class.
 So even if you’ve never created an object of that class
you can call a static method or access a piece of static
data.
 With ordinary, non-static data and methods, you must
create an object and use that object to access the
data or method, since non-static data and methods
must know the particular object they are working with.

24
9/15/2010

The Meaning of Static


 Because static members exist whether or not
any object of the type is instantiated, static
members can reference only other static
members
 static methods can call only other static methods
 static methods can reference only static variables

The Meaning of Static


 Static methods are also referred to as "class
methods", and static variables as "class
variables, because they are shared by all
objects in the class.
 Is this a way of cheating on the "everything is

objects" and "there are no globals?" Only until


you get a more complete understanding of
how things such as class loading really work.

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

 Static variable initialization


 The first time an object of a given type is
instantiated, or a static member of that class
is referenced, the JVM locates the .class
file and loads it into memory.
 When the class is loaded, all static initializers
are run in the order they are encountered in
the .class file.

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

 Non-static variable allocation and


initialization.
 Constructor is called.

Naming Variables, Methods, and Classes

 Programmer constantly has to invent names for classes, methods,


variables, constants, etc
 We call these names identifiers
 You need to give considerable thought to every name you create –
they are your bricks glued together with the mortar of the operators
 Names should be:
 Unique
 Meaningful
 Unambiguous
 Consistent
 Enhance by case
 There are also reserved words (which are always in lower case):
identifiers with special meaning which must be used in predefined
ways e.g. class, public, etc

28
9/15/2010

Rules for Identifiers


 Consist only of letters, digits, _ or $
 Cannot start with a digit
 Cannot be a reserved word
 Case sensitive, example:
 StNo, stno, STNO, Stno are all different variables
 Can be any length

Guidelines for Identifers


 Meaningful: give a name that truly reflects the nature
of value it hold e.g. studentNo is different to
noOfStudents
 Readable: e.g. studentNo not stdnbr
 Consistent: be consistent in all aspects – abbreviation,
case, identation, etc
 Avoid verbosity:
identification_Number_Of_The_Studen
t that length is unlimited avoid overly long names
 Use underscore to good effect
 Use capitalization to good effect

29
9/15/2010

Java Identifier Naming Convention

 Constants should be completely uppercase


 Example:
public static final int MAXSTUDENTS =
30000;
 Class name should be capitalized
 Example:
public class ThisIsAClass
 Methods and variables should be internally
capitalized
 Example:
public void thisIsAMethod();
private double thisIsAVariable;

Classes in Java: .java Files and Class Names

 The naming conventions in java specify that a class name


should be capitalised.
 Each class definition should be in its own .java file.
 The name of the .java file should follow the same
convention.
 Problems can sometimes arise when using an operating system
which is not case sensitive (i.e. MS−DOS).
 The act of compiling an application will result in a .class
file being generated for each Java class defined. This
should mean for each .java file.
 The class files will contain the Java byte code to be
interpreted when the application is run using the Java
interpreter.

30
9/15/2010

Classes in Java: .java Files and Class Names

 A reasonable size application can have hundreds of .java files!


 This means that you have to stay organised
 Keep all of the .java files for an application in one folder
 DO NOT keep any .java files which are not associated with the
application in the folder.
 Name the folder with the same name as the application.
 Much of the Java that you write might be applicable across a
number of applications.
 These general purpose classes should be grouped together in a
library which is accessible to all of your applications.
 In Java we call such a library a package.

Nouns and Verbs


 Like algorithm design, the determination of what classes should be used is
still, by and large, an art form.
 One shallow technique is the nouns and verb approach:
 Nouns are mapped to classes.
 Verbs are mapped to sub modules within classes
 The definition of noun and verb gets stretched to cover collections of words.
 Result is that:
 sub module names should always describe an action (i.e. getName)
 Class names should always describe a thing (e.g. PersonClass)
 It is important to note that the set of classes proposed will change over the
time the software is being designed.
 This is exactly the same principle as the steps in algorithms changing as the
algorithm is being refined.
 This approach is both shallow and naive but its a very good starting point.

31

You might also like