• No results found

Core Java Handout v1.0

N/A
N/A
Protected

Academic year: 2021

Share "Core Java Handout v1.0"

Copied!
379
0
0

Loading.... (view fulltext now)

Full text

(1)

Handout: Core Java

Version: Core Java/Handout/0408/1.0

Date: 30-04-08

Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com

(2)

TABLE OF CONTENTS

Introduction ... 28 

About this Module ... 28 

Target Audience ... 28 

Module Objectives ... 28 

Pre-requisite ... 28 

Session 02: Introduction to OOPS ... 29 

Learning Objectives ... 29 

Object Oriented Programming ... 29 

Procedural Versus OOP ... 29 

Objects ... 29 

Class ... 30 

Try It Out ... 30 

Tips and Tricks ... 31 

Summary ... 31 

Test Your Understanding ... 31 

Session 03: Introduction to OOPS ... 33 

Learning Objectives ... 33  Abstraction ... 33  Encapsulation ... 33  Class Hierarchy ... 34  Inheritance ... 34  Need of inheritance ... 35  Try It Out ... 35 

Tips and Tricks ... 36 

Summary ... 36 

Test Your Understanding ... 36 

Session 04: Introduction to OOPS ... 37 

Learning Objectives ... 37 

Polymorphism ... 37 

Method Overloading ... 37 

Subclassing Polymorphism ... 37 

(3)

Tips and Tricks ... 39 

Summary ... 39 

Test Your Understanding ... 39 

Session 05: Introduction to Java and SDE ... 40 

Learning Objectives ... 40 

History of Java ... 40 

Java Technology... 40 

Features or Characteristics of Java ... 41 

Applets ... 41 

Overview of Java Virtual Machine ... 41 

Java SE or J2SE Runtime Environment ... 41 

Tips and Tricks ... 42 

Summary ... 42 

Test Your Understanding ... 42 

Session 06: Introduction to Java and SDE ... 43 

Learning Objectives ... 43  Defining a Class ... 43  Creating Objects ... 44  Packages ... 44  Import Statement ... 44  Object Class ... 45  Object Messaging ... 45  this keyword ... 46  Try It Out ... 46 

Tips and Tricks ... 47 

Summary ... 47 

Test Your Understanding ... 47 

Session 07: Introduction to Java and SDE ... 48 

Learning Objectives ... 48 

The main Method ... 48 

The System.out.println (SOP) Method... 48 

Code Structure in Java ... 48 

Compile and Run a Java Program ... 49 

Try It Out ... 49 

Tips and Tricks ... 50 

(4)

Test Your Understanding ... 51 

Session 08: Introduction to Java and SDE ... 52 

Learning Objectives ... 52 

Introduction to Java and SDE ... 52 

Tools ... 53 

Tips and Tricks ... 54 

Summary ... 54 

Test Your Understanding ... 54 

Session 09: Introduction to Java and SDE ... 55 

Learning Objectives ... 55 

Creating New Java Project ... 55 

Creating Java Package ... 56 

Creating Java Classes ... 57 

Building Java Classes ... 58 

Running Java Programs ... 59 

Tools ... 60 

Tips and Tricks ... 60 

Summary ... 61 

Test Your Understanding ... 61 

Session 14: Language Fundamentals and Operators ... 62 

Learning Objectives ... 62 

Java Keywords ... 62 

Java Literals ... 62 

Java Literals: Integer ... 62 

Java Literals: Floating point ... 63 

Java Literals: Boolean ... 63 

Java Literals: Character ... 63 

Java Literals: Character ... 63 

Java Literals: String ... 63 

Primitive Data Types ... 64 

Primitive Data Types: Logical-boolean ... 64 

Primitive Data Types: Textual-char ... 64 

Primitive Data Types: Integral – byte, short, int, and, long ... 64 

Integral data type have the following ranges: ... 65 

Primitive Data Types: Floating Point-float and double ... 65 

(5)

Tips and Tricks ... 66 

Summary ... 67 

Test Your Understanding ... 67 

Session 15: Language Fundamentals and Operators ... 68 

Learning Objectives ... 68 

Variables ... 68 

Declaring and Initializing Variables... 68 

Reference Variables Versus Primitive Variables ... 68 

Example of a reference variable and primitive variable... 69 

Example of memory handling of a reference variable and a primitive variable ... 69 

Type Casting ... 69 

Casting Primitive Types ... 69 

Implicit Casting ... 69 

Explicit Casting ... 70 

Explicit Casting Examples ... 70 

Casting Objects ... 70 

Casting Objects Example ... 70 

Try It Out ... 71 

Tips and Tricks ... 72 

Summary ... 72 

Test Your Understanding ... 73 

Session 16: Language Fundamentals and Operators ... 74 

Learning Objectives ... 74 

Declaring and Initializing Variables: Sample Program ... 74 

Declaring and Initializing Variables: Coding Guidelines ... 74 

Try It Out ... 75 

Tips and Tricks ... 75 

Summary ... 76 

Test Your Understanding ... 76 

Session 18: Language Fundamentals and Operators ... 77 

Learning Objectives ... 77 

Operators ... 77 

Arithmetic Operators ... 77 

Arithmetic Operators: Sample Program Output ... 78 

Arithmetic Operators ... 78 

(6)

Increment and Decrement Operators: Coding Guidelines ... 79 

Relational Operators ... 79 

Relational Operators: Sample Program ... 80 

Relational Operators: Sample Program Output ... 81 

Logical Operators ... 81 

Logical Operators: &&(logical) and &(boolean logical) AND ... 82 

Logical Operators: || (logical) and | (boolean logical) inclusive OR ... 83 

Logical Operators: ^ (boolean logical exclusive OR) ... 84 

Logical Operators: ! ( logical NOT) ... 85 

Logical Operators: Conditional Operator (?:) ... 85 

The instanceof Operator ... 86 

Operator Precedence ... 87 

Operator Precedence: Coding Guidelines ... 87 

Try It Out ... 87 

Tips and Tricks ... 88 

Summary ... 89 

Test Your Understanding ... 89 

Session 21: Language Fundamentals and Operators ... 90 

Learning Objectives ... 90 

Importance of Test ... 90 

Test Driven Development ... 90 

Unit Testing ... 90 

JUnit ... 90 

Importance of JUnit ... 91 

Key Goals of JUnit ... 91 

Services Provided by JUnit ... 91 

Guidelines for Writing Code Based on JUnit Test (Minimum) ... 91 

Test Methods ... 91 

Example 1: Very Simple Test ... 92 

Guidelines for Writing Code Based on JUnit Test (Sophisticated) ... 92 

Example 2: More Sophisticated Example ... 92 

Assert Statements ... 93 

Fixtures ... 94 

Example: setUp ... 94 

Test Suites ... 94 

Example: Test Suites ... 95 

TestRunners ... 95 

(7)

Automating Testing (Ant) ... 96 

Ant Batch Mode ... 96 

JUnit Class Diagram ... 97 

Best Practices: What Should You Test? ... 97 

Test First and What to Test ... 98 

Testing for Exceptions ... 98 

Test Then Fix ... 98 

Test then Refactor ... 98 

Design Patterns for Testing ... 98 

Design for Testing: Factories ... 99 

Design for Testing: Mock Objects ... 99 

Testing with Resources (EJB or DB) ... 99 

JUnit Extensions ... 99 

JUnitReport ... 99 

Cactus (from Jakarta) ...100 

JWebUnit ...100 

XMLUnit ...100 

Mock Objects ...101 

StrutsTestCase ...101 

Try It Out ...101 

Tips and Tricks ...105 

Summary ...105 

Test Your Understanding ...106 

Session 23: Language Fundamentals and Operators ...107 

Learning Objectives ...107 

Introduction to Arrays ...107 

Declaring Arrays ...107 

Array Instantiation ...108 

Sample Program ...109 

Accessing an Array Element ...109 

Coding Guidelines ...110  Array Length ...110  Coding Guidelines ...110  Multidimensional Arrays ...111  Enum ...111  enum Keyword ...111  enum Type ...112 

(8)

Key Points on enum and its Constructor ...112 

Detailed Example...112 

Output ...113 

Try It Out ...113 

Tips and Tricks: ...114 

Summary ...114 

Test Your Understanding ...115 

Session 26: Wrapper Classes, Selection Statements and Iteration Blocks ...116 

Learning Objectives ...116 

The Wrapper Classes ...116 

Why Should You Use Wrapper Classes? ...117 

Converting Primitive Types to Objects (Wrapper) and the Reverse ...117 

Wrappers are Immutable ...118 

Try It Out ...118 

Tips and Tricks: ...119 

Summary ...119 

Test Your Understanding ...119 

Session 27: Wrapper Classes, Selection Statements and Iteration Blocks ...120 

Learning Objectives ...120 

Primitive Types: Wrapper Classes ...120 

Converting Strings to Primitive Types ...120 

Converting Primitive Types to Strings ...121 

Converting Primitive Types to Strings (Example) ...121 

Autoboxing ...122 

Without Autoboxing (Java versions before 5.0) ...122 

With Autoboxing (Java versions 5.0 or greater) ...122 

Autoboxing Illustrations ...122 

Method Arguments ...123 

Return Values ...123 

Boolean Expressions ...123 

Autoboxing With Switch Statement ...123 

Operations on Numbers ...123 

Assignments ...124 

Try It Out ...124 

Tips and Tricks: ...125 

Summary ...126 

(9)

Session 30: Wrapper Classes, Selection Statements and Iteration Blocks ...127 

Learning Objectives ...127 

Control Structures ...127 

Decision Control Structures ...127 

if-statement ...127  if-statement Flowchart ...128  Examples of if-statement ...128  Coding Guidelines ...128  if-else Statement ...129  if-else Flowchart ...129 

Examples of if-else Statement ...129 

Coding Guidelines ...130 

if-else-else if Statement ...130 

if-else-else if Flowchart ...130 

Example of if-else-else if Statement ...131 

Common Errors ...131 

Sample Program ...132 

switch Statement ...132 

Flowchart of switch Statement ...133 

Coding Guidelines ...134 

Try It Out ...134 

Tips and Tricks: ...135 

Summary ...135 

Test Your Understanding ...135 

Session 31: Wrapper Classes, Selection Statements and Iteration Blocks ...137 

Learning Objectives ...137 

Repetition Control Structures ...137 

while-loop ...137  Examples of while-loop ...137  do-while-loop ...138  Examples of do-while-loop ...138  Coding Guidelines ...139  for-loop ...139  Example of for-loop ...139  Branching Statements ...140 

Unlabelled Break Statement ...140 

Example of Unlabelled Break Statement ...140   

(10)

Example of Labeled Break Statement ...141 

Unlabelled Continue Statement ...141 

Labeled Continue Statement ...141 

Return Statement ...142 

Try It Out ...142 

Tips and Tricks: ...143 

Summary ...143 

Test Your Understanding ...143 

Session 35: Access Specifiers, Constructors and Methods ...145 

Learning Objectives ...145 

Constructors ...145 

Default Constructor (Method) ...145 

Overloading Constructor Methods ...146 

Applying Constructors ...146 

“this()” Constructor Call ...146 

Example of “this()” Constructor Call ...147 

“this” Reference ...147 

Example of “this” Reference ...147 

Declaring Methods ...148 

Accessor (Getter) Methods ...148 

Example 1: Accessor (Getter) Method ...148 

Example 2: Accessor (Getter) Method ...148 

Mutator (Setter) Methods ...149 

Multiple Return Statements ...149 

Example: Multiple Return Statements ...149 

Static Methods ...150 

Coding Guidelines ...150 

When to Define Static Method? ...150 

Source Code for StudentRecord Class ...150 

Sample Source Code that uses StudentRecord Class ...151 

Try It Out ...152 

Tips and Tricks: ...153 

Summary ...153 

Test Your Understanding ...154 

Session 38: Access Specifiers, Constructors and Methods ...155 

Learning Objectives ...155 

(11)

Example of Method Overloading ...155 

Program Output ...156 

Try It Out ...156 

Tips and Tricks: ...157 

Summary ...158 

Test Your Understanding ...158 

Session 39: Access Specifiers, Constructors and Methods ...159 

Learning Objectives ...159 

Access Modifiers...159 

public Accessibility ...159 

Example: “public” Access Modifier ...159 

protected Accessibility ...160 

Example: “protected” Access Modifier ...160 

default Accessibility ...160 

Example: “default” Access Modifier ...160 

private Accessibility ...160 

Example: “private” Access Modifier ...161 

Java Program Structure: The Access Modifiers ...161 

Coding Guidelines ...161 

Try It Out ...161 

Tips and Tricks: ...162 

Summary ...163 

Test Your Understanding ...163 

Session 42: Inheritance, Interfaces and Abstract Classes ...164 

Learning Objectives ...164 

Inheritance ...164 

Importance of Inheritance ...164 

Deriving a Subclass ...164 

extends Keyword ...165 

What you can do in a Subclass ...165 

What you can do in a Sub-class Regarding Fields ...165 

What you can do in a Sub-class Regarding Methods ...165 

Object Class ...166 

Class Hierarchy ...166 

Superclass and Subclass ...166 

How Constructor Method of a Super Class gets Called ...166 

(12)

Example: Constructor Calling Chain...167 

The “super” Keyword ...167 

Overriding Methods ...168 

Example: Overriding Methods ...168 

Modifiers in the Overriding Methods ...169 

Run-time Polymorphism with Overriding Methods ...169 

Example: Run-time Polymorphism ...169 

Hiding Methods ...169 

Example: Coding of Hiding Static Method ...169 

Overriding Method Versus Hiding Method ...170 

Example: Overriding Method Versus Hiding Method During Runtime ...170 

Hiding Fields ...170 

Try It Out ...170 

Tips and Tricks: ...172 

Summary ...172 

Test Your Understanding ...172 

Session 46: Inheritance, Interfaces and Abstract Classes ...174 

Learning Objectives ...174 

Abstract Methods ...174 

Abstract Class ...174 

Sample Abstract Class ...174 

Extending An Abstract Class ...175 

When to use Abstract Methods and Abstract Class ...175 

What is an Interface? ...175 

Example 1: Interface ...176 

Example 2: OperatorCar Interface...176 

Why do you use Interfaces? Reason #1 ...176 

Why do you use Interfaces? Reason #2 ...176 

Why do you use Interfaces? Reason #3 ...177 

Interface versus Abstract Class ...177 

Interface as a Type ...177 

Example: Interface as a Type ...177 

Interface versus Class: Commonality ...177 

Interface versus Class: Differences ...178 

Defining Interface...178 

Implementing Interfaces ...178 

Implementing Class ...179 

(13)

Example: Implementing Multiple Interfaces ...180 

Inheritance among Interfaces ...180 

Interface and Polymorphism ...180 

Problem of Rewriting an Existing Interface ...180 

Solution of Rewriting an Existing Interface ...181 

When to use an Abstract Class Over Interface? ...181 

Try It Out ...181 

Tips and Tricks: ...182 

Summary ...182 

Test Your Understanding ...183 

Session 48: Inheritance, Interfaces and Abstract Classes ...184 

Learning Objectives ...184 

Using IS-A and HAS-A ...184 

IS-A Relationship Test ...184 

Try It Out ...185 

Tips and Tricks: ...185 

Summary ...186 

Test Your Understanding ...186 

Session 49: Inheritance, Interfaces and Abstract Classes ...187 

Learning Objectives ...187 

What is a “Type”? ...187 

Significance of Type ...187 

Casting Primitive Types ...187 

Implicit Casting ...188 

Implicit Casting: Example ...188 

Explicit Casting ...188 

Explicit Casting: Example ...188 

Casting Objects ...188 

Casting Objects: Example ...189 

Implicit Type Casting ...189 

Type Casting Between Objects ...189 

Explicit Type Casting ...190 

Runtime Type Mismatch Exception ...190 

Use instanceof Operator To Prevent Runtime Type Mismatch Error ...190 

Try It Out ...190 

Tips and Tricks: ...191 

(14)

Test Your Understanding ...192 

Session 50: Inheritance, Interfaces and Abstract Classes ...193 

Learning Objectives ...193 

Inner Class ...193 

Accessing Members of Outer Class Within an Inner Class ...193 

Java Program Structure: Inner Classes ...193 

Static Nested Classes ...194 

Static Nested Class: Example ...194 

Nested Classes versus Inner Classes ...194 

Anonymous Classes ...195 

Anonymous Inner Class: Example ...195 

Anonymous Inner Class: Example ...195 

Try It Out ...195 

Tips and Tricks: ...196 

Summary ...197 

Test Your Understanding ...198 

Session 52: Inheritance, Interfaces and Abstract Classes ...199 

Learning Objectives ...199  Breakpoint View ...199  Console View ...199  Debug View ...200  Display View ...200  Expressions View ...200  Registers View ...200 

Tips and Tricks: ...200 

Summary ...201 

Test Your Understanding ...201 

Session 54: Exception Handling ...202 

Learning Objectives ...202 

Exception ...202 

Exception Example ...202 

Example: Default Exception Handling ...202 

What Happens when an Exception Occurs? ...203 

Searching the Call Stack for an Exception Handler ...204 

Benefits of Java Exception Handling Framework ...204 

(15)

Traditional Programming: No Separation of Error Handling Code ...205 

Separating Error Handling Code from Regular Code ...205 

Exception Class Hierarchy ...206 

Catching Exceptions: The try-catch Statements ...207 

Catching Exceptions: Multiple catch ...208 

Catching Exceptions: Nested trys ...208 

Catching Exceptions: Nested trys with Methods ...208 

Catching Exceptions: The finally Keyword ...209 

Try It Out ...210 

Tips and Tricks: ...212 

Summary ...212 

Test Your Understanding ...213 

Session 55: Exception Handling ...214 

Learning Objectives ...214 

Throwing Exceptions: The throw Keyword ...214 

Example: Throwing Exceptions ...214 

Propagating Errors up the Call Stack ...214 

Traditional Way of Propagating Errors ...215 

Using Java Exception Handling ...216 

Grouping and Differentiating Error Types ...216 

Try It Out ...217 

Tips and Tricks: ...217 

Summary ...218 

Test Your Understanding ...218 

Session 58: Exception Handling ...219 

Learning Objectives ...219 

Checked and Unchecked Exceptions ...219 

Creating Your Own Exception Class ...219 

How to use Your own Exceptions ...219 

Try It Out ...220 

Tips and Tricks: ...222 

Summary ...222 

Test Your Understanding ...222 

Session 61: Strings, String Buffer, and its Functions ...223 

Learning Objectives ...223 

(16)

The String Class: Constructors ...223 

The String Class: Methods ...224 

Try It Out ...224 

Tips and Tricks: ...225 

Summary ...226 

Test Your Understanding ...226 

Session 62: Strings, String Buffer, and its Functions ...227 

Learning Objectives ...227 

The String Class: Example ...227 

Try It Out ...228 

Tips and Tricks: ...229 

Summary ...229 

Test Your Understanding ...230 

Session 65: Strings, String Buffer, and its Functions ...231 

Learning Objectives ...231 

Java Object Law for equals() and hashCode() Methods ...231 

Try It Out ...231 

Tips and Tricks: ...232 

Summary ...233 

Test Your Understanding ...233 

Session 66: Strings, String Buffer, and its Functions ...234 

Learning Objectives ...234 

The StringBuffer Class ...234 

The StringBuffer Class: Methods ...234 

The StringBuffer Class: Example ...234 

The java.lang.StringBuilder Class ...235 

Try It Out ...236 

Tips and Tricks: ...237 

Summary ...237 

Test Your Understanding ...238 

Session 69: Collections and Util package ...239 

Learning Objectives ...239 

Collection ...239 

Collection Framework ...239 

(17)

Collection Interfaces ...240 

Implementations ...240 

Types of Implementations ...240 

General Purpose Implementations ...240 

Algorithms ...240 

Core Collection Interfaces Hierarchy ...241 

Core Collection Interfaces ...241 

“Collection” Interface ...241 

“Collection” Interface (Java SE 5) ...241 

Example: Usage “Collection” Interface as a Type ...242 

add() and remove() Methods of Collection Interface ...242 

Bulk Operations ...242 

Example: removeAll() ...243 

Array Operations...243 

Example: Array Operations ...243 

Try It Out ...243 

Tips and Tricks: ...244 

Summary ...245 

Test Your Understanding ...245 

Session 70: Collections and Util package ...246 

Learning Objectives ...246 

“Set” Interface ...246 

“Set” Interface (Java SE 5) ...246 

“equals” Operation of Set Interface ...247 

“SortedSet” Interface ...247 

Implementations of “Set” Interface ...247 

HashSet ...247 

Caveats of Using HashSet ...247 

Example: Set Interface and HashSet ...247 

TreeSet ...248 

Example: Set Interface and TreeSet ...248 

LinkedHashSet ...249 

Example: Set Interface and LinkedHashSet ...249 

“List” Interface ...249 

Additional Operations Supported by “List” Interface over “Collection” ...249 

“List” Interface ...250 

Implementations of “List” Interface ...250 

(18)

“Map” Interface (Java SE 5) ...251 

“SortedMap” Interface ...251 

Implementations of “Map” Interface ...251 

“Queue” Interface...252 

Implementations of Queue Interface ...252 

Implementations of Queue Interface ...252 

Abstract Classes ...252 

Routine Data Manipulation ...252 

Searching ...253 

Composition ...253 

Try It Out ...253 

Tips and Tricks: ...254 

Summary ...255 

Test Your Understanding ...255 

Session 73: Collections and Util package ...256 

Learning Objectives ...256 

Two Schemes of Traversing Collections ...256 

Iterator Interface ...256 

Use Iterator Over for-each ...256 

The Iterable Interface ...257 

Try It Out ...257 

Tips and Tricks: ...258 

Summary ...259 

Test Your Understanding ...259 

Session 75: Collections and Util package ...260 

Learning Objectives ...260 

The Date Class ...260 

The Date Class: Example ...260 

The Properties Class ...260 

The Properties Class: Example ...260 

Try It Out ...261 

Tips and Tricks: ...262 

Summary ...262 

Test Your Understanding ...262 

Session 81: Threads ...263 

(19)

Threads ...263 

Multi-Threading in Java Platform ...263 

Thread Priorities ...263 

Try It Out ...264 

Tips and Tricks : ...265 

Summary ...265 

Test Your Understanding ...266 

Session 82: Threads ...267 

Learning Objectives ...267 

The Thread Class: Constructor ...267 

The Thread Class: Constants ...267 

The Thread Class: Methods ...268 

Two Ways of Creating and Starting a Thread ...268 

Extending Thread Class ...268 

Two Schemes of Starting a Thread from a Subclass ...268 

Scheme 1: start() Method is not in the Constructor of Subclass ...268 

Scheme 2: start() Method is in a Constructor of the Subclass ...269 

Runnable Interface ...270 

Two Ways of Starting a Thread for a Class that Implements Runnable ...270 

Scheme 1: Caller Thread Creates a Thread Object and Starts it Explicitly...270 

Scheme 2: Thread Object is Created and Started Within a Constructor ...271 

Extending Thread versus Implementing Runnable Interface ...272 

ThreadGroup Class ...272 

Example: ThreadGroup ...272 

Try It Out ...273 

Tips and Tricks: ...273 

Summary ...274 

Test Your Understanding ...274 

Session 84: Threads ...275 

Learning Objectives ...275 

Race Condition and How to Solve it ...275 

An Unsynchronized Example ...275 

Synchronization: Locking an Object ...276 

Option 1: Use Synchronized Method ...276 

Option 1: Executing Synchronized Method ...277 

Option 2: Use Synchronized Statement on a Common Object ...277 

(20)

wait() Method of Object Class ...278 

notify() Method ...279 

Try It Out ...279 

Tips and Tricks: ...280 

Summary ...280 

Test Your Understanding ...281 

Session 86: Threads ...282 

Learning Objectives ...282 

Concurrency Utilities: JSR-166 ...282 

Why Use Concurrency Utilities? ...282 

Concurrency Utilities ...282 

Task Scheduling Framework ...282 

Executor Interface ...283 

Executor and ExecutorService ...283 

Creating ExecutorService From Executors ...283 

Code example of poor resource management (pre-J2SE 5.0 code) ...284 

Code example for better resource management (Using Executors of Java2,v5.0) ...284 

Callable's and Future's: Problem (pre-J2SE 5.0) ...285 

Callables and Futures ...285 

Build CallableExample (This is Callee) ...285 

Future Example (Caller) ...285 

Semaphores ...286 

Semaphore Example ...286 

BlockingQueue Interface ...286 

Blocking Queue Example 1 ...287 

Blocking Queue Example 2 ...287 

Atomics ...287 

Locks ...288 

ReadWriteLock ...288 

ReadWrite Lock Example ...288 

Try It Out ...289 

Tips and Tricks: ...290 

Summary ...290 

Test Your Understanding ...291 

Session 89: I/O operations in JAVA ...292 

Learning Objectives ...292 

(21)

Input Stream ...292 

Output Stream ...293 

General Stream Types ...293 

Character and Byte Streams ...293 

Input and Output Streams ...293 

Node and Filter Streams ...294 

Streams ...294 

Tips and Tricks: ...294 

Summary ...295 

Test Your Understanding ...295 

Session 90: I/O operations in JAVA ...296 

Learning Objectives ...296 

InputStream Abstract Class ...296 

Node InputStream Classes ...297 

Filter InputStream Classes ...297 

OutputStream Abstract Class ...298 

Node OutputStream Classes ...298 

Filter OutputStream Classes ...299 

The Reader Class: Methods ...299 

The Reader Class: Methods ...299 

Node Reader Classes ...300 

Filter Reader Classes ...300 

The Writer Class: Methods ...301 

Node Writer Classes ...301 

Filter Writer Classes ...302 

Control Flow of an I/O Operation ...302 

Byte Stream ...302 

When not to use Byte Stream ...302 

Example: FileInputStream and FileOutputStream ...302 

Simple Byte Stream Input and Output ...303 

Character Stream ...303 

Example: FileReader and FileWriter...304 

Character Stream and Byte Stream ...304 

Line-Oriented I/O ...305 

Example: Line-oriented I/O ...305 

Buffered Streams ...305 

How to Create Buffered Streams?...305 

(22)

Flushing Buffered Streams ...306 

Standard Streams on Java Platform...306 

Data Streams ...306 

DataOutputStream ...306 

DataInputStream...307 

Object Streams ...307 

Input and Output of Complex Object ...307 

Write Object ...307 

I/O of Multiple Referred-to Objects ...308 

Always Close Streams ...308 

The File Class ...308 

The File Class: Constructors ...308 

The File Class: Methods ...309 

The File Class: Example ...309 

Try It Out ...311 

Tips and Tricks: ...312 

Summary ...312 

Test Your Understanding ...312 

Session 92: I/O operations in JAVA ...313 

Learning Objectives ...313 

Random Access File ...313 

Problem Scenario ...313 

Benefits of Random Access File ...314 

java.io.RandomAccessFile ...314 

Creating a Random Access File ...314 

File Pointer ...314 

RandomAccessFile Methods ...315 

Try It Out ...315 

Tips and Tricks: ...316 

Summary ...316 

Test Your Understanding ...316 

Session 93: I/O operations in JAVA ...317 

Learning Objectives ...317 

Serialization ...317 

Streams Used for Serialization ...317 

Requirement for Serialization ...317 

(23)

What is Preserved when an Object is Serialized? ...318 

The transient Keyword ...318 

Example: transient Keyword ...318 

Serialization: Writing an Object Stream ...319 

Deserialization: Reading an Object Stream ...319 

Version Control: Problem Scenario ...320 

Unique Identifier...320 

How do you Generate a Unique ID?...321 

Provide your own implementation for readObject() and writeObject() methods ...321 

Provide your own implementation for readObject() and writeObject() methods ...321 

Externalizable Interface ...321 

How does Object Serialization Scheme works with Externalizable ...321 

Try It Out ...322 

Tips and Tricks: ...323 

Summary ...323 

Test Your Understanding ...323 

Session 96: JDBC ...324  Learning Objectives ...324  JDBC ...324  JDBC API ...324  JDBC Driver ...324  JDBC Driver ...325  Database URL ...325  Steps of Applying JDBC ...325 

Load DB-Specific Database Driver ...325 

Get a Connection Object ...326 

DriverManager and Connection ...326 

Get a Statement Object ...326 

Executing Query or Update ...327 

Reading Results ...327 

Read ResultSet MetaData and DatabaseMetaData (Optional) ...328 

ResultSetMetaData Example ...328 

Try It Out ...328 

Tips and Tricks: ...329 

Summary ...329 

Test Your Understanding ...330 

(24)

Learning Objectives ...331 

javax.sql.DataSource Interface and DataSource Object ...331 

Properties of DataSource Object ...331 

Where are Properties of a DataSource Defined? ...331 

DataSource (JDBC Resource) Definition in domain.xml of Sun Java System AppServer ...332 

Sun Java System Application Server Admin Console ...332 

Sun Java System Application Server Admin Console ...333 

JNDI Registration of a DataSource Object ...334 

JNDI Registration of a DataSource (JDBC Resource) Object ...334 

Need of Connection Pooling ...334 

Connection Pooling and DataSource ...335 

Example: PointBasePool ...335 

Retrieval and Usage of a DataSource Object ...335 

Example: Retrieval of DataSource Object by JNDI ...335 

JNDI Resource Information in web.xml of bookstore1 ...336 

JNDI and Resource Mapping in sun-web.xml of bookstore1 ...336 

Transaction ...336 

JDBC Transaction Methods ...336 

Transactions Example ...337 

Try It Out ...338 

Tips and Tricks: ...338 

Summary ...339 

Test Your Understanding ...339 

Session 98: JDBC ...340 

Learning Objectives ...340 

Prepared and Callable Statements...340 

PreparedStatement ...340 

PreparedStatement Steps ...341 

CallableStatement ...342 

CallableStatement Example ...342 

Stored Procedure Example ...342 

Try It Out ...342 

Tips and Tricks: ...343 

Summary ...344 

Test Your Understanding ...344 

Session 102: Garbage Collection ...345 

(25)

Garbage Collector ...345 

Important Facts About GC ...345 

What Does a GC Perform? ...345 

Overview of GC Designs ...345 

Some of the Common Garbage Collector Designs ...346 

Memory Leaks ...346 

Examples for Memory Leaks ...346 

Try It Out ...347 

Tips and Tricks: ...348 

Summary ...349 

Test Your Understanding ...349 

Session 103: Garbage Collection ...350 

Learning Objectives ...350 

Important GC Performance Metrics ...350 

Types of Garbage Collector ...350 

Serial Collector ...350 

Parallel Collector...350 

Parallel Compact Collector ...351 

Concurrent Mark Sweep Collector ...351 

CMS Collector in Incremental Mode ...351 

Other Incremental CMS Options ...351 

Tips and Tricks: ...352 

Summary ...352 

Test Your Understanding ...352 

Session 105: Overview of Annotation ...353 

Learning Objectives ...353 

How Annotations are Used? ...353 

Ad-hoc Annotation-like Examples in pre-J2SE 5.0 Platform ...353 

Need of Annotation ...353 

Built-in Annotations ...354 

Annotation Retention Policy ...354 

@Retention ...354  @Documented ...355  @Target ...355  @Inherited ...355  @Override ...356  @Deprecated ...356 

(26)

@SuppressWarnings ...356 

Tips and Tricks: ...356 

Summary ...356 

Test Your Understanding ...357 

Session 106: Overview of Annotation ...358 

Learning Objectives ...358 

How to “Define” Annotation Type? ...358 

Example: Annotation Type Definition ...358 

How To “Use” Annotation ...358 

Example: Usage of Annotation ...359 

Three Different Kinds of Annotations ...359 

Marker Annotation ...359 

Single Member (or Value) Annotation ...359 

Normal Annotation ...360 

Example: Definition and Usage of a User-defined Annotation ...360 

Reflection ...361 

The AnnotatedElement Interface ...361 

Methods Defined by AnnotatedElement ...361 

Usage of Reflection in Annotations ...362 

Try It Out ...362 

Tips and Tricks: ...363 

Summary ...363 

Test Your Understanding ...363 

Session 108: Updates in JDK 1.6 ...364 

Learning Objectives ...364 

The Java SE 6 (JDK 1.6) Top 10 Features ...364 

Motivation for Scripting Support ...364 

Scripting: Developer Example ...365 

Web Services Support on Java SE 6 Platform ...365 

API Support ...365 

Database: JDBC 4.0 Support ...365 

Java DB ...366 

Desktop APIs ...366 

Tray Icon ...366 

Tray Icon: Usage ...366 

Splash Screen: Overview ...367 

(27)

Desktop APIs ...367 

Dialog Modality Enhancement ...367 

Modality Types ...368 

New Dialog Modality API ...368 

Text Printing ...368 

SwingWorker ...369 

javax.swing.GroupLayout Class ...369 

JTable Sorting and Filtering ...369 

Monitoring and Management ...369 

Pluggable Annotations ...370 

Desktop Deployment ...370 

Windows Look and Feel Improvements SwingSet on Vista with 5.0 ...370 

Windows Look and Feel Improvements SwingSet on Vista with 6 ...371 

Security ...372 

Quality, Stability, and Compatibility ...373 

Performance Improvement ...373 

Running Applications on Java SE 6 ...374 

Building Applications on Java SE 6 ...374 

Building Applications on Java SE 6 ...374 

Summary ...374 

Test Your Understanding ...375 

Glossary ...376 

References ...378 

Websites ...378 

Books ...378 

(28)

Introduction

About this Module

This module provides students with the knowledge and skills that are needed to develop applications by using the Sun Java (Java Standard Edition, version 2.0).

Target Audience

This module is designed for beginners of Java who are expected to know the basic concepts of Object Oriented Programming.

Module Objectives

After completing this module handout, you will be able to:

‰ Describe the characteristics of Java language

‰ Define Java platform

‰ Explain the concepts of packages, classes, objects, main method and System.out.println methods in Java language

‰ Create Java application programs manually

‰ Run Java application programs manually

‰ Describe the features of Standard Development Environment (SDE)

‰ Create a simple JAVA program in SDE

‰ Execute a simple JAVA program in SDE

‰ Write Java programs using keywords, variable declaration, operators, data types, arrays and Enum

‰ Write Java programs using Control Flow statements, wrapper classes and autoboxing

‰ Write Java programs using access specifiers, constructors, and methods

‰ Write Java programs using the concepts of inheritance, interfaces, and abstract classes

‰ Write Java programs implementing exceptions handling

‰ Write Java programs using Strings, StringBuffer, StringBuilder, and its functions

‰ Write Java programs using Collections and Util package

‰ Write Java programs based on threading concepts

‰ Write Java programs based on I/O operations

‰ Write database application Java programs using JDBC

‰ Explain Garbage Collection concepts

‰ Implement Annotations in Java programs

‰ List the new features of JDK 1.6

Pre-requisite

(29)

Session 02: Introduction to OOPS

Learning Objectives

After completing this session, you will be able to:

‰ Describe OOP as a programming methodology

‰ Explain classes and objects

Object Oriented Programming

OOP maps your problem in the real world.

OOP defines “things” (objects), which can either do something or have something done to them. OOP creates a “type” (class) for these objects so that you do not have to redo all the work in defining the properties and behavior of an object.

Examples of class:

‰ Classroom

‰ Car

‰ Person

Procedural Versus OOP

“Nouns” refer to data and “Verbs” refer to operations. Procedural Languages:

‰ C or Pascal and so on

‰ Verb-oriented

‰ No formal noun-verb structure (not enforced by language or compiler)

OOP languages: Operations (verbs) are performed by or on “Actors” (objects), which have names

and store data (nouns)

Objects

An object is a unique programming entity that has attributes to describe it (like adjectives in grammar) and methods to retrieve or set attribute values (like verbs in grammar).

Part of a program which:

‰ Models some real or conceptual object

‰ Has behavioural responsibilities (behaviors)

‰ Has informational responsibilities (attributes)

‰ Behaviors (methods):

(30)

‰ Like procedures and functions in other languages

‰ Attributes (fields):

‰ Information an object “knows” (has-a)

‰ Like data and variables in other languages (records)

Class

Exists once:

The class is the template for the object Defines the attributes and behavior of the objects

Every object must belong to a class: The creation (construction) of an object is called instantiation. The created object is often called an instance (or an instance of class X)

Example:

Person is a class

EdmundHillary is an instance of class Person

Try It Out

Problem Statement:

What is the difference between a class and an object?

Answer:

A class is not an object. But it is used to construct objects.

A class is a blueprint for an object. It tells the virtual machine how to make an object of that

particular type. Each object made from the class can have its own values for the instance variables of that class. Class Book { String id; String title; String author; void getChaptersList() {

System.out.println(“Getting the chapters list”); }

public static void main(String[] args) { Book book1 = new Book();

book1.getChaptersList(); Book book2 = new Book(); book2.getChaptersList(); }

(31)

Refer File Name: Book.java to obtain soft copy of the program code How It Works:

In the example provided, you have used the Book class to make different books, and each book has its own id, title, and author.

Tips and Tricks

Please tell whether the following file could be compiled: Class DiscDeck {

boolean canRecord = false; void playDisc() { System.out.println(“disc playing”); } void recordDisc() { System.out.println(“disc recording”); }

public static void main(String[] args) { dd.canRecord = true; dd.playDisc(); if (dd.canRecord == true) { dd.recordDisc(); } } }

Solution: The preceding file will result in compilation error since object is not created for the

DiscDeck class. This error will be fixed by adding DiskDeck dd = new DiscDeck(); statement in the main method.

Summary

‰ Object-oriented programming lets you to extend a program without having to touch the working code that is tested earlier.

‰ A class describes how to make an object of that class type. A class is like a blueprint.

‰ An object knows things and does things.

‰ The things an object knows about itself are called instance variables. They represent the state of an object.

‰ The things an object does are called methods. They represent the behavior of an object.

Test Your Understanding

Find out who am I from the following: 1. I am compiled from a .java file ____ 2. I behave like a template or blueprint ____ 3. I have behaviors ____

(32)

4. I declare methods ____ 5. I represent ‘state’ ____

6. I am used to create object instances ____ 7. I am located in objects ____, ____

(33)

Session 03: Introduction to OOPS

Learning Objectives

After completing this session, you will be able to:

‰ Describe abstraction, encapsulation, and inheritance

Abstraction

One of the chief advantages of object oriented programming is the idea that programmers can essentially focus on the “big picture” and ignore specific details regarding the inner-workings of an object. This concept is called abstraction.

Encapsulation

‰ Abstraction in OOP is closely related to a concept called encapsulation.

‰ The Object Orientation has two major promises/benefits. They are: flexibility and maintainability.

‰ You have to write your classes and code in a way that supports flexibility and maintainability.

‰ The ability to make changes in your implementation code without breaking the code of others who use your code is a key benefit of encapsulation.

‰ If you want maintainability, flexibility and extensibility your design must include encapsulation.

‰ The following are some of the ways to include encapsulation:

o Keep instance variables protected (with an access modifier, often private). o Make public accessor methods, and force calling code to use those methods

rather than directly accessing the instance variable.

o For the methods, use the JavaBeans naming convention of set<someProperty> and get<someProperty>

‰ Encapsulation is the mechanism that binds together the code and the data it manipulates, and keeps both safe from outside interference and misuse.

public variables and methods

private variables and methods

public variables are not recommended

(34)

Encapsulation: Example Bank machine Hidden data Account balance Personal information Interface

Deposit, Withdraw, Transfer Display account information

Class Hierarchy

Classes are arranged in a tree hierarchy:

‰ A class’ “superclass” is the class preceding it in the hierarchy

‰ Classes following it are “subclasses” Classes have all the properties of their superclasses:

General: Towards the root (top)

More specific: Towards the leaves (down)

NB: In Computer Science trees grow upside down!

Class Hierarchy: Example

Object Animal Bird Duck ... ... ... ... Inheritance

One of the main tenets of OOP is inheritance.

The process by which a class inherits the properties of its superclasses is called inheritance:

‰ Methods

‰ Instance variables

A child class inherits its properties and attributes from its parents.

Inheritance is the process by which one object acquires the properties of another object. By use of inheritance, an object needs only to define all of its characteristics that make it unique within its class; it can inherit its general attributes from its parent.

The inheriting class contains all the attributes and behaviors of its parent class. Moreover the inheriting class can define its own attributes and behaviors.

(35)

The inheriting class can override the definition of existing methods by providing its own implementation.

The code of the inheriting class consists only the changes and additions to the base class.

Need of inheritance

Inheritance is required for the following reasons:

Modular coding, which means less code and easier to get an idea about the code

‰ Code reuse:

‰ Do not break what is already working

‰ Easier updates

Inheritance: Example

Try It Out

Problem Statement:

Design a class inheritance class diagram (tree structure) for the following:

Class Superclasses Subclasses

Clothing --- Shirt, Trouser

Shirt Clothing BankAccount int acctNum Client acctHolder double balance bankAccount(Client info) void deposit(double amt) boolean withdraw(double amt) void printStatement() double interestRate double accruedInterest Time lastBalanceChange savingsAccount(...) void updateIntRate(double rate)

void deposit(double amt) boolean withdraw(double amt) CurrentAccount double minBalance currentAccount(…) boolean withdraw(double amt) double calcServiceFee() SavingsAccount

(36)

Class Superclasses Subclasses

Trouser Clothing

Answer:

Inheritance Class Diagram

Refer File Name: Clothing.java, Shirt.java, Trouser.java to obtain soft copy of the program code

How It Works:

In the given example, Clothing is the superclass and its subclasses are Shirt and Trouser that is a Shirt extends Clothing and also a Trouser extends Clothing.

Tips and Tricks

1. The typical problems include real-time problems and challenges: 2. Are there any practical limits on the level of subclassing using Java? 3. Can you extend any class in Java?

Solution: With regard to Java API, there is no hard limit for the limits on the level of subclassing.

Using Java, you cannot extend any class as such. The factors like access control and access modifier determine whether a class can be subclassed.

Summary

A class can inherit instance variables and methods from a more abstract superclass.

Test Your Understanding

1. Fill in the blanks for the following:

a) A sub class ______ all the public instance variables and methods of the super class.

b) If the base class or super class has functionality, then its ______ automatically gets the same functionality.

2. State true or false for the following: a) Guitar extends Instrument b) Animal extends Cat

Clothing

Trouser Shirt

(37)

Session 04: Introduction to OOPS

Learning Objectives

After completing this session, you will be able to:

‰ Describe polymorphism

‰ Explain the relationship between objects

Polymorphism

Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be used for a general class of actions that is one interface with multiple methods.

Idea of polymorphism:

‰ See internet definition: On Google type “definition polymorphism” and see the results

‰ Moreover, refer the following url:

http://www.wordiq.com/definition/Polymorphism_%28computer_science%29

Generally, polymorphism allows you to mix methods and objects of different types in a consistent way.

Method Overloading

This is called ad hoc polymorphism, or method overloading. In this case, different methods within the same class or in a common hierarchy share the same name but have different method signatures (name + parameters)

public static float max(float a, float b)

public static float max(float a, float b, float c) public static int max(int a, int b)

When a method is called, the call signature is matched to the correct method version.

Note: This is done during program compilation

Subclassing Polymorphism

Subclassing polymorphism is sometimes called “true polymorphism”. It consists basically of two ideas:

‰ Method overriding:

o A method defined in a superclass is redefined in a subclass with an identical method signature.

o As the signatures are identical, rather than overloading the method, it is instead overriding the method:

o For subclass objects, the definition in the subclass replaces the version in the superclass.

‰ Dynamic (or late) binding:

o The code executed for a method call is associated with the call during run-time. o The actual method executed is determined by the type of the object and not the

(38)

o Allows superclass and subclass objects to be accessed in a regular and consistent way:

o Array or collection of superclass references can be used to access a mixture of superclass and subclass objects

o This is very useful if you want access collections of mixed data types (for example draw different graphical objects using the same draw() method call for each)

Example of a class

move()

Example of objects of the subclasses

Each subclass overrides the move() method in its own way. Animal [] A = new Animal[3];

A[0] = new Bird(); A[1] = new Person(); A[2] = new Fish();

for (int i = 0; i < A.length; i++) A[i].move();

References are all the same, but objects are not.

The method invoked is associated with the object and not with the reference.

Relationship Between Objects

Association:

‰ Association states that there is a relation between two classes.

‰ Example: The relation is of association type between Car and Owner or BankAccount

(39)

Aggregation:

‰ Aggregation is a special form of association. The relation may be referred alternatively as “contains”, “is composed of”, or “is part of”.

‰ Example: A car contains wheels. Wheels can exist independently from the car and

are not necessarily destroyed when the car is wrecked. Composition:

‰ Composition is the relation in which the objects cannot exist independently from the whole.

‰ Example: The car registration cannot exist without a car. So the relationship between

car and car registration number is composition.

Tips and Tricks

If you do not have access to the source code for a class, but you want to change the way a method of that class works, then could you use subclassing to do that that is to extend the “bad” class and override the method with your own better code?

Solution: Yes. This is a great feature of Object Oriented approach, and sometimes it saves you

from having to rewrite the class from scratch, or track down the programmer who is hiding the source code.

Summary

‰ Object-oriented programming lets you to extend a program without having to touch the working code that is tested earlier.

‰ All Java code is defined in a class.

‰ A class describes how to make an object of that class type. A class is like a blueprint.

‰ An object can take care of itself, you do not have to know or care how the object does it.

‰ An object knows things and does things.

‰ The things an object knows about itself are called instance variables. They represent the state of an object.

‰ The things an object does are called methods. They represent the behavior of an object.

‰ When you create a class, you may also want to create a separate test class, which you will use to create objects of your new class type.

‰ A class can inherit instance variables and methods from a more abstract superclass.

‰ At run-time, a Java program is nothing more than objects ‘talking’ to other objects.

Test Your Understanding

1. State true or false for the following:

a) Polymorphism means many forms.

(40)

Session 05: Introduction to Java and SDE

Learning Objectives

After completing this session, you will be able to:

‰ Explain the history of Java

‰ Describe the features or characteristics of Java

‰ Explain applets

‰ Describe Java Virtual Machine (JVM) and bytecode

‰ Explain Java Runtime Environment (JRE) and Java Development Kit (JDK)

History of Java

The original name of Java was Oak, and it was developed as a part of the Green project at Sun Microsystems.

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridon at Sun Microsystems in 1991.

The ultimate objectives of the team were:

‰ To ensure security

‰ To ensure reliability

‰ To set up a platform independent language completely that would function seamlessly, regardless of the CPU

The World Wide Web (WWW), by nature, had requirements such as reliability, security, and architecture independence, which were fully compatible with the design patterns of Java. Sun formally announced the Java SunWorld in 1995.

Java Technology

‰ Java is a programming language.

‰ Java is a development environment that provides tools such as compiler, interpreter, documentation generator, and so on.

‰ Java is an application environment to run standalone programs that run on any machine where the Java Runtime Environment (JRE) is installed.

‰ Java is a deployment environment that supplies Java2 Software Development Kit (J2SDK) with complete set of Application Programming Interface (APIs) as packages.

‰ Java provides an easy-to-use language by avoiding pitfalls of other languages, such as pointer arithmetic and memory management, which affect the robustness of the code.

(41)

Features or Characteristics of Java

The features of Java are:

‰ Simple ‰ Object oriented ‰ Secure ‰ Platform independent ‰ Robust ‰ Portable

‰ Automatic garbage collection

‰ Dynamic

‰ Multithreaded

‰ Distributed

Applets

‰ An applet is a program written in the Java programming language that can be included in a HTML page, much in the same way an image is included in a page.

‰ An applet is designed to be transmitted over the Internet and is executed by a Java compatible Web browser.

‰ An applet can react to user input dynamically.

‰ Because applets are executed in the client machine, Java enforces a lot of restriction on applets.

Overview of Java Virtual Machine

‰ Java Virtual Machine (JVM) specification defines the JVM as an imaginary (virtual) machine that is implemented by emulating it in software on a real machine. Code for the JVM is stored in .class files, each of which contains code for at most one public class.

‰ The specification enables the Java language to be platform independent.

‰ JVM is implemented in a Java technology development tool or in a Web browser.

‰ Bytecode: Bytecode is a highly optimized set of instructions designed to be executed

by the JVM.

‰ The key that allows Java to solve both the security and the portability problem is the output of Java compiler, which is not an executable code rather it is the bytecode.

‰ The JVM is ported to different platforms to provide hardware and operating system independence, which is environment independent of hardware and operating system.

‰ JVM needs to be implemented for each platform.

Java SE or J2SE Runtime Environment

‰ J2SE stands for Java 2 Standard Edition. From Java SDK API version 1.5 onwards, this is referred to as Java SE (Java Standard Edition).

‰ The JRE provides the libraries, JVM, Java Interpreter, and other components necessarily for you to run applets and applications written in Java.

(42)

‰ JRE is responsible for loading, verifying, and executing the bytecodes.

‰ The JDK includes the JRE as well as command-line development tools, such as compilers and debuggers that are necessary or useful for developing applets and applications.

‰ The Java API is a code that is written earlier, organized into packages of similar topics, and it is a part of JDK libraries.

Tips and Tricks

What is a Java program? What do you actually deliver?

Solution: A Java program is a pile of classes (or at least one class). In a Java application, one of

the classes must have a main method, used to start-up the program. So as a programmer, you write one or more classes, which you deliver. If the end-user does not have a JVM, then you will also need to include that with the classes of your application, so that they can run your program. There are a number of installer programs that lets you to bundle your classes with a variety of JVMs (say, for different platforms), and put it all on a CD-ROM. Then the end-user can install the correct version of JVM (assuming they do not already have it on their machine.).

Summary

‰ Keeping the following objectives in mind, Java language has been developed: o Security

o Reliability

‰ Completely platform independent and functions seamlessly regardless of the type of CPU

‰ Java is a development environment, which provides tools like compiler, interpreter, documentation generator, and so on.

‰ Secure, object oriented, robust, portable, platform independent, multithreaded are some of the salient features of Java.

‰ An applet is a program, which is downloaded in the client machine and executed by the JVM of the client machine.

‰ Bytecode is a highly optimized set of instructions designed to be executed by the JVM.

‰ The JRE provides the libraries, JVM, Java Interpreter, and other components necessary for you to run applets and applications written in Java.

Test Your Understanding

1. State true or false for the following:

a) Java is an Object Oriented Programming language. b) Java is developed at Microsoft.

c) Java is secure, robust, and multi-threaded. d) Java is platform dependent.

e) A Java source file (*.java) is compiled and the corresponding bytecode is available in the *.class file.

f) To run a Java program on any Operating System, JRE appropriate to that OS must be available.

(43)

Session 06: Introduction to Java and SDE

Learning Objectives

After completing this session, you will be able to:

‰ Define a class

‰ Create objects

‰ Identify packages, import statement, and Object class

‰ Explain object messaging

Defining a Class

A class is a basic building block of an object oriented language.

A class is a template that describes the data and the methods that manipulate the data. Examples of class:

‰ Classroom

‰ Car

‰ Person

The following Java program defines a class Person with data member name: Class Person

private String name;

public void setName(String aName) { name = aName;

}

public String getName() { return name;

} }

The data members in a class can be defined as follows:

‰ Instance variable:

o This differentiates one object from another, giving an object its individuality. For example, the particular name and address for a given Person object is declared as an instance variable.

o An instance variable relates to an instance (object) of its class.

‰ Class variable:

o The data that is shared by all the objects are declared as class variables.

o There is only one copy of each of these variables no matter how many objects are created for the class.

(44)

o These variables are also referred to as static fields because they are declared with the keyword static.

o Data members of the class are normally declared as instance variables using the keyword private.

Creating Objects

An object is created from a class.

The following statement creates an object: Person EdmundHillary = new Person();

The preceding statement has three parts:

‰ Declaration: This notifies the compiler that you will use name to refer to data whose

type is type;

Person EdmundHillary

‰ Instantiation: The new keyword is a Java operator that creates the object.

EdmundHillary = new Person()

‰ Initialization: The new operator is followed by a call to a constructor. The constructor

will contain code that initializes the new object to the desired values.

Packages

‰ Every class in the Java library belong to a package.

‰ In the Java API, classes are grouped into packages.

‰ A class has a full name, which is a combination of the package name and the class name. For example, the class ArrayList is actually java.util.ArrayList.

‰ To use a class in a package other than java.lang, you must tell Java the full name of the class.

‰ Packages are important for three main reasons:

o Firstly, they help in the overall organization of a project or library.

o Secondly, packages give you a name-scoping, to help to prevent collisions if many programmers in a company decide to make a class with the same name.

o Thirdly, packages provide a level of security, because you can restrict the code, which you write so that only other classes in the same package can access it.

‰ To put a class in a package, put a package statement at the top of the source code file, before any import statement like package com.mypack;.

‰ To be in a package, a class must be in a directory structure that exactly matches the package structure. For a class, com.mypack.Book, the Book class must be in a directory named mypack, which is in a directory named com.

‰ Organizing your classes into packages prevents naming collisions with other classes, if you preponed your reverse domain name on to the front of a class name.

Import Statement

A typical set of import statements might look like the following:

‰ import java.io.*;

(45)

‰ import java.util.Date;

‰ import java.util.Properties;

The import statements must come right after the package statement, before the class statement. Purpose of import statement:

‰ Because of the rigid source code naming convention, the Java compiler can easily find the corresponding source or class files just from the fully qualified name of a package and class. This can be illustrated with the following example:

java.util.ArrayList myList = new java.util.ArrayList(50);

‰ The alternative to this long-winded style of coding (as shown earlier), is to use import statements like the following:

import java.util.ArrayList;

ArrayList myList = new ArrayList(50);

To derive a class from an external superclass, you must first import the superclass using the import statement.

Object Class

Every class in Java extends class Object that is the Object class is the mother of all classes. It is the superclass of everything.

Any class that does not explicitly extend another class, implicitly extends Object class. Few of the important methods of the Object class are as follows:

‰ equals(Object obj) : Indicates whether some other object is "equal to" this one

and it returns a boolean value as true or false

‰ toString() : Returns a string representation of the object

‰ hashCode() : Returns a hash code value (of integer type) for the object

Object Messaging

‰ Objects cooperate and communicate with other objects in a program by passing messages to one another (setting a value, returning a value, or sending an email).

‰ When an object invokes a method on itself or on the method of another object, it is said to pass a message to the object that contains the target method.

‰ The message contains the name of the method and any data that the method requires.

‰ Example: person.setName(“EdmundHillary”);

‰ Data that are passed to a method are known as arguments. The required arguments for a method are defined by a parameter list of the method.

‰ After performing the operation, the body of the method uses the return statement to return the value to the calling object.

‰ this keyword:

o Used to represent the object that invokes the method:

(46)

this keyword

‰ this keyword refers to the object that is currently executing.

‰ this keyword also allows one constructor to explicitly invoke another constructor in the same class.

‰ It is useful for a method to refer to instance variables relative to this keyword when a local variable hides the data member with the same name, like the following code: Class Person { String name; Person(String name) { this.name = name; } ……. } Try It Out Problem Statement:

Illustrate the importance of the objects with relevant to entries in the address book.

Code:

class AddressBook { String id;

int telephoneNumber;

public void getName() { }

public String setName(String aName) { } public String changeName(String aName) { } }

Refer File Name: AddressBook.java to obtain soft copy of the program code How It Works:

‰ One analogy for objects is a packet of unused visiting cards in the address book.

‰ Each card has the same blank fields (the instance variables).

‰ When you fill out a card, you are creating an instance (object), and the entries you make on that card represent its state.

‰ The methods of the class are the things you do to a particular card.

‰ getName() , changeName(String aName) , and setName(String aName) could all be the methods for the class AddressBook.

‰ So, each card can do the same things (getName() , setName(String aName) ,and so on), but each card knows things unique to that particular card.

(47)

Tips and Tricks

What if you have a hundred classes or a thousand? Is not that a big pain to deliver all those individual files? Can these classes be bundled into one application thing?

Solution: Yes, it would be a big pain to deliver a huge bunch of individual files to your end-users,

but you will not have to. You can put all of your application files into a Java Archive or a .jar file that is based on the pkzip format. In the jar file, you can include a simple text file formatted as

something called a manifest, that defines which class in that jar holds the main() method that should run.

Summary

‰ Object-oriented programming lets you to extend a program without having to touch the working code that is tested earlier.

‰ A class describes how to make an object of that class type. A class is like a blueprint.

‰ An object knows things and does things.

‰ The things an object knows about itself are called instance variables. They represent the state of an object.

‰ The things an object does are called methods. They represent the behaviour of an object.

Test Your Understanding

1. State true or false for the following:

a) The package statement in a Java program, if available, can be written anywhere in the code.

b) The import statement can be placed next to the package statement in a Java program.

c) A Java class is made up of data members and methods. d) Every class in Java does not extend the Object class.

References

Related documents

A dose is given EVERY TIME you eat any carbs AND/OR have a high blood sugar that requires insulin.. Delivered just as if you were taking a shot of Humalog, Novolog

– I wish to transfer my Stocks and Shares ISA to Threadneedle Investment Services Limited – I have read the Terms and Conditions attached to this transfer form. – I have read

Content Outline: This session examines the different ways to evaluate technologies for young children, focusing on the different factors, in particular the role of adults, which

Fields or local variables in Java are of one of two sorts Primitive type: variable stores the value. declaration implies memory allocation to store its value (depending on

In the current study, we examined the effect of oral administration of CNN on severity of colitis, inflammatory state in the colon, colonic histology, goblet cell number,

at 10 (emphasis by Majority omitted, current emphasis added). Instantly, Selective will not suffer detriment from the trial court’s decision so much as from its own

SACK may not be used for every connection, as it is not always supported locally or a TCP peer does not want to use the option. In cases of multiple segments loss when.. using

We amend the real EF data by generating a certain number of papers by author X and linking each of them with 35 randomly chosen users (35 is the average paper degree in the