Core Java Handout v1.0

379
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

Transcript of Core Java Handout v1.0

Page 1: Core Java Handout v1.0

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

Page 2: Core Java Handout v1.0

Handout - Core Java

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 

Relationship Between Objects .................................................................................................... 38 

Page 2 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 3: Core Java Handout v1.0

Handout - Core Java

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 

Summary .................................................................................................................................... 50 

Page 3 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 4: Core Java Handout v1.0

Handout - Core Java

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 

Try It Out ..................................................................................................................................... 65 

Page 4 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 5: Core Java Handout v1.0

Handout - Core Java

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 

Increment and Decrement Operators ......................................................................................... 79 

Page 5 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 6: Core Java Handout v1.0

Handout - Core Java

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 

TestRunners: Swing ................................................................................................................... 95 

Page 6 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 7: Core Java Handout v1.0

Handout - Core Java

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 

Example: enum in for Loop .......................................................................................................112 

Page 7 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 8: Core Java Handout v1.0

Handout - Core Java

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 

Test Your Understanding ..........................................................................................................126 

Page 8 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 9: Core Java Handout v1.0

Handout - Core Java

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 

Labeled Break Statement .........................................................................................................140 

Page 9 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 10: Core Java Handout v1.0

Handout - Core Java

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 

Method Overloading .................................................................................................................155 

Page 10 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 11: Core Java Handout v1.0

Handout - Core Java

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 

Example: Constructor Calling Chain.........................................................................................166 

Page 11 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 12: Core Java Handout v1.0

Handout - Core Java

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 

Relationship of an Interface to a Class .....................................................................................179 

Page 12 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 13: Core Java Handout v1.0

Handout - Core Java

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 

Summary ..................................................................................................................................192 

Page 13 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 14: Core Java Handout v1.0

Handout - Core Java

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 

Separating Error Handling Code from Regular Code ...............................................................204 

Page 14 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 15: Core Java Handout v1.0

Handout - Core Java

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 

The String Class .......................................................................................................................223 

Page 15 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 16: Core Java Handout v1.0

Handout - Core Java

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 

Benefits of Collection Framework .............................................................................................239 

Page 16 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 17: Core Java Handout v1.0

Handout - Core Java

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 

“Map” Interface .........................................................................................................................250 

Page 17 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 18: Core Java Handout v1.0

Handout - Core Java

“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 

Learning Objectives ..................................................................................................................263 

Page 18 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 19: Core Java Handout v1.0

Handout - Core Java

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 

Inter-thread Communication: Methods from Object Class .......................................................278 

Page 19 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 20: Core Java Handout v1.0

Handout - Core Java

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 

I/O Streams ...............................................................................................................................292 

Page 20 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 21: Core Java Handout v1.0

Handout - Core Java

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 

Buffered Stream Classes ..........................................................................................................306 

Page 21 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 22: Core Java Handout v1.0

Handout - Core Java

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 

Non-Serializable Objects ..........................................................................................................318 

Page 22 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 23: Core Java Handout v1.0

Handout - Core Java

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 

Session 97: JDBC .......................................................................................................................331 

Page 23 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 24: Core Java Handout v1.0

Handout - Core Java

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 

Learning Objectives ..................................................................................................................345 

Page 24 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 25: Core Java Handout v1.0

Handout - Core Java

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 

Page 25 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 26: Core Java Handout v1.0

Handout - Core Java

@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 

Splash Screen: Usage ..............................................................................................................367 

Page 26 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 27: Core Java Handout v1.0

Handout - Core Java

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 

STUDENT NOTES: ......................................................................................................................379 

Page 27 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 28: Core Java Handout v1.0

Handout - Core Java

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

The prerequisite of Core Java is knowledge in concepts of Object Oriented Programming.

Page 28 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 29: Core Java Handout v1.0

Handout - Core Java

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): Things an object can “do”

Page 29 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 30: Core Java Handout v1.0

Handout - Core Java

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

}

}

Page 30 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 31: Core Java Handout v1.0

Handout - Core Java

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 ____

Page 31 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 32: Core Java Handout v1.0

Handout - Core Java

4. I declare methods ____ 5. I represent ‘state’ ____ 6. I am used to create object instances ____ 7. I am located in objects ____, ____

Page 32 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 33: Core Java Handout v1.0

Handout - Core Java

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

A Class

Page 33 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 34: Core Java Handout v1.0

Handout - Core Java

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.

Page 34 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 35: Core Java Handout v1.0

Handout - Core Java

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

Page 35 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 36: Core Java Handout v1.0

Handout - Core Java

Page 36 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

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

Page 37: Core Java Handout v1.0

Handout - Core Java

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

type of the reference.

Page 37 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 38: Core Java Handout v1.0

Handout - Core Java

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

and Customer.

Page 38 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 39: Core Java Handout v1.0

Handout - Core Java

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. b) An overloaded method is not the same as overridden method.

Page 39 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 40: Core Java Handout v1.0

Handout - Core Java

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.

Page 40 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 41: Core Java Handout v1.0

Handout - Core Java

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.

Page 41 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 42: Core Java Handout v1.0

Handout - Core Java

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.

Page 42 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 43: Core Java Handout v1.0

Handout - Core Java

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. o These variables exist even if no object of the class has been created.

Page 43 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 44: Core Java Handout v1.0

Handout - Core Java

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.*;

import java.util.ArrayList;

Page 44 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 45: Core Java Handout v1.0

Handout - Core Java

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: o Used within the member methods of the class those are not static

Page 45 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 46: Core Java Handout v1.0

Handout - Core Java

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.

Page 46 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 47: Core Java Handout v1.0

Handout - Core Java

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.

Page 47 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 48: Core Java Handout v1.0

Handout - Core Java

Session 07: Introduction to Java and SDE

Learning Objectives

After completing this session, you will be able to explain the following: The main() method and SOP (System.out.println method) Code structure in Java

The main Method

In Java, everything goes in a class. The source code is typed into a file (with a .java extension). This is then compiled into a new class file (with a .class extension)

When you run your program, you are really running a class. Running a program means telling the Java Virtual Machine (JVM) to “Load the class”

(Book class for example), then starting to execute its main() method. Keep running till all the code in main() method is finished.

The main() method is where a Java application starts running. Every Java application has to have at least one class, and at least one main() method. The main() method will be written as shown in the following code:

public static void main (String[] args) {

// your code goes here

}

Uses of main() method: o To test your real class o To launch or start your Java application

The System.out.println (SOP) Method

The System class is available in the java.lang package. The “out” is a field of the System class representing the “standard” output stream. Typically this stream corresponds to display output or another output destination

specified by the host environment or user. For simple stand-alone Java applications, a typical way to write a line of output data is

System.out.println(data) . System.out.println inserts a new line while System.out.print keeps printing to the same

line.

Code Structure in Java

Put a class in a source file Put methods in a class Put statements in a method

Page 48 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 49: Core Java Handout v1.0

Handout - Core Java

Example /** *

* Sample program to print This is my first Java program

*

*/

class MyFirstProgram { // Declare class MyFirstProgram

void displayMessage() {

System.out.println(“This is my first Java program”);

}

public static void main(String[] args) {

MyFirstProgram myFirstProgram = new MyFirstProgram();

myFirstProgram.displayMessage();

}

}

Save the preceding contents in a file called MyFirstProgram.java

Compile and Run a Java Program

Compile: To compile MyFirstProgram.java source file in a MS-DOS prompt, give the following command: javac MyFirstProgram.java

After successfully compiling the earlier source file, the compiler generates MyFirstProgram.class file, which is made up of bytecodes. The compiled bytecode is platform independent. Run: To run the earlier Java program in a MS-DOS prompt, give the following command: java MyFirstProgram The JVM translates the bytecode into something that the underlying platform understands, and runs your program. The following output will be displayed in the command prompt after running the earlier command: This is my first Java program

Try It Out

Problem Statement: Illustrate the basic structure of a Java application program. Code: /**

* A Simple application.

*/

Page 49 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 50: Core Java Handout v1.0

Handout - Core Java

public class SimpleApp1 {

public static void main(String args[]) {

// A method to output to the console.

System.out.println("Simple program");

}

}

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

/** * A Simple application.*/ : A comment describing the program

public class SimpleApp1 { : Begin with the class specification public static void main(String args[]) { : Required method for

application programs // A method to output to the console. : Comment using two slashes System.out.println("Simple program"); : Print to console }: Curly braces span the code for a class. They also bracket the code of a method.

Tips and Tricks

Does a Java program need to have a main() method in every class written? Solution: No, a Java program might use dozens of classes (even hundreds), but you might have only one with a main() method, the one that starts the running of the program. You might write test classes, though, that have main methods for testing your other classes.

Summary

The method signature for the main method in a Java application is as follows: public static void main(String[] args)

Briefly explain the reason that the main method in a Java application is declared public.

The keyword public indicates that the method can be called by any object. Explain the reason that the main method in a Java application must be declared static. The keyword static indicates that the method is a class method which can be called

without the requirement to instantiate an object of the class. This is used by the Java interpreter to launch the program by invoking the main method of the class identified in the command to start the program.

Describe the purpose of the keyword void when used as the return type for the main method.

The void keyword when used as the return type for any Java methods indicates that the method does not return anything.

Page 50 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 51: Core Java Handout v1.0

Handout - Core Java

Test Your Understanding

1. State true or false for the following: a) The execution of a Java Program always starts with the main() method. b) There is no difference between System.out.print and System.out.println methods

in displaying the output. c) javac and java are the tools available in Java Development Kit (JDK). d) A bytecode is platform dependent.

Page 51 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 52: Core Java Handout v1.0

Handout - Core Java

Session 08: Introduction to Java and SDE

Learning Objectives

After completing this session, you will be able to: Describe the Standard Development Environment (SDE) Identify the various kinds of projects in SDE

Introduction to Java and SDE

SDE 4.x was built on top of Eclipse 3.3.0 (Europa) Features of SDE 4.x:

Easy to install You can build variety of applications such as: Simple Java Application Java Applets Dynamic Web applications using different frameworks such as Struts (1.1-2.0) and

Spring MVC (MVC stands for Model View Controller) Has good support to build JSF and Struts application J2EE Applications (Web applications with EJB and Web services) CTS Project

The new features of SDE 4.x are:

Platform Support: JBoss and Tomcat (Advanced version) Web Sphere community Ed Oracle application server Web logic Other runtime support WEB UI Tech: UML tools JavaScript Debugger AJAX tools JSF Designer Struts 1.3 & Struts 2.0 support Business Tier Tech: Spring tools Advanced Spring JPA EJB 3.0 *

Page 52 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 53: Core Java Handout v1.0

Handout - Core Java

Hibernate support Database tools Others: o Testing tool and Profiling tool o Reporting tool o SHRIMP 2.0 support o JBoss seam support o MyLyn support o Portlet support o Cheatsheet Support (ongoing updates)

CTS Project:

Designed for the Application Development Projects of CTS You can build Java, Web, andJ2EE projects

The following features can be enabled:

Formatting Part of a daily build Enable PMD Code Review tool (available on JCoE update site for this version) Enable JUnit Enable Code coverage using JCoverage (JCoverage not available for SDE 4.0) Associate a Repository Deployment environment Tomcat or JBoss

System Requirements: Hardware:

Intel Pentium III 800 MHz or higher recommended 1 GB RAM minimum and 2GB RAM works well Disk space requirements: 1.5GB minimum for installing SDE 4.0, Apache Tomcat

6.x, and MySQL 5.x Software: Windows XP and Linux

Tools

Purpose Plugins

J2EE Development Tools Lomboz STRUTS, Spring IDE, AspectJ Dev Tools

Server Plug-ins JBoss IDE, Tomcat Launcher, Weblogic, WASCE, OC4J

Code/Descriptor Generation XDoclet, Commonclipse, CodeSugar

Code Analysis & Formatting Jalopy, Checkstyle

Automated Testing JUnit

Profiler, Code Management and Metrics TPTP (Test and Performance Tool Platform), Metrics plugin, STAN

Page 53 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 54: Core Java Handout v1.0

Handout - Core Java

Tips and Tricks

Problem: Eclipse does not startup Solution: If Eclipse does not startup by clicking on short cut on desktop, then you do not have JDK 1.5 configured in your path. Please check the version of java by running java –version command. The JRE version needs to be 1.5.0. If the JDK version is lesser than 1.5, then please update the path settings to have %JAVA_HOME%\bin in the path before all other entries or run eclipse using eclipse.exe -vm %JAVA_HOME%\bin\javaw.exe command.

Summary

SDE 4.x was built on top of Eclipse 3.3.0 SDE is easy to install The following applications can be built using SDE: o Simple Java Application o Java Applets o Dynamic web applications using different frameworks such as Struts (1.1-2.0) and

Spring MVC o J2EE Applications (Web applications + EJB and Web Services).

Test Your Understanding

1. State true or false for the following: a) SDE 4.x was built on top of Eclipse 2.3.0. b) Jalopy and Checkstyle plugins are available in SDE for doing the code analysis

and formatting work. c) The Java Perspective in SDE supports developers who create, edit, and build

Java code.

Page 54 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 55: Core Java Handout v1.0

Handout - Core Java

Session 09: Introduction to Java and SDE

Learning Objectives

After completing this session, you will be able to: Create Java classes and packages

Creating New Java Project

Java projects contain the resources needed for Java applications, including Java files and class files.

Java projects are used to create Java packages. To create a new Java project, select File > New > Project.

1. Select Java Project from this page and click Next.

Page 55 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 56: Core Java Handout v1.0

Handout - Core Java

2. Name the Java project and specify the directory, where the project files should be stored. 3. Click Finish. 4. The project is configured with default options.

Creating Java Package

Once the Java project has been created, you can add Java packages to it. Select the project in the Package Explorer view and New > Package from the context

menu. In the dialog window, enter the fully qualified name of the package. Click Finish to create the package.

Page 56 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 57: Core Java Handout v1.0

Handout - Core Java

Creating Java Classes

After you have created the new package, you can add classes to it. To create a new class, select the package that has been created in the preceding step

and select New > Class. In the Name field of the new Java class dialog, you have to enter the name of the new

class. You can also set the modifiers, the name of the super class, add interfaces which

should be implemented, and create method stubs for the new class.

Page 57 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 58: Core Java Handout v1.0

Handout - Core Java

After all the settings have been made, click Finish to create the class.

Building Java Classes

The java files are compiled by the build process in SDE. All the files in the java project are compiled in one shot when the build process is

invoked. SDE provides facilities for both automatically building a java file and building it

manually. In automatic build, all the java files are recompiled when a resource is saved.

To enable automatic build for a project, click on Project > Build Automatically. To manually build a project, select the project and click on Project > Build Project.

Page 58 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 59: Core Java Handout v1.0

Handout - Core Java

Running Java Programs

After the code has been completed and is free of compile errors, it can be executed using the Workbench Java Application Launcher.

To launch the program, you click the Run icon from the toolbar. If you launch the program for the first time, then the Launch Configuration dialog

opens. In the Launch Configuration dialog box, you can select the type of configuration you

would like to create to run the program. Select Java Application from the list and right click New or simply double-click. A new launch configuration with the appropriate settings for the selected class is

created. You can also specify arguments, JRE, and classpath settings for your launch

configuration. Clicking Run invokes the main method of the class.

Page 59 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 60: Core Java Handout v1.0

Handout - Core Java

Tools

SDE (Standard Development Environment)

Tips and Tricks

Locating compile errors Solution:

All compilation errors in your Java code are shown in the Problems view. Double-clicking the entry in the problems list will navigate to the line in the source

editor, when the error was detected. Fix the errors highlighted by SDE and go on saving the work.

Page 60 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 61: Core Java Handout v1.0

Handout - Core Java

Summary

When a new Java project is created in SDE, the following can be performed: Create new packages Create new Java classes Build the Java classes Run the Java programs

Test Your Understanding

1. How is a new project created? a) Select File > New > Project b) Select File > New > Project Creation c) Select File > Make > Project d) Select File > New Elements > Project

Page 61 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 62: Core Java Handout v1.0

Handout - Core Java

Session 14: Language Fundamentals and Operators

Learning Objectives

After completing this session, you will be able to: Identify Java keywords, Java literals, and primitive data types

Java Keywords

Keywords are predefined identifiers reserved by Java for a specific purpose. You cannot use keywords as names for your variables, classes, methods, and so on.

A list of Java keywords are as follows:

Java Literals

Literals are tokens that do not change. They are constant in value. The different types of literals in Java are:

Integer Literals Floating-Point Literals Boolean Literals Character Literals String Literals

Java Literals: Integer

Integer literals come in different formats: decimal (base 10) hexadecimal (base 16) octal (base 8)

Page 62 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 63: Core Java Handout v1.0

Handout - Core Java

Special notations in using integer literals in Java programs: Decimal:

No special notation Example: 12

Hexadecimal:

Precede by 0x or 0X Example: 0xC

Octal:

Precede by zero Example: 014

Java Literals: Floating point

Represents decimals with fractional parts: Example: 3.1416

Can be expressed in standard or scientific notation:

Example: 583.45 (standard), 5.8345e2 (scientific)

Java Literals: Boolean

Boolean literals have only two values, true or false.

Java Literals: Character

Character Literals represent single Unicode characters. Unicode character:

A 16-bit character set that replaces the 8-bit ASCII character set Unicode allows the inclusion of symbols and special characters from other languages

Java Literals: Character

To use a character literal, enclose the character in single quote delimiter. For example: The letter a, is represented as ‘a’. Special characters such as a newline character, a backslash is used followed by the

character code. For example, ‘\n’ for the newline character, ‘\r’ for the carriage return, and ‘\b’ for backspace.

Java Literals: String

String literals represent multiple characters and are enclosed by double quotes. An example of a string literal is, “Hello World”.

Page 63 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 64: Core Java Handout v1.0

Handout - Core Java

Primitive Data Types

The Java programming language defines eight primitive data types: boolean (for logical) char (for textual) byte short int long (integral) double float (floating point)

Primitive Data Types: Logical-boolean

A boolean data type represents two states of true and false. An example is boolean result = true; The earlier example shown, declares a variable named result as boolean type and

assigns it a value of true.

Primitive Data Types: Textual-char

A character data type (char), represents a single Unicode character. It must have its literal enclosed in single quotes(’ ’). For example the following code:

‘a’ //The letter a

‘\t’ //A tab

To represent special characters like ' (single quotes) or " (double quotes), use the escape character \. For example the following code: '\'' //for single quotes

'\"' //for double quotes

Important points to remember:

A string represents a data type that contains multiple characters. It is not a primitive data type, rather it is a class.

It has its literal enclosed in double quotes(“”). For example, String message=“Hello world!”;

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

Integral data types in Java uses three forms of decimal, octal, or hexadecimal. Examples are:

2 // The decimal value 2 077 // The leading 0 indicates an octal value 0xBACC // The leading 0x indicates a hex value

Integral types has int as default data type.

Page 64 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 65: Core Java Handout v1.0

Handout - Core Java

You can define its long value by appending the letter l or L. For example: 10L

Integral data type have the following ranges:

Integer Length Name or Type Range

8 bits byte -27 to 27-1

16 bits short -215 to 215-1

32 bits int -231 to 231-1

64 bits long -263 to 263-1

Coding Guidelines: In defining a long value, a lowercase L is not recommended because it is hard to distinguish from the digit 1.

Primitive Data Types: Floating Point-float and double

Floating point types has double as default data type. Floating-point literal includes either a decimal point or one of the following,

E or e //(add exponential value) F or f //(float) D or d //(double)

Examples are:

3.14 //A simple floating-point value (a double) 6.02E23 //A large floating-point value 2.718F //A simple float size value 123.4E+306D //A large double value with redundant D

Floating-point data types have the following ranges:

Try It Out

Problem Statement: Write a program that contains the literal values for the following statements:

1. Declare an int named size and assign it the value 32 2. Declare a char named initial and assign it the value ‘j’. 3. Declare double named d and assign it the value 456.709 4. Declare a boolean named isAvailable(no assignment) 5. Assign the value true to the isAvailable that is declared earlier 6. Declare an int named y, and assign it the value that is the sum of whatever x and 456.

Page 65 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 66: Core Java Handout v1.0

Handout - Core Java

Code: class LiteralValues {

public static void main(String[] args) {

int size = 32;

char initial = 'j';

double d = 456.709;

boolean isAvailable;

isAvailable = true;

int y = size + 456;

}

}

Refer File Name: LiteralValues.java to obtain soft copy of the program code How It Works: You can assign a value to a variable in one of the following several ways including:

Type a literal value after the equals sign (x = 12, isGood = true, and so on) Assign the value of one variable to another (x = y) Use an expression combining the two (x = y + 43)

For the given problem statement, the literal values are shown in bold italics: int size = 32;

char initial = ‘j’;

double d = 456.709;

boolean isAvailable;

isAvailable = true;

int y = x + 456;

Tips and Tricks

List out few important points while using identifiers, literals, and keywords in Java. Solution:

An identifier must begin with a letter, dollar sign($), or underscore (_). Subsequent characters may be letters, $, _ (underscore), or digits.

An identifier cannot have a name of a Java keyword. Embedded keywords are accepted. true, false, and null are literals (not keywords), but they cannot be used as identifiers as well.

const and goto are reserved words, but not used. All numeric data types are signed. char is the only unsigned integral type. A number is by default an int literal. A decimal number is by default a double literal. 1E-5d is a valid double literal and E2d is not (since it starts with a letter, compiler

thinks that it’s an identifier).

Page 66 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 67: Core Java Handout v1.0

Handout - Core Java

Summary

Integer literals can be decimal, octal (e.g. 013), or hexadecimal (e.g. 0x3d). Literals for longs end in L or l (lowercase of the alphabet L). Float literals end in F or f, double literals end in a digit D or d. The boolean literals are true and false. Literals for chars are single character inside single quotes: ‘d’.

Test Your Understanding

1. Which one of the following is not a token? a) keyword b) identifier c) method d) literal

2. Which one of the following is not a valid identifier? total

a) _count b) sum c) 2root

3. The size of a long integer data type is: a) 8-bits b) 16-bits c) 32-bits d) 64-bits

Page 67 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 68: Core Java Handout v1.0

Handout - Core Java

Session 15: Language Fundamentals and Operators

Learning Objectives

After completing this session, you will be able to: Define variables Declare variables Initialize variables Convert data types Cast data types

Variables

A variable is an item of data used to store the state of objects. A variable has a:

data type: The data type indicates the type of value that the variable can hold. name: The variable name must follow rules for identifiers.

Declaring and Initializing Variables

Declare a variable as follows: <data type> <name> [=initial value];

Note: Values enclosed in <> are required values, while those values in [] are optional.

Reference Variables Versus Primitive Variables

Two types of variables in Java: Primitive Variables Reference Variables

Primitive Variables:

Variables with primitive data types such as int or long. Stores data in the actual memory location of where the variable is present

Reference Variables:

Variables that store the address in the memory location Points to another memory location where the actual data is present When you declare a variable of a certain class, you are actually declaring a reference

variable to the object with that certain class

Page 68 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 69: Core Java Handout v1.0

Handout - Core Java

Example of a reference variable and primitive variable

Suppose you have two variables with data types int and String. int num = 10; // primitive type

String name = "Hello"; // reference type

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

The following picture is the actual memory of your computer, wherein you have the address of the memory cells, the variable name, and the data they hold.

Type Casting

Type Casting is the mapping type of an object to another.

Casting Primitive Types

Casting between primitive types enables you to convert the value of one data from one type to another primitive type

Commonly occurs between numeric types There is one primitive data type that you cannot do casting and that is the boolean

data type Types of Casting: o Implicit Casting o Explicit Casting

Implicit Casting

Suppose you want to store a value of int data type to a variable of data type double. int numInt = 10;

double numDouble = numInt; //implicit cast

In this example, as the data type (double) of the destination variable holds a larger value than the data type (int) of the value, the data is implicitly casted to the data type double of the destination variable.

Page 69 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 70: Core Java Handout v1.0

Handout - Core Java

Example of implicit casting: int numInt1 = 1;

int numInt2 = 2;

//result is implicitly cast to type double

double numDouble = numInt1/numInt2;

Explicit Casting

When you convert a data that has a large type to a smaller type, you must use an explicit cast. Explicit casts take the following form: (Type)value where, Type is the name of the type you are converting to value. It is an expression that results in the value of the source type.

Explicit Casting Examples

double valDouble = 10.12;

int valInt = (int)valDouble;

//convert valDouble to int type

double x = 10.2;

int y = 2;

int result = (int)(x/y); //typecast result of operation to int

Casting Objects

Instances of classes also can be cast into instances of other classes, with one restriction. The source and destination classes must be related by inheritance. One class must be a subclass of the other. Casting objects is analogous to converting a primitive value to a larger type. Some objects might not need to be cast explicitly. Cast, (classname)object where, classname is the name of the destination class and object is a reference to the source object.

Casting Objects Example

The following example casts an instance of the class VicePresident to an instance of the class Employee. VicePresident is a subclass of Employee with more information, which here defines that the VicePresident has executive washroom privileges. Employee emp = new Employee();

VicePresident vp = new VicePresident();

// no cast needed for upward use

Page 70 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 71: Core Java Handout v1.0

Handout - Core Java

emp = vp;

// must cast explicitly

vp = (VicePresident)emp;

Try It Out

Problem Statement: Write a program that illustrates the implementation of the automatic initialization of member variables. Code: class Initialization {

boolean bo;

byte by;

char c;

short s;

int i;

long l;

float f;

double d;

Object o;

public static void main(String[] args) {

Initialization app = new Initialization();

app.run();

}

// continued …

Refer File Name: Initialization.java to obtain soft copy of the program code How It Works: The Initialization program illustrates the use of the automatic initialization of member variables. It displays the following output: boolean: false

byte: 0

char:

short: 0

int: 0

long: 0

float: 0.0

double: 0.0

Object: null

Page 71 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 72: Core Java Handout v1.0

Handout - Core Java

Tips and Tricks

List out the key points related to ‘instance’ (or member) variables and ‘local’ variables. Solution:

Instance (or member) variables: o Accessible anywhere in the class o Automatically initialized before invoking any constructor o Static variables are initialized at class load time o Can have the same name as the class

Local variables: o Must be initialized explicitly and (Or, the compiler will catch it.) Object references

can be initialized to null to make the compiler happy o The following code will not compile. Specify else part or initialize the local variable

explicitly.

public String testMethod(int a) {

String tmp;

if (a > 0) tmp = “Positive”;

return tmp;

}

Can have the same name as a member variable and resolution is based on scope Note: Here is the figure of allowable primitive conversion byte -> short -> int -> long -> float -> double char

Summary

Automatic conversion from narrow to wider type. For e.g., whenever division is performed between a floating type and an integer type, the integer type is automatically converted (sometimes called promoted) to a floating type and floating arithmetic is performed.

Arithmetic with boolean is not allowed. Variables can be initialized when declared All Java variables can be initialized when they are declared. Member (or instance) variables are automatically initialized If the programmer doesn't initialize the variables declared inside the class but outside

of a method (often referred to as member variables as opposed to local variables), they are automatically initialized to a default value.

The default value for a boolean member variable is false. Local variables are not automatically initialized Unlike instance (or member) variables, if you fail to initialize a local variable, the

variable is not automatically initialized. Must initialize or assign value to all local variables

Page 72 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 73: Core Java Handout v1.0

Handout - Core Java

Thus, the programmer is responsible for either initializing all local variables, or assigning a value to them before attempting to access their value with code later in the program.

Cannot access value from uninitialized local variable If you attempt to access and use the value from an uninitialized local variable before

you assign a value to it, you will get a compiler error.

Test Your Understanding

1. Which one of the following is not true in the case of Type declaration statement? a) Any number of variables can be declared in a Type declaration statement. b) Different types of variables can be declared in a single Type declaration

statement. c) The list of variables in a Type declaration statement should be separated by

commas. d) The Type declaration statement can be used to declare as well as initialize a

variable.

Page 73 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 74: Core Java Handout v1.0

Handout - Core Java

Session 16: Language Fundamentals and Operators

Learning Objectives

After completing this session, you will be able to: Write Java programs by declaring and initializing variables

Declaring and Initializing Variables: Sample Program

1 public class VariableSamples {

2 public static void main( String[] args ){

3 //declare a data type with variable name

4 //result and boolean data type

5 boolean result;

6

7 //declare a data type with variable name

8 // option and char data type

9 char option;

10 option = 'C'; //assign 'C' to option

11

12 //declare a data type with variable name

13 //grade, double data type and initialized

14 //to 0.0

15 double grade = 0.0;

16 }

17 }

Declaring and Initializing Variables: Coding Guidelines

It is always good to initialize your variables as you declare them. Apply descriptive names for your variables. For example, for a student’s grade, the variable name can be given as “grade” or

“studentGrade” instead of giving any other names. Declare one variable in each line of code. For example, the variable declarations:

double exam = 0; double quiz = 10; double grade = 0;

is preferred over the declaration double exam=0, quiz=10, grade=0;

Page 74 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 75: Core Java Handout v1.0

Handout - Core Java

Try It Out

Problem Statement: What will happen if you try to compile the code given in the next slide? Code: class Digit {

public void add() {

int k;

int s = k + 3;

}

}

Refer File Name: Digit.java to obtain soft copy of the program code How It Works: The preceding code will not compile. You can declare k without a value, but as soon as you try to use it, the compiler freaks out.

Tips and Tricks

Provide some important tips on conversion of primitives in Java Solution:

The three types of conversion are namely assignment conversion, method call conversion, and arithmetic promotion.

boolean may not be converted to or from any type that is not boolean. byte and short, cannot be converted to char and char cannot be converted to byte and

short. Arithmetic promotion:

Unary operators:

If the operand is byte, short or char {

convert it to int;

}

else {

do nothing; no conversion needed;

}

Binary operators:

If the operand is double {

all double; convert the other operand to double;

}

else if one operand is float {

Page 75 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 76: Core Java Handout v1.0

Handout - Core Java

all double; convert the other operand to double;

}

else if one operand is float {

all double; convert the other operand to double;

}

else {

all int; convert all to int;

}

Summary

Local variables (method variables) live on the stack. Objects and their instance variables live on the heap. Scope of a variable refers to the lifetime of variable. There are four basic scopes: Static variables live basically as long as their class lives. Instance variables live as long as their object lives. Local variables live as long as their method is on the stack; however, if their method

invokes another method, they are temporarily unavailable. Block variables (e.g., in a for or an if) live until the block completes.

Test Your Understanding

1. State true or false for the following: a) Extended assignment operators (for example +=) do an implicit cast. (Useful when

applied to byte, short or char as provided in the following example) byte b = 10;

b += 10;

Page 76 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 77: Core Java Handout v1.0

Handout - Core Java

Session 18: Language Fundamentals and Operators

Learning Objectives

After completing this session, you will be able to: Identify the different types of operators in Java

Operators

Different types of operators are: arithmetic operators relational operators logical operators conditional operators binary operator

These operators follow a certain kind of precedence so that the compiler will know which operator to evaluate first, in case multiple operators are used in one statement.

Arithmetic Operators

Arithmetic Operators: Sample Program 1 public class ArithmeticDemo {

2 public static void main(String[] args){

3 //a few numbers

4 int i = 37;

5 int j = 42;

6 double x = 27.475;

7 double y = 7.22;

8 System.out.println("Variable values...");

9 System.out.println(" i = " + i);

10 System.out.println(" j = " + j);

11 System.out.println(" x = " + x);

12 System.out.println(" y = " + y);

13 System.out.println("Adding...");

14 System.out.println(" i + j = " + (i + j));

15 System.out.println(" x + y = " + (x + y));

16 //subtracting numbers

17 System.out.println("Subtracting...");

18 System.out.println(" i - j = " + (i – j));

19 System.out.println(" x - y = " + (x – y));

20

21 //multiplying numbers

Page 77 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 78: Core Java Handout v1.0

Handout - Core Java

22 System.out.println("Multiplying...");

23 System.out.println(" i * j = " + (i * j));

24 System.out.println(" x * y = " + (x * y));

25

26 //dividing numbers

27 System.out.println("Dividing...");

28 System.out.println(" i / j = " + (i / j));

29 System.out.println(" x / y = " + (x / y));

30 //computing the remainder resulting from dividing

31 // numbers

32 System.out.println("Computing the remainder...");

33 System.out.println(" i % j = " + (i % j));

34 System.out.println(" x % y = " + (x % y));

35

36 //mixing types

37 System.out.println("Mixing types...");

38 System.out.println(" j + y = " + (j + y));

39 System.out.println(" i * x = " + (i * x));

40 }

Arithmetic Operators: Sample Program Output

Variable values... Dividing... i = 37 i / j = 0

j = 42 x / y = 3.8054

x = 27.475

y = 7.22 Computing the remainder... i % j = 37

Adding... x % y = 5.815

i + j = 79

x + y = 34.695 Mixing types... j + y = 49.22

Subtracting... i * x = 1016.58

i - j = -5

x - y = 20.255

Multiplying... i * j = 1554

x * y = 198.37

Arithmetic Operators

Note: When an integer and a floating-point number are used as operands to a single arithmetic operation, the result is a floating point. The integer is implicitly converted to a floating-point number before the operation takes place.

Page 78 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 79: Core Java Handout v1.0

Handout - Core Java

Increment and Decrement Operators

unary increment operator (++) and unary decrement operator (--) are the two increment and decrement operators. Increment and decrement operators increase and decrease a value stored in a number variable by 1. For example the expression, count=count + 1; //increment the value of count by 1 is equivalent to count++;.

Operator Use Description

++ op++ Increments op by 1; evaluates to the value of op before it was incremented

++ ++op Increments op by 1; evaluates to the value of op before it was incremented

-- op-- Decrements op by 1; evaluates to the value of op before it was decremented

-- --op Decrements op by 1; evaluates to the value of op after it was decremented

The increment and decrement operators can be placed before or after an operand. When used before an operand, it causes the variable to be incremented or decremented by 1, and then the new value is used in the expression in which it appears. For example: int i = 10;

int j = 3;

int k = 0;

k = ++j + i; //will result to k = 4+10 = 14

When the increment and decrement operators are placed after the operand, the old value of the variable will be used in the expression where it appears. For example: int i = 10;

int j = 3;

int k = 0;

k = j++ + i; //will result to k = 3+10 = 13

Increment and Decrement Operators: Coding Guidelines

Always keep expressions containing increment and decrement operators simple and easy to explain.

Relational Operators

Relational operators compare two values and determine the relationship between those values. The output of evaluation is the boolean value of true or false.

Page 79 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 80: Core Java Handout v1.0

Handout - Core Java

Operator Use Description

++ op++ Increments op by 1; evaluates to the value of op before it was incremented

++ ++op Increments op by 1; evaluates to the value of op before it was incremented

-- op-- Decrements op by 1; evaluates to the value of op before it was decremented

-- --op Decrements op by 1; evaluates to the value of op after it was decremented

Relational Operators: Sample Program

1 public class RelationalDemo{

2 public static void main(String[] args){

3 //a few numbers

4 int i = 37;

5 int j = 42;

6 int k = 42;

7 System.out.println("Variable values...");

8 System.out.println(" i = " +i);

9 System.out.println(" j = " +j);

10 System.out.println(" k = " +k);

11 //greater than

12 System.out.println("Greater than...");

13 System.out.println(" i > j = "+(i>j));//false

14 System.out.println(" j > i = "+(j>i));//true

15 System.out.println(" k > j = "+(k>j));//false

16 //greater than or equal to

17 System.out.println("Greater than or equal to");

18 System.out.println(" i >= j = "+(i>=j));//false

19 System.out.println(" j >= i = "+(j>=i));//true

20 System.out.println(" k >= j = "+(k>=j));//true

21 //less than

22 System.out.println("Less than...");

23 System.out.println(" i < j = "+(i<j));//true

24 System.out.println(" j < i = "+(j<i));//false

25 System.out.println(" k < j = "+(k<j));//false

26 //less than or equal to

27 System.out.println("Less than or equal to...");

28 System.out.println(" i <= j = "+(i<=j));//true

29 System.out.println(" j <= i = "+(j<=i));//false

30 System.out.println(" k <= j = "+(k<=j));//true

31 //equal to

32 System.out.println("Equal to...");

33 System.out.println(" i == j = " + (i==j));//false

34 System.out.println(" k == j = " + (k==j));//true

Page 80 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 81: Core Java Handout v1.0

Handout - Core Java

35 //not equal to

36 System.out.println("Not equal to...");

37 System.out.println(" i != j = " + (i!=j));//true

38 System.out.println(" k != j = " + (k!=j));//false

39 }

40 }

Relational Operators: Sample Program Output

Variable values: i = 37

j = 42

k = 42

Greater than: i > j = false

j > i = true

k > j = false

Greater than or equal to: i >= j = false

j >= i = true

k >= j = true

Less than: i < j = true

j < i = false

k < j = false

Less than or equal to: i <= j = true

j <= i = false

k <= j = true

Equal to: i == j = false k == j = true

Not equal to... i != j = true k != j = false

Logical Operators

Logical operators have one or two boolean operands that yield a boolean result. There are six logical operators:

&& (logical AND) & (boolean logical AND) || (logical OR)

Page 81 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 82: Core Java Handout v1.0

Handout - Core Java

| (boolean logical inclusive OR) ^ (boolean logical exclusive OR) ! (logical NOT)

The basic expression for a logical operation is, x1 op x2 where, x1, x2 can be boolean expressions, variables or constants. op is either &&, &, ||, | or ^ operator. The truth tables that will be shown next, summarize the result of each operation for all possible combinations of x1 and x2.

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

Here is the truth table for && and &:

x1 x2 Result

TRUE TRUE TRUE

TRUE FALSE FALSE

FALSE TRUE FALSE

FALSE FALSE FALSE

The basic difference between && and & operators is that && supports short-circuit evaluations (or partial evaluations), while & does not. Given an expression exp1 && exp2 where:

&& will evaluate the expression exp1, and immediately return a false value if exp1 is false.

If exp1 is false, then the operator never evaluates exp2 because the result of the operator will be false regardless of the value of exp2.

In contrast, the & operator always evaluates both exp1 and exp2 before returning an answer.

1 public class TestAND {

2 public static void main( String[] args ){

3 int i = 0;

4 int j = 10;

5 boolean test= false;

6 //demonstrate &&

7 test = (i > 10) && (j++ > 9);

8 System.out.println(i);

9 System.out.println(j);

10 System.out.println(test);

11 //demonstrate &

12 test = (i > 10) & (j++ > 9);

13 System.out.println(i);

14 System.out.println(j);

Page 82 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 83: Core Java Handout v1.0

Handout - Core Java

15 System.out.println(test);

16 }

17 }

The output of the program is: 0

10

false

0

11

false

Note, that the j++ on the line containing the && operator is not evaluated because the first expression (i>10) is already equal to false

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

Here is the truth table for || and |:

x1 x2 Result

TRUE TRUE TRUE

TRUE FALSE FALSE

FALSE TRUE FALSE

FALSE FALSE FALSE

The basic difference between || and I operators is that || supports short-circuit evaluations (or partial evaluations), while | does not. Given an expression exp1 || exp2 where:

|| will evaluate the expression exp1 and immediately return a true value if exp1 is true. If exp1 is true, then the operator never evaluates exp2 because the result of the

operator will be true regardless of the value of exp2. In contrast, the | operator always evaluates both exp1 and exp2 before returning an

answer.

1 public class TestOR {

2 public static void main( String[] args ){

3 int i = 0;

4 int j = 10;

5 boolean test= false;

6 //demonstrate ||

7 test = (i < 10) || (j++ > 9);

8 System.out.println(i);

9 System.out.println(j);

10 System.out.println(test);

Page 83 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 84: Core Java Handout v1.0

Handout - Core Java

11 //demonstrate |

12 test = (i < 10) | (j++ > 9);

13 System.out.println(i);

14 System.out.println(j);

15 System.out.println(test);

16 }

17 }

The output of the program is: 0

10

true

0

11

true

Note, that the j++ on the line containing the || operator is not evaluated because the first expression (i<10) is already equal to true

Logical Operators: ^ (boolean logical exclusive OR)

Here is the truth table for ^:

x1 x2 Result

TRUE TRUE TRUE

TRUE FALSE FALSE

FALSE TRUE FALSE

FALSE FALSE FALSE

The result of an exclusive OR operation is TRUE, if and only if one operand is true and the other is false. Note that both operands must always be evaluated in order to calculate the result of an exclusive OR. 1 public class TestXOR {

2 public static void main( String[] args ){

3 boolean val1 = true;

4 boolean val2 = true;

5 System.out.println(val1 ^ val2);

6 val1 = false; val2 = true;

7 System.out.println(val1 ^ val2);

8 val1 = false; val2 = false;

9 System.out.println(val1 ^ val2);

10 val1 = true; val2 = false;

Page 84 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 85: Core Java Handout v1.0

Handout - Core Java

11 System.out.println(val1 ^ val2);

12 }

13 }

The output of the program is: false

true

false

true

Logical Operators: ! ( logical NOT)

The logical NOT takes in one argument, wherein that argument can be an expression, variable, or constant. Here is the truth table for !.

x1 Result

TRUE FALSE

FALSE TRUE

1 public class TestNOT {

2 public static void main( String[] args ){

3 boolean val1 = true;

4 boolean val2 = false;

5 System.out.println(!val1);

6 System.out.println(!val2);

7 }

8 }

The output of the program is: false

true

Logical Operators: Conditional Operator (?:)

The conditional operator ? is a ternary operator. This means that it takes in three arguments that together form a conditional expression: The structure of an expression using a conditional operator is exp1?exp2:exp3wherein exp1 is a boolean expression whose result must either be true or false

Page 85 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 86: Core Java Handout v1.0

Handout - Core Java

Result: If exp1 is true, then exp2 is the value returned If it is false, then exp3 is returned

1 public class ConditionalOperator {

2 public static void main( String[] args ){

3 String status = "";

4 int grade = 80;

5 //get status of the student

6 status = (grade >= 60)?"Passed":"Fail";

7 //print status

8 System.out.println( status );

9 }

10 }

The output of this program will be: Passed

Flowchart related to student’s grade

The instanceof Operator

The instanceof operator is a binary operator that determines whether an object reference (the left operand) is an instance of the class, interface, or array type specified by the right operand.

The instanceof operator cannot be used with primitive types (this results in a compilation error).

The instanceof operator returns a boolean value of true if the left operand references a non-null object of class C (or array of type T), so that at least one of the following conditions hold:

The right operand is a class name C' and C is a subclass of C'. The right operand is an interface name I, and C implements I. The right operand is an array of type T‘ , the left operand is an array of type T, and T is

a subclass or subinterface of T' or equal to T'.

Page 86 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 87: Core Java Handout v1.0

Handout - Core Java

The instanceof operator returns false if none of the preceding conditions are met or if the left operand is null.

Operator Precedence

In a complicated expression, 6%2*5+4/2+88-10 you can rewrite the expression and place some parenthesis based on operator precedence, like ((6%2)*5)+(4/2)+88-10;.

Operator Precedence: Coding Guidelines

To avoid confusion in evaluating mathematical operations, keep your expressions simple and use parentheses.

Try It Out

Problem Statement: Write a program that illustrates the use of the instanceof operator. Code: import java.util.*;

class Instance {

public static void main(String args[]) {

String s = "abcd";

Vector v = new Vector();

v.add(s);

Object o = v.elementAt(0);

System.out.println(s instanceof String);

System.out.println(s instanceof Object);

Page 87 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 88: Core Java Handout v1.0

Handout - Core Java

System.out.println(o instanceof String);

System.out.println(o instanceof Object);

System.out.println(o instanceof Vector);

}

}

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

When you run the program, it produces the following results: true

true

true

true

false

The first two output lines reflect the fact that s is a String and therefore an Object (because String is a subclass of Object)

The third output line displays a value of true even though o is declared to be of type Object because the object assigned to o is the String object that was added to Vector v

The fourth and fifth output lines result from the fact that a String object is an Object object but not a Vector object.

Tips and Tricks

On what situations can you use the ‘==‘ operator? Solution: To compare two primitives, use the == operator. Example:

int a = 3; int b = 3; if (a == b) { // true}

To see if two references are the same, (which means they refer to the same object on the heap) use the == operator. Example:

Foo a = new Foo(); Foo b = new Foo(); Foo c = a; if (a == b) { // false } if (a == c) { // true } if (b == c) { // false }

To compare if two different objects are equal, use the equals() method.

Page 88 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 89: Core Java Handout v1.0

Handout - Core Java

Summary

The different types of operators are: o Arithmetic operators o Increment and decrement operators o Relational operators o Conditional operators o Logical operators

To avoid confusion in evaluating mathematical operations, keep your expressions simple and use parentheses.

Test Your Understanding

1. State true or false for the following: a) The character pair ?: is called the relational operator. b) In a mixed expression, the highest ranking operand is identified and the values of

all other operands in the expression are automatically converted to the type of the highest ranking operand.

Page 89 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 90: Core Java Handout v1.0

Handout - Core Java

Session 21: Language Fundamentals and Operators

Learning Objectives

After completing this session, you will be able to: Define JUnit Framework Identify the importance of JUnit Framework Describe JUnit mechanics List the Fixtures Identify Test Suites List Test Runners Identify JUnit classes Identify the best practice guidelines Identify the design patterns for testing List Extensions

Importance of Test

Automated tests prove feature Tests retain their value over time and allow others to prove that the software still works

(as tested)). Write test cases first and then code it. Code quality is improved since the code is tested against the test cases at various

stages.

Test Driven Development

TDD (Test Driven Development) is a software development technique that involves repeatedly first writing a test case and then implementing only the code necessary to pass the test.

TDD gives rapid feedback.

Unit Testing

Unit testing is a procedure used to validate that individual units of source code are working properly.

A unit is the smallest testable part of an application. In procedural programming a unit may be an individual program, function, procedure, Web page, menu, and so on while in object-oriented programming, the smallest unit is always a class, which may be a base or super class, abstract class or derived or child class.

JUnit

JUnit is a regression testing framework. JUnit is used by developers to implement unit tests in Java (de-facto standard)

Page 90 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 91: Core Java Handout v1.0

Handout - Core Java

Integrated with Ant: Testing is performed as part of nightly build process Goal: Accelerate programming and increase the quality of code JUnit is a part of XUnit family testing framework

Importance of JUnit

Without JUnit, you will have to use println() to print out some result: No explicit concept of test passing or failure No mechanism to collect results in a structured fashion No replicability JUnit addresses all these issues

Key Goals of JUnit

The key goals of JUnit are: Easy to use to create tests Create tests that retain their value overtime Leverage existing tests to write new ones (reusable)

Services Provided by JUnit

The services provided by JUnit are: API for easily creating Java test case Comprehensive assertion facilities Verify expected versus actual results Test runners for running tests Aggregation facility (test suites) Reporting

Guidelines for Writing Code Based on JUnit Test (Minimum)

The guidelines for writing code based on JUnit test are: Include junit.jar in the classpath Define a subclass of TestCase class Define one or more public testXxx() methods in the subclass Write assert statements inside testXxx() method Optionally define main() method to run the test case in standalone mode

Test Methods

Test methods has name pattern testXxx(). Xxx reflects the method of the target class. Test methods must have no arguments. Test methods are type of void.

Page 91 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 92: Core Java Handout v1.0

Handout - Core Java

Example 1: Very Simple Test

import junit.framework.TestCase;

public class SimpleTest extends TestCase {

public SimpleTest(String name) {

super(name);

}

// Test code

public void testSomething() {

System.out.println("About to call assertTrue() method...");

assertTrue(4 == (2 * 2));

}

// You don't have to have main() method, use Test runner

public static void main(String[] args){

junit.textui.TestRunner.run(SimpleTest.class);

}

}

Guidelines for Writing Code Based on JUnit Test (Sophisticated)

The guidelines for writing code based on JUnit test are: Optionally override the setUp() and tearDown() methods: Create common test data Optionally define a static suite() factory method Create a TestSuite containing all the tests

Example 2: More Sophisticated Example

//Define a subclass of TestCase

public class StringTest extends TestCase {

// Create fixtures

protected void setUp(){ /* run before */}

protected void tearDown(){ /* after */ }

// Add testing methods

public void testSimpleAdd() {

String s1 = new String(“abcd”);

String s2 = new String(“abcd”);

assertTrue(“Strings not equal”, s1.equals(s2));

}

Page 92 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 93: Core Java Handout v1.0

Handout - Core Java

// Could run the test in batch mode

public static void main(String[] args){

junit.textui.TestRunner.run (suite ());

}

// continued …

// Create TestSuite object

public static Test suite (){

suite = new TestSuite ("StringTest");

String tests = System.getProperty("tests");

if (tests == null){

suite.addTest(new TestSuite(StringTest.class));

} else {

StringTokenizer tokens = new

StringTokenizer(tests, ",");

while (tokens.hasMoreTokens()){

suite.addTest(new

StringTest((String)tokens.nextToken()));

}

}

return suite;

}

Assert Statements

JUnit assertions are methods starting with the keyword assert. An assert statement determines the success or failure of a test. An assert is simply a comparison between an expected result and the actual value. Two variants are: o assertXxx(...)

o assertXxx(String message, ...)

The message is displayed when assertXxx() fails. assertTrue() statement asserts that the given condition is true: o assertTrue(boolean condition)

o assertTrue(String message, boolean condition)

assertFalse() statement asserts that the given condition is false o assertFalse(boolean condition)

o assertFalse(String message, boolean condition)

assertEquals() statement asserts that the expected result is equal to the actual behavior o assertEquals(expected, actual)

o assertEquals(String message, expected, actual)

assertSame() statement asserts that the expected result is same as the actual behavior o assertSame(Object expected, Object actual)

o assertSame(String message, Object expected, Object actual)

Page 93 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 94: Core Java Handout v1.0

Handout - Core Java

assertNull() statement asserts that the object reference is null o assertNull(Object obj)

o assertNull(String message, Object obj)

assertNotNull() statement asserts that the object reference is not null o assertNotNull(Object obj)

o assertNotNull(String message, Object obj)

The fail() statement forces a failure o fail()

o fail(String message)

Fixtures

setUp() and tearDown()methods are used to initialize and release common test data. The setUp() method is run before every test invocation and the tearDown() method is

run after every test method.

Example: setUp

public class MathTest extends TestCase {

protected double fValue1, fValue2;

protected void setUp() {

fValue1= 2.0;

fValue2= 3.0;

}

public void testAdd() {

double result= fValue1 + fValue2;

assertTrue(result == 5.0);

}

public void testMultiply() {

double result= fValue1 * fValue2;

assertTrue(result == 6.0);

}

}

Test Suites

Test Suites are used to collect all the test cases Test Suites can contain testCases and testSuites:

TestSuite(java.lang.Class theClass, <java.lang.String name>)

addTest(Test test) or addTestSuite(java.lang.Class testClass)

Test Suites can have hierarchy

Page 94 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 95: Core Java Handout v1.0

Handout - Core Java

Example: Test Suites

public static void main (String [] args){

junit.textui.TestRunner.run (suite ());

}

public static Test suite (){

suite = new TestSuite("AllTests");

suite.addTest(new TestSuite (AllTests.class));

suite.addTest(StringTest.suite());

}

public void testAllTests () throws Exception{

assertTrue (suite != null);

}

public static Test suite() {

TestSuite suite = new TestSuite(IntTest.class);

suite.addTest(new TestSuite(FloatTest.class));

suite.addTest(new TestSuite(BoolTest.class));

return suite;

}

TestRunners

Highlights of the Test Runner in text mode: Lightweight, quick quiet Run from command line Example: java StringTest

.......

Time: 0.05

Tests run: 7, Failures: 0, Errors: 0

TestRunners: Swing

Run with java junit.swingui.TestRunner:

Page 95 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 96: Core Java Handout v1.0

Handout - Core Java

The swingui TestRunner provides the summary of test runs in GUI mode.

Automating Testing (Ant)

The JUnit task is shown in the following code: <target name="test" depends="compile-tests">

<junit printsummary="yes" fork="yes">

<classpath>

<pathelement location="${build}" />

<pathelement location="${build}/test" />

</classpath>

<formatter usefile="yes" type="plain" />

<test name="AllTests" />

</junit>

</target>

Ant Batch Mode

<target name="batchtest" depends="compile-tests">

<junit printsummary="yes" fork="yes" haltonfailure="no"> <classpath>

<pathelement location="${build.dir}" />

Page 96 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 97: Core Java Handout v1.0

Handout - Core Java

Page 97 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

<pathelement location="${build.dir}/test" />

</classpath>

<formatter type="plain" usefile="yes"/>

<batchtest fork="yes" todir="">

<fileset dir="${test.dir}">

<include name="**/*Test.java" />

</fileset>

</batchtest>

</junit>

</target>

JUnit Class Diagram

Class diagram of JUnit framework API

? Best Practices: What Should You Test

Tests things, which could break Write test case methods such that the testing should succeed quietly

etter methods Do not write test case methods for the compiler

What should not you test Do not write test case methods for the setter or g

Page 98: Core Java Handout v1.0

Handout - Core Java

Test First and What to Test

Key points on Testing Write your test first, or at least at the same time Test what can break Create new tests to show bugs and then fix the bug Test driven development says write the test case first and then make it pass by coding

to it

Testing for Exceptions

public void testExpectException()

{

String s1 = null;

String s2 = new String("abcd");

try {

s1.toString();

fail("Should see null pointer");

} catch(NullPointerException ex) {

assertTrue(true);

}

}

Test Then Fix

Bugs occasionally slip through (gasp!). Write a test first, which demonstrates the error. Obviously, this test is needed. Now, fix the bug and watch the bar go green!! Your tests assure that the bug will not reappear.

Test then Refactor

Once the code is written you will want to improve it. The test cases should be written keeping the following factors in mind are

performance, maintainability, and readability. Tests help you to make sure that you do not break it while improving it. Test a little, code a little, test a little, code a little...

Design Patterns for Testing

Separation of interface and implementation: Allows substitution of implementation to tests Factory pattern: Provides abstraction of creation of implementations from the tests Strategy pattern: Because FactoryFinder dynamically resolves desired factory, implementations are pluggable.

Page 98 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 99: Core Java Handout v1.0

Handout - Core Java

Design for Testing: Factories

Allows writing tests, which can be used across multiple implementations Promotes frequent testing by writing tests, which work against objects without requiring extensive setUp: “extra-container” testing

Design for Testing: Mock Objects

You can use the concept of mock objects when your implementation requires a resource that is unavailable for testing.

The mock objects mock the functionality of the desired resource. For example, using the mock objects concept, the external system or database can be

simulated. The mock objects eliminate the dependency of the external system or database

whenever these actual resources are either not available or be difficult for testing. In these cases, the testing gets continued with the mock objects.

Testing with Resources (EJB or DB)

Testing with resources use fixtures to request resource connection by factory pattern. Testing with resources also use vm args or resource bundle to drive, which factory is

used. Data initialization or clearing is handled by fixtures to preserve order independence of

tests.

JUnit Extensions

The extensions of JUnit are: JUnitReport Cactus JWebUnit XMLUnit MockObjects StrutsTestCase

JUnitReport

JUnitReport is an Apache Ant extension task. This uses XML and XSLT to generate HTML.

Page 99 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 100: Core Java Handout v1.0

Handout - Core Java

Cactus (from Jakarta)

A simple test framework for unit testing server-side Java code is as follows:

JWebUnit

JWebUnit is a framework that facilitates creation of acceptance tests for Web applications.

XMLUnit

XMLUnit provides a XMLTestCase class, which enables assertions to be made about the content and structure of XML:

Differences between two pieces of XML Validity of a piece of XML Outcome of transforming a piece of XML using XSLT Evaluation of an XPath expression on a piece of XML

Page 100 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 101: Core Java Handout v1.0

Handout - Core Java

Mock Objects

The goal of generic unit testing framework is to facilitate developing unit tests in the mock object style.

Mock object: "double agent" used to test the behavior of other objects Dummy object, which mimics the external behavior of a true implementation Observes how other objects interact with its methods and compares actual behavior

with preset expectations

StrutsTestCase

StrutsTestCase extends the JUnit TestCase class that provides facilities for testing code based on the Struts framework. You can test the following:

Implementation of your action objects Mappings declarations Form beans declarations Forwards declarations

Try It Out

Problem Statement: Write a JUnit test file for a Java source and run it using JUnit tool in SDE. Code: package com.testing;

import junit.framework.TestCase;

public class HelloTest extends TestCase {

public static void main(String[] args) {

junit.textui.TestRunner.run(HelloTest.class);

}

Hello hello = new Hello();

protected void setUp() throws Exception {

super.setUp();

}

// continued …

Refer Files: Hello.java, HelloTest.java to obtain soft copy of the program code

Page 101 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 102: Core Java Handout v1.0

Handout - Core Java

How It Works: To test a file using JUnit tool in SDE, create a new JUnit test case by clicking NEW >

JUnit Test Case. There you can also give the name of the class you are intending to test. Like in this

case, Hello is the class, which is to be, tested using JUnit. The class only contains getters and setters for the string ‘str’.

1. Click Next to go the next page where you can specify, which all methods you need to test in the Hello class.

Page 102 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 103: Core Java Handout v1.0

Handout - Core Java

2. Click Finish to create the JUnit test case. 3. Write your logic in the test method that is automatically generated. 4. To run the JUnit test, right click on the test case class created and click on RUN > JUnit

Test. 5. The JUnit window will be opened indicating which were the tests that failed and which all

passed.

Page 103 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 104: Core Java Handout v1.0

Handout - Core Java

Screenshot of sample JUnit test run

After selecting a test case method in JUnit console on the left hand side pane, the specified method statements are highlighted in the Editor window.

You can also see the expected and the actual result by clicking the ‘Compare actual with the expected result’ button. In this case, the expected result was ‘Hello world” but the actual result was ‘Hello world!”.

Page 104 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 105: Core Java Handout v1.0

Handout - Core Java

Tips and Tricks

You have got really strange ClassNotFoundExceptions with JUnit 3.7 Solution:

Does your class work fine if you run the test cases using the TextRunner? If yes, then the following explanation is probably correct: The graphical test runners apply a different class loader than the text version. This

class loader uses a special list, junit/runner/excluded.properties to define, which classes are never reloaded, and it typically contains classes such as sun.* , javax.* , com.sun.* , and so on.

The class loader does not load files from a jar-file, and as most of the external libraries are distributed as such, you need to either unpack your external jar, or tell the JUnit class loader, which classes should never be reloaded.

The latter is probably more sensible, so you will not have unpacked jars cluttering your directory structure.

You need to unpack the junit.jar file, and edit the excluded.properties file to add packages like org.apache.* and org.xml.*.

Then repack the junit.jar file and apply that. Here is an example of excluded.properties file:

#

# The list of excluded package paths for the TestCaseClassLoader

#

excluded.0=sun.*

excluded.1=com.sun.*

excluded.2=org.omg.*

excluded.3=javax.*

excluded.4=sunw.*

excluded.5=java.*

excluded.6=junit.*

excluded.7=oracle.*

excluded.8=org.apache.*

Summary

Testing Idioms: Keep the following things in mind when writing JUnit tests: o The software does well those things that the tests check. o Test a little, code a little, test a little, code a little... o Make sure all tests always run at 100%. o Run all the tests in the system at least once per day (or night). o Write tests for the areas of code with the highest probability of breakage. o Write tests that have the highest possible return on your testing investment. o If you find yourself debugging using System.out.println(), write a test to

automatically check the result instead.

Page 105 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 106: Core Java Handout v1.0

Handout - Core Java

o When a bug is reported, write a test to expose the bug. o The next time someone asks you for help debugging, help them write a test. o Write unit tests before writing the code and only write new code when a test is

failing.

Test Your Understanding

1. State true or false for the following: a) JUnit is a regression testing framework. b) setUp() is run before every test invocation and tearDown() is run after every test

method.

Page 106 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 107: Core Java Handout v1.0

Handout - Core Java

Session 23: Language Fundamentals and Operators

Learning Objectives

After completing this session, you will be able to: Define an array Declare an array Instantiatiate an array Access array element Identify array length, array of multiple dimension, and Enum

Introduction to Arrays

Suppose you have here three variables of type int with different identifiers for each variable. int number1;

int number2;

int number3;

number1 = 1;

number2 = 2;

number3 = 3;

As you can see, it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose. In Java and other programming languages, there is one capability wherein you can apply one variable to store a list of data and manipulate them more efficiently. This type of variable is called an array. An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots.

Declaring Arrays

To declare an array, write the data type, followed by a set of square brackets[], followed by the identifier name. For example,

int []ages;

or int ages[];

Page 107 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 108: Core Java Handout v1.0

Handout - Core Java

Array Instantiation

After declaring, you must create the array and specify its length with a constructor statement. Definitions: Instantiation: In Java, this means creation Constructor: In order to instantiate an object, you need to use a constructor for this. A constructor is a method that is called to create a certain object. You will cover more about instantiating objects and constructors later. To instantiate (or create) an array, write the new keyword, followed by the square brackets containing the number of elements you want the array to have. For example, //declaration

int ages[];

//instantiate object

ages = new int[100];

or, can also be written as, //declare and instantiate object

int ages[] = new int[100];

Sample diagram illustrating array instantiation

You can also instantiate an array by directly initializing it with data. For example, int arr[] = {1, 2, 3, 4, 5};

This statement declares and instantiates an array of integers with five elements (initialized to the values 1, 2, 3, 4, and 5).

Page 108 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 109: Core Java Handout v1.0

Handout - Core Java

Sample Program

1 //creates an array of boolean variables with identifier

2 //results. This array contains 4 elements that are

3 //initialized to values {true, false, true, false}

4

5 boolean results[] = { true, false, true, false };

6

7 //creates an array of 4 double variables initialized

8 //to the values {100, 90, 80, 75};

9

10 double []grades = {100, 90, 80, 75};

11

12 //creates an array of Strings with identifier days and

13 //initialized. This array contains 7 elements

14

15 String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”};

Accessing an Array Element

To access an array element, or a part of the array, you use a number called an index or a subscript. Index number or subscript: Assigned to each member of the array, to allow the program to access an individual member of the array Begins with zero and progress sequentially by whole numbers to the end of the array Note: Elements inside your array are from zero to (sizeOfArray-1). For example, in the given array you have declared a while ago (see slide 10), you have: //assigns 10 to the first element in the array

ages[0] = 10;

//prints the last element in the array

System.out.print(ages[99]);

Note: Once an array is declared and constructed, the stored value of each member of the array will be initialized to zero for number data. For reference data types such as Strings, they are not initialized to blanks or an empty string “”. Therefore, you must populate the String arrays explicitly.

Page 109 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 110: Core Java Handout v1.0

Handout - Core Java

The following is a sample code on how to print all the elements in the array. This uses a for loop, so your code is shorter. 1 public class ArraySample{

2 public static void main( String[] args ){

3 int[] ages = new int[100];

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

5 System.out.print( ages[i] );

6 }

7 }

8 }

Coding Guidelines

It is usually better to initialize or instantiate the array right away after you declare it. For example, the declaration, int []arr = new int[100];

is preferred over, int []arr;

arr = new int[100];

The elements of an n-element array have indexes from zero to n-1. Note that there is no array element arr[n]! This will result in an array-index-out-of-bounds exception. Remember you cannot resize an array.

Array Length

In order to get the number of elements in an array, you can use the length field of an array.

The length field of an array returns the size of the array. It can be applied by writing,

arrayName.length

1 public class ArraySample {

2 public static void main( String[] args ){

3 int[] ages = new int[100];

4

5 for( int i=0; i<ages.length; i++ ){

6 System.out.print( ages[i] );

7 }

8 }

9 }

Coding Guidelines

When creating for loops to process the elements of an array, use the length field of the array object in the condition statement of the for loop. This will allow the loop to adjust automatically for different-sized arrays.

Page 110 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 111: Core Java Handout v1.0

Handout - Core Java

Declare the sizes of arrays in a Java program using named constants to make them easy to change. For example,

final int ARRAY_SIZE = 1000; //declare a constant

. . .

int[] ages = new int[ARRAY_SIZE];

Multidimensional Arrays

Multidimensional arrays are implemented as arrays of arrays. Multidimensional arrays are declared by appending the appropriate number of bracket

pairs after the array name. For example: // integer array 512 x 128 elements

int[][] twoD = new int[512][128];

// character array 8 x 16 x 24

char[][][] threeD = new char[8][16][24];

// String array 4 rows x 2 columns

String[][] dogs = {{ "terry", "brown" },

{ "Kristin", "white" },

{ "toby", "gray"},

{ "fido", "black"}

};

To access an element in a multidimensional array is just the same as accessing the elements in an one dimensional array. For example, to access the first element in the first row of the array dogs, you write, System.out.print( dogs[0][0] );

This will print the String "terry" on the screen.

Enum

An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST,

and WEST) and the days of the week. As they are constants, the names of the fields of an enum type are in uppercase

letters.

enum Keyword

In the Java programming language, you define an enum type by using the enum keyword.

Page 111 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 112: Core Java Handout v1.0

Handout - Core Java

For example, you would specify a days-of-the-week enum type as:

public enum Day {

SUNDAY, MONDAY, TUESDAY, WEDNESDAY,

THURSDAY, FRIDAY, SATURDAY

}

enum Type

You should use enum types any time you need to represent a fixed set of constants, which includes natural enum types such as the planets in your solar system and data sets where you know all possible values at compile time

For example, the choices on a menu, command line flags, and so on Java programming language enum types are much more powerful than their

counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of

the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

Example: enum in for Loop

For example, the following code iterates over all the planets in the solar system. for (Planet p : Planet.values()) {

System.out.println(“Your weight on ” + p + “ is : ”,

+ p.surfaceWeight(mass));

}

Key Points on enum and its Constructor

All enums implicitly extend java.lang.Enum. As Java does not support multiple inheritance, an enum cannot extend anything else. The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum

body. You cannot invoke an enum constructor on yourself.

Detailed Example

Here is some code that shows you how to apply the Day enum defined earlier: public class EnumTest {

Day day;

public EnumTest(Day day) {

this.day = day;

}

public void tellItLikeItIs() {

Page 112 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 113: Core Java Handout v1.0

Handout - Core Java

switch (day) {

case MONDAY:

System.out.println("Mondays are bad.");

break;

case FRIDAY:

System.out.println("Fridays are better.");

break;

case SATURDAY:

case SUNDAY:

System.out.println("Weekends are best.");

break;

default:

System.out.println("Midweek days are so-so.");

break;

}

}

public static void main(String[] args) {

EnumTest firstDay = new EnumTest(Day.MONDAY);

firstDay.tellItLikeItIs();

EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);

thirdDay.tellItLikeItIs();

EnumTest fifthDay = new EnumTest(Day.FRIDAY);

fifthDay.tellItLikeItIs();

EnumTest sixthDay = new EnumTest(Day.SATURDAY);

sixthDay.tellItLikeItIs();

EnumTest seventhDay = new EnumTest(Day.SUNDAY);

seventhDay.tellItLikeItIs();

}

}

Output

The output is: Mondays are bad.

Midweek days are so-so.

Fridays are better.

Weekends are best.

Weekends are best.

Try It Out

Problem Statement: Consider the following : Bird myBird = new Bird(); myBird.name = “Parrot”;

Page 113 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 114: Core Java Handout v1.0

Handout - Core Java

From the preceding code, you have created a Bird object and used the dot operator on the reference variable myBird to access the name variable. You can further use the myBird reference to get the bird to sing() or fly()as given below: cuckoo.sing();

cuckoo.fly();

What happens if the Bird is in a Bird array? You can access the instance variables of Bird and methods using the dot operator, but on what? Code: class Bird {

String name;

public void sing() { };

public static void main(String[] args) {

Bird[] myBirds = new Bird[3];

myBirds[0] = new Bird();

myBirds[0].name = “Parrot”;

myBirds[0].sing();

}

}

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

When the Bird is in an array, you do not have an actual variable name (like “myBird”). Instead, you apply array notation and the dot operator on an object at a particular

index (position) in the array. For example myBirds[0].name = “Parrot”;

Tips and Tricks:

Can a method declare multiple return values? Or is there some way to return more than one value? Solution: A method can declare only one return value, but, if you want to return, say, three int values, then the declared return type can be an int array. Stuff those ints into the array, and pass it on back.

Summary

Arrays can hold primitives or objects, but the array itself is always an object. When you declare a array, the square brackets can be placed left side or right side of

its name. You must include the size of an array when you construct it (using new) unless you

are creating an anonymous array.

Page 114 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 115: Core Java Handout v1.0

Handout - Core Java

You’ll get a NullPointerException if you try to use an array element in an object array, if that element does not refer to a real object.

Arrays are indexed beginning with zero. An ArrayIndexOutOfBoundsException occurs if you use a bad index value. The last index you can access is always one less than the length of the array. Multidimensional arrays are just arrays of arrays. The dimensions in a multidimensional array can have different lengths.

Test Your Understanding

1. Which one of the following is true? a) All elements of an array should be of the same type. b) The ‘for’ loop shall be used to initialize the elements of an array. c) You cannot create a larger array and supply fewer values. d) All the earlier options are true.

2. Which one of the following is true? a) A two-dimensional array is stored internally as a one-dimensional array. b) The range of an array index is checked in Java. c) More than two dimensions are allowed in Java. d) All the earlier options are true.

Page 115 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 116: Core Java Handout v1.0

Handout - Core Java

Session 26: Wrapper Classes, Selection Statements and Iteration Blocks

Learning Objectives

After completing this session, you will be able to: Implement wrapper classes

The Wrapper Classes

Some Facts: Primitive data types are not objects: Cannot access methods of the Object class Only actual objects can access methods of the Object class Need of wrapper classes: Need an object representation for the primitive type

variables to apply methods that are in-built in Java Definition: Object representations of simple variables that are not object variables

The designers decided instead that for each primitive type there would be a corresponding wrapper class.

An instance of a wrapper contains, or wraps, a primitive value of the corresponding type.

The wrappers are normal classes in the java.lang package that extend the Object superclass like all Java classes.

Other than for the primitive type int, the wrappers come with the same name as the corresponding primitive type except that the first letter is capitalized: o Integer is a wrapper class of the primitive int o Character is a wrapper class of the primitive char o Double is a wrapper class of the primitive double

Wrapping a value: Give the primitive to the wrapper constructor as shown in the following example: Example: int i = 123;

Integer iWrap = new Integer(i);

UnWrapping a value: Each wrapper class has its own method for unwrapping a value. For example, Boolean class has the method booleanValue(),

Character class has the method charValue() , and so on Example: int unWrapped = iWrap.intValue();

Page 116 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 117: Core Java Handout v1.0

Handout - Core Java

Why Should You Use Wrapper Classes?

Wrappers allow for situations where numerical values are needed but objects instead of primitives are required.

For example, a very useful tool is as the Vector class, which is a list that that can grow or shrink, unlike an array.

The elements of a Vector instance are object references. If one wants to use a Vector to hold a list of numbers, then the numbers must be

wrapped in instances of their corresponding type. The wrapper classes also provide various tools such as constants (the smallest and

largest possible int value, for example) and static methods. You will often use wrapper methods to convert a number type value to a string or a

string to a number type.

Converting Primitive Types to Objects (Wrapper) and the Reverse

The wrapper constructors create class objects from the primitive types. For example, for a double floating point number "d" : double d = 5.0;

Double aDouble = new Double(d);

Here a Double wrapper object is created by passing the double value in the Double constructor argument. In turn, each wrapper provides a method to return the primitive value like: double r = aDouble.doubleValue();

Each wrapper has a similar method to access the primitive value:

intValue() for Integer, booleanValue() for Boolean, and so forth

The following statement creates an instance of the Integer class with the integer value 7801. Integer dataCount = new Integer(7801);

The following statement converts an Integer object to its primitive data type int. The result is an int with value 7801. int newCount = dataCount.intValue();

A common translation you need in programs is converting a String to a numeric type, such as an int (Object->primitive). String pennsylvania = "65000";

int penn = Integer.parseInt(pennsylvania);

Page 117 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 118: Core Java Handout v1.0

Handout - Core Java

Wrappers are Immutable

The two main applications of wrapper classes are: Wrapping a primitive so it can pretend to be an object. Applying the static utility methods (for example, Integer.parseInt()).

Once you create a wrapper object, there is no way to change the value of that object. There is no setter method for a wrapper object. Example: If you create a wrapper object like: Integer iWrap = new Integer(25); then, The value of iWrap will always be 25 You can, of course, refer iWrap to a different wrapper object, but then you will have two objects.

Try It Out

Problem Statement: Write a program that illustrates the use of Boolean Wrapper class. Code: class BooleanWrapper {

public static void main(String args[]) {

boolean booleanVar = 1 > 2;

Boolean booleanObj = new Boolean("True");

/*

* primitive to object; can also use valueOf method

*/

Boolean booleanObj2 = new Boolean(booleanVar);

System.out.println("booleanVar = " + booleanVar);

System.out.println("booleanObj = " + booleanObj);

System.out.println("booleanObj2 = " + booleanObj2);

System.out.println("compare 2 wrapper objects: "

+ booleanObj.equals(booleanObj2));

/* object to primitive */

booleanVar = booleanObj.booleanValue();

System.out.println("booleanVar = " + booleanVar);

}

}

Refer File Name: BooleanWrapper.java to obtain soft copy of the program code

Page 118 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 119: Core Java Handout v1.0

Handout - Core Java

How It Works: When you run the program, it produces the following results:

booleanVar = false

booleanObj = true

booleanObj2 = false

compare 2 wrapper objects: false

booleanVar = true

Tips and Tricks:

What happens in Integer.parseInt() if the thing you pass is not a number? And does it recognize spelled-out numbers like “three”? Solution:

Integer.parseInt() is used to get the int value of a String Integer.parseInt() works only on Strings that represent the ASCII values for digits

(0,1,2,3,4,5,6,7,8,9). If you try to parse something like “two” or “real”, then the code will throw an exception.

Summary

The wrapper classes correlate to the primitive types. Wrappers have two main functions: o To wrap primitives so that they can be handled like objects. o To provide utility methods for primitives (usually conversions)

The three most important methods available in the wrapper classes are: o xxxValue() takes no argument, returns a primitive o parseXxx() takes a String, returns a primitive, and throws

NumberFormatException o valueOf() takes a String, returns a wrapped object, throws

NumberFormatException Wrapper constructors can take a String or a primitive, except for Character, which can

only take a char.

Test Your Understanding

1. Which one of the following is wrong? a) All the type wrappers are defined in java.lang package. b) The isNaN() method is made available by the Double class. c) A number cannot be converted to and from Strings. d) The Runtime class encapsulates the java run time environment. e) ‘Like the String class, the wrapper classes are immutable’. Comment on this

statement.

Page 119 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 120: Core Java Handout v1.0

Handout - Core Java

Session 27: Wrapper Classes, Selection Statements and Iteration Blocks

Learning Objectives

After completing this session, you will be able to: Identify Wrapper classes for the primitive data types Describe Auto boxing Explain unboxing

Primitive Types: Wrapper Classes

The following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapper

boolean java.lang.Boolean

byte java.lang.Byte

char java.lang.Character

double java.lang.Double

float java.lang.Float

int java.lang.Integer

long java.lang.Long

short java.lang.Short

void java.lang.Void

Converting Strings to Primitive Types

The primitive type wrappers provide various static utility methods such as those to convert numbers to strings and strings to numbers. You occasionally want to pass values to an applet. The applet hypertext tag includes the param sub-tag for this like the following: <applet ...>

<param name = "string_name" value = "string_value" > </applet>

Page 120 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 121: Core Java Handout v1.0

Handout - Core Java

for passing strings to the applet program. The parameter has a name and corresponding value. For example, you could pass two strings with numbers like the following: <applet code="myApplet" codebase="Java" width=100 height=50>

<param name="fpNumber" value="12.45">

<param name="intNumber" value="10">

</applet>

In the applet code, usually in the init() method, you then use the getParameter(String) method from the applet class to obtain a given parameter, as in the following code: String fpStr = getParameter ("fpNumber"); String intStr = getParameter ("intNumber");

You now have the parameter values in string form and need to convert them to numbers. The wrapper classes provide tools for this in the form of static methods. For example, the following code: public void init () {

string fpStr= getParameter ("fpNumber"); double fpNum = Double.parseDouble (fpStr); String intStr = getParameter ("intNumber"); int intNum = Integer.parseInt (intStr);

……

shows the use of the parseDouble method in Double and the parseInt method in Integer.

Converting Primitive Types to Strings

You can convert a primitive type to a string in several ways. The String class provides the static valueOf methods (there is one for each primitive

type). The easiest way to turn a number into a string is to simply concatenate using the "+"

operator: The “+” operator is overloaded in Java (in fact, it is the only overloaded operator) as a

string concatenator. Anything added to a string is also a string.

Converting Primitive Types to Strings (Example)

In the following code, you convert numerical values to strings using the valueOf() methods (there is one for each primitive type) of String class: int i = 1;

double d = 5.0;

String dStr = String.valueOf(d);

String iStr = String.valueOf(i);

Page 121 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 122: Core Java Handout v1.0

Handout - Core Java

In the following code, you convert numerical values to strings using the "+" operator: String aStr = "d = " + d;

String bStr = "i = " + i;

Now dStr and iStr objects hold string representations of 5.0 and 1, while aStr holds "d = 5.0" and bStr holds "i = 1“.

Autoboxing

The autoboxing feature added to Java 5.0 does the conversion (wrapping) from primitive to wrapper object.

This "wrapping" is called "autoboxing" in the sense that the primitive value is automatically "boxed up" into the wrapper object.

Autoboxing is available for all the primitive or wrapper types.

Without Autoboxing (Java versions before 5.0)

Example: An ArrayList of primitive ints public void doNumsOldWay() {

ArrayList listOfNumbers = new ArrayList

listOfNumbers.add(new Integer(3));

Integer one = (Integer) listOfNumbers.get(0);

int intOne = one.intValue();

}

With Autoboxing (Java versions 5.0 or greater)

Example: An ArrayList of primitive ints public void doNumsNewWay() {

ArrayList<Integer> listOfNumbers = new ArrayList<Integer>;

listOfNumbers.add(3);

int num = listOfNumbers.get(0);

}

Autoboxing Illustrations

The general rule is that boxing and unboxing work wherever you can normally use a primitive or a wrapped object. It can be illustrated in the following:

Method arguments Return values Boolean expressions Operations on numbers Assignments

Page 122 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 123: Core Java Handout v1.0

Handout - Core Java

Method Arguments

If a method takes a wrapper type, then you can pass a reference to a wrapper or a primitive of the matching type.

If a method takes a primitive, then you can pass in either a compatible primitive or a reference to a wrapper of that primitive type.

Example: void takeNumber(Integer i) { }

Return Values

If a method declares a primitive return type, then you can return either a compatible primitive or a reference to the wrapper of that primitive type.

If a method declares a wrapper return type, then you can return either a reference to the wrapper type or a primitive of the matching type.

Example:

int giveNumber() {

return x;

}

In the preceding example, x can be either a reference to Integer wrapper or int primitive type.

Boolean Expressions

Any place a boolean value is expected, you can use either an expression that evaluates to a boolean (4 > 2), or a primitive boolean, or a reference to a Boolean wrapper. Example: boolean one = true; // nothing new here Boolean two = true; // autoboxing of primitive 'true' to Boolean type if (one && two) // auto unboxing do_something ();

Before Java 5.0, the if, while, and do-while statements are all expected as boolean expressions. Through the use of unboxing, those flow control statements now also accept expressions that evaluate to Boolean types.

Autoboxing With Switch Statement

Similarly, the old switch statement expects a byte, short, int, or char type in Java 1.4 and earlier to Java 1.4. With the addition of autoboxing in Java 5.0, switch now also accepts Byte, Short, Integer, and Character types.

Operations on Numbers

This is probably the strangest one. You can now use a wrapper type as an operand in operations where the primitive type is expected.

Page 123 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 124: Core Java Handout v1.0

Handout - Core Java

That means you can apply, say, the increment operator against a reference to an Integer object! Examples: Integer i = new Integer(56);

i++;

Integer j = new Integer(4);

Integer k = j + 3;

Assignments

You can assign either a wrapper or primitive to a variable declared as a matching wrapper or primitive. For example, a primitive int can be assigned to an Integer reference variable and a reference to an Integer object can be assigned to a variable declared as an int primitive. Example: Double d = x; In the preceding example, x can be either a reference to Double wrapper or double primitive type.

Try It Out

Problem Statement: Write a program that illustrates the use of Wrapper classes for the primitive types namely int, char, long, float, double, and boolean. Code: public class WrappedClassApp {

public static void main(String args[]) {

Boolean b1 = new Boolean("TRUE");

Boolean b2 = new Boolean("FALSE");

System.out.println(b1.toString() + " or " + b2.toString());

for (int j = 0; j < 16; ++j)

System.out.print(Character.forDigit(j, 16));

System.out.println();

Integer i = new Integer(Integer.parseInt("ef", 16));

Long l = new Long(Long.parseLong("abcd", 16));

long m = l.longValue() * i.longValue();

System.out.println(Long.toString(m, 8));

System.out.println(Float.MIN_VALUE);

System.out.println(Double.MAX_VALUE);

}

}

Refer File Name: WrappedClassApp.java to obtain soft copy of the program code

Page 124 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 125: Core Java Handout v1.0

Handout - Core Java

How It Works: The program examines some of the more useful methods provided by the wrapped

classes. It creates two objects of class Boolean from string arguments passed to their

constructors. It assigns these objects to b1 and b2 and then converts them back to String objects

when it displays them. They are displayed in lowercase, as boolean values are traditionally represented. The program then executes a for loop that prints out the character corresponding to

each of the hexadecimal digits. The static forDigit() method of the Character class is used to generate the character

values of digits in a number system of a different radix. The static parseInt() and parseLong() methods are used to parse strings according to

different radices. In the example, they are used to convert strings representing hexadecimal numbers

into Integer and Long values. These values are then multiplied together and converted to a string that represents the

resulting value in base 8. This is accomplished using an overloaded version of the toString() method. The sample program concludes by displaying the minimum float value and the

maximum double value, using the predefined class constants of the Float and Double classes.

The output of the program is as follows:

true or false

0123456789abcdef

50062143

1.4E-45

1.7976931348623157E308

Tips and Tricks:

Typical problems include real-time problems or challenges: Java 5 (JDK 1.5 and further) includes autoboxing and auto-unboxing. A developer might be tempted to apply objects such Integer or Double exclusively, abandoning primitives altogether. For example, it is possible to write code like this: // A bad use of autoboxing/unboxing!

Double a, b, c;

a = 10.0;

b = 4.0;

c = Math.sqrt(a*a + b*b);

System.out.println(“Hypotenuse is “ + c);

Page 125 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 126: Core Java Handout v1.0

Handout - Core Java

Solution: In this example, objects of type Double hold values that are used to calculate the

hypotenuse of a right triangle. Although this code is technically correct, and in fact, work properly, it is a very bad use

of autoboxing or unboxing. It is far less efficient than the equivalent code written applying the primitive double. The reason is that each autobox and auto-unbox adds overhead that is not present if

the primitive type is used. In general, you should restrict your use of the type wrappers to only those cases in

which the object representation of a primitive type is required.

Summary

As of Java 5, autoboxing / unboxing allow you to convert primitives to wrappers or to convert wrappers to primitives automatically.

Using the == with wrappers is tricky; wrappers with the same small values (typically lower than 127), will be ==, larger values will not be ==.

Test Your Understanding

1. State true or false for the following: a) Autoboxing always creates the proper object, and auto-unboxing always produces

the proper value. There is no way for the process to produce the wrong type of object or value.

b) Using Java 5 (JDK 1.5 and furhter), the method calls such as intValue() or doubleValue() are very much needed in the code.

Page 126 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 127: Core Java Handout v1.0

Handout - Core Java

Session 30: Wrapper Classes, Selection Statements and Iteration Blocks

Learning Objectives

After completing this session, you will be able to: Use decision control structures (if, if-else, switch), which allows selection of specific

sections of code to be executed.

Control Structures

Control structures allows you to change the ordering of how the statements in your programs are executed Two types of control structures are:

Decision control structures: Allows you to select specific sections of code to be executed

Repetition control structures: Allows you to execute specific sections of the code a number of times.

Decision Control Structures

Decision control structures are Java statements that allows you to select and execute specific blocks of code while skipping other sections Types of decision control structures are:

if-statement if-else-statement if-else if-statement

if-statement

if-statement specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true. if-statement has the form: if( boolean_expression )

statement

or

if( boolean_expression ){

statement1;

statement2;

}

where boolean_expression is either a boolean expression or boolean variable.

Page 127 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 128: Core Java Handout v1.0

Handout - Core Java

if-statement Flowchart

The following figure shows the flowchart of an if statement:

Examples of if-statement

Example 1: int grade = 68;

if( grade > 60 )

System.out.println("Congratulations!");

Example 2: int grade = 68;

if( grade > 60 ) {

System.out.println("Congratulations!");

System.out.println("You passed!");

}

Coding Guidelines

The boolean_expression part of a statement should evaluate to a boolean value, which means that the execution of the condition should either result to a value of true or a false.

Indent the statements inside the if-block. For example,

if( boolean_expression ) {

//statement1;

//statement2;

}

Page 128 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 129: Core Java Handout v1.0

Handout - Core Java

if-else Statement

if-else statement is used when you want to execute a certain statement if a condition is true, and a different statement if the condition is false.

if-else statement has the form:

if( boolean_expression ) {

statement1;

statement2;

. . .

}

else {

statement3;

statement4;

. . .

}

if-else Flowchart

The following figure shows the flowchart of an if-else statement:

Examples of if-else Statement

Example 1: int grade = 68;

if( grade > 60 )

System.out.println("Congratulations!");

else

System.out.println("Sorry you failed");

Example 2: int grade = 68;

if( grade > 60 ){

System.out.println("Congratulations!");

System.out.println(“You passed!");

}

Page 129 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 130: Core Java Handout v1.0

Handout - Core Java

else{

System.out.println("Sorry you failed");

}

Coding Guidelines

To avoid confusion, always place the statement or statements of an if or if-else block inside brackets {}.

You can have nested if-else blocks. This means that you can have other if-else blocks inside another if-else block.

For example,

if( boolean_expression ){

if( boolean_expression ){

//some statements here

}

}

else{

//some statements here

}

if-else-else if Statement

The statement in the else-clause of an if-else block can be another if-else structure. This cascading of structures allows you to make more complex selections. The statement has the form:

if( boolean_expression1 )

statement1;

else if( boolean_expression2 )

statement2;

else

statement3;

if-else-else if Flowchart

The following figure shows the flowchart of an if-else-else if statement:

Page 130 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 131: Core Java Handout v1.0

Handout - Core Java

Example of if-else-else if Statement

Example: int grade = 68;

if( grade > 90 ){

System.out.println("Very good!");

}

else if (grade > 60){

System.out.println("Good");

}

else{

System.out.println("Sorry you failed");

}

Common Errors

The condition inside the if-statement does not evaluate to a boolean value, for example, //WRONG

int number = 0;

if( number ) {

//some statements here

}

The variable number does not hold a boolean value. Writing elseif instead of else if Using = instead of == for comparison.

Page 131 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 132: Core Java Handout v1.0

Handout - Core Java

For example, //WRONG

int number = 0;

if( number = 0 ){

//some statements here

}

This should be written as, //CORRECT

int number = 0;

if( number == 0 ){

//some statements here

}

Sample Program

1 public class Grade {

public static void main( String[] args )

{

4 double grade = 92.0;

5 if( grade >= 90 ){

6 System.out.println( "Excellent!" );

7 }

8 else if( (grade < 90) && (grade >= 80)){

9 System.out.println("Good job!" );

10 }

11 else if( (grade < 80) && (grade >= 60)){

12 System.out.println("Study harder!" );

13 }

14 else{

15 System.out.println("Sorry, you failed.");

16 }

17 }

18 }

switch Statement

switch allows branching on multiple outcomes switch statement has the form: switch( switch_expression ){

case case_selector1:

statement1;//

statement2;//block 1

break;

case case_selector2:

Page 132 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 133: Core Java Handout v1.0

Handout - Core Java

statement1;//

statement2;//block 2

break;

:

default:

statement1;//

statement2;//block n

}

where: switch_expression is an integer or character expression case_selector1, case_selector2 and so on, are unique integer or character constants When a switch is encountered:

Java first evaluates the switch_expression, and jumps to the case whose selector matches the value of the expression.

The program executes the statements in order from that point on until a break statement is encountered, skipping then to the first statement after the end of the switch structure.

If none of the cases are satisfied, then the default block is executed. Take note however, that the default part is optional.

Note: Unlike with the if statement, the multiple statements are executed in the switch

statement without needing the curly braces. When a case in a switch statement has been matched, all the statements associated

with that case are executed. Not only that, the statements associated with the succeeding cases are also executed.

To prevent the program from executing statements in the subsequent cases, you use a break statement as your last statement.

Flowchart of switch Statement

Sample Program: 1 public class Grade {

2 public static void main( String[] args )

3 {

4 int grade = 92;

5 switch(grade){

6 case 100:

7 System.out.println( "Excellent!" );

8 break;

9 case 90:

10 System.out.println("Good job!" );

11 break;

12 case 80:

13 System.out.println("Study harder!" );

14 break;

Page 133 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 134: Core Java Handout v1.0

Handout - Core Java

15 default:

16 System.out.println("Sorry, you failed.");

17 }

18 }

19 }

Coding Guidelines

Deciding whether to use an if statement or a switch statement, is a judgment call. You can decide which to use, based on readability and other factors. An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or character value. Also, the value provided to each case statement must be unique.

Try It Out

Problem Statement: Write a program that illustrates the use of switch with break statements. Code: class SwitchWithBreak {

public static void main(String[] args) {

int n = 3;

switch (n) {

case 1:

System.out.println(1);

break;

case 2:

System.out.println(2);

break;

case 3:

System.out.println(3);

break;

// continued …

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

SwitchWithBreak program shows how the break statement is used to ensure that only a single case of a switch statement is executed.

This program displays the following single line of output: 3

Page 134 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 135: Core Java Handout v1.0

Handout - Core Java

Tips and Tricks:

List out the few important tips on selection statements. Solution:

if (false) { x = 3}; // will compile, to provide the ability to conditionally compile the code. The if statement takes boolean arguments. Parenthesis is required. else part is

optional. The compiler checks each case value against the range of the data type of switch

expression. The following code will not compile.

byte b;

switch (b) {

case 200: // 200 not in the range of byte

default:

}

You need to place a break statement in each case block to prevent the execution to fall through other case blocks. But this is not a part of switch statement and not enforced by the compiler.

Default case can be placed anywhere. It will be executed only if none of the case values match.

Empty switch construct is a valid construct. But any statement within the switch block should come under a case label or the default case label.

Summary

The only legal expression in an if statement is a boolean expression; in other words an expression that resolves to a boolean or a Boolean variable.

Watch out for boolean assignments (=) that can be mistaken for boolean equality (==) tests.

Curly braces are optional for if blocks that have only one conditional statement. But watch out for misleading indentations.

switch statements can evaluate only to enums or the byte, short, int, and char data types.

The case constant must be a literal or final variable, or a constant expression, including an enum. You cannot have a case that includes a non-final variable, or a range of values.

The default keyword can be located anywhere in the switch block.

Test Your Understanding

1. Which one of the following is false in the case of ‘if’ statement? a) This statement is used when there are two possible alternative actions. b) The test condition may be a logical expression or an arithmetic expression. c) The else part is optional. d) More than one statement may be present in the if block and else block

statements.

Page 135 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 136: Core Java Handout v1.0

Handout - Core Java

2. Which one of the following is not correct in the case of ‘switch’ statement? a) The expression involved in a switch statement may be an arithmetic expression. b) The body of a case may be empty. c) The body of a case should have the break statement. d) The default part is optional.

Page 136 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 137: Core Java Handout v1.0

Handout - Core Java

Session 31: Wrapper Classes, Selection Statements and Iteration Blocks

Learning Objectives

After completing this session, you will be able to: Use repetition control structures (while, do-while, for), which allow executing specific

sections of code a number of times Use branching statements (break, continue, return), which allows redirection of

program flow

Repetition Control Structures

Repetition control structures are Java statements that allows you to execute specific blocks of code a number of times. Types of repetition control structures are:

while-loop do-while loop for-loop

while-loop

while loop is a statement or block of statements that is repeated as long as some condition is satisfied. while loop has the following form: while( boolean_expression ){

statement1;

statement2;

. . .

}

The statements inside the while loop are executed as long as the boolean_expression evaluates to true.

Examples of while-loop

Example 1: int x = 0;

while (x<10) {

System.out.println(x);

x++;

}

Page 137 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 138: Core Java Handout v1.0

Handout - Core Java

Example 2: //infinite loop

while(true)

System.out.println(“hello”);

Example 3: //no loops

// statement is not even executed

while (false)

System.out.println(“hello”);

do-while-loop

do-while loop: Similar to the while-loop Statements inside a do-while loop are executed several times as long as the condition

is satisfied The main difference between a while and do-while loop is that the statements inside a

do-while loop are executed at least once do-while loop has the following form:

do{

statement1;

statement2;

. . .

}while( boolean_expression );

Examples of do-while-loop

Example 1: int x = 0;

do {

System.out.println(x);

x++;

} while (x<10);

Example 2: //infinite loop

do {

System.out.println(“hello”);

] while(true);

Page 138 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 139: Core Java Handout v1.0

Handout - Core Java

Example 3: //one loop

// statement is not executed only once

do {

System.out.println(“hello”);

} while (false);

Coding Guidelines

Common programming mistakes when using the do-while loop is forgetting to write the semi-colon after the while expression. do{

...

}while(boolean_expression)//WRONG->forgot semicolon; Just like in while loops, make sure that your do-while loops will terminate at some point.

for-loop

for loop allows execution of the same code a number of times. for loop has the following form: for(InitializationExpression;LoopCondition;StepExpression)

{

statement1;

statement2;

. . .

}

Where:

InitializationExpression initializes the loop variable. LoopCondition compares the loop variable to some limit value. StepExpression updates the loop variable.

Example of for-loop

int i;

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

System.out.println(i);

}

The preceding code shown is equivalent to the following while loop: int i = 0;

while( i < 10 ){

System.out.println(i);

i++;

}

Page 139 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 140: Core Java Handout v1.0

Handout - Core Java

Branching Statements

Branching statements allows you to redirect the flow of program execution. Java offers three branching statements:

break continue return

Unlabelled Break Statement

Unlabelled break: Terminates the enclosing switch statement, and flow of control transfers to the

statement immediately following the switch This can also be used to terminate a for, while, or do-while loop

Example of Unlabelled Break Statement

String names[]={"Beah","Bianca","Lance","Belle","Nico","Yza","Gem","Ethan"};

String searchName = "Yza";

boolean foundName = false;

for( int i=0; i< names.length; i++ ){

if( names[i].equals( searchName )){

foundName = true;

break;

}

}

if( foundName ) System.out.println( searchName + " found!" );

else System.out.println( searchName + " not found." );

Labeled Break Statement

Labeled break statement: This terminates an outer statement, which is identified by the label specified in the

break statement The flow of control transfers to the statement immediately following the labeled

(terminated) statement. The sample program in the following slide searches for a value in a two dimensional

array. Two nested for loops traverse the array. When the value is found, a labeled break terminates the statement labeled search, which is the outer for loop.

Page 140 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 141: Core Java Handout v1.0

Handout - Core Java

Example of Labeled Break Statement

int[][] numbers = {{1, 2, 3}, {4, 5, 6},{7, 8, 9}};

int searchNum = 5;

boolean foundNum = false;

searchLabel:

for( int i=0; i<numbers.length; i++ ){

for( int j=0; j<numbers[i].length; j++ ){

if( searchNum == numbers[i][j] ){

foundNum = true;

break searchLabel;

}

}

}

if( foundNum ) System.out.println(searchNum + " found!" );

else System.out.println(searchNum + " not found!");

Unlabelled Continue Statement

Unlabelled continue statement skips to the end of the body of the innermost loop and evaluates the boolean expression that controls the loop, basically skipping the remainder of this iteration of the loop. Example of Unlabelled Continue Statement String names[] = {"Beah", "Bianca", "Lance", "Beah"};

int count = 0;

for( int i=0; i<names.length; i++ ){

if( !names[i].equals("Beah") ){

continue; //skip next statement

}

count++;

}

System.out.println("There are "+count+" Beahs in the list");

Labeled Continue Statement

Labeled continue statement skips the current iteration of an outer loop marked with the given label. Example of Labeled Continue Statement outerLoop:

for( int i=0; i<5; i++ ){

for( int j=0; j<5; j++ ){

System.out.println("Inside for(j) loop"); //message1

Page 141 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 142: Core Java Handout v1.0

Handout - Core Java

if( j == 2 ) continue outerLoop;

}

System.out.println("Inside for(i) loop"); //message2

}

In this example, message 2 never gets printed since you have the statement continue outerLoop, which skips the iteration.

Return Statement

Return statement: Applied to exit from the current method Flow of control returns to the statement that follows the original method call To return a value: Simply put the value (or an expression that calculates the value) after the return keyword. For example: return ++count;

or

return "Hello";

The data type of the value returned by return must match the type of the declared return value of the method. When a method is declared void, use the form of return that does not return a value. For example: return;

Try It Out

Problem Statement: Write a program that illustrates the use of for loop. Code: class ForLoop {

public static void main(String[] args) {

int i, j;

for (i = 0, j = 0; i + j < 20; ++i, j += i) {

System.out.println(i + j);

}

}

}

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

A little-known fact about the for statement is that commas can be used to separate multiple statements in the initialization and iteration part of the statement.

The only catch is, if you apply a comma separator in the initialization block, then you cannot declare variables within the initialization block.

Page 142 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 143: Core Java Handout v1.0

Handout - Core Java

For example, the following for statement results in a compilation error:

for(int i=0,int j=0; i+j < 20; ++i, j += i) {

System.out.println(i+j);

}

When you run ForLoop.java program, it produces the following output: 0 2 5 9 14

Tips and Tricks:

Provide few important tips on branching statements. Solution:

break statement can be used with any kind of loop or a switch statement or just a labeled block.

continue statement can be used with only a loop. (any kind of loop). Loops can have labels. You can use break and continue statements to branch out of

multiple levels of nested loops using labels. Names of the labels follow the same rules as the name of the variables (Identifiers). Labels can have the same name, as long as they do not enclose one another. There is no restriction against applying the same identifier as a label and as the name

of a package, class, interface, method, field, parameter, or local variable.

Summary

The types of Repetition Control Structures are: while do-while for The types of Branching Statements are: break continue return

Test Your Understanding

1. Which of the following is true in the case of ‘while’ structure? a) Condition is checked at the bottom of the loop b) Condition is checked at the top of the loop c) Condition is checked at the top and bottom of the loop d) No condition is checked

Page 143 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 144: Core Java Handout v1.0

Handout - Core Java

2. Which of the following is true in the case of ‘break’ statement? a) Transfers the control to the top of the loop b) Transfers the control to the bottom of the loop c) Transfers the control to a specified statement of the loop d) Does not transfer the control at all

Page 144 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 145: Core Java Handout v1.0

Handout - Core Java

Session 35: Access Specifiers, Constructors and Methods

Learning Objectives

After completing this session, you will be able to: Identify constructors and the different types of method declaration

Constructors

Java provides a special construct named constructor exclusively for creating an object of a class and initializing its instance variables.

Constructors should have the same name as the name of the class. It is generally declared as public. It may have optional list of arguments. It does not have any return type and not even void. You cannot invoke a constructor on an existing object. You can use a constructor only in combination with the new operator.

To declare a constructor, you write, <modifier> <className> (<parameter>*) {

<statement>*

}

Default Constructor (Method)

The default constructor (no-arg constructor): Constructor without any parameters If the class does not specify any constructors, then an implicit default constructor is

created Example: Default Constructor Method of StudentRecord Class public StudentRecord()

{

//some code here

}

Page 145 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 146: Core Java Handout v1.0

Handout - Core Java

Overloading Constructor Methods

public StudentRecord()

//some initialization code here

}

public StudentRecord(String temp) {

this.name = temp;

}

public StudentRecord(String name, String address {

this.name = name;

this.address = address;

}

public StudentRecord(double mGrade, double eGrade,

double sGrade) {

mathGrade = mGrade;

englishGrade = eGrade;

scienceGrade = sGrade;

}

Applying Constructors

To apply these constructors, you have the following code: public static void main( String[] args ){

//create three objects for Student record

StudentRecord annaRecord=new StudentRecord("Anna");

StudentRecord beahRecord=new StudentRecord("Beah",

"Philippines");

StudentRecord crisRecord=new

StudentRecord(80,90,100);

//some code here

}

“this()” Constructor Call

Constructor calls can be chained, which means that you can call another constructor from inside another constructor.

You use the this() method call for this. There are a few things to remember when using the this() method constructor call: When using this constructor call, it must occur as the first statement in a constructor. It can only be used in a constructor definition. The this call can then be followed by

any other relevant statements.

Page 146 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 147: Core Java Handout v1.0

Handout - Core Java

Example of “this()” Constructor Call

1: public StudentRecord(){

2: this("some string");

3:

4: }

5:

6: public StudentRecord(String temp){

7: this.name = temp;

8: }

9:

10: public static void main( String[] args )

11: {

12:

13: StudentRecord annaRecord = new StudentRecord();

14: }

“this” Reference

The this reference: Refers to current object instance itself Used to access the instance variables shadowed by the parameters To use the this reference, you type, this.<nameOfTheInstanceVariable> You can only use the this reference for instance variables and not for static or class

variables The this reference is assumed when you call a method from the same object. public class MyClass {

void aMethod() {

// same thing as this.anotherMethod()

anotherMethod();

}

void anotherMethod() {

// method definition here...

}

}

Example of “this” Reference

public void setAge( int age ){

this.age = age;

}

Page 147 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 148: Core Java Handout v1.0

Handout - Core Java

Declaring Methods

To declare methods you write, <modifier> <returnType>

<name>(<parameter>*) {

<statement>*

}

Where: <modifier> can carry a number of different modifiers <returnType> can be any data type (including void) <name> can be any valid identifier <parameter> can be one or more parameters passed as argument to the method.

Each <parameter> is associated with a parameter type (primitive or object) and a parameter name.

Accessor (Getter) Methods

Accessor methods: Used to read values from your class variables (instance or static) Usually written as get<NameOfInstanceVariable> It also returns a value

Example 1: Accessor (Getter) Method

Example: public class StudentRecord {

private String name; :

public String getName(){

return name;

}

}

where: public means that the method can be called from objects outside the class. String is the return type of the method. This means that the method should return a

value of type String. getName is the name of the method. () means that your method does not have any parameters.

Example 2: Accessor (Getter) Method

public class StudentRecord {

private String name;

// some code

// An example in which the business logic is

Page 148 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 149: Core Java Handout v1.0

Handout - Core Java

// used to return a value on an accessor method

public double getAverage(){

double result = 0;

result=(mathGrade+englishGrade+scienceGrade)/3;

return result;

}

}

Mutator (Setter) Methods

Mutator Methods: Used to write or change values of your class variables (instance orstatic) Usually written as set<NameOfInstanceVariable>

Example: Mutator (Setter) Method Example: public class StudentRecord {

private String name;

:

public void setName( String temp ){

name = temp;

}

}

Where: public means that the method can be called from objects outside the class. void means that the method does not return any value. setName is the name of the method. (String temp) is a parameter that will be used inside your method.

Multiple Return Statements

You can have multiple return statements for a method as long as they are not on the same block.

You can also use constants to return values instead of variables.

Example: Multiple Return Statements

public String getNumberInWords( int num ){

String defaultNum = "zero";

if( num == 1 ){

return "one"; //return a constant

}

else if( num == 2){

return "two"; //return a constant

}

//return a variable

Page 149 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 150: Core Java Handout v1.0

Handout - Core Java

return defaultNum;

}

Static Methods

Example: public class StudentRecord {

private static int studentCount;

public static int getStudentCount(){

return studentCount;

}

}

where, public means that the method can be called from objects outside the class. static means that the method is static and should be called by typing,

[ClassName].[methodName. For example, in this case, you call the method StudentRecord.getStudentCount()

int is the return type of the method. This means that the method should return a value of type int.

getStudentCount is the name of the method. () means that your method does not have any parameters.

Coding Guidelines

Method names should start with a small letter Method names should be verbs Always provide documentation before the declaration of the method

When to Define Static Method?

When the logic and state does not involve specific object instance: Computation method: add(int x, int y) method

When the logic is a convenience without creating an object instance:

Integer.parseInt();

Source Code for StudentRecord Class

public class StudentRecord {

// Instance variables

private String name;

private String address;

private int age;

private double mathGrade;

private double englishGrade;

private double scienceGrade;

Page 150 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 151: Core Java Handout v1.0

Handout - Core Java

private double average;

private static int studentCount;

/**

* Returns the name of the student (Accessor method)

*/

public String getName(){

return name;

}

/**

* Changes the name of the student (Mutator method)

*/

public void setName( String temp ){

name = temp;

}

/**

* Computes the average of the english, math and science

* grades (Accessor method)

*/

public double getAverage(){

double result = 0;

result = ( mathGrade+englishGrade+scienceGrade )/3;

return result;

}

/**

* returns the number of instances of StudentRecords

* (Accessor method)

*/

public static int getStudentCount(){

return studentCount;

}

Sample Source Code that uses StudentRecord Class

public class StudentRecordExample

{

public static void main( String[] args ){

//create three objects for Student record

StudentRecord annaRecord = new StudentRecord();

StudentRecord beahRecord = new StudentRecord();

StudentRecord crisRecord = new StudentRecord();

//set the name of the students

annaRecord.setName("Anna");

Page 151 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 152: Core Java Handout v1.0

Handout - Core Java

beahRecord.setName("Beah");

crisRecord.setName("Cris");

//print anna's name

System.out.println( annaRecord.getName() );

//print number of students System.out.println("Count="+StudentRecord.getStudentCount());

}

}

Program Output Anna

Student Count = 0

Try It Out

Problem Statement: Write a program that illustrate the use of ‘this’ statement in constructor overloading. Code: public class Box {

double x, y, width, height;

public Box(double x, double y, double width, double height) {

this.x = x;

this.y = y;

this.width = width;

this.height = height;

}

public Box(double x, double y) {

this(x, y, 10, 10);

}

// continued …

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

The first Box() constructor takes the arguments x, y, width, and height and assigns them to the appropriate field variables.

Page 152 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 153: Core Java Handout v1.0

Handout - Core Java

The second Box() constructor takes just the coordinates of the box as arguments and invokes the first constructor, passing 10 as the default value for the height and width of the box.

The third constructor has no arguments and invokes the second constructor with the default value of 1 for the x and y coordinates of the box.

The this(x,y,10,10) and this(1,1) used in the second and third constructors is a special notation provided by Java to enable you to invoke a constructor of the same class from another constructor of that class.

It is referred to as a constructor call statement. In order to use a constructor call statement, there must be a constructor whose argument list matches those supplied with this() .

Note: If this() appears in a constructor, then it must appear as the first statement in the constructor.

Tips and Tricks:

How can you differentiate a constructor from a method? Can you also have a method that has the same name as the class? Are constructors inherited? If you do not provide a constructor but your superclass

does,then do you get the superclass constructor instead of the default? A static method cannot access a variable that is not static. But can a method that is not static access a static variable?

Solution:

Java lets you to declare a method with the same name as your class, which does not make it a constructor, though.

The thing that separates a method from a constructor is the return type. Methods must have a return type, but constructors cannot have a return type and not

even void. No, constructors are not inherited. A method that is not static in a class can always call a static method in the class or

access a static variable of the class.

Summary

A constructor is always invoked when a new object is created. Every class, even an abstract class, has at least one constructor. Interfaces do not have constructors. Constructors must have the same name as the class. Constructors can use any access modifier (even private!) The default constructor is a no-arg constructor with a no-arg call to super(). The first statement of every constructor must be a call to either this() (an overloaded

constructor) or super(). Calls to this() and super() cannot be in the same constructor, you can have one or the

other, but never both.

Page 153 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 154: Core Java Handout v1.0

Handout - Core Java

Test Your Understanding

1. The overloaded constructors in a class will have: a) Different names b) Different parameter names c) Different return types d) None of these

2. How many constructors can a class have? 3. What is the advantage of using the ‘this’ keyword?

Page 154 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 155: Core Java Handout v1.0

Handout - Core Java

Session 38: Access Specifiers, Constructors and Methods

Learning Objectives

After completing this session, you will be able to: Explain method overloading

Method Overloading

Method overloading: Allows a method with the same name but different parameters, to have different

implementations and return values of different types Can be applied when the same operation has different implementations Always remember that overloaded methods have the following properties: The same method name Different parameters or different number of parameters Return types can be different or same

Example of Method Overloading

public void print( String temp ){

System.out.println("Name:" + name);

System.out.println("Address:" + address);

System.out.println("Age:" + age);

}

public void print(double eGrade, double mGrade,

double sGrade)

System.out.println("Name:" + name);

System.out.println("Math Grade:" + mGrade);

System.out.println("English Grade:" + eGrade);

System.out.println("Science Grade:" + sGrade);

}

public static void main( String[] args )

{

StudentRecord annaRecord = new StudentRecord();

annaRecord.setName("Anna");

annaRecord.setAddress("Philippines");

annaRecord.setAge(15);

annaRecord.setMathGrade(80);

annaRecord.setEnglishGrade(95.5);

annaRecord.setScienceGrade(100);

Page 155 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 156: Core Java Handout v1.0

Handout - Core Java

//overloaded methods

annaRecord.print( annaRecord.getName() );

annaRecord.print( annaRecord.getEnglishGrade(),

annaRecord.getMathGrade(),

annaRecord.getScienceGrade());

}

Program Output

You will have the output for the first call to print: Name:Anna

Address:Philippines

Age:15

You will have the output for the second call to print: Name:Anna

Math Grade:80.0

English Grade:95.5

Science Grade:100.0

Try It Out

Problem Statement: Write a program that illustrates invoking overloaded methods. Code: class TestAdder {

public int addThem(int x, int y) {

System.out.println("Inside addThem(int x, int y) method...");

return x + y;

}

// Overload the addThem method to add doubles instead of ints

public double addThem(double x, double y) {

System.out.println("Inside addThem(double x, double y) method...");

return x + y;

}

}

//From another class, invoke the addThem() method

public class TestAdder {

public static void main(String[] args) {

Adder a = new Adder();

int b = 27;

Page 156 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 157: Core Java Handout v1.0

Handout - Core Java

int c = 3;

int result = a.addThem(b, c); // which addThem is invoked?

double doubleResult = a.addThem(22.5, 9.3); // which addThem?

}

}

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

In the TestAdder program, the first call to a.addThem(b,c) passes two ints to the method.

So, for the above call, the first version of addThem() – the overloaded method that contains two int arguments – is done.

The second call to a.addThem(22.5, 9.3) passes two doubles to the method. So, for the above call, the second version of addThem() – the overloaded method that

contains two double arguments – is done.

Tips and Tricks:

Differentiate between Overloading methods and Overriding methods. Solution:

Overloading Overriding

Signature has to be different. Just a difference in return type is not enough.

Signature has to be the same. (including the return type)

Accessibility may vary freely. Overriding methods cannot be more private than the overridden methods.

Just the name is reused. Methods are independent methods. Resolved at compile-time based on method signature.

Related directly to sub-classing. Overrides the parent class method. Resolved at run-time based on type of the object.

Can call each other by providing appropriate argument list.

Overriding method can call overridden method by super.methodName() , this can be used only to access the immediate method of superclass. super.super will not work. Also, a class outside the inheritance hierarchy cannot use this technique.

Methods can be static or non-static. If two methods have the same signature, declaring one as static and another as non-static does not provide a valid overload. It’s a compile time error.

static methods do not participate in overriding, since they are resolved at compile time based on the type of reference variable. A static method in a sub-class cannot use super. A static method cannot be overridden to be non-static and vice-versa.

There is no limit on number of overloaded methods a class can have.

Each parent class method may be overridden at most once in any sub-class.

Page 157 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 158: Core Java Handout v1.0

Handout - Core Java

Summary

Methods can be overridden or overloaded; constructors can be overloaded but not overridden.

Overloading means reusing a method name, but with different arguments. Overloaded methods: o Must have different argument lists o May have different return types, if argument lists are also different o May have different access modifiers o May throw different exceptions

Methods from a superclass can be overloaded in a subclass. Reference type determines which overloaded method will be used at compile time.

Test Your Understanding

1. What is meant by method overloading’? 2. Differentiate between constructor overloading and method overloading.

Page 158 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 159: Core Java Handout v1.0

Handout - Core Java

Session 39: Access Specifiers, Constructors and Methods

Learning Objectives

After completing this session, you will be able to: Apply access modifiers

Access Modifiers

You can define the scope of a variable or method or class by using the access modifiers. There are four different types of access modifiers in Java:

public (Least restrictive) protected default private (Most restrictive)

The first three access modifiers are explicitly written in the code to indicate the access type, for the third one, which is default, no keyword is used.

public Accessibility

Public access: Specifies that class members (variables or methods) are accessible to anyone, both

inside and outside the class and outside of the package Any object that interacts with the class can have access to the public members of the

class Keyword: public

Example: “public” Access Modifier

public class StudentRecord {

//default access to instance variable

public int name;

//default access to method

public String getName(){

return name;

}

}

Page 159 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 160: Core Java Handout v1.0

Handout - Core Java

protected Accessibility

Protected access: Specifies that the class members are accessible only to methods in that class and the

subclasses of the class The subclass can be in different packages

Keyword: protected

Example: “protected” Access Modifier

public class StudentRecord {

//default access to instance variable

protected int name;

//default access to method

protected String getName(){

return name;

}

}

default Accessibility

Default access: Specifies that only classes in the same package can have access to the variables and

methods of the class No actual keyword is their for the default modifier and it is applied in the absence of an

access modifier

Example: “default” Access Modifier

public class StudentRecord {

//default access to instance variable

int name;

//default access to method

String getName(){

return name;

}

}

private Accessibility

Private accessibility: Specifies that the class members are only accessible by the class in which they are defined Keyword: private

Page 160 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 161: Core Java Handout v1.0

Handout - Core Java

Example: “private” Access Modifier

public class StudentRecord {

//default access to instance variable

private int name;

//default access to method

private String getName(){

return name;

}

}

Java Program Structure: The Access Modifiers

Coding Guidelines

The instance variables of a class should normally be declared private, and the class will just provide accessor (getter) and mutator (setter) methods to these variables.

Try It Out

Problem Statement: Write a program that illustrates about access modifiers. Code: package learn;

public class OtherClass {

void testIt() { // No modifier means method has default access

System.out.println(“OtherClass”);

}

}

------------------------------------------------------------------------

In another source code, you have the following:

package somethingElse;

import learn.OtherClass;

Page 161 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 162: Core Java Handout v1.0

Handout - Core Java

class AccessClass {

static public void main(String[] args) {

OtherClass o = new OtherClass();

o.testIt();

}

}

Refer Files : OtherClass.java, AccessClass.java to obtain soft copy of the program code How It Works:

In the OtherClass program, the testIt() method has default (think: package-level) access.

Notice also that class OtherClass is in a different package from the AccessClass. Now the question is, will AccessClass be able to apply the method testIt() ? Will it

cause a compiler error? No method matching testIt()is found in class learn.OtherClass. o.testIt();. From the preceding results, you can see that AccessClass cannot use the OtherClass

method testIt() because testIt() has default access, and AccessClass is not in the same package as OtherClass. So AccessClass cannot see it, and hence the compiler complains.

Tips and Tricks:

Provide the key tips on access modifiers in Java. Solution:

Access modifiers can be public, protected, and private. If no access modifier is specified, then the accessibility is default package visibility. All

classes in the same package can access the feature. It is called as friendly access. But friendly is not a Java keyword. Same directory is same package in consideration of Java.

‘private’ means only the class can access it and not even sub-classes. So, it will cause access denial to the variable or method of the sub class.

These modifiers dictate, which classes can access the features. An instance of a class can access the private features of another instance of the same class.

‘protected’ means all classes in the same package (like default) and sub-classes in any package can access the features. But a subclass in another package can access the protected members in the super-class by only the references of subclass or its subclasses. A subclass in the same package does not have this restriction. This ensures that classes from other packages are accessing only the members that are part of their inheritance hierarchy.

Methods cannot be overridden to be more private. Only the direction shown in following figure is permitted from parent classes to sub-classes.

private --> friendly (default) --> protected --> public Parent classes Sub-classes

Page 162 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 163: Core Java Handout v1.0

Handout - Core Java

Summary

The different access modifiers in Java are default, public, private, and protected.

Test Your Understanding

1. State true or false for the following: a) For the default (or package-level access), the keyword default is used. b) protected variables and methods can be accessed by all members of subclasses

in different packages.

Page 163 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 164: Core Java Handout v1.0

Handout - Core Java

Session 42: Inheritance, Interfaces and Abstract Classes

Learning Objectives

After completing this session, you will be able to: Define Inheritance Explain the need of Inheritance Identify how to derive a subclass Define Object class Explain constructor calling chain Identify “super” keyword Override methods Hide methods and fields Apply type casting Write final class and final methods

Inheritance

Inheritance is the concept of a child class (sub class) automatically inheriting the variables and methods defined in its parent class (super class).

The primary features of object-oriented programming are encapsulation and polymorphism.

Importance of Inheritance

The benefit of inheritance in OOP is reusability. Once a behavior (method) is defined in a super class, that behavior is automatically inherited by all subclasses

Thus, you write a method only once and it can be used by all subclasses: Once a set of properties (fields) are defined in a super class, the same set of

properties are inherited by all subclasses. A class and its children share common set of properties

A subclass only needs to implement the differences between itself and the parent.

Deriving a Subclass

To derive a child class, you use the extends keyword. Suppose you have a parent class called Person.

public class Person {

protected String name;

protected String address;

/**

* Default constructor

*/

Page 164 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 165: Core Java Handout v1.0

Handout - Core Java

public Person(){

System.out.println(“Inside Person:Constructor”);

name = ""; address = "";

}

. . . .

}

extends Keyword

Now, you want to create another class named Student. Since a student is also a person, you decide to just extend the class Person, so that

you can inherit all the properties and methods of the existing class Person. To do this, you write,

public class Student extends Person {

public Student(){

System.out.println(“Inside Student:Constructor”);

}

. . . .

}

What you can do in a Subclass

A subclass inherits all of the “public” and “protected” members (fields or methods) of its parent, no matter what package the subclass is in.

If the subclass is in the same package as its parent, then it also inherits the package-private members (fields or methods) of the parent.

What you can do in a Sub-class Regarding Fields

The inherited fields can be used directly, just like any other fields. You can declare new fields in the subclass that are not in the super class. You can declare a field in the subclass with the same name as the one in the super

class, thus hiding it (not recommended). A subclass does not inherit the private members of its parent class. However, if the

super class has public or protected methods for accessing its private fields, these can also be applied by the subclass.

What you can do in a Sub-class Regarding Methods

The inherited methods can be used directly as they are. You can write a new instance method in the subclass that has the same signature as

the one in the super class, thus overriding it. You can write a new static method in the subclass that has the same signature as the

one in the super class, thus hiding it. You can declare new methods in the subclass that are not in the super class.

Page 165 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 166: Core Java Handout v1.0

Handout - Core Java

Object Class

Object class is mother of all classes. In Java language, all classes are subclassed (extended) from the Object super class. Object class is the only class that does not have a parent class Object class defines and implements behavior common to all classes including the ones that you write. Following are some of the important methods of the Object class:

getClass()

equals()

toString()

Class Hierarchy

A sample class hierarchy is shown in the following figure:

Superclass and Subclass

Superclass (Parent class) : Any class preceding a specific class in the class hierarchy

Sub class (Child class) : Any class following a specific class in the class hierarchy

How Constructor Method of a Super Class gets Called

A subclass constructor invokes the constructor of the superclass implicitly. When a Student object, a subclass (child class), is instantiated, the default constructor of its super class (parent class), Person class, is invoked implicitly before the constructor method of the subclass is invoked.

A subclass constructor can invoke the constructor of the super explicitly by using the “super” keyword:

The constructor of the Student class can explicitly invoke the constructor of the Person class using “super” keyword

Used when passing parameters to the constructor of the super class

Example: Constructor Calling Chain

To illustrate this, consider the following code: public static void main( String[] args ){

Student anna = new Student();

}

In the code, you create an object of class Student.

Page 166 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 167: Core Java Handout v1.0

Handout - Core Java

The output of the program is: Inside Person:Constructor

Inside Student:Constructor

Example: Constructor Calling Chain

The program flow is shown in the following figure:

The “super” Keyword

A subclass can also explicitly call a constructor of its immediate super class. This is done by using the super constructor call. A super constructor call in the constructor of a subclass will result in the execution of

relevant constructor from the super class, based on the arguments passed. For example, in your preceding example classes Person and Student, you show an

example of a super constructor call. In the given the following code for Student:

public Student(){

super( "SomeName", "SomeAddress" );

System.out.println("Inside Student:Constructor");

}

Few things to remember when using the super constructor call: The super() call must occur as the first statement in a constructor. The super() call can only be used in a constructor (not in ordinary methods).

Another use of super is to refer to members of the super class (just like the this reference ).

Page 167 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 168: Core Java Handout v1.0

Handout - Core Java

For example: public Student() {

super.name = “somename”;

super.address = “some address”;

}

Overriding Methods

If a derived class needs to have a different implementation of a certain instance method from that of the super class, then override that instance method in the sub class:

Note that the scheme of overriding applies only to instance methods. For static methods, it is called hiding methods. The overriding method has the same name, number and type of parameters, and

return type as the method it overrides. The overriding method can also return a subtype of the type returned by the

overridden method This is called a covariant return type.

Example: Overriding Methods

Suppose you have the following implementation for the getName method in the Person super class: public class Person {

:

:

public String getName(){

System.out.println("Parent: getName");

return name;

}

}

To override the getName() method of the superclass Person in the subclass Student, reimplement the method with the same signature. public class Student extends Person{

:

public String getName(){

System.out.println("Student: getName");

return name;

}

:

}

Now, when you invoke the getName() method of an object of the subclass Student, the getName() method of the Student class would be called, and the output would be: Student: getName

Page 168 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 169: Core Java Handout v1.0

Handout - Core Java

Modifiers in the Overriding Methods

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the super class can be made public, but not private, in the subclass.

You will get a compile-time error if you attempt to change an instance method in the super class to a class method in the subclass, or change the class method to an instance method in the super class.

Run-time Polymorphism with Overriding Methods

Polymorphism in a Java program means: The ability of a reference variable to change behavior according to what object

instance it is holding This allows multiple objects of different subclasses to be treated as objects of a single

super class, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to

Example: Run-time Polymorphism

Code: Person person2 = new Student();

person2.myMethod("test4");

Person person3 = new InternationalStudent();

person3.myMethod("test5");

Result: myMethod(test4) in Student class is called

myMethod(test5) in InternationalStudent class is called.

Hiding Methods

If a subclass defines a class method (static method) with the same signature as a class method in the super class, then the method in the subclass “hides” the one in the super class.

Example: Coding of Hiding Static Method

class Animal {

public static void testClassMethod() {

System.out.println("The class method in Animal.");

}

}

// The testClassMethod() of the child class hides the one of

// the super class – it looks like overriding, doesn't it?

class Cat extends Animal {

Page 169 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 170: Core Java Handout v1.0

Handout - Core Java

public static void testClassMethod() {

System.out.println("The class method in Cat.");

}

}

Overriding Method Versus Hiding Method

Hiding a static method of a super class looks like overriding an instance method of a super class. The difference comes during run time:

When you override an instance method, you get the benefit of run-time polymorphism. When you override a static method, there is no runt-time polymorphism.

Example: Overriding Method Versus Hiding Method During Runtime

// Create object instance of Cat.

Cat myCat = new Cat();

// The object instance is Cat type

// and assigned to Animal type variable.

Animal myAnimal2 = myCat;

// For static method, the static method of

// the super class gets called.

Animal.testClassMethod();

// For instance method, the instance method

// of the subclass is called even though

// myAnimal2 is a super class type. This is

// run-time polymorphism.

myAnimal2.testInstanceMethod();

Hiding Fields

Within a sub class, a field that has the same name as a field in the super class, hides the super class' field, even if their types are different.

Within the subclass, the field in the super class cannot be referenced by its simple name, instead, the field must be accessed through super keyword.

Generally speaking, hiding fields is not a recommended programming practice as it makes code difficult to read.

Try It Out

Problem Statement: Write a program that illustrate the use of ‘this’ and ‘super’.

Page 170 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 171: Core Java Handout v1.0

Handout - Core Java

Code: class ThisSuper extends SuperClass {

String s = "this";

public static void main(String[] args) {

new ThisSuper();

}

ThisSuper() {

display(this.s);

display(super.s);

this.display(s);

super.display(s);

}

void display(String s) {

System.out.println("this: " + s);

}

}

Refer Files: ThisSuper.java, SuperClass.java to obtain soft copy of the program code How It Works:

The ThisSuper class extends SuperClass. Both ThisSuper and SuperClass define the s member variable and display() method. The ThisSuper s variable hides the SuperClass s variable and the ThisSuper display() method overrides the SuperClass display method.

The ThisSuper constructor uses this and super like the following:

display(this.s);

display(super.s);

this.display(s);

super.display(s);

These statements produce the following output:

this: this

this: super

this: this

super: this

The first three statements use the display() method of ThisSuper to display the s member variable.

The first and third statements refer to the current (ThisSuper) object instance. The second statement uses super to refer to the s variable of SuperClass. The last statement uses super to refer to the display() method and s variable of

ThisSuper.

Page 171 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 172: Core Java Handout v1.0

Handout - Core Java

Tips and Tricks:

What is the purpose of using Object class? What if you make a concrete subclass and you need to override a method, but you

want the behavior in the superclass version of the method? Why would anyone want to make a class final? Does not that defeat the whole

purpose of object orientation? Solution:

The Object class serves two main purposes, namely to act as a polymorphic type for methods that need to work on any class that you or anyone else makes, and to provide real method code that all objects in Java need at run time. Some of the most important methods in Object are related to threads.

One area of good object oriented design looks at how to design concrete code that is meant to be overridden. The keyword super lets you to invoke a superclass version of an overridden method, from within the subclass.

A typical reason for making a class final is for security. You cannot, for example make a subclass of the String class. Imagine the havoc if someone extended the String class and substituted their own String subclass objects, polymorphically, where String objects are expected.

Summary

Abstract methods must be overridden by the first concrete (non-abstract) subclass. With respect to the method that it overrides, the overriding method Must have the same argument list. Must have the same return type, except that as of Java 5, the return type can be a

subclass – this is known as covariant return. Must not have a more restrictive access modifier. May have a less restrictive access modifier. Must not throw new or broader checked exceptions. May throw fewer or narrower checked exceptions, or any unchecked exception. final methods cannot be overridden. A subclass uses super.overriddenMetodName() to call the superclass version of an

overridden method. Polymorphism applies to overriding, not to overloading. Object type (not the reference variable’s type), determines which overridden method is

used at runtime.

Test Your Understanding

1. Which one of the following statements regarding derived subclasses is not correct? a) A derived class inherits both the variables and the methods in the base class. b) A derived class can inherit from two or more base classes. c) A derived class can implement two or more interfaces. d) A derived class can act as a base class for another derived class.

Page 172 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 173: Core Java Handout v1.0

Handout - Core Java

2. What is the usage of the keyword ‘super’? 3. Differentiate between overriding and overloading a method.

Page 173 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 174: Core Java Handout v1.0

Handout - Core Java

Session 46: Inheritance, Interfaces and Abstract Classes

Learning Objectives

After completing this session, you will be able to: Define abstract method and an abstract class Define an interface Explain the importance of interface Identify interface as a type Differentiate between interface and class Implement an interface Implementing multiple interfaces Identify inheritance among interfaces Describe interface and polymorphism Rewrite an interface

Abstract Methods

Methods that do not have implementation (body) are called abstract methods To create an abstract method, just write the method declaration without the body and use the keyword abstract No { } Please make this point that there are no parentheses will be available. For example, // Note that there is no body

public abstract void someMethod();

Abstract Class

An abstract class is a class that contains one or more abstract methods. An abstract class cannot be instantiated. You will get a compile error on the following code

MyAbstractClass a1 = new MyAbstractClass();

Another class (Concrete class) has to provide implementation of abstract methods: Concrete class has to implement all abstract methods of the abstract class in order to

be used for instantiation Concrete class uses extends keyword

Sample Abstract Class

public abstract class LivingThing {

public void breath(){

Page 174 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 175: Core Java Handout v1.0

Handout - Core Java

System.out.println("Living Thing breathing...");

}

public void eat(){

System.out.println("Living Thing eating...");

}

/**

* Abstract method walk()

* We want this method to be implemented by a

* Concrete class.

*/

public abstract void walk();

}

Extending An Abstract Class

When a concrete class extends the LivingThing abstract class, it must implement the abstract method walk() , or else, that subclass will also become an abstract class, and therefore cannot be instantiated. For example, public class Human extends LivingThing {

public void walk(){ System.out.println("Human walks...");

}

}

When to use Abstract Methods and Abstract Class

Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations. These subclasses extend the same abstract class and provide different implementations for the abstract methods. Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class.

What is an Interface?

It defines a standard and public way of specifying the behavior of classes: Defines a contract

All methods of an interface are abstract methods: Defines the signatures of a set of methods, without the body (implementation of the methods)

A concrete class must implement the interface (all the abstract methods of the Interface)

It allows classes, regardless of their locations in the class hierarchy, to implement common behaviours

Page 175 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 176: Core Java Handout v1.0

Handout - Core Java

Example 1: Interface

// Note that Interface contains just set of method

// signatures without any implementations.

// No need to say abstract modifier for each method

// since it assumed.

public interface Relation {

public boolean isGreater( Object a, Object b);

public boolean isLess( Object a, Object b);

public boolean isEqual( Object a, Object b);

}

Example 2: OperatorCar Interface

public interface OperateCar {

// constant declarations, if any

// method signatures

int turn(Direction direction,

double radius, double startSpeed,

double endSpeed);

int changeLanes(Direction direction,

double startSpeed,

double endSpeed);

int signalTurn(Direction direction, boolean signalOn);

int getRadarFront(double distanceToCar,

double speedOfCar);

int getRadarRear(double distanceToCar,

double speedOfCar);

......

// more method signatures

}

Why do you use Interfaces? Reason #1

To reveal the programming interface of an object (functionality of the object) without revealing its implementation:

This is the concept of encapsulation The implementation can change without affecting the caller of the interface The caller does not need the implementation at the compile time: It needs only the interface at the compile time During runtime, actual object instance is associated with the interface type

Why do you use Interfaces? Reason #2

To have unrelated classes implement similar methods (behaviors): One class is not a sub-class of another

Page 176 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 177: Core Java Handout v1.0

Handout - Core Java

Example: Class Line and class MyInteger They are not related through inheritance You want both to implement comparison methods checkIsGreater(Object x, Object y)

checkIsLess(Object x, Object y)

checkIsEqual(Object x, Object y)

Define Comparison interface, which has the three earlier abstract methods

Why do you use Interfaces? Reason #3

To model multiple inheritance: A class can implement multiple interfaces while it can extend only one class

Interface versus Abstract Class

All methods of an interface are abstract methods while some methods of an abstract class are abstract methods. Abstract methods of abstract class have abstract modifier

An interface can only define constants while abstract class can have fields. Interfaces have no direct inherited relationship with any particular class, they are

defined independently. Interfaces themselves have inheritance relationship among themselves.

Interface as a Type

When you define a new interface, you are defining a new reference type. If you define a reference variable whose type is an interface, then any object you

assign to it must be an instance of a class that implements the interface.

Example: Interface as a Type

Person class implements PersonInterface interface. You can do:

Person p1 = new Person();

PersonInterface pi1 = p1;

PersonInterface pi2 = new Person();

Interface versus Class: Commonality

Interfaces and classes are both types: This means that an interface can be used in places where a class can be used. For example: // Recommended practice

PersonInterface pi = new Person();

// Not recommended practice

Person pc = new Person();

Interface and class can both define methods.

Page 177 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 178: Core Java Handout v1.0

Handout - Core Java

Interface versus Class: Differences

The methods of an interface are all abstract methods. They cannot have bodies. You cannot create an instance from an interface. For example: PersonInterface pi = new PersonInterface(); //ERROR!

An interface can only be implemented by classes or extended by other interfaces.

Defining Interface

To define an interface, you write: public interface [InterfaceName] {

//some methods without the body

}

As an example, create an interface that defines relationships between two objects according to the “natural order” of the objects. public interface Relation {

public boolean isGreater( Object a, Object b);

public boolean isLess( Object a, Object b);

public boolean isEqual( Object a, Object b);

}

Implementing Interfaces

To create a concrete class that implements an interface, use the implements keyword. /**

* Line class implements Relation interface

*/

public class Line implements Relation {

private double x1;

private double x2;

private double y1;

private double y2;

public Line(double x1, double x2, double y1, double y2){

this.x1 = x1;

this.x2 = x2;

this.y1 = y1;

this.y2 = y2;

}

public double getLength(){ double length = Math.sqrt((x2-x1)*(x2-x1) +

(y2-y1)* (y2-y1));

return length;

Page 178 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 179: Core Java Handout v1.0

Handout - Core Java

}

public boolean isGreater( Object a, Object b){

double aLen = ((Line)a).getLength();

double bLen = ((Line)b).getLength();

return (aLen > bLen);

}

public boolean isLess( Object a, Object b){

double aLen = ((Line)a).getLength();

double bLen = ((Line)b).getLength();

return (aLen < bLen);

}

public boolean isEqual( Object a, Object b){

double aLen = ((Line)a).getLength();

double bLen = ((Line)b).getLength();

return (aLen == bLen);

}

}

When your class tries to implement an interface, always make sure that you implement all the methods of that interface, or else, you would encounter the following error:

Line.java:4: Line is not abstract and does not override abstract method isGreater(java.lang.Object,java.lang.Object) in Relation

public class Line implements Relation

^

1 error

Implementing Class

Implementing class can have its own methods. Implementing class extend a single super class or abstract class.

Relationship of an Interface to a Class

A concrete class can only extend one super class, but it can implement multiple Interfaces. The Java programming language does not permit multiple inheritance (inheritance is discussed later in this lesson), but interfaces provide an alternative.

All abstract methods of all interfaces have to be implemented by the concrete class

Page 179 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 180: Core Java Handout v1.0

Handout - Core Java

Example: Implementing Multiple Interfaces

A concrete class extends one super class but multiple Interfaces: public class ComputerScienceStudent

extends Student

implements PersonInterface,

AnotherInterface,

ThirdInterface{

// All abstract methods of all interfaces

// need to be implemented.

}

Inheritance among Interfaces

Interfaces are not part of the class hierarchy. However, interfaces can have inheritance relationship among themselves. public interface PersonInterface {

void doSomething();

}

public interface StudentInterface

extends PersonInterface {

void doExtraSomething();

}

Interface and Polymorphism

Interfaces exhibit polymorphism as well, because program may call an interface method, and the proper version of that method will be executed depending on the type of object instance passed to the interface method call.

Problem of Rewriting an Existing Interface

Consider an interface that you have developed called DoIt: public interface DoIt {

void doSomething(int i, double x);

int doSomethingElse(String s);

}

Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now becomes: public interface DoIt {

void doSomething(int i, double x);

int doSomethingElse(String s);

boolean didItWork(int i, double x, String s);

}

Page 180 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 181: Core Java Handout v1.0

Handout - Core Java

If you make this change, then all classes that implement the old DoIt interface will break because they do not implement all methods of the interface anymore.

Solution of Rewriting an Existing Interface

Create more interfaces later For example, you could create a DoItPlus interface that extends DoIt: public interface DoItPlus extends DoIt {

boolean didItWork(int i, double x, String s);

}

Now users of your code can choose to continue to apply the old interface or to upgrade to the new interface

When to use an Abstract Class Over Interface?

For methods that are not abstract, you want to use them when you want to provide common implementation code for all subclasses: Reducing the duplication

For abstract methods, the motivation is the same with the ones in the interface to impose a common behavior for all subclasses without dictating how to implement it.

Remember that a concrete can extend only one super class whether that super class is in the form of concrete class or abstract class

Try It Out

Problem Statement: Write a program that illustrates an inheritance tree with two abstract classes and one concrete (that is not abstract) class. Code: public abstract class Vehicle {

private String type;

public abstract void goUpHill();

public String getType() {

return type;

}

}

public abstract class Car extends Vehicle {

public abstract void goUpHill();

public void doCarThings() {

// special car code goes here

}

}

public class Mini extends Car {

public void goUpHill() {

Page 181 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 182: Core Java Handout v1.0

Handout - Core Java

// Mini-specific going uphill code

}

}

Refer File Name: Vehicle.java, Car.java, Mini.java to obtain soft copy of the program code How It Works:

The class Mini have three methods. It inherits both the getType() and doCarThings() methods, because they are public and

concrete (nonabstract). goUpHill() is abstract in the super class Vehicle, and is never implemented in the Car

class (so it remains abstract). It means the class Mini as the first concrete class below Vehicle must implement the

goUpHill() method. In other words, class Mini cannot pass the buck (of abstract method implementation)

to the next class down the inheritance tree, but class Car can, because Car like Vehicle, is abstract.

Tips and Tricks:

Interfaces do not really give you multiple inheritance, because you cannot put any implementation code in them. If all the methods of an interface are abstract, then what does an interface really buy you? Solution:

When all the methods of an interface are abstract, it leads to polymorphism. Moreover, Interfaces are really flexible.

A class can extend one class, and implement an interface. But another class might implement the same interface, yet coming from a different inheritance tree!

In fact, if you wrote your code to use interfaces, you will not even have to give anyone a super class that they has to extend. You could just give them the interface.

The fact that you cannot put in implementation code turns out not to be a problem for most good object oriented designs. Most interface methods need to be overridden even if the methods were not forced to be abstract.

Summary

Interfaces can be implemented by any class, from any inheritance tree. An interface is like a 100-percent abstract class, and is implicitly abstract whether you

type the abstract modifier in the declaration or not. An interface can have only abstract methods, no concrete methods allowed. Interface methods are by default public and abstract – explicit declaration of these

modifiers is optional. Interfaces can have constants, which are always implicitly public, static and final. A class implementing an interface can itself be abstract. An abstract implementing class does not have to implement the interface methods (but

the first concrete subclass must implement all of the interface’s methods).

Page 182 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 183: Core Java Handout v1.0

Handout - Core Java

A class can extend only one class (no multiple inheritance), but it can implement many interfaces.

Interfaces can extend one or more interfaces. Interfaces cannot extend a class, or implement a class or interface.

Test Your Understanding

1. Which one of the following statements is wrong? a) A class can extend only one class but it can implement any number of interfaces. b) A class can extend any number of classes but it can implement only one interface. c) An interface can be implemented in different ways by different classes. d) An interface cannot contain method definitions.

2. Differentiate between an abstract class and an interface.

Page 183 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 184: Core Java Handout v1.0

Handout - Core Java

Session 48: Inheritance, Interfaces and Abstract Classes

Learning Objectives

After completing this session, you will be able to: Define IS-A and HAS-A relationship

Using IS-A and HAS-A

When one class inherits from another, you say that the subclass extends the super class. When you want to know if one thing should extend another, use the IS-A test. Examples for IS-A relationship:

Triangle IS-A Shape Green IS-A Color

When two classes are related, but not through inheritance, (for example, one class has a reference to another class) then you say that the two classes are joined by HAS-A relationship. Examples for HAS-A relationship:

Bathroom HAS-A Tub Tub HAS-A Bubble

IS-A Relationship Test

The IS-A test works anywhere in the inheritance tree. Do not apply inheritance if the subclass and super class do not pass the IS-A test. Always ask yourself if the subclass IS-A more specific type of the super class. Example: Tea IS-A beverage makes sense. Beverage IS-A tea does not make sense. The IS-A relationship works only in one direction. The IS-A relationship implies that if X IS-A Y, then X can do anything a Y can do (and possibly more). Examples:

If class B extends class A, then class B IS-A class A. If class C extends class B, then class C passes the IS-A test for both B and A. Triangle IS-A Shape makes sense, so you can have Triangle extends Shape. But the

reverse, Shape IS-A Triangle does not make sense, so Shape should not extend Triangle.

Page 184 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 185: Core Java Handout v1.0

Handout - Core Java

Try It Out

Problem Statement: Write a program that illustrates the HAS-A relationship between Horse and Halter. Code: public class Animal { }

public class Horse extends Animal {

private Halter myHalter;

public void tie (LeadRope rope) {

myHalter.tie(rope); // Delegate tie behavior to the Halter object

}

}

public class Halter {

public void tie(LeadRope aRope) {

// Do the actual tie work here

}

}

Refer Files: Animal.java, Halter.java, Horse.java to obtain soft copy of the program code How It Works:

A Horse IS-A Animal. A Horse HAS-A Halter. The following point summarizes the HAS-A relationship between Horse and Halter. Horse class has a Halter, because Horse declares an instance variable of type Halter. When code invokes tie() on a Horse instance, the Horse invokes tie() on the Halter

instance variable of the Horse object.

Tips and Tricks:

How do you know whether to make class, a subclass, an abstract class, or an interface? Solution:

Make a class that does not extend anything (other than Object) when your new class does not pass the IS-A test for any other type.

Make a subclass (in other words, extend a class) only when you need to make a more specific version of a class and need to override or add new behaviors.

Use an abstract class when you want to define a template for a group of subclasses, and you have at least some implementation code that all subclasses could use. Make the class abstract when you want to guarantee that nobody can make objects of that type.

Page 185 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 186: Core Java Handout v1.0

Handout - Core Java

Use an interface when you want to define a role that other classes can play, regardless of where those classes are in the inheritance tree.

Summary

IS-A refers to inheritance. IS-A is expressed with the keyword extends. IS-A, “inherits from” and “is a subtype of” are all equivalent expressions. HAS-A means an instance of one class “has a” reference to an instance of another

class or another instance of the same class.

Test Your Understanding

1. State true or false for the following: a) The IS-A test is applied to check whether one class inherits from another class. b) Using HAS-A test, one can check whether a class has a reference to another

class. 2. Put a check next to the relationships that make sense (Hint: Apply IS-A test)

a) Guitar extends Instrument b) Ferrari extends Engine c) Metal extends Titanium d) Container extends Jar

Page 186 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 187: Core Java Handout v1.0

Handout - Core Java

Session 49: Inheritance, Interfaces and Abstract Classes

Learning Objectives

After completing this session, you will be able to: Define a “Type”? Cast Primitive Types Describe Implicit Type Casting Explain Explicit Type Casting Cast Objects

What is a “Type”?

When an object instance is created from a class, you say the object instance is “type” of the class and its super classes. Example: Student student1 = new Student();

student1 object instance is the type of Student or it is of Student type student1 object instance is also type of Person if Student is a child class of Person student1 object instance is also type of Object

Significance of Type

An object instance of a particular type can be used in any place where an instance of the type and its super type is called for. Example:

student1 object instance is a “type” of TuftsStudent, Student, and Person student1 object can be used in any place where object instance of the type of

TuftsStudent, Student, or Person is called for This enables polymorphism.

Casting Primitive Types

Casting between primitive types enables you to convert the value of one data from one type to another primitive type. Commonly occurs between numeric types. There is one primitive data type that you cannot do casting though, and that is the boolean data type Types of Casting:

Implicit Casting Explicit Casting

Page 187 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 188: Core Java Handout v1.0

Handout - Core Java

Implicit Casting

Suppose you want to store a value of int data type to a variable of data type double. int numInt = 10;

double numDouble = numInt; //implicit cast

In this example, as the data type (double) of the destination variable holds a larger value than the data type (int) of the value, the data is implicitly casted to the data type double of the destination variable.

Implicit Casting: Example

Another example: int numInt1 = 1;

int numInt2 = 2;

//result is implicitly casted to type double

double numDouble = numInt1/numInt2;

Explicit Casting

When you convert a data that has a large type to a smaller type, you must use an explicit cast. Explicit casts take the following form: (Type)value

where, Type is the name of the type you are converting to and value is an expression that results in the value of the source type.

Explicit Casting: Example

double valDouble = 10.12;

int valInt = (int)valDouble;

//convert valDouble to int type

double x = 10.2;

int y = 2;

int result = (int)(x/y); //typecast result of operation to int

Casting Objects

Instances of classes also can be cast into instances of other classes, with one restriction. The source and destination classes must be related by inheritance. One class must be a subclass of the other. Casting objects is analogous to converting a primitive value to a larger type, some objects might not need to be cast explicitly.

Page 188 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 189: Core Java Handout v1.0

Handout - Core Java

Cast (classname)object where, classname is the name of the destination class and object is a reference to the source object

Casting Objects: Example

The following example casts an instance of the class VicePresident to an instance of the class Employee. VicePresident is a subclass of Employee with more information, which here defines that the VicePresident has executive washroom privileges. Employee emp = new Employee();

VicePresident veep = new VicePresident();

// no cast needed for upward use

emp = veep;

// must cast explicitly

veep = (VicePresident)emp;

Implicit Type Casting

An object instance of a subclass can be assigned to a variable (reference) of a parent class through implicit type casting. This is safe because an object instance of a subclass “is” also the type of the super class. Example:

Assume Student class as a child class of Person class Assume CollegeStudent class as a child class of Student class CollegeStudent collegeStudent = new CollegeStudent(); Student student = collegeStudent; // Implicit type casting Person person = collegeStudent; // Implicit type casting Object object = collegeStudent; // Implicit type casting

Type Casting Between Objects

Type casting between objects is shown in the following figure:

collegeStudent

student

person

CollegeStudent Object instance

Page 189 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 190: Core Java Handout v1.0

Handout - Core Java

Explicit Type Casting

An object instance of a super class must be assigned to a variable (reference) of a child class through explicit type casting: Not doing it will result in a compile error because the type assignment is not safe Compiler wants to make sure that you know what you are doing Example: Assume Student class is a child class of Person class Person person1 = new Student();

Student student1 = (Student) person1; // Explicit type casting

Runtime Type Mismatch Exception

Even with explicit casting, you could still end up having a runtime error Example: Assume Student class is a child class of Person class

Assume Teacher class is also a child class of Person class

Person person1 = new Student();

Person person2 = new Teacher();

Student student1 = (Student) person1; // Explicit type casting

// No compile error, but runtime type mismatch exception

Student student2 = (Student) person2;

Use instanceof Operator To Prevent Runtime Type Mismatch Error

You can check the type of the object instance using instanceof operator before the type casting. Example: Person person1 = new Student();

Person person2 = new Teacher();

// Do the casting only when the type is verified

if (person2 instanceof Student) {

Student student2 = (Student) person2;

}

Try It Out

Problem Statement: Write a program that illustrates the use of Casting Object References.

Page 190 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 191: Core Java Handout v1.0

Handout - Core Java

Code: import java.util.*;

class CastObjRef {

public static void main(String args[]) {

String s1 = "abc";

String s2 = "def";

Vector v = new Vector();

v.add(s1);

s2 = (String) v.elementAt(0);

System.out.println(s2);

}

}

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

When you run the program, it produces the following result:

abc

Without the (String) cast operator, the result returned by v.elementAt(0) is an object of the Object class.

The compiler recognizes this inconsistency and generates an error message. When the (String) cast operator is used, the compiler recognizes that you are casting

the reference to an Object object into a String object and proceeds with the compilation.

Tips and Tricks:

Provide some key tips on casting of primitives, Object references, and rules that are followed during compile-time and Run-time. Solution: Casting of Primitives:

Explicit type casting is required for the narrow conversion of primitive data types. Can cast any type that is not boolean type to another type that is not boolean Cannot cast a boolean or to a boolean type

Casting of Object references: Allows super-types to be assigned to subtypes. Extensive checks done both at compile and runtime. At compile time, class of the object may not be known, so at runtime if checks fail, then a ClassCastException is thrown. Cast operator, instanceof operator and the == operator behave in the same way in allowing references to be the operands of them. You cannot cast or apply instanceof or compare unrelated references, sibling references or any incompatible references.

Page 191 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 192: Core Java Handout v1.0

Handout - Core Java

Compile-time rules: When old and new types are classes, one class must be the subclass of the other. When old and new types are arrays, both must contain reference types and it must be legal to cast between those types (primitive arrays cannot be cast, conversion possible only between same type of primitive arrays). You can always cast between an interface and an object that is not final. Run-time rules:

If new type is a class, then the class of the expression being converted must be new type or extend new type.

If new type is an interface, then the class of the expression being converted must implement the interface.

Summary

Reference Variable Casting: There are two types of reference variable casting: downcasting and upcasting. o Downcasting: If you have a reference variable that refers to a subtype object, you

can assign it to a reference variable of the subtype. You must make an explicit cast to do this, and the result is that you can access the subtype’s members with this new reference variable.

o Upcasting: You can assign a reference variable to a supertype reference variable explicitly or implicitly. This is an inherently safe operation because the assignment restricts the access capabilities of the new variable.

Test Your Understanding

1. State true or false for the following: a) Casting cannot be done for the boolean primitive type. b) Differentiate between Implicit type casting and Explicit type casting.

Page 192 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 193: Core Java Handout v1.0

Handout - Core Java

Session 50: Inheritance, Interfaces and Abstract Classes

Learning Objectives

After completing this session, you will be able to: Identify inner classes, static nested classes, and, anonymous classes

Inner Class

Inner class is a class declared within another class Accessing the members of the inner class: Need to instantiate an object instance of an inner class first Example:

innerObj.innerMember = 5;

//innerObj is an instance of the inner class

//innerMember is a member of the inner class

Accessing Members of Outer Class Within an Inner Class

Methods of the inner class can directly access members of the outer class: Example: 1 class Out {

2 int outData;

3 class In {

4 void inMeth() {

5 outData = 10;

6 }

7 }

8 }

Java Program Structure: Inner Classes

1 class OuterClass {

2 int data = 5;

3 class InnerClass {

4 int data2 = 10;

5 void method() {

6 System.out.println(data);

7 System.out.println(data2);

8 }

9 }

10

11 //continued...

Page 193 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 194: Core Java Handout v1.0

Handout - Core Java

9 public static void main(String args[]) {

10 OuterClass oc = new OuterClass();

11 InnerClass ic = oc.new InnerClass();

12 System.out.println(oc.data);

13 System.out.println(ic.data2);

14 ic.method();

15 }

16 }

Static Nested Classes

A static nested class is just a class enclosed within another class, and marked with the keyword static.

Static nested classes are considered a member of the enclosing or outer class. Static nested classes can access only the private static members of the outer class. Static nested class is not connected to an instance of the outer class. Static nested class cannot access the variables that are not static and methods of the

outer class.

Static Nested Class: Example

public class OuterClass {

static class InnerClass

void sayIt() {

System.out.println(“method of a static inner class”);

}

}

}

class Test {

public static void main(String[] args) {

OuterClass.InnerClass inner = new OuterClass.InnerClass();

inner.sayIt();

}

}

Nested Classes versus Inner Classes

Any Java class that is defined within the scope of another class is known as a nested class.

It does not matter if it is anonymous, static, normal, or whatever. If it is inside another class, then it is technically considered as a nested class. Nested classes that are not static, often referred to as inner classes. All inner classes are nested classes, but not all nested classes are inner classes.

Page 194 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 195: Core Java Handout v1.0

Handout - Core Java

Anonymous Classes

It is common in Java programming to encounter situations where you need to create an object but do not need to bother giving it an explicit name.

With the inner classes you can take this to another level by creating and instantiating a class without bothering to give it a name. This is called as an anonymous class.

This anonymity eliminates a lot unnecessary named objects and makes the code more readable.

Anonymous Inner Class: Example

In the following code an instance of the ActionListener class is created in the argument of the addActionListener method: .. public class AnOuterClass extends Applet { Button fBt = new Button("OK"); public AnOuterClass () { int i = 0; fBt.addActionListener ( // The argument is the object created by the following: new ActionListener () // no name given to this object { public void actionPerformed (ActionEvent e) { i++; System.out.println ("Pressed "+i+" times"); } } ); add(fBt); } } // class AnOuterClass

Anonymous Inner Class: Example

In this example, in one step you have created an implementation of the ActionListener interface and created an instance of it for application by the button. Now the compiler will create a class file name AnOuterClass$1.class where a number, in this case "1", is used to identify the class files for anonymous inner classes.

Try It Out

Problem Statement: Write a program that illustrates the use of an instance of an inner class and an outer class.

Page 195 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 196: Core Java Handout v1.0

Handout - Core Java

Code: class Outer {

String s = "Outer";

public static void main(String[] args) {

new Outer().new Inner();

}

class Inner {

String s = "Inner";

Inner() {

System.out.println(this.s);

System.out.println(Outer.this.s);

}

}

}

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

The program displays the line Inner followed by the line Outer. In the Inner() constructor, this.s, yields the value of the s variable corresponding to the

Inner class and Outer.this.s refers to the s variable of the Outer class. To refer to the instance of an outer class preponed the outer class name and a period

to this.

Tips and Tricks:

List out the key points on local class (static and non-static), anonymous class (static and non-static) Solution:

Entity Declaration context

Accessibility Modifiers

Outer instance

Direct access to enclosing

context

Defines static or non-

static members

Package level As package member

public or default No N/A Both static

and non-static

Top level nested class (static)

As static class member All No

static members in enclosing context

Both static and non-static

Non static inner class

As non-static class member All Yes

All members in enclosing context

Only non-static

Page 196 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 197: Core Java Handout v1.0

Handout - Core Java

Page 197 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Entity Declaration context

Accessibility Modifiers

Outer instance

Direct access to enclosing

context

Defines static or non-

static members

Local class (non-static)

In block with non-static context

None Yes

All members in enclosing context + local final variables

Only non-static

Local class (static)

In block with static context None No

Static members in enclosing context + local final variables

Only non-static

Non static inner class

As non-static class member All Yes

All members in enclosing context

Only non-static

Anonymous class (non-static)

In block with non-static context

None Yes

All members in enclosing context + local final variables

Only non-static

Anonymous class (static)

In block with static context None No

Static members in enclosing context + local final variables

Only non-static

Package level interface

As package member

public or default No N/A

static variables and non-static prototypes

Top level nested interface (static)

As static class member All No

Static members in enclosing context

static variables and non-static method prototypes

Summary

Inner Classes: A “regular” inner class is declared inside the curly braces of another class, but outside

any method or other code block. To instantiate an inner class, you must have a reference to an instance of the outer

class.

Page 198: Core Java Handout v1.0

Handout - Core Java

Static Nested Classes Static nested classes are inner classes marked with the static modifier. A static nested class is not an inner class; it’s a top-level nested class. You don’t need an instance of the outer class to instantiate a static nested class.

Anonymous Inner Classes:

Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface.

An anonymous inner class is always created as part of a statement; don’t forget to close the statement after the class definition with a curly brace.

An anonymous inner class can extend one subclass or implement one interface. An anonymous-local inner class is declared, defined, and automatically instantiated as

part of a method invocation.

Test Your Understanding

Differentiate between static class, inner class, and anonymous class.

Page 198 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 199: Core Java Handout v1.0

Handout - Core Java

Session 52: Inheritance, Interfaces and Abstract Classes

Learning Objectives

After completing this session, you will be able to describe the process of debugging Web applications using the following views in SDE:

Breakpoint view Console view Debug view Display view Expressions view Registers view

Breakpoint View

Breakpoints are indicators to the debugger that it should stop execution at specific places in the code, and let you step through it.

A breakpoint causes the execution of a thread to suspend at the location where the breakpoint is set.

Breakpoints view lists all the breakpoints you have set in the workbench projects. In this view, you can double-click a breakpoint to display its location in the editor. You can also enable or disable breakpoints, delete them, or add new ones. Breakpoints can be set to trigger always or when a certain condition has been met. The Breakpoints view lists Java exception breakpoints, which suspend execution at

the point where the exception is thrown. You can add or remove exceptions. To add a breakpoint in the code, do the following: Open the file in the Java editor Place your cursor in the grey bar (along the left edge of the editor area) on the line Double-click to set a breakpoint and a marker will be shown at the line

Console View

This view shows the output of the execution of your program and allows you to enter input for the program. The console shows three kinds of text, each in a different color:

Standard output Standard error Standard input

You can choose the different colors for these kinds of text on the preferences pages. (Window > Preferences > Run/Debug > Console).

Page 199 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 200: Core Java Handout v1.0

Handout - Core Java

Debug View

This view allows you to manage the debugging or running of a program in the workbench.

It displays the stack frame for the suspended threads for each target you are debugging.

Each thread in your program appears as a node in the tree. It displays the process for each target you are running. If the thread is suspended, then its stack frames are shown as child elements.

Display View

This view displays the result of evaluating an expression in the context of the current stack frame.

You can evaluate and display a selection either from the editor or directly from the Display view.

Expressions View

Data can be inspected in the Expressions view. You can inspect data from a scrapbook page, a stack frame of a suspended thread,

and other places. The Expressions view opens automatically when the Inspect command is activated.

Registers View

You can view the contents of a register from the Registers view. To view the contents of a register in the Register view: In the Debug view, select the thread for which you want to view the registers. In the Registers view, expand the register group that you want to view. If necessary, use the scroll bars or PageUp and PageDown keys to scroll the Register

view until the register is visible. Nodes in the Registers view are visible if they are at the top level of the tree structure,

or if the nodes at a level higher have been expanded. For all nodes that are visible in this view, you can jump to a specific node by typing the

first letter of the node. The view will jump to the next node that begins with that letter.

Tips and Tricks:

When a thread is suspended, how the execution of a Java program is stepped through line by line using SDE?

Page 200 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 201: Core Java Handout v1.0

Handout - Core Java

Solution: When a thread is suspended, the step controls can be used to step through the

execution of the program line-by-line. Step Over: The currently selected line is executed and suspends on the next

executable line. Click on Run > Step Over in the tool bar or press F6 key to perform this operation.

Step Into: The next expression on the currently selected line to be executed is invoked, and execution suspends at the next executable line in the method that is invoked. Click on Run > Step Into in the tool bar or press F5 key.

Step Return: Execution resumes until the next return statement in the current method is executed, and execution suspends on the next executable line. Click on Run > Step Return in the tool bar or press F7 key.

Summary

Breakpoints view lists all the breakpoints you have set in the workbench projects. Console view shows the output of the execution of your program and allows you to

enter input for the program. Debug view allows you to manage the debugging or running of a program in the

workbench. Display view displays the result of evaluating an expression in the context of the

current stack frame. Data can be inspected in the Expressions view. Registers view displays the contents of a register.

Test Your Understanding

1. What is a Breakpoint? a) Breakpoints are indicators to the debugger that it should stop execution at specific places. b) Breakpoints display variables applied in the code. c) Breakpoints are used to exit from code abruptly during execution. d) All the above e) How are stack frames of a suspended thread displayed in the Debug view? a) Parent elements b) Child elements

Page 201 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 202: Core Java Handout v1.0

Handout - Core Java

Session 54: Exception Handling

Learning Objectives

After completing this session, you will be able to: Define an exception Identify what happens when an exception occurs List the benefits of Exception Handling framework Catch exceptions with try-catch and finally

Exception

Exceptional event Error that occurs during run-time Cause normal program flow to be disrupted Examples are:

Divide by zero errors Accessing the elements of an array beyond its range Invalid input Hard disk crash Opening a file that does not exist Heap memory exhausted

Exception Example

1 class DivByZero {

2 public static void main(String args[]) {

3 System.out.println(3/0);

4 System.out.println(“Pls. print me.”);

5 }

6 }

Example: Default Exception Handling

Displays this error message: Exception in thread "main“ java.lang.ArithmeticException: / by zero at DivByZero.main(DivByZero.java:3)

Default exception handler: Provided by Java run time Prints out exception description Prints the stack trace: Hierarchy of methods where the exception occurred Causes the program to terminate

Page 202 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 203: Core Java Handout v1.0

Handout - Core Java

What Happens when an Exception Occurs?

When an exception occurs within a method, the method creates an exception object and hands it off to the run-time system:

Creating an exception object and handing it to the run-time system is called “throwing an exception”.

Exception object contains information about the error, including its type and the state of the program when the error occurred.

The run time system searches the call stack for a method that contains an exception handler.

When an appropriate handler is found, the run-time system passes the exception to the handler:

An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.

The exception handler chosen is said to catch the exception. If the run-time system exhaustively searches all the methods on the call stack without

finding an appropriate exception handler, then the run-time system (and, consequently, the program) terminates and uses the default exception handler.

Page 203 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 204: Core Java Handout v1.0

Handout - Core Java

Searching the Call Stack for an Exception Handler

Sample diagram representing the Exception handling framework

Benefits of Java Exception Handling Framework

The benefits of Java Exception Handling Framework are: Separating Error-Handling code from “regular” business logic code Propagating errors up the call stack Grouping and differentiating error types

Separating Error Handling Code from Regular Code

In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code. Consider the pseudo code method here that reads an entire file into memory: readFile {

open the file;

determine its size;

allocate that much memory;

read the file into memory;

close the file;

}

Page 204 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 205: Core Java Handout v1.0

Handout - Core Java

Traditional Programming: No Separation of Error Handling Code

In traditional programming, to handle such cases, the readFile function must have more code to do error detection, reporting, and handling. errorCodeType readFile {

initialize errorCode = 0;

open the file;

if (theFileIsOpen) {

determine the length of the file;

if (gotTheFileLength) {

allocate that much memory;

if (gotEnoughMemory) {

read the file into memory;

if (readFailed) {

errorCode = -1;

}

} else {

errorCode = -2;

}

} else { errorCode = -3;

}

close the file;

if (theFileDidntClose && errorCode == 0) {

errorCode = -4;

} else {

errorCode = errorCode and -4;

}

} else {

errorCode = -5;

}

return errorCode;

}

Separating Error Handling Code from Regular Code

Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere. readFile {

try {

open the file;

determine its size;

allocate that much memory;

read the file into memory;

Page 205 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 206: Core Java Handout v1.0

Handout - Core Java

close the file;

} catch (fileOpenFailed) {

doSomething;

} catch (sizeDeterminationFailed) {

doSomething;

} catch (memoryAllocationFailed) {

doSomething;

} catch (readFailed) {

doSomething;

} catch (fileCloseFailed) {

doSomething;

}

}

Note that exceptions do not spare your effort of doing the work of detecting, reporting, and handling errors, but they help you to organize the work more effectively.

Exception Class Hierarchy

The Throwable, Exception, and Error classes: Throwable class:

Root class of exception classes Immediate subclasses: Error Exception

Exception class:

Conditions that user programs can reasonably deal with Usually the result of some flaws in the user program code Examples: o Division by zero error o Array out-of-bounds error

Error class:

Used by the Java run-time system to handle errors occurring in the run-time environment

Generally beyond the control of user programs Examples: o Out of memory errors o Hard disk crash

Page 206 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 207: Core Java Handout v1.0

Handout - Core Java

Catching Exceptions: The try-catch Statements

Syntax of try-catch statements: try {

<code to be monitored for exceptions>

} catch (<ExceptionType1> <ObjName>) {

<handler if ExceptionType1 occurs>

}

...

} catch (<ExceptionTypeN> <ObjName>) {

<handler if ExceptionTypeN occurs>

}

1 class DivByZero {

2 public static void main(String args[]) {

3 try {

4 System.out.println(3/0);

5 System.out.println(“Please print me.”);

6 } catch (ArithmeticException exc) {

7 //Division by zero is an ArithmeticException

8 System.out.println(exc);

9 }

10 System.out.println(“After exception.”);

11 }

12 }

Page 207 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 208: Core Java Handout v1.0

Handout - Core Java

Catching Exceptions: Multiple catch

1 class MultipleCatch {

2 public static void main(String args[]) {

3 try {

4 int den = Integer.parseInt(args[0]);

5 System.out.println(3/den);

6 } catch (ArithmeticException exc) {

7 System.out.println(“Divisor was 0.”);

8 } catch (ArrayIndexOutOfBoundsException exc2) {

9 System.out.println(“Missing argument.”);

10 }

11 System.out.println(“After exception.”);

12 }

13 }

Catching Exceptions: Nested trys

class NestedTryDemo {

public static void main(String args[]){

try {

int a = Integer.parseInt(args[0]);

try {

int b = Integer.parseInt(args[1]);

System.out.println(a/b);

} catch (ArithmeticException e) {

System.out.println(“Div by zero error!");

}

} catch (ArrayIndexOutOfBoundsException) {

System.out.println(“Need 2 parameters!");

}

}

}

Catching Exceptions: Nested trys with Methods

1 class NestedTryDemo2 {

2 static void nestedTry(String args[]) {

3 try {

4 int a = Integer.parseInt(args[0]);

5 int b = Integer.parseInt(args[1]);

6 System.out.println(a/b);

7 } catch (ArithmeticException e) {

8 System.out.println("Div by zero error!");

9 }

10 }

Page 208 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 209: Core Java Handout v1.0

Handout - Core Java

11 public static void main(String args[]){

12 try {

13 nestedTry(args);

14 } catch (ArrayIndexOutOfBoundsException e) {

15 System.out.println("Need 2 parameters!");

16 }

17 }

18 }

Catching Exceptions: The finally Keyword

Syntax: try {

<code to be monitored for exceptions>

} catch (<ExceptionType1> <ObjName>) {

<handler if ExceptionType1 occurs>

}

...

} finally {

<code to be executed before the try block ends>

}

Contains the code for cleaning up after a try or a catch Block of code is always executed in spite of the following different scenarios:

Forced exit occurs using a return, a continue, or a break statement Normal completion Caught exception thrown: Exception was thrown and caught in the method Uncaught exception thrown: Exception thrown was not specified in any catch block in

the method

1 class FinallyDemo {

2 static void myMethod(int n) throws Exception{

3 try {

4 switch(n) {

5 case 1: System.out.println("1st case");

6 return;

7 case 3: System.out.println("3rd case");

8 throw new RuntimeException("3!");

9 case 4: System.out.println("4th case");

10 throw new Exception("4!");

11 case 2: System.out.println("2nd case");

12 }

13 } catch (RuntimeException e) {

15 System.out.print("RuntimeException: ");

16 System.out.println(e.getMessage());

17 } finally {

Page 209 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 210: Core Java Handout v1.0

Handout - Core Java

18 System.out.println("try-block entered.");

19 }

20 }

21 //continued

22 public static void main(String args[]){

23 for (int i=1; i<=4; i++) {

24 try {

25 FinallyDemo.myMethod(i);

26 } catch (Exception e){

27 System.out.print("Exception caught: ");

28 System.out.println(e.getMessage());

29 }

30 System.out.println();

31 }

32 }

33 }

Try It Out

Problem Statement: Write a program that illustrates the importance of handling classes in the Exception Hierarchy. Code: import java.io.*;

public class ExceptionHierarchyApp {

public static void main(String[] args) {

try {

RandomAccessFile raf = new RandomAccessFile("myfile.txt", "r");

byte b[] = new byte[1000];

raf.readFully(b, 0, 1000);

} catch (FileNotFoundException fnfe) {

System.err.println("File not found");

System.err.println(fnfe.getMessage());

fnfe.printStackTrace();

} catch (IOException ioe) {

System.err.println("IO Error");

System.err.println(ioe.toString());

ioe.printStackTrace();

}

}

}

Refer File Name: ExceptionHierarchyApp.java to obtain soft copy of the program code

Page 210 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 211: Core Java Handout v1.0

Handout - Core Java

How It Works: When you run the program, it produces the following result: File not found myfile.txt (The system cannot find the file specified)

java.io.FileNotFoundException: myfile.txt (The system cannot find the file specified)

at java.io.RandomAccessFile.open(Native Method)

at java.io.RandomAccessFile.<init>(Unknown Source)

at java.io.RandomAccessFile.<init>(Unknown Source)

at ExceptionHierarchyApp.main(ExceptionHierarchyApp.java:6)

This program attempts to open a file and read some data from it. Opening and reading files can generate many exceptions, most of which are some

type of IOException. Imagine that in this program you are interested in knowing only whether the exact

exception is a FileNotFoundException. FileNotFoundException is a subclass of IOException. You can handle it in the catch clause that catches all subtypes of IOException, but

then you will have to test the exception to determine whether it was a FileNotFoundException.

Instead, you have coded a special exception handler for the FileNotFoundException and a separate exception handler for all other IOException subtypes.

If this code generates a FileNotFoundException, then it will be handled by the catch clause related to FileNotFoundException.

If it generates another IOException perhaps EOFException, which is a subclass of IOException, then it will be handled by the catch clause related to IOException.

If some other exception is generated, such as a run time exception of some type, then neither catch clause will be executed nor the exception will be propagated down the call stack.

Notice that the catch clause for the FileNotFoundException has been placed before the handler for the IOException. This is really important.

If you do it in the opposite way, then the program will not compile. The handlers for the most specific exceptions must always be placed before those for

more general exceptions. The following program will not compile:

try {

// do risky IO things

} catch (IOException ioe) {

// handle general IOExceptions

} catch (IOException ioe) {

// handle general IOExceptions

}

You will get a compiler error message like this: Unreachable catch block for FileNotFoundException. It is already handled by the catch

block for IOException.

Page 211 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 212: Core Java Handout v1.0

Handout - Core Java

Tips and Tricks:

List out some of the key exception rules that need to be followed while writing a Java program. Solution: You cannot have a catch or finally without a try. void go() {

Foo f = new Foo();

f.foof();

catch(FooException fe) { }

}

You cannot put code between the try and the catch. try {

x.doStuff();

}

int y = 50;

} catch(FooException fe) { }

A try must be followed by either a catch or a finally. try {

x.doStuff();

} finally {

// cleanup

}

A try with only a finally (no catch) must still declare the exception. void go() throws FooException {

try {

x.doStuff();

} finally { }

}

Summary

Exceptions come in two flavours: checked and unchecked. Checked exceptions include all subtypes of Exception, excluding classes that extend

RuntimeException. Checked exceptions are subject to the handle or declare rule; any method that might

throw a checked exception must either declare the exception using throws, or handle the exception with an appropriate try/catch.

Subtypes of Error or RuntimeException are unchecked. If you use an optional finally block, it will always be invoked, regardless of whether an

exception in the corresponding try is thrown or not, and regardless of whether a thrown exception is caught or not.

Page 212 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 213: Core Java Handout v1.0

Handout - Core Java

The only exception to the finally-will-always-be-called true is that a finally will not be invoked if the JVM shuts down. That could happen if code from the try or catch blocks calls System.exit().

Just because finally is invoked does not mean it will complete. Code in the finally block could itself raise an exception or issue a System.exit().

Test Your Understanding

1. Which one of the following statements is wrong? a) An exception is an abnormal condition that is caused by a run-time error. b) The try…catch mechanism can be used only once in a Java program. c) Error messages defined by user can be displayed by using the try…catch

mechanism. d) When the try…catch mechanism is used, execution will resume even after an

error is detected and reported. 2. Which one of the following statements is correct?

a) The ‘try’ block should be followed by a ‘catch’ block. b) The ‘try’ block should be followed by a ‘finally’ block. c) The ‘try’ block should be followed by either a ‘catch’ block or a ‘finally’ block. d) The ‘try’ block should be followed by at least two ‘catch’ blocks.

Page 213 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 214: Core Java Handout v1.0

Handout - Core Java

Session 55: Exception Handling

Learning Objectives

After completing this session, you will be able to: Throw Exceptions Apply Throw and Throws clauses Propagate exceptions

Throwing Exceptions: The throw Keyword

Java allows you to throw exceptions (generate exceptions). throw <exception object>; An exception you throw is an object. You have to create an exception object in the same way you create any other object. Example:

throw new ArithmeticException(“testing...”);

Example: Throwing Exceptions

1 class ThrowDemo {

2 public static void main(String args[]){

3 String input = “invalid input”;

4 try {

5 if (input.equals(“invalid input”)) {

6 throw new RuntimeException("throw demo");

7 } else {

8 System.out.println(input);

9 }

10 System.out.println("After throwing");

11 } catch (RuntimeException e) {

12 System.out.println("Exception caught:" + e);

13 }

14 }

15 }

Propagating Errors up the Call Stack

Suppose that the readFile method is the fourth method in a series of nested method calls made by the main program. method1 calls method2, which calls method3 that finally calls readFile.

Page 214 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 215: Core Java Handout v1.0

Handout - Core Java

Suppose also that method1 is the only method interested in the errors that might occur within readFile. method1 {

call method2;

}

method2 {

call method3;

}

method3 {

call readFile;

}

Traditional Way of Propagating Errors

Traditional error notification techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1, which is the only method that is interested in them. method1 {

errorCodeType error;

error = call method2;

if (error)

doErrorProcessing;

else

proceed;

}

errorCodeType method2 {

errorCodeType error;

error = call method3;

if (error)

return error;

else

proceed;

}

errorCodeType method3 {

errorCodeType error;

error = call readFile;

if (error)

return error;

else

proceed;

}

Page 215 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 216: Core Java Handout v1.0

Handout - Core Java

Using Java Exception Handling

A method can duck any exception thrown within it, thereby allowing a method farther up the call stack to catch it. Hence, only the methods that care about errors have to worry about detecting errors. Any checked exceptions that can be thrown within a method must be specified in its throws clause. method1 {

try {

call method2;

} catch (Exception ex) {

doErrorProcessing;

}

}

method2 throws Exception {

call method3;

}

method3 throws Exception {

call readFile;

}

Grouping and Differentiating Error Types

Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy.

An example of a group of related exception classes in the Java platform are those defined in java.io IOException and its descendants:

IOException is the most general and represents any type of error that can occur when performing I/O.

Its descendants represent more specific errors. For example, FileNotFoundException means that a file could not be located on disk.

A method can write specific handlers that can handle a very specific exception. The FileNotFoundException class has no descendants, so the following handler can

handle only one type of exception.

catch (FileNotFoundException e) {

...

}

A method can catch an exception based on its group or general type by specifying any of the super classes of the exception in the catch statement.

For example, to catch all I/O exceptions, regardless of their specific type, an exception handler specifies an IOException argument.

// Catch all I/O exceptions, including

// FileNotFoundException, EOFException, and so on.

catch (IOException e) {

...

}

Page 216 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 217: Core Java Handout v1.0

Handout - Core Java

Try It Out

Problem Statement: Write a program that looks for code that invokes a method declaring an exception, where the calling method does not handle or declare the checked exception. Code: import java.io.IOException;

public class ExceptionThrowApp {

void doStuff() {

doMore();

}

void doMore() {

throw new IOException();

}

}

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

First, the doMore() method throws a checked exception, but does not declare it. But suppose you fix the doMore() method like the following: void doMore() throws IOException { … } The doStuff() method is still in trouble, because it, too, must declare the IOException,

unless it handles it by providing a try or catch, with a catch clause that can take an IOException.

Tips and Tricks:

When should you use the keyword throws related to exception handling? Solution:

If you throw an exception in your code, then you must declare it using the throws keyword in your method declaration.

If you call a method that throws an exception (in other words, a method that declares it throws an exception), then you must acknowledge that you are aware of the exception possibility. One way to satisfy the compiler is to wrap the call in a try or catch.

Page 217 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 218: Core Java Handout v1.0

Handout - Core Java

Summary

Uncaught exceptions propagate back through the call stack, starting from the method where the exception is thrown and ending with either the first method that has a corresponding catch for that exception type or a JVM shutdown.

Subtypes of Error or RuntimeException are unchecked, so the compiler does not enforce the handle or declare rule. You are free to handle them, or to declare them, but the compiler does not care one way or the other.

Test Your Understanding

Differentiate between ‘throws’ and ‘throw’ keywords.

Page 218 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 219: Core Java Handout v1.0

Handout - Core Java

Session 58: Exception Handling

Learning Objectives

After completing this session, you will be able to: Identify Checked and Unchecked exception Create your own exception Describe Run time exception

Checked and Unchecked Exceptions

Checked exception: Java compiler checks if the program either catches or lists the occurring checked

exception If not, then compiler error will occur

Unchecked exceptions: Not subjected to checking at the time of compilation for exception handling Built-in unchecked exception classes: o Error o RuntimeException o Their subclasses

Handling all these exceptions may make the program cluttered and may become a nuisance

Creating Your Own Exception Class

Steps to follow for creating your own exception class are: 1. Create a class that extends the RuntimeException or the Exception class 2. Customize the class: Members and constructors may be added to the class

Example: 1 class HateStringExp extends RuntimeException {

2 /* some code */

3 }

How to use Your own Exceptions

1 class TestHateString {

2 public static void main(String args[]) {

3 String input = "invalid input";

4 try {

5 if (input.equals("invalid input")) {

6 throw new HateStringExp();

7 }

Page 219 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 220: Core Java Handout v1.0

Handout - Core Java

8 System.out.println("Accept string.");

9 } catch (HateStringExp e) {

10 System.out.println("Hate string!”);

11 }

12 }

13 }

Try It Out

Problem Statement: Write a program that illustrates the creation and usage of your own exceptions. Code: import java.io.*;

public class ExceptionTest {

public static void main(String args[]) {

boolean finished = false;

do {

try {

processUserInput();

} catch (VowelException x) {

System.out.println("A vowel exception occurred.");

} catch (BlankException x) {

System.out.println("A blank exception occurred.");

} catch (ExitException x) {

System.out.println("An exit exception occurred.");

finished = true;

} finally {

System.out.println("This is the finally clause.\n");

}

} while (!finished);

}

}

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

The ExceptionTest program reads a character entered by the user. It then throws and catches a VowelException, BlankException, or ExitException based

on the input of the user.

Page 220 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 221: Core Java Handout v1.0

Handout - Core Java

ExceptionTest provides two static methods, main() and processUserInput() . The main() method consists of a simple do statement that repeatedly tries to invoke

processUserInput() . The try statement has three catch clauses and a finally clause. The three catch clauses notify the user of the type of exception they catch. The catch clause with an ExitException parameter causes the do statement and the

program to terminate by setting finished to true. The finally clause just displays the fact that it has been executed. The processUserInput() method prompts the user to enter a character. The actual reading of the character occurs within a try statement. IOException is

caught by the try statement, eliminating the need to declare the exception in the processUserInput() throws clause.

The IOException is handled by notifying the user that the exception occurred and continuing with program execution.

The processUserInput() method throws one of the three exceptions based upon the character entered by the user.

If the user enters a vowel, then VowelException is thrown. If the user enters a line beginning with a character that cannot be printed, then

BlankException is thrown. If the user enters x or X, then ExitException is thrown. When you run ExceptionTest, it produces the following prompt: o Enter a character: o Enter a blank line, and the following output is displayed: o A blank exception occurred. o This is the finally clause. o Enter a character:

The program notifies you that a blank exception has occurred and displays the fact that the finally clause of the main() try statement was executed.

The processUserInput() method, upon encountering a space character returned by getChar() , throws the BlankException, which is caught by the main() method.

The finally clause always executes no matter whether processUserInput() throws an exception or not.

Enter a at the program prompt, and the following output appears: o Enter a character: a o A vowel exception occurred. o This is the finally clause. o Enter a character:

Here the program notifies you that a VowelException has occurred. The processing of the VowelException is similar to the blank exception. o Enter j, and the following is displayed: o Enter a character: j o This is the finally clause. o Enter a character:

No exceptions are thrown for the j character, but the finally clause is executed.

Page 221 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 222: Core Java Handout v1.0

Handout - Core Java

The finally clause is always executed, no matter what happens during the execution of a try statement.

Go ahead and type x to exit the ExceptionTest program. The program displays the output as shown below: o Enter a character: x o An exit exception occurred. o This is the finally clause.

The program then returns you to the command prompt. The output acknowledges the fact that the Exit Exception was thrown by

processUserInput() and caught by main().

Tips and Tricks:

Why does not the compiler care about those run time exceptions? Are not they just as likely to bring the whole show to a stop? Solution:

Most run time exceptions come from a problem in your code logic, rather than conditions that fails at run time in ways that you cannot predict or prevent. You cannot guarantee that the file is there. You cannot guarantee the server is up. But you can make sure your code does not index off the end of an array (that is what the .length attribute is for).

You want run time exceptions to happen at development and testing time. You do not want to code in a try or catch.

A try or catch is for handling exceptional situations and not flaws in your code. Use your catch blocks to try to recover from situations that you cannot guarantee will succeed. Or at the very least, print out a message to the use and a stack trace, so that somebody can figure out what had happened.

Summary

You can create your own exceptions, normally by extending Exception or one of its subtypes. Your exception will then be considered a checked exception, and the compiler will enforce the handle or declare rule for that exception.

All catch blocks must be ordered from most specific to most general. If you have a catch clause for both IOException and Exception, you must put the catch for IOException and Exception, you must put the catch for IOException first in your code. The compiler will stop you from defining catch clauses that can never be reached.

Some exceptions are created by programmers, some by the JVM.

Test Your Understanding

1. State true or false for the following: a) In Java, exceptions are divided into two categories, namely checked and

unchecked exceptions. b) All subclasses of the RuntimeException and Error classes are unchecked

exceptions.

Page 222 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 223: Core Java Handout v1.0

Handout - Core Java

Session 61: Strings, String Buffer, and its Functions

Learning Objectives

After completing this session, you will be able to: Identify the String class and its methods

The String Class

Definition: Represents combinations of character literals Using Java, strings can be represented using: o Array of characters o The String class

Note: A String object is different from an array of characters There are totally 12 constructors available in the String class in Java 2, v5.0.

The String Class: Constructors

1 class StringConstructorsDemo {

2 public static void main(String args[]) {

3 String s1 = new String(); //empty string

4 char chars[] = { 'h', 'e', 'l', 'l', 'o'};

5 String s2 = new String(chars); //s2="hello";

6 byte bytes[] = { 'w', 'o', 'r', 'l', 'd' };

7 String s3 = new String(bytes); //s3="world"

8 String s4 = new String(chars, 1, 3);

9 String s5 = new String(s2);

10 String s6 = s2;

11 System.out.println(s1);

12 System.out.println(s2);

13 System.out.println(s3);

14 System.out.println(s4);

15 System.out.println(s5);

16 System.out.println(s6);

17 }

18 }

Page 223 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 224: Core Java Handout v1.0

Handout - Core Java

The String Class: Methods

The methods of String class are: public char charAt (int index): Returns the character located in the

specified index. public int compareTo (String anotherString): Compares this string with

the specified parameter. Returns a negative value if this string comes lexicographically before the outer string, zero if both of the strings have the same value and a positive value if this string comes after the other string lexicographically.

public int compareToIgnoreCase (String str): Like compareTo but ignores the case used in this string and the specified string.

public boolean equals (Object anObject): Returns true if this string has the same sequence of characters as that of the Object specified, which should be a String object. Otherwise if the specified parameter is not a String object or it does not match the sequence of symbols in this string, then the method will return false.

public boolean equalsIgnoreCase (String anotherString): Like equals but ignores the case used in this string and the specified string.

public void getChars (int srcBegin, int srcEnd, char[] dst, int dstBegin): Gets the characters from this string starting at the srcBegin index up to the srcEnd index and copies these charcters to the dst array starting at the dstBegin index.

public int length() :Returns a length of this string. public String replace (char oldChar, char newChar): Returns the

string wherein all occurences of the oldChar in this string is replaced with newChar. public String substring (int beginIndex, int endIndex): Returns the

substring of this string starting at the specified beginIndex up to the endIndex index. public char[] toCharArray() :Returns the character array equivalent of this

string. public String trim(): Returns a modified copy of the string wherein the leading

and trailing white space are removed. public static String valueOf(-): Takes in a simple data type such as

boolean, integer, or character, or it takes in an object as a parameter and returns the String equivalent of the specified parameter.

Try It Out

Problem Statement: Write a program that illustrates the usage of String constructors. Code: class StringConstructors {

public static void main(String args[]) {

String s1 = new String(); // empty string

char chars[] = { 'h', 'e', 'l', 'l', 'o' };

String s2 = new String(chars); // s2="hello";

byte bytes[] = { 'w', 'o', 'r', 'l', 'd' };

Page 224 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 225: Core Java Handout v1.0

Handout - Core Java

String s3 = new String(bytes); // s3="world"

String s4 = new String(chars, 1, 3);

String s5 = new String(s2);

String s6 = s2;

System.out.println(s1);

System.out.println(s2);

System.out.println(s3);

System.out.println(s4);

System.out.println(s5);

System.out.println(s6);

}

}

Refer File Name: StringConstructors.java to obtain soft copy of the program code How It Works: When you run the program, it produces the following results: hello

world

ell

hello

hello

Tips and Tricks:

List out key points on Strings. Solution:

Strings are immutable. They can be created from a literal, a byte array, a char array, or a string buffer. A String created by a new operator is always a different new object, even if it is

created from a literal. All string operations (concat, trim, replace, substring, and so on) construct and return

new strings. toUpperCase and toLowerCase will return the same string if no case conversion was

needed. Passing null to indexOf or lastIndexOf will throw NullPointerrException, passing empty

string returns zero, and passing a string that is not in the target string returns -1. trim method removes all leading and trailing white-space from a String and returns a

new String. White spaces means, all characters with values less than or equal to the space character – ‘\u0020’.

String class is final. = and += operators are overloaded for Strings. reverse, append, and insert are not String methods.

Page 225 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 226: Core Java Handout v1.0

Handout - Core Java

Summary

String objects are immutable, and String reference variables are not. If you create a new String without assigning it, it will be lost to your program. If you redirect a String reference to a new String, the old String can be lost. String methods use zero-based indexes, except for the second argument of

substring(). The String class is final – its methods can’t be overridden.

Test Your Understanding

1. Differentiate between indexOf() and lastIndexOf() methods. 2. Differentiate between substring(m,n) and substring(m) formats.

Page 226 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 227: Core Java Handout v1.0

Handout - Core Java

Session 62: Strings, String Buffer, and its Functions

Learning Objectives

After completing this session, you will be able to: Write Java programs using String class

The String Class: Example

1 class StringDemo {

2 public static void main(String args[]) {

3 String name = "Jonathan";

4 System.out.println("name: " + name);

5 System.out.println("3rd character of name: " +

6 name.charAt(2));

7 /* character that first appears alphabetically

8 has lower unicode value */

9 System.out.println("Jonathan compared to Solomon: "

10 + name.compareTo("Solomon"));

11 System.out.println("Solomon compared to Jonathan: "

12 + "Solomon".compareTo("Jonathan"));

13 /* 'J' has lower unicode value compared to 'j' */

14 System.out.println("Jonathan compared to jonathan: " +

15 name.compareTo("jonathan"));

16 System.out.println("Jonathan compared to jonathan

17 (ignore case): " + name.compareToIgnoreCase("jonathan"));

18 System.out.println("Is Jonathan equal to Jonathan? " +

name.equals("Jonathan"));

20 //continued...

21 System.out.println("Is Jonathan equal to jonathan? " +

22 name.equals("jonathan"));

23 System.out.println("Is Jonathan equal to jonathan

(ignore case)? " + name.equalsIgnoreCase("jonathan"));

25 char charArr[] = "Hi XX".toCharArray();

26 /* Need to add 1 to the endSrc index of getChars */

27 "Jonathan".getChars(0, 2, charArr, 3);

28 System.out.print("getChars method: ");

29 System.out.println(charArr);

30 System.out.println("Length of name: " +

31 name.length());

32 System.out.println("Replace a's with e's in name: " +

33 name.replace('a', 'e'));

34 /* Need to add 1 to the endIndex parameter of

Page 227 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 228: Core Java Handout v1.0

Handout - Core Java

35 substring*/

36 System.out.println("A substring of name: " +

37 name.substring(0, 2));

38 //continued...

39 System.out.println("Trim \" a b c d e f \": \"" +

40 " a b c d e f ".trim() + "\"");

41 System.out.println("String representation of boolean

42 expression 10>10: " + String.valueOf(10>10));

43 /* toString method is implicitly called in the println

44 method*/

45 System.out.println("String representation of boolean

46 expression 10<10: " + (10<10));

47 /* Note there's no change in the String object name

48 even after applying all these methods. */

49 System.out.println("name: " + name);

50 }

51 }

Try It Out

Problem Statement: Write a program that illustrates the usage of various methods available in the String class. Code: public class StringApp {

public static void main(String args[]) {

String s = " Java 2 Certification ";

System.out.println(s);

System.out.println(s.toUpperCase());

System.out.println(s.toLowerCase());

System.out.println("[" + s + "]");

s = s.trim();

System.out.println("[" + s + "]");

s = s.replace('J', 'X');

s = s.replace('C', 'Y');

s = s.replace('2', 'Z');

System.out.println(s);

// continued …

Refer File Name: StringApp.java to obtain soft copy of the program code

Page 228 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 229: Core Java Handout v1.0

Handout - Core Java

How It Works: This program performs several manipulations of a string s, which is initially set to "

Java 2 Certification ". It prints the original string and then prints uppercase and lowercase versions of it,

illustrating the use of the toUpperCase() and toLowerCase() methods. It prints the string enclosed between two braces to show that it contains leading and

trailing spaces. It then trims away these spaces using the trim() method and reprints the string to show

that these spaces were removed. The program uses the replace() method to replace 'J‘ , 'C‘ , and '2' with 'X', 'Y', and 'Z',

and prints out the string to show the changes. The replace() method is case sensitive. It uses the indexOf() method to get the indices of 'X', 'Y', and 'Z' within s. It uses the toCharArray() to convert the string to a char array. It then uses the indices to put 'J', 'C', and '2' back in their proper locations within the

character array. The String() constructor is used to construct a new string from the character array. The new string is assigned to s and is printed. The output of the program is as follows:

Java 2 Certification

JAVA 2 CERTIFICATION

java 2 certification

[ Java 2 Certification ]

[Java 2 Certification]

Xava Z Yertification

Java 2 Certification

Tips and Tricks:

What will happen if you concatenate null with a string? Solution:

String concatenation process will add a string with the value of “null”, if an object reference is null and that object is appearing in a concatenation expression by itself. But if you try to access its members or methods, then a NullPointerException is thrown.

The same is true for arrays. Array name is replaced with null, but trying to index it when the null of it throws a NullPointerException.

Summary

String methods to remember are charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toString(), toUpperCase(), and trim().

Strings have a method: length(); arrays have an attribute named length. When the JVM finds a String literal, it is added to the String literal pool. Remember that chained methods are evaluated from left to right.

Page 229 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 230: Core Java Handout v1.0

Handout - Core Java

Test Your Understanding

Differentiate the methods compareTo(), equals(), and equalsIgnoreCase().

Page 230 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 231: Core Java Handout v1.0

Handout - Core Java

Session 65: Strings, String Buffer, and its Functions

Learning Objectives

After completing this session, you will be able to: Identify equals() method and hashCode() method

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

The Java API docs for the class Object state the following rules that a Java programmer must adhere:

If two objects are equal, then they must have matching hashcodes. If two objects are equal, then calling equals() on the other object must return true. In

other words, if (a.equals(b)), then (b.equals(a)) . Java Object Law for equals() and hashCode() Methods (Contd.) If two objects have the same hashcode value, then they are not required to be equal.

But if they are equal, they must have the same hashcode value. So, if you override equals() , you must override hashCode() .

The default behavior of hashCode() is to generate a unique integer for each object on the heap. So if you do not override hashCode() in a class, then no two objects of that type can ever be considered equal.

The default behavior of equals() is to do a == comparison. In other words, the default behavior of equals() is to test whether the two references refer to a single object on the heap. So if you do not override equals() in a class, then no two objects can ever be considered equal because references to two different objects will always contain a different bit pattern.

a.equals(b) must also mean that a.hashCode() == b.hashCode(). But, a.hashCode() == b.hashCode() does not have to mean a.equals(b).

Try It Out

Problem Statement: Write a program that illustrates the usage of equals() and hashCode() methods. Code: class HashHash {

public int x;

public HashHash(int xVal) {

x = xVal;

}

public boolean equals(Object obj) {

HashHash h = (HashHash) obj;

Page 231 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 232: Core Java Handout v1.0

Handout - Core Java

if (h.x == this.x) {

return true;

} else {

return false;

}

}

public int hashCode() {

return (x * 17);

}

// continued …

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

This program has overridden both the equals() and hashCode() methods. Notice that in order for an object to be located, the search object and the object in the

collection must have both identical hashcode values and return true for the equals() method.

So there is just no way out of overriding both methods to be absolutely certain that your objects can be applied in Collections that implement hashing.

Tips and Tricks:

How come hashcodes can be the same even if objects are not equal? Solution:

HashSets use hashcodes to store the elements in a way that makes it much faster to access. If you try to find an object in an ArrayList by giving the ArrayList a copy of the object (as opposed to an index value), then the ArrayList has to start searching from the beginning, looking at each element in the list to see if it matches. But a HashSet can find an object more quickly, because it uses the hashcode as a kind of label on the “bucket” where it stored the element.

Hashcodes can be the same without necessarily guaranteeing that the objects are equal, because the “hashing algorithm” applied in the hashCode() method might happen to return the same value for multiple Objects. This means that multiple objects would all land in the same bucket in the HashSet.

Hashcode values are sometimes used to narrow down the search, but to find the one exact match, the HashSet still has to take all the objects in that one bucket (the bucket for all objects with the same hashcode) and then call equals() on them to see if the object it is looking for is in that bucket.

Page 232 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 233: Core Java Handout v1.0

Handout - Core Java

Summary

equals(), hashCode(), and toString() are public. When overridding equals(), use the instanceof operator to be sure you are evaluating

an appropriate class. Highlights of the equals() contract: o Reflexive: x.equals(x) is true. o Symmetric: if x.equals(y) is true, then y.equals(x) must be true. o Transitive: if x.equals(y) is true, and y.equals(z) is true, then z.equals(x) is true. o Consistent: Multiple calls to x.equals(y) will return the same result. o Null: If x.equals(y) is true, then x.hashCode() == y.hashCode() is true. o If you override equals(), override hashCode().

Highlights of the hashCode() contract: o Consistent: multiple calls to x.hashCode() return the same integer. o If x.equals(y) is true, x.hashCode() == y.hashCode() is true. o If x.equals(y) is false, then x.hashcode() == y.hashCode() can be either true or

false, but false will tend to create better efficiency. o transient variables are not appropriate for equals() and hashCode().

Test Your Understanding

1. State true or false for the following: a) If two objects are equal, then they must have matching hashcodes. b) a.equals(b) must also mean that a.hashCode() == b.hashCode() c) a.hashCode() == b.hashCode() must also mean that a.equals(b)

Page 233 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 234: Core Java Handout v1.0

Handout - Core Java

Session 66: Strings, String Buffer, and its Functions

Learning Objectives

After completing this session, you will be able to: Define StringBuffer and StringBuilder

The StringBuffer Class

Problem with String objects: Once created, can no longer be modified (It is a final class) A StringBuffer object:

Similar to a String object But, mutable or can be modified: Unlike String in this aspect Length and content may get changed through some method calls

The StringBuffer Class: Methods

The StringBuffer Class: Example

1 class StringBufferDemo {

2 public static void main(String args[]) {

3 StringBuffer sb = new StringBuffer("Jonathan");

4 System.out.println("sb = " + sb);

Page 234 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 235: Core Java Handout v1.0

Handout - Core Java

5 /* initial capacity is 16 */

6 System.out.println("capacity of sb: "+sb.capacity());

7 System.out.println("append \'O\' to sb: " +

8 sb.append('O'));

9 System.out.println("sb = " + sb);

10 System.out.println("3rd character of sb: " +

11 sb.charAt(2));

12

13 char charArr[] = "Hi XX".toCharArray();

14 /* Need to add 1 to the endSrc index of getChars */

15 sb.getChars(0, 2, charArr, 3);

16 System.out.print("getChars method: ");

17 System.out.println(charArr);

18 System.out.println("Insert \'jo\' at the 3rd cell: "

19 + sb.insert(2, "jo"));

20 System.out.println("Delete \'jo\' at the 3rd cell: "

21 + sb.delete(2,4));

22 System.out.println("length of sb: " + sb.length());

23

24 System.out.println("replace: " +

25 sb.replace(3, 9, " Ong"));

26 /* Need to add 1 to the endIndex parameter of

27 substring*/

28 System.out.println("substring (1st two characters): "

29 + sb.substring(0, 3));

30 System.out.println("implicit toString(): " + sb);

31 }

32 }

The java.lang.StringBuilder Class

J2SE5.0 added the StringBuilder class, which is a drop-in replacement for StringBuffer in cases where thread safety is not an issue.

Because StringBuilder is not synchronized, it offers faster performance than StringBuffer.

In general, you should apply StringBuilder in preference over StringBuffer. In fact, the J2SE 5.0 javac compiler normally uses StringBuilder instead of StringBuffer whenever you perform string concatenation as in System.out.println("The result is " + result);

All the methods available on StringBuffer are also available on StringBuilder, so it really is a drop-in replacement.

StringBuilder is identical to the well-known StringBuffer class of Java except for one important difference it is not synchronized, which means it is not thread-safe.

The advantage of using StrignBuilder is faster performance. However, in cases in which you are applying multithreading, you must apply

StringBuffer rather than StringBuilder.

Page 235 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 236: Core Java Handout v1.0

Handout - Core Java

The String class defines a new constructor that enables you to construct a String from a StringBuilder as shown in the following code:

String(StringBuilder strBuildObj)

Try It Out

Problem Statement: Write a program that illustrates the manipulation of the StringBuffer objects using the append() , insert() , and setCharAt() methods. Code: public class StringBufferApp {

public static void main(String args[]) {

StringBuffer sb = new StringBuffer(" is ");

sb.append("Hot");

sb.append('!');

sb.insert(0, "Java");

sb.append('\n');

sb.append("This is ");

sb.append(true);

sb.setCharAt(21, 'T');

sb.append('\n');

sb.append("Java is #");

sb.append(1);

String s = sb.toString();

System.out.println(s);

}

}

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

The program creates a StringBuffer object using the string " is ". It appends the string "Hot" using the append() method and the character '!' using an overloaded version of the same method.

The insert() method is used to insert the string "Java" at the beginning of the string buffer.

Three append methods are used respectively to tack on the following: o A new line character (\n), the string "This is ", and the boolean value true.

The append() method is overloaded to support the appending of the primitive data types as well as arbitrary Java objects.

The setCharAt() method is used to replace the letter 't' at index 21 with the letter 'T‘ . The charAt() and setCharAt() methods allow StringBuffer objects to be treated as arrays of characters.

Finally, another newline character is appended to sb, followed by the string "Java is #" and the int value 1.

Page 236 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 237: Core Java Handout v1.0

Handout - Core Java

The StringBuffer object is then converted to a string and displayed to the console window.

The output of the program is as follows:

Java is Hot!

This is True

Java is #1

Tips and Tricks:

List out key points on String Buffers. Solution:

String Buffers are mutable strings. StringBuffer is a final class. They can be created empty, from a string or with a capacity. An empty StringBuffer is

created with 16-character capacity. A StringBuffer created from a String has the capacity of the length of String + 16. StringBuffer created with the specified capacity has the exact capacity specified. As they can grow dynamically in size without bounds, capacity does not have much effect.

append, insert, setCharAt, and reverse are used to manipulate the string buffer. setLength changes the length. If the current content is larger than specified length,

then it is truncated. If it is smaller than the specified length, then nulls are padded. This method does not affect the capacity.

equals on StringBuffer does a shallow comparison (same like ==) and will return true only if the objects are same. Do not use it to test content equality.

trim is not a StringBuffer method. There is no relationship between String and StringBuffer. Both extend Object class. String context means, ‘+’ operator appearing with one String operand. String

concatenation cannot be applied to StringBuffer. A new StringBuffer is created. All operands are appended by calling toString method, if needed. Finally a string is returned by calling toString on the StringBuffer.

Summary

The StringBuffer’s API is the same as the new StringBuilder’s API, except that StringBuilder’s methods are not synchronized for thread safety.

StringBuilder methods should run faster than StringBuffer methods. All of the following apply to both StringBuffer and StringBuilder: They are mutable – they can change without creating a new object. StringBuffer methods act on the invoking object, and objects can change without an

explicit assignment in the statement. StringBuffer equals() is not overridden; it doesn’t compare values. StringBuffer methods to remember: append(), delete(), insert(), reverse(), and

toString().

Page 237 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 238: Core Java Handout v1.0

Handout - Core Java

Test Your Understanding

Differentiate between length() and capacity() methods of the StringBuffer class.

Page 238 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 239: Core Java Handout v1.0

Handout - Core Java

Session 69: Collections and Util package

Learning Objectives

After completing this session, you will be able to describe the following: Define collections Describe the importance of collections Identify Core Collection Interfaces List the implementations

Collection

A “collection” object sometimes called a container is simply an object that groups multiple elements into a single unit.

Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers).

Collection Framework

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:

Interfaces Implementations Algorithms

Benefits of Collection Framework

The benefits of collection framework are: Reduces programming effort Increases program speed and quality Allows interoperability among unrelated APIs: The collection interfaces are the

vernacular by which APIs pass collections back and forth Reduce effort to learn and use new APIs Reduces effort to design new APIs Fosters software reuse: New data structures that conform to the standard collection

interfaces are by nature reusable

Page 239 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 240: Core Java Handout v1.0

Handout - Core Java

Page 240 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Collection Interfaces

Collection interfaces are abstract data types that represent collections. Collection interfaces are in the form of Java interfaces.

Interfaces allow collections to be manipulated independently of the implementation details of their representation, which is called the polymorphic behavior.

In Java programming language (and other object-oriented languages), interfaces generally form a hierarchy. You choose one that meets your need as a type.

Implementations

Implementations are the data objects used to store collections, which implement the interfaces.

Each of the implementations for general purpose (you will see in the following slide) provide all optional operations contained in its interface.

Java Collections Framework also provides several implementations for special purpose situations that require nonstandard performance, usage restrictions, or other unusual behavior.

Types of Implementations

The types of implementations are: General-purpose implementations Special-purpose implementations Concurrent implementations Wrapper implementations Convenience implementations Abstract implementations

General Purpose Implementations

Algorithms

These are the methods that perform useful computations, such as searching and sorting, on objects, which implement collection interfaces.

Page 241: Core Java Handout v1.0

Handout - Core Java

Page 241 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

The algorithms are said to be polymorphic that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.

Core Collection Interfaces Hierarchy

The hierarchy of Core Collection Interfaces are shown in the following figure:

Core Collection Interfaces

Core Collection Interfaces are the foundation of the Java Collections Framework. Core Collection Interfaces form an inheritance hierarchy among themselves. You can create a new collection interface from them (highly likely you do not have to).

“Collection” Interface

Collection interface is the root of the collection hierarchy. Collection interface is the least common denominator that all collections implement.

Every collection object is a type of Collection interface. Collection interface is used to pass collection objects around and to manipulate them

when maximum generality is desired. Apply Collection interface as a type. JDK (Java Development Kit) does not provide any direct implementations of this

interface but provides implementations of more specific sub interfaces, such as Set and List.

“Collection” Interface (Java SE 5)

public interface Collection<E> extends Iterable<E> {

// Basic operations

int size();

boolean isEmpty();

boolean contains(Object element);

boolean add(E element); //optional

boolean remove(Object element); //optional

Iterator<E> iterator();

// Bulk operations

boolean containsAll(Collection<?> c);

Page 242: Core Java Handout v1.0

Handout - Core Java

boolean addAll(Collection<? extends E> c); //optional

boolean removeAll(Collection<?> c); //optional

boolean retainAll(Collection<?> c); //optional

void clear(); //optional

// Array operations

Object[] toArray();

<T> T[] toArray(T[] a);

}

Example: Usage “Collection” Interface as a Type

// Create a ArrayList collection object instance and assign it

// to Collection type.

Collection c1 = new ArrayList();

// Use methods of Collection interface.

//

// Polymorphic behavior is expected. For example,

// the add() implementation of ArrayList class will be

// invoked. For example, depending on the implementation,

// duplication is allowed or not allowed.

boolean b1 = c1.isEmpty();

boolean b2 = c1.add(new Integer(1))

add() and remove() Methods of Collection Interface

The add() method is defined generally enough so that it makes sense for collections, which allow duplicates as well as those that do not.

It guarantees that the Collection will contain the specified element after the call completes, and returns true if the Collection changes as a result of the call. add() method of Set interface follows “no duplicate” rule.

Bulk Operations

The various bulk operations are: containsAll() returns true if the target Collection contains all of the elements in the

specified Collection. addAll() adds all of the elements in the specified Collection to the target Collection. removeAll() removes from the target Collection all of its elements that are also

contained in the specified Collection. retainAll() removes from the target Collection all its elements that are not also

contained in the specified Collection. It retains only those elements in the target Collection that are also contained in the specified Collection.

clear() removes all elements from the Collection.

Page 242 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 243: Core Java Handout v1.0

Handout - Core Java

Example: removeAll()

removeAll() removes all instances of a specified element, e, from a Collection, c:

c.removeAll(Collections.singleton(e));

removeAll() removes all of the null elements from a Collection:

c.removeAll(Collections.singleton(null));

Collections.singleton() , which is a static factory method returns an immutable Set containing only the specified element.

Array Operations

The toArray() method is provided as a bridge between collections and older APIs that expect arrays on input.

The array operations allow the contents of a Collection to be translated into an array.

Example: Array Operations

The simple form with no arguments creates a new array of Object. Object[] a = c.toArray();

Suppose c is known to contain only strings. The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in c. String[] a = c.toArray();

Try It Out

Problem Statement: Write a program that illustrates the usage of ArrayList class, which is implemented from the List interface. Code: import java.util.*;

public class TestArrayList {

public static void main(String[] args) {

List<String> test = new ArrayList<String>();

String str = "hi";

test.add("string");

test.add(str);

test.add(str + str);

System.out.println(test.size());

System.out.println(test.contains(42));

System.out.println(test.contains("hihi"));

test.remove("hi");

System.out.println(test.size());

}

}

Page 243 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 244: Core Java Handout v1.0

Handout - Core Java

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

When you run TestArrayList, it produces the following prompt:

3

false

true

2

The java.util.ArrayList class is one of the most commonly used of all the classes in the Collections framework.

As of Java 5, you can declare an ArrayList that contains Strings as List<String> myList = new ArrayList<String>();

In many ways, ArrayList<String> is similar to a String[]as in that it declares a container that can hold only String, but it is more powerful than a String[] .

In the TestArrayList program, notice that when you have declared the ArrayList, you did not give it a size.

Then you were able to ask the ArrayList for its size. You were able to ask it whether it contained specific objects. You removed an object

right out from the middle of it, and then you have its size.

Tips and Tricks:

List out key points on String Buffers. Solution:

String Buffers are mutable strings. StringBuffer is a final class. They can be created empty, from a string or with a capacity. An empty StringBuffer is

created with 16-character capacity. A StringBuffer created from a String has the capacity of the length of String + 16. StringBuffer created with the specified capacity has the exact capacity specified. As they can grow dynamically in size without bounds, capacity does not have much effect.

append, insert, setCharAt, and reverse are used to manipulate the string buffer. setLength changes the length. If the current content is larger than specified length,

then it is truncated. If it is smaller than the specified length, then nulls are padded. This method does not affect the capacity.

equals on StringBuffer does a shallow comparison (same like ==) and will return true only if the objects are same. Do not use it to test content equality.

trim is not a StringBuffer method. There is no relationship between String and StringBuffer. Both extend Object class. String context means, ‘+’ operator appearing with one String operand. String

concatenation cannot be applied to StringBuffer. A new StringBuffer is created. All operands are appended by calling toString method, if needed. Finally a string is returned by calling toString on the StringBuffer.

Page 244 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 245: Core Java Handout v1.0

Handout - Core Java

Summary

Common collection activities include adding objects, removing objects, verifying object inclusion, retrieving objects, and iterating.

Three meanings for “collection”: o Collection: Represents the data structure in which objects are stored o Collection: java.util interface from which Set and List extend o Collections: A class that holds static collection utility methods

Four basic sub-flavors of collections: Sorted, Unsorted, Ordered, Unordered o Ordered: Iterating through a collection in a specific, non-random order. o Sorted: Iterating through a collection in a sorted order.

Sorting can be alphabetic, numeric, or programmer-defined.

Test Your Understanding

1. State true or false for the following: a) The Collection interface helps you to work with collection of objects. This interface

is at the top of the collections hierarchy. The collections framework is built on this interface.

b) Certain static methods, which operate on collections, are defined in the Collections class. Such methods are known as algorithms.

Page 245 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 246: Core Java Handout v1.0

Handout - Core Java

Session 70: Collections and Util package

Learning Objectives

After completing this session, you will be able to: Set Interface and Implementations List Interface and Implementations Map Interface and Implementations Queue Interface and Implementations Define Abstract Classes Explain Routine Data Manipulation Describe Searching Define Composition

“Set” Interface

The Set interface is a collection that cannot contain duplicate elements. The Set interface models the mathematical set abstraction and is used to represent sets:

Cards comprising a poker hand Courses making up the schedule of a student The processes running on a machine

The Set interface contains only methods inherited from Collection and adds the restriction to prohibit the duplicate elements.

“Set” Interface (Java SE 5)

public interface Set<E> extends Collection<E> {

// Basic operations

int size();

boolean isEmpty();

boolean contains(Object element);

boolean add(E element); //optional

boolean remove(Object element); //optional

Iterator<E> iterator();

// Bulk operations

boolean containsAll(Collection<?> c);

boolean addAll(Collection<? extends E> c); //optional

boolean removeAll(Collection<?> c); //optional

boolean retainAll(Collection<?> c); //optional

void clear(); //optional

Page 246 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 247: Core Java Handout v1.0

Handout - Core Java

// Array Operations

Object[] toArray();

<T> T[] toArray(T[] a);

}

“equals” Operation of Set Interface

Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.

“SortedSet” Interface

Sorted Set interface is a set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership roll.

Implementations of “Set” Interface

The implementations of Set interface are: HashSet TreeSet LinkedHashSet

HashSet

HashSet is much faster than TreeSet (constant-time versus log-time for most operations) but offers no ordering guarantees.

HashSet is the mostly commonly used implementation.

Caveats of Using HashSet

Iteration is linear in the sum of the number of entries and the number of buckets (the capacity): Choosing an initial capacity that is too high, can waste both space and time Choosing an initial capacity that is too low, wastes time by copying the data structure

each time it is forced to increase its capacity

Example: Set Interface and HashSet

public class MyOwnUtilityClass {

// Note that the first parameter type is set to

// Set interface not a particular implementation

// class such as HashSet. This makes the caller of

// this method to pass instances of different

// implementations of Set interface while

// this function picks up polymorphic behavior

// depending on the actual implementation type

Page 247 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 248: Core Java Handout v1.0

Handout - Core Java

// of the object instance passed.

public static void checkDuplicate(Set s, String[] args){

for (int i=0; i<args.length; i++)

if (!s.add(args[i])) {

System.out.println("Duplicate detected: "+args[i]);

}

System.out.println(s.size()+" distinct words detected: "+s);

}

}

public class SetExample {

public static void main(String[] args) {

Set s = new HashSet(); // Order is not guaranteed

MyOwnUtilityClass.checkDuplicate(s, args);

s = new TreeSet(); // Order according to values

MyOwnUtilityClass.checkDuplicate(s, args);

s = new LinkedHashSet(); // Order according to insertion

MyOwnUtilityClass.checkDuplicate(s, args);

}

}

For example, the numbers 1, 2, 3, and 4 can be added in the following ways:

Set type = java.util.HashSet [3, 2, 4, 1]

Set type = java.util.TreeSet [1, 2, 3, 4]

Set type = java.util.LinkedHashSet [2, 3, 4, 1]

TreeSet

The TreeSet is one of two sorted collections (the other being TreeMap). No duplicates, iterates in sorted order. It generally guarantees that the elements will be in ascending order, according to

natural order.

Example: Set Interface and TreeSet

public static void main(String[] args) {

Set ts = new TreeSet();

ts.add("one");

ts.add("two");

Page 248 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 249: Core Java Handout v1.0

Handout - Core Java

ts.add("three");

ts.add("four");

ts.add("three");

System.out.println("Members from TreeSet = " + ts);

}

Result: Members from TreeSet = [four, one, three, two]

LinkedHashSet

LinkedHashSet is implemented as a hash table with a linked list running through it. It provides insertion-ordered iteration (least recently inserted to most recently) and

runs nearly as fast as HashSet. It spares its clients from the unspecified, generally chaotic ordering provided by

HashSet without incurring the increased cost associated with TreeSet.

Example: Set Interface and LinkedHashSet

public static void main(String[] args) {

Set ts2 = new LinkedHashSet();

ts2.add(2);

ts2.add(1);

ts2.add(3);

ts2.add(3);

System.out.println("Members from LinkedHashSet = " + ts2);

}

Result: Members from LinkedHashSet = [2, 1, 3]

“List” Interface

List interface is an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List interface generally has precise control over where in the each list

element is inserted and can access elements by their integer index (position).

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

The additional operations supported by List interface over Collection interface are: Positional access manipulates elements based on their numerical position in the list. Search searches for a specified object in the list and returns its numerical position. Iteration extends Iterator semantics to take advantage of the sequential nature of the

list. Range-view performs arbitrary range operations on the list.

Page 249 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 250: Core Java Handout v1.0

Handout - Core Java

“List” Interface

public interface List<E> extends Collection<E> {

// Positional access

E get(int index);

E set(int index, E element); //optional

boolean add(E element); //optional

void add(int index, E element); //optional

E remove(int index); //optional

boolean addAll(int index,

Collection<? extends E> c); //optional

// Search

int indexOf(Object o);

int lastIndexOf(Object o);

// Iteration

ListIterator<E> listIterator();

ListIterator<E> listIterator(int index);

// Range-view

List<E> subList(int from, int to);

}

Implementations of “List” Interface

The implementations of List interface are: ArrayList: o Offers constant-time positional access o Gives you fast iteration and fast random access o It is an ordered collection (by index), but not sorted o Most commonly used implementation

LinkedList: You use it frequently to add elements to the beginning of the List or iterate over the List to delete elements from its interior

“Map” Interface

Map interface handles key or value pairs. A Map interface cannot contain duplicate keys. Each key can map to at most one

value.

Page 250 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 251: Core Java Handout v1.0

Handout - Core Java

“Map” Interface (Java SE 5)

public interface Map<K,V> {

// Basic operations

V put(K key, V value);

V get(Object key);

V remove(Object key);

boolean containsKey(Object key);

boolean containsValue(Object value);

int size();

boolean isEmpty();

// Bulk operations

void putAll(Map<? extends K, ? extends V> m);

void clear();

// Collection Views

public Set<K> keySet();

public Collection<V> values();

public Set<Map.Entry<K,V>> entrySet();

// Interface for entrySet elements

public interface Entry {

K getKey();

V getValue();

V setValue(V value);

}

“SortedMap” Interface

A Map interface that maintains its mappings in ascending key order is called the SortedMap interface. This is the Map analog of SortedSet.

Sorted maps are used for naturally ordered collections of key or value pairs, such as dictionaries and telephone directories.

Implementations of “Map” Interface

The implementations of the Map interface are: HashMap: You use this if you want maximum speed and do not want to care about

iteration order. Most commonly used implementation. TreeMap: You use this when you need SortedMap operations or key-ordered

Collection-view iteration. LinkedHashMap: Although it will be somewhat slower than HashMap for adding and

removing elements, you can expect faster iteration with a LinkedHashMap.

Page 251 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 252: Core Java Handout v1.0

Handout - Core Java

“Queue” Interface

Queue interface is a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue interface provides additional insertion,

extraction, and inspection operations. Typically, but do not necessarily, Queue interface order elements in a FIFO (First-In,

First-Out) manner.

Implementations of Queue Interface

General purpose Queue implementations: LinkedList implements the Queue interface, providing FIFO queue operations for add,

poll, and so on. PriorityQueue class is a priority queue based on the heap data structure. This queue orders elements according to an order specified at construction time,

which can be the natural ordering of the elements or the ordering imposed by an explicit Comparator.

Implementations of Queue Interface

Concurrent Queue implementations: The java.util.concurrent package contains a set of synchronized Queue interfaces and classes. BlockingQueue extends Queue with operations that wait for the queue to become nonempty when retrieving an element and for space to become available in the queue when storing an element. This interface is implemented by the following classes:

LinkedBlockingQueue: An optionally bounded FIFO blocking queue backed by linked nodes

ArrayBlockingQueue: A bounded FIFO blocking queue backed by an array PriorityBlockingQueue: An unbounded blocking priority queue backed by a heap DelayQueue: A time-based scheduling queue backed by a heap SynchronousQueue: A simple rendezvous mechanism that uses the BlockingQueue

interface

Abstract Classes

Abstract classes include the following abstract implementations: AbstractCollection

AbstractSet

AbstractList

AbstractSequentialList

AbstractMap

Routine Data Manipulation

The Collections class provides five algorithms for doing routine data manipulation on List objects: reverse reverses the order of the elements in a List fill overwrites every element in a List with the specified value and this operation is

useful for reinitializing a List

Page 252 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 253: Core Java Handout v1.0

Handout - Core Java

copy takes two arguments, namely a destination List and a source List, and copies the elements of the source into the destination, overwriting its contents. The destination List must be at least as long as the source. If it is longer, then the remaining elements in the destination List are unaffected.

swap swaps the elements at the specified positions in a List. addAll adds all the specified elements to a Collection. The elements to be added may

be specified individually or as an array.

Searching

The Collections class has binarySearch() method for searching a specified element in a sorted List // Set up testing data

String name[] = {

new String("Sang"),

new String("Shin"),

new String("Boston"),

new String("Passion"),

new String("Shin"),

};

List l = Arrays.asList(name);

int position = Collections.binarySearch(l, "Boston");

System.out.println("Position of the searched item = " + position);

Composition

Collections.frequency(l) counts the number of times the specified element occurs in the specified collection.

Collections.disjoint(l1, l2) determines whether two Collections are disjoint that is, whether they contain no elements in common. The Collections class has binarySearch() method for searching a specified element in a sorted List.

Try It Out

Problem Statement: Write a program that illustrates the usage of Set interface and its implementation class namely HashSet. Code: import java.util.*;

public class SetApp {

public static void main(String args[]) {

HashSet set = new HashSet();

set.add("This");

set.add("is");

Page 253 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 254: Core Java Handout v1.0

Handout - Core Java

set.add("is");

set.add("a");

set.add("a");

set.add(null);

set.add("test");

displaySet(set);

}

// continued …

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

SetApp begins by creating a HashSet object and assigning it to the set variable. It then adds the same elements to the set as ListApp did to its list.

Note that because sets are not ordered, there are no addFirst() and addLast() methods.

The displaySet() method is invoked to display the set. When you run SetApp, it displays the following results:

The size of the set is: 5 This is a null test

Note that the set does not allow duplicate elements, but allows the null value as an element.

The displaySet() method uses the size() method to determine the number of elements in the set.

It uses the iterator() method to create an Iterator object. The Iterator object is used to step through and display the elements of the set.

Tips and Tricks:

Provide the implementing classes in the collection interfaces for the data structures namely HashTable, ResizableArray, BalancedTree, and LinkedList. Solution: Note: Some of the operations in the collection interfaces are optional, meaning that the implementing class may choose not to provide a proper implementation of such an operation. In such a case, an UnsupportedOperationException is thrown when that operation is invoked.

Page 254 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 255: Core Java Handout v1.0

Handout - Core Java

Data structures used to implement

Interfaces

Set SortedSet List Map SortedMap

HashTable HashSet (Nulls OK)

This field is blank.

This field is blank.

HashMap (Nulls OK) HashTable (No Nulls)

This field is blank.

Resizable Array This field is blank.

This field is blank.

ArrayList (Nulls OK) Vector (Nulls OK)

This field is blank.

This field is blank.

Balanced Tree This field is blank.

TreeSet This field is blank.

This field is blank.

TreeMap

Linked List This field is blank.

This field is blank.

LinkedList (Nulls OK)

This field is blank.

This field is blank.

Summary

The four basic flavors of collections include Lists, Sets, Maps, Queues:

Lists of things Ordered, duplicates allowed, with an index.

Sets of things May or may not be ordered and/or sorted; duplicates not allowed.

Maps of things with keys May or may not be ordered and/or sorted; Duplicate keys are not allowed.

Queues of things to process Ordered by FIFO or by priority.

Test Your Understanding

1. Which one of the following statements is wrong? a) All classes in collection framework implement the Collection interface. b) HashSet class implements the Map interface. c) Hashtable class is a concrete class. d) HashMap class implements the Map interface.

2. When will the search() method return -1?

Page 255 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 256: Core Java Handout v1.0

Handout - Core Java

Session 73: Collections and Util package

Learning Objectives

After completing this session, you will be able to: Describe the two schemes of Traversing Collections Define Iterator interface and Iterable Interface Apply Iterator

Two Schemes of Traversing Collections

The two schemes of traversing collections are: for-each: The for-each construct allows you to concisely traverse a collection or array

using a for loop

for (Object o: collection)

System.out.println(o);

Iterator: An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired.

Iterator Interface

public interface Iterator {

boolean hasNext();

Object next();

void remove(); //optional

}

hasNext() method returns true if the iteration has more elements. next() method returns the next element in the iteration. remove() is the only safe way to modify a collection during iteration. The behavior is

unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Use Iterator Over for-each

Iterator is used over for-each for removing the current element: The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.

static void filter(Collection<?> c) {

for (Iterator<?> it = c.iterator(); it.hasNext(); )

if (!cond(it.next()))

it.remove();

}

Iterating over multiple collections in parallel

Page 256 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 257: Core Java Handout v1.0

Handout - Core Java

The Iterable Interface

Iterable is a generic interface that was added by Java 2, v5.0. The Iterable interface must be implemented by any class whose objects will be applied

by the for-each version of the for loop. In other words, a class must implement Iterable whenever an object needs to be used

within a for-each style for loop in that class. Iterable has the following declaration:

interface Iterable<T>

It defines one method, iterator() , as shown here: Iterator<T> iterator()

It returns an iterator to the set of elements contained in the invoking object. Although the for-each form of the for loop was designed with arrays and collections in

mind, it can be used to cycle through the contents of any object that implements the Iterable interface.

This enables you to create classes whose objects can be applied with the for-each form of the for loop.

This is a powerful feature that substantially increases the types of programming situations to which the for can be applied.

Try It Out

Problem Statement: Write a program that illustrates the usage of List and an Iterator. Code: import java.util.*;

class Dog {

public String name;

Dog(String n) {

name = n;

}

}

class IteratorTest {

public static void main(String[] args) {

List<Dog> d = new ArrayList<Dog>();

Dog dog = new Dog("aiko");

d.add(dog);

d.add(new Dog("clover"));

d.add(new Dog("magnolia"));

Iterator<Dog> itr = d.iterator(); // make an iterator

while (itr.hasNext()) {

Dog d2 = itr.next(); // cast not required

System.out.println(d2.name);

}

Page 257 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 258: Core Java Handout v1.0

Handout - Core Java

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

When you run IteratorTest, it displays the following results: aiko clover magnolia size 3 get1 clover aiko 0 oa aiko oa clover

Firstly, you have used generics syntax to create the Iterator (an Iterator of type Dog). Because of this, when you have used the next() method, you did not have to cast the

object returned by next() to a Dog. You could have declared the Iterator like this (on using JDK1.4 or lesser version): Iterator itr = d.iterator; // make an Iterator

But then you would have had to cast the following returned value: Dog d2 = (Dog)itr.next();

The rest of the code demonstrates using the size() , get() , indexOf() , and toArray() methods.

Note: Invoking hasNext() does not move the iterator to the next element of the collection.

Tips and Tricks:

Explain briefly about the ConcurrentModificationException related to Iterators. Solution:

ConcurrentModificationException exception (extends RuntimeException) may be thrown by methods that have detected concurrent modification of a backing object when such modification is not permissible.

For example, it is not permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results are undefined under these circumstances. Some Iterator implementations (including those of all the collection implementations provided by the JDK) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary behavior that is not deterministic at an undetermined time in the future.

Page 258 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 259: Core Java Handout v1.0

Handout - Core Java

Summary

Iterable is a generic interface that was added by Java 2, v5.0. Iterable contains only one method as shown below: Iterator<T> iterator()

The earlier method returns an Iterator to the elements contained in the invoking object. Because the iterator() method of Iterable returns an Iterator, often a class that

implements Iterable will also implement Iterator. Iterator is a generic class in Java 2, v5.0, when the entire Collections Framework was

retrofitted for generics. Earlier versions of Iterator were not generic.

Test Your Understanding

1. State true or false for the following: a) An interface, which provides you a standardized way of accessing the elements

within a collection applied for general purpose, is also defined in the collections framework. This interface is known as Iterator interface.

Page 259 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 260: Core Java Handout v1.0

Handout - Core Java

Session 75: Collections and Util package

Learning Objectives

After completing this session, you will be able to: Identify java.util.Date and java.util.Properties classes

The Date Class

Date class represents a precise moment in time, down to the millisecond. Dates are represented as a long type that counts the number of milliseconds since

midnight, January 1, 1970, Greenwich Mean Time.

The Date Class: Example

// Return the number of milliseconds in the Date

// as a long, using the getTime() method

Date d1 = new Date();

// timed code goes here

for (int i=0; i<1000000; i++) { int j = i;}

Date d2 = new Date();

long elapsed_time = d2.getTime() - d1.getTime();

System.out.println("That took " + elapsed_time

+ " milliseconds");

The Properties Class

The Properties class represents a persistent set of properties. The properties can be saved to a stream or loaded from a stream: Typically a file Each key and its corresponding value in the property list is a string. A property list can contain another property list as its "defaults“. This second property

list is searched if the property key is not found in the original property list.

The Properties Class: Example

// set up new properties object

// from file "myProperties.txt"

FileInputStream propFile

= new FileInputStream("myProperties.txt");

Properties p

= new Properties(System.getProperties());

p.load(propFile);

Page 260 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 261: Core Java Handout v1.0

Handout - Core Java

// set the system properties

System.setProperties(p);

// display new properties

System.getProperties().list(System.out);

Try It Out

Problem Statement: Write a program that illustrates the usage of java.util.Date class along with java.util.GregorianCalendar and java.util.TimeZone classes in order to access date and time information. Code: import java.util.*;

public class DateApp {

public static void main(String args[]) {

Date today = new Date();

GregorianCalendar cal = new GregorianCalendar();

cal.setTime(today);

System.out.println("Today: ");

displayDateInfo(cal);

cal.clear();

cal.set(2000, 0, 1);

System.out.println("\nNew Years Day 2000: ");

displayDateInfo(cal);

}

// continued …

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

The program creates a Date object and a GregorianCalendar object using the default Date() and GregorianCalendar() constructors.

The Date object is assigned to the today variable, and the GregorianCalendar object is assigned to the cal variable.

The cal variable is updated with the current date by invoking its setTime() method with the Date object stored in today.

The displayDateInfo() method is then invoked to display date and time information about the cal variable.

The clear() method of the Calendar class is invoked to reset the date of the GregorianCalendar object stored in cal.

The set() method is used to set its date to New Year's 2000. There are several versions of the set() method, each of which takes a different set of parameters.

Page 261 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 262: Core Java Handout v1.0

Handout - Core Java

The version used in DateApp takes the year, month, and date as parameters. Note that the month value ranges from zero to 12, where the year and date values

begin at one. The displayDateInfo() method is invoked again to display information about the new

calendar date. The displayDateInfo() method creates the days, months, and am_pm arrays to define

string values corresponding to the days of the week, months of the year, and a.m./p.m. It then prints a line corresponding to date and time values. These values are retrieved using the get() method of the Calendar class and the

Calendar constants corresponding to date and time values. The getTimeZone() method of Calendar is invoked to retrieve the local TimeZone

object. The getID() method of the TimeZone class is used to retrieve the local time zone ID

string.

Tips and Tricks:

Instead of using Date class, what is the alternate way to get the current time? Solution:

To get the current time use System.currentTimeMillis(). However, the catch is that the time is provided in milliseconds. The value corresponds to the difference between the current time and midnight,

January 1, 1970 UTC. This method is useful for program timing studies.

Summary

The classes you need to understand are java.util.Date, java.util.Calendar, java.text.DateFormat, java.text.NumberFormat, and java.util.Locale.

Most of the Date class’s methods have been deprecated. A Date is stored as a long, the number of milliseconds since January 1, 1970. Date objects are go-betweens the Calendar and Locale classes. The Calendar provides a powerful set of methods to manipulate dates, performing

tasks such as getting days of the week, or adding some number of months or years to a date.

The DateFormat.format() method is used to create Strings containing properly formatted dates.

The Locale class is used in conjunction with DateFormat and NumberFormat.

Test Your Understanding

1. Properties class is a subclass of the Hashtable class. Do you agree with this statement? 2. Which methods do you use to add and retrieve data in a Properties object?

Page 262 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 263: Core Java Handout v1.0

Handout - Core Java

Page 263 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Session 81: Threads

Learning Objectives

After completing this session, you will be able to: Define a thread Identify the thread priorities

Threads

Threads are required to handle concurrent processes. Definition of threads: Single sequential flow of control within a program For simplicity, think of threads as processes executed by a program Example: o Operating System o HotJava Web browser

The following diagram shows sequential program and multi-threaded program:

Multi-Threading in Java Platform

Every application has at least one thread or several, if you count "system" threads that do things like memory management and signal handling.

But from the point of view of application programmer, you start with just one thread, called the main thread. This thread has the ability to create additional threads.

Thread Priorities

Priorities determine, which thread receives CPU control and gets to be executed first. Definition: Integer value ranging from one to 10 Higher the thread priority larger is the chance of being executed first Example:

Two threads are ready to run First thread: priority of 5, already running Second thread = priority of 10, comes in while first thread is running

Context switch: Occurs when a thread snatches the control of CPU from another

Page 264: Core Java Handout v1.0

Handout - Core Java

When does it occur? o Running thread voluntarily relinquishes CPU control o Running thread is preempted by a higher priority thread

There might occur some situations that more than one highest priority threads are ready to run.

The decision that which of the highest priority threads receives the CPU control is dependent on the operating system.

Windows 95/98/NT: Uses time-sliced round-robin Solaris: Executing thread should voluntarily relinquish CPU control

Try It Out

Problem Statement: Write a program that illustrates the construction of threads and starting the threads. Code: class ThreadPriorityApp {

public static void main(String args[]) {

MyThread t1 = new MyThread("t1");

MyThread t2 = new MyThread("t2");

t1.start();

t2.start();

}

}

class MyThread extends Thread {

public void displayOutput(String s) {

System.out.println(s);

}

// continued …

Refer File Name: ThreadPriorityApp.java to obtain soft copy of the program code

Page 264 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 265: Core Java Handout v1.0

Handout - Core Java

How It Works: When you run the program, the output sequence will vary from computer to computer. Also, the output differs between each and every run.

After first time execution After second time execution

t2 t1 t1 t1 t2 t2 t1 t2 t2 t2 t1 t1 t1 t2 t2 t2 t1 t2 t1 t1

t2 t2 t1 t2 t1 t1 t1 t2 t1 t2 t2 t1 t2 t1 t2 t2 t1 t2 t1 t1

Tips and Tricks :

What are thread priorities? Is it a way that you can control scheduling? Solution: Thread priorities might help you to influence the scheduler, but they still do not offer any guarantee. Thread priorities are numerical values that tell the scheduler (if it cares) how important a thread is to you. In general, the scheduler will kick a lower priority out of the running state if a higher priority thread suddenly becomes runnable. Still, there is no guarantee. It is recommended that you use priorities only if you want to influence performance, but never, ever rely on them for program correctness.

Summary

Once a thread is started, it will always enter the runnable state. The setPriority() method is use don Thread objects to give threads a priority of

between 1 (low) and 10 (high), although priorities are not guaranteed, and not all JVMs recognize 10 distinct priority levels.

If not explicitly set, a thread’s priority will have the same priority as the priority of the thread that created it.

Page 265 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 266: Core Java Handout v1.0

Handout - Core Java

The yield() method may cause a running thread to back out if there are runnable threads of the same priority.

The closest thing to a guarantee is that at any given time, when a thread is running it will usually not have a lower priority than any thread in the runnable state. If a low-priority thread is running when a high priority thread enters runnable, the JVM will usually preempt the running low-priority thread and put the high-priority thread in.

Test Your Understanding

1. Which of the following are correct? a) Threads are useful when mutually exclusive tasks are to be performed b) Threads consume considerable amount of OS resources c) Threads require synchronization when they access common resources d) All the above

2. Which one of the following is not correct? a) Every thread will go through the ‘waiting’ state during its lifetime b) A thread will reach ‘dead’ state when the execution of its run() method is over c) Every thread will start its life with the ‘new’ state d) When the run() method of a thread is being executed, then it is said to be in

‘running’ state. 3. Name the different states in the life cycle of a thread.

Page 266 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 267: Core Java Handout v1.0

Handout - Core Java

Page 267 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Session 82: Threads

Learning Objectives

After completing this session, you will be able to: Identify Thread class and Runnable interface Create Thread classes using the earlier concepts Define Thread Group

The Thread Class: Constructor

The Thread class has eight constructors. Some of the important constructors are as follows:

The Thread Class: Constants

The Thread class contains fields for priority values.

Page 268: Core Java Handout v1.0

Handout - Core Java

The Thread Class: Methods

Some Thread methods of Thread class are as follows:

Two Ways of Creating and Starting a Thread

The two ways of creating and starting a thread are: Extending the Thread class Implementing the Runnable interface

Extending Thread Class

The subclass extends Thread class. The subclass overrides the run() method of Thread class.

An object instance of the subclass can then be created. Calling the start() method of the object instance starts the execution of the thread.

Java runtime starts the execution of the thread by calling run() method of object instance.

Two Schemes of Starting a Thread from a Subclass

The two schemes of starting a thread from a subclass are: The start() method is not in the constructor of the subclass. The start() method needs

to be explicitly invoked after object instance of the subclass is created in order to start the thread.

The start() method is in the constructor of the subclass. Creating an object instance of the subclass will start the thread.

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

1 class PrintNameThread extends Thread {

2 PrintNameThread(String name) {

3 super(name);

4 }

Page 268 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 269: Core Java Handout v1.0

Handout - Core Java

5 public void run() {

6 String name = getName();

7 for (int i = 0; i < 100; i++) {

8 System.out.print(name);

9 }

10 }

11 }

12

13

14 class ExtendThreadClassTest1 {

15 public static void main(String args[]) {

16 PrintNameThread pnt1 =

17 new PrintNameThread("A");

18 pnt1.start(); // Start the first thread

19 PrintNameThread pnt2 =

20 new PrintNameThread("B");

21 pnt2.start(); // Start the second thread

22

23 }

24 }

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

1 class PrintNameThread extends Thread {

2 PrintNameThread(String name) {

3 super(name);

4 start(); //runs the thread once instantiated

5 }

6 public void run() {

7 String name = getName();

8 for (int i = 0; i < 100; i++) {

9 System.out.print(name);

10 }

11 }

12 }

13

14 class ExtendThreadClassTest2 {

15 public static void main(String args[]) {

16 PrintNameThread pnt1 =

17 new PrintNameThread("A");

18 PrintNameThread pnt2 =

19 new PrintNameThread("B");

20

21 }

22 }

Page 269 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 270: Core Java Handout v1.0

Handout - Core Java

You can replace the class ExtendThreadClassTest2 and its main() method given earlier with the following code: 14 class ExtendThreadClassTest3 {

15 public static void main(String args[]) {

16 new PrintNameThread("A");

17 new PrintNameThread("B");

18 }

19 }

Runnable Interface

The Runnable interface should be implemented by any class whose instances are intended to be executed as a thread.

The class must define run() method of no arguments. The run() method is like main() for the new thread.

The Runnable interface provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target.

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

The two ways of starting a thread for a class that implements Runnable are: Caller thread creates Thread object and starts it explicitly after an object instance of

the class that implements Runnable interface is created. The start() method of the Thread object needs to be explicitly invoked after object instance is created.

The Thread object is created and started within the constructor method of the class that implements Runnable interface. The caller thread just needs to create object instances of the Runnable class.

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

// PrintNameRunnable implements Runnable interface

class PrintNameRunnable implements Runnable {

String name;

PrintNameRunnable(String name) {

this.name = name;

}

// Implementation of the run() defined in the

// Runnable interface.

public void run() {

for (int i = 0; i < 10; i++) {

System.out.print(name);

}

Page 270 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 271: Core Java Handout v1.0

Handout - Core Java

}

}

public class RunnableThreadTest1 {

public static void main(String args[]) {

PrintNameRunnable pnt1 = new PrintNameRunnable("A");

Thread t1 = new Thread(pnt1);

t1.start();

}

}

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

// PrintNameRunnable implements Runnable interface

class PrintNameRunnable implements Runnable {

Thread thread;

PrintNameRunnable(String name) {

thread = new Thread(this, name);

thread.start();

}

// Implementation of the run() defined in the

// Runnable interface.

public void run() {

String name = thread.getName();

for (int i = 0; i < 10; i++) {

System.out.print(name);

}

}

}

public class RunnableThreadTest2 {

public static void main(String args[]) {

// Since the constructor of the PrintNameRunnable

// object creates a Thread object and starts it,

// there is no need to do it here.

new PrintNameRunnable("A");

new PrintNameRunnable("B");

new PrintNameRunnable("C");

}

}

Page 271 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 272: Core Java Handout v1.0

Handout - Core Java

Extending Thread versus Implementing Runnable Interface

Choosing between Thread and Runnable interface is a matter of taste. Implementing the Runnable interface:

May take more work since you still: Declare a Thread object Call the Thread methods on this object Your class can still extend other class

Extending the Thread class:

Easier to implement Your class can no longer extend any other class

ThreadGroup Class

A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups

form a tree in which every thread group except the initial thread group has a parent. A thread is allowed to access information about its own thread group, but not to

access information about the parent thread group of the thread group or any other thread groups.

Example: ThreadGroup

1 // Start three threads

2 new SimpleThread("Jamaica").start();

3 new SimpleThread("Fiji").start();

4 new SimpleThread("Bora Bora").start();

5

6 ThreadGroup group

7 = Thread.currentThread().getThreadGroup();

8

9 Thread[] tarray = new Thread[10];

10 int actualSize = group.enumerate(tarray);

11 for (int i=0; i<actualSize;i++){

12 System.out.println("Thread " +

13 tarray[i].getName() + " in thread group "

14 + group.getName());

15 }

Page 272 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 273: Core Java Handout v1.0

Handout - Core Java

Try It Out

Problem Statement: Write a program that illustrates the usage of Runnable interface in the creation of threads. Code: class ThreadUsingRunnableApp {

public static void main(String args[]) {

Thread thread1 = new Thread(new MyClass("thread1: "));

Thread thread2 = new Thread(new MyClass("thread2: "));

thread1.start();

thread2.start();

boolean thread1IsAlive = true;

boolean thread2IsAlive = true;

do {

if (thread1IsAlive && !thread1.isAlive()) {

thread1IsAlive = false;

System.out.println("Thread 1 is dead.");

}

Refer File Name: ThreadUsingRunnableApp.java to obtain soft copy of the program code Refer File Name: ThreadUsingRunnableApp_output_on_two_executions.txt for the console output on two different occasions How It Works:

The advantage of using the Runnable interface is that your class does not need to extend the Thread class. Instead, your class can extend some other required class, if desired.

This is a very helpful feature when you create multithreaded applets. The only disadvantage to this approach is that you have to do a little more work to

create and execute your threads.

Tips and Tricks:

How good is the idea of making a subclass of Thread and override the run() method of thread instead of using a separate Runnable implementation? [Thread t = new Thread(); // no Runnable] Solution:

Yes, that is another way of making your own thread. Remember that there are two things to be noticed, which are the Thread and the job of the thread. From an OO view, those two are very separate activities, and belong to separate classes.

The only time you want to subclass or extend the Thread class is if you are making a new and more specific type of Thread. In other words, if you think of the Thread as the worker, then do not extend the Thread class unless you need more specific worker behaviors.

Page 273 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 274: Core Java Handout v1.0

Handout - Core Java

But if all you need is a new job to be run by a Thread or worker, then implement Runnable in a separate class that is specific to job and not specific to worker.

This is a design issue and not a performance or language issue. It is perfectly legal to subclass Thread and override then run() method, but it is rarely a good idea.

Summary

Threads can be created by extending Thread and overriding the public void run() method.

Thread objects can also be created by calling the Thread constructor that takes a Runnable argument. The Runnable object is said to be the target of the thread.

You can call start() on a Thread object only once. If start() is called more than once on a Thread object, it will throw a RuntimeException.

It is legal to create many Thread objects using the same Runnable object as the target.

When a Thread object is created, it does not become a thread of execution until its start() method is invoked. When a Thread object exists but hasn’t been started, it is in the new state and is not considered alive.

Test Your Understanding

1. Write the different forms of constructor of the Thread class. 2. What useful purpose does the isAlive() method of the Thread class serve? 3. How can you assign priority to a thread? Does the priority value always lie between one

and 10?

Page 274 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 275: Core Java Handout v1.0

Handout - Core Java

Session 84: Threads

Learning Objectives

After completing this session, you will be able to: Describe Thread Synchronization Explain lifecycle of threads Identify wait() method and notify() method of the Object class

Race Condition and How to Solve it

Race conditions occur when multiple, asynchronously executing threads access the same object (called a shared resource) returning unexpected (wrong) results.

Example: Threads often need to share a common resource that is a file, with one thread reading from the file while another thread writes to the file.

They can be avoided by synchronizing the threads, which access the shared resource.

An Unsynchronized Example

1 class TwoStrings {

2 static void print(String str1, String str2) {

3 System.out.print(str1);

4 try {

5 Thread.sleep(500);

6 } catch (InterruptedException ie) {

7 }

8 System.out.println(str2);

9 }

10 }

11

12 class PrintStringsThread implements Runnable {

13 Thread thread;

14 String str1, str2;

15 PrintStringsThread(String str1, String str2) {

16 this.str1 = str1;

17 this.str2 = str2;

18 thread = new Thread(this);

19 thread.start();

20 }

21 public void run() {

22 TwoStrings.print(str1, str2);

23 }

24 }

Page 275 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 276: Core Java Handout v1.0

Handout - Core Java

25

26 class TestThread {

27 public static void main(String args[]) {

28 new PrintStringsThread("Hello ", "there.");

29 new PrintStringsThread("How are ", "you?");

30 new PrintStringsThread("Thank you ",

31 "very much!");

32 }

33 }

Sample output: Hello How are Thank you there.

you?

very much!

Synchronization: Locking an Object

A thread is synchronized by becoming an owner of the monitor of the object: Consider it as locking an object A thread becomes the owner of the monitor of the object in one of following ways:

Option 1: Use synchronized method Option 2: Use synchronized statement on a common object

Option 1: Use Synchronized Method

1 class TwoStrings {

2 synchronized static void print(String str1,

3 String str2) {

4 System.out.print(str1);

5 try {

6 Thread.sleep(500);

7 } catch (InterruptedException ie) {

8 }

9 System.out.println(str2);

10 }

11 }

12

13 class PrintStringsThread implements Runnable {

14 Thread thread;

15 String str1, str2;

16 PrintStringsThread(String str1, String str2) {

17 this.str1 = str1;

18 this.str2 = str2;

19 thread = new Thread(this);

Page 276 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 277: Core Java Handout v1.0

Handout - Core Java

20 thread.start();

21 }

22 public void run() {

23 TwoStrings.print(str1, str2);

24 }

25 }

26

27 class TestThread {

28 public static void main(String args[]) {

29 new PrintStringsThread("Hello ", "there.");

30 new PrintStringsThread("How are ", "you?");

31 new PrintStringsThread("Thank you ",

32 "very much!");

33 }

34 }

Option 1: Executing Synchronized Method

Sample output: Hello there.

How are you?

Thank you very much!

Option 2: Use Synchronized Statement on a Common Object

1 class TwoStrings {

2 static void print(String str1, String str2) {

3 System.out.print(str1);

4 try {

5 Thread.sleep(500);

6 } catch (InterruptedException ie) {

7 }

8 System.out.println(str2);

9 }

10 }

11

12 class PrintStringsThread implements Runnable {

13 Thread thread;

14 String str1, str2;

15 TwoStrings ts;

16 PrintStringsThread(String str1, String str2,

17 TwoStrings ts) {

18 this.str1 = str1;

19 this.str2 = str2;

20 this.ts = ts;

Page 277 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 278: Core Java Handout v1.0

Handout - Core Java

Page 278 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

21 thread = new Thread(this);

22 thread.start();

23 }

24

25 public void run() {

26 synchronized (ts) {

27 ts.print(str1, str2);

28 }

29 }

30 }

31 class TestThread {

32 public static void main(String args[]) {

33 TwoStrings ts = new TwoStrings();

34 new PrintStringsThread("Hello ", "there.", ts);

35 new PrintStringsThread("How are ", "you?", ts);

36 new PrintStringsThread("Thank you ",

37 "very much!", ts);

38 }

39 }

Inter-thread Communication: Methods from Object Class

wait() Method of Object Class

wait() method causes a thread to release the lock it is holding on an object allowing another thread to run.

wait() method is defined in the Object class. wait() can only be invoked from within synchronized code. It should always be wrapped in a try block as it throws IOException. wait() can only be invoked by the thread that owns the lock on the object. When wait() is called, the thread becomes disabled for scheduling and lies dormant

until one of the four things occur: Another thread invokes the notify() method for this object and the scheduler arbitrarily

chooses to run the thread. Another thread invokes the notifyAll() method for this object.

Page 279: Core Java Handout v1.0

Handout - Core Java

Another thread interrupts this thread. The specified wait() time elapses. When one of the earlier occurs, the thread becomes re-available to the Thread

scheduler and competes for a lock on the object Once it regains the lock on the object, everything resumes as if no suspension had

occurred.

notify() Method

notify() method wakes up a single thread that is waiting on the monitor of this object: If any threads are waiting on this object, then one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. notify() method can only be used within synchronized code. The awakened thread will not be able to proceed until the current thread relinquishes

the lock on this object.

Try It Out

Problem Statement: Write a program that illustrates the usage of synchronized statement in thread synchronization. Code: class ThreadSynchronizedStmtApp extends Thread {

static String message[] = { "Java", "is", "hot,", "aromatic,", "and",

"invigorating." };

public static void main(String args[]) {

ThreadSynchronizedStmtApp thread1 = new ThreadSynchronizedStmtApp("thread1: ");

ThreadSynchronizedStmtApp thread2 = new ThreadSynchronizedStmtApp("thread2: ");

thread1.start();

thread2.start();

boolean thread1IsAlive = true;

boolean thread2IsAlive = true;

Refer File Name: ThreadSynchronizedStmtApp.java to obtain soft copy of the program code Refer File Name : ThreadSynchronizedStmtApp_output_on_two_executions.txt for the console output on two different occasions

Page 279 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 280: Core Java Handout v1.0

Handout - Core Java

How It Works: The synchronized statement is similar to a synchronized method in that. It is used to

acquire a lock on an object before performing an action. The synchronized statement differs from a synchronized method in that. It can be used

with the lock of any object. The synchronized method can only be used with the lock of object or class.

It also differs in a way that it applies to a statement block, rather than an entire method.

The syntax of the synchronized statement is as follows:

synchronized (object) {

statement(s)

}

The statements enclosed by the braces are only executed when the current thread acquires the lock for the object or class enclosed by parentheses.

Tips and Tricks:

Can you reuse a Thread object? Can you give it a new job to do and then restart it by calling start() again? Solution:

No. Once the run() method of a thread has completed, the thread can never be restarted. In fact, at that point the thread moves into the dead state. In the dead state, the thread has finished its run() method and can never be restarted. The Thread object might still be on the heap, as a living object that you can call other methods on (if appropriate), but the Thread object has permanently lost its ‘threadness’. In other words, the Thread object is no longer a thread. It is just an object, at that point, like all other objects.

But, there are design patterns, for making a pool of threads that you can keep using to perform different jobs. But you do not do it by restarting a dead thread.

Summary

Synchronized methods prevent more than one thread from accessing an object’s critical method code simultaneously.

You can use the synchronized keyword as a method modifier, or to start a synchronized block of code.

To synchronize a block of code, you must specify an argument that is the object whose lock you want to synchronize on.

While only one thread can be accessing synchronized code of particular instance, multiple threads can still access the same object’s unsynchronized code.

Static methods can be synchronized, using the lock from the java.lang.Class instance representing that class.

Page 280 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 281: Core Java Handout v1.0

Handout - Core Java

Test Your Understanding

1. What do you mean by ‘Synchronization’? Why do you need it? 2. What is ‘deadlock’? What harmful effect does it have? 3. Differentiate between notify() and notifyAll() methods. 4. Why do you need join() method?

Page 281 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 282: Core Java Handout v1.0

Handout - Core Java

Session 86: Threads

Learning Objectives

After completing this session, you will be able to: List the Concurrency Utilities

Concurrency Utilities: JSR-166

Concurrency utilities enable development of simple yet powerful multi-threaded applications. Like Collection it provides rich data structure handling capability.

It beats C performance in high-end server applications. It provides richer set of concurrency building blocks. wait() , notify() , and synchronized

methods are too primitive. It enhances scalability, performance, readability, and thread safety of Java

applications.

Why Use Concurrency Utilities?

Concurrency utilities are used because: Reduced programming effort Increased performance Increased reliability: Eliminate threading hazards such as deadlock, starvation, race

conditions, or excessive context switching are eliminated Improved maintainability Increased productivity

Concurrency Utilities

The Concurrency Utilities are: Task Scheduling Framework Callable's and Future's Synchronizers Concurrent Collections Atomic Variables Locks Nanosecond-granularity timing

Task Scheduling Framework

Executor /ExecutorService/Executors framework supports: o Standardizing invocation o Scheduling o Execution

Page 282 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 283: Core Java Handout v1.0

Handout - Core Java

o Control of asynchronous tasks according to a set of execution policies Executor is an interface ExecutorService extends Executor Executors is factory class for creating various kinds of ExercutorService

implementations

Executor Interface

Executor interface provides a way of de-coupling task submission from the execution: Execution: Mechanics of how each task will be run, including details of thread use and

scheduling Example: o Executor executor = getSomeKindofExecutor();

o executor.execute(new RunnableTask1());

o executor.execute(new RunnableTask2());

Many Executor implementations impose some sort of limitation on how and when tasks are scheduled.

Executor and ExecutorService

ExecutorService adds lifecycle management:

public interface Executor {

void execute(Runnable command);

}

public interface ExecutorService extends Executor {

void shutdown();

List<Runnable> shutdownNow();

boolean isShutdown();

boolean isTerminated();

boolean awaitTermination(long timeout,

TimeUnit unit);

// other convenience methods for submitting tasks

}

Creating ExecutorService From Executors

public class Executors {

static ExecutorService

newSingleThreadedExecutor();

static ExecutorService

newFixedThreadPool(int n);

static ExecutorService

newCachedThreadPool(int n);

Page 283 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 284: Core Java Handout v1.0

Handout - Core Java

static ScheduledExecutorService

newScheduledThreadPool(int n);

// additional versions specifying ThreadFactory

// additional utility methods

}

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

class WebServer {

public static void main(String[] args) {

ServerSocket socket = new ServerSocket(80);

while (true) {

final Socket connection = socket.accept();

Runnable r = new Runnable() {

public void run() {

handleRequest(connection);

}

};

// Don't do this!

new Thread(r).start();

}

}

}

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

class WebServer {

Executor pool =

Executors.newFixedThreadPool(7);

public static void main(String[] args) {

ServerSocket socket = new ServerSocket(80);

while (true) {

final Socket connection = socket.accept();

Runnable r = new Runnable() {

public void run() {

handleRequest(connection);

}

};

pool.execute(r);

}

}

}

Page 284 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 285: Core Java Handout v1.0

Handout - Core Java

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

If a new thread (callable thread) is started in an application, then there is currently no way to return a result from that thread to the thread (calling thread) that started it without the use of a shared variable and appropriate synchronization. This is complex and makes code harder to explain and maintain.

Callables and Futures

Callable thread (Callee) implements Callable interface: Implement call() method rather than run()

Calling thread (Caller) submits Callable object to Executor and then moves on through submit() and not execute()

The submit() returns a Future object Calling thread (Caller) retrieves the result using get() method of Future object: If result is ready, then it is returned If result is not ready, then calling thread will block

Build CallableExample (This is Callee)

class CallableExample

implements Callable<String> {

public String call() {

String result = “The work is ended”;

/* Do some work and create a result */

return result;

}

}

Future Example (Caller)

ExecutorService es =

Executors.newSingleThreadExecutor();

Future<String> f =

es.submit(new CallableExample());

/* Do some work in parallel */

try {

String callableResult = f.get();

} catch (InterruptedException ie) {

/* Handle */

} catch (ExecutionException ee) {

/* Handle */

}

Page 285 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 286: Core Java Handout v1.0

Handout - Core Java

Semaphores

Semaphores are typically used to restrict access to fixed size pool of resources. New Semaphore object is created with same count as number of resources. Thread trying to access resource, calls the aquire() method: o Returns immediately if semaphore count is greater than zero o Blocks if count is zero until release() is called by different thread o aquire() and release() are thread safe atomic operations

Semaphore Example

private Semaphore available;

private Resource[] resources;

private boolean[] used;

public Resource(int poolSize) {

available = new Semaphore(poolSize);

/* Initialise resource pool */

}

public Resource getResource() {

try { available.aquire() } catch (IE) {}

/* Acquire resource */

}

public void returnResource(Resource r) {

/* Return resource to pool */

available.release();

}

BlockingQueue Interface

BlockingQueue interface provides thread safe way for multiple threads to manipulate collection.

ArrayBlockingQueue is the simplest concrete implementation. Full set of methods are: o put() o offer() [non-blocking] o peek() o take() o poll() [non-blocking and fixed time blocking]

Page 286 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 287: Core Java Handout v1.0

Handout - Core Java

Blocking Queue Example 1

private BlockingQueue<String> msgQueue;

public Logger(BlockingQueue<String> mq) {

msgQueue = mq;

}

public void run() {

try {

while (true) {

String message = msgQueue.take();

/* Log message */

}

} catch (InterruptedException ie) {

/* Handle */

}

}

Blocking Queue Example 2

private ArrayBlockingQueue messageQueue =

new ArrayBlockingQueue<String>(10);

Logger logger = new Logger(messageQueue);

public void run() {

String someMessage;

try {

while (true) {

/* Do some processing */

/* Blocks if no space available */

messageQueue.put(someMessage);

}

} catch (InterruptedException ie) { }

}

Atomics

java.util.concurrent.atomic is a small toolkit of classes that support lock-free threadsafe programming on single variables.

Page 287 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 288: Core Java Handout v1.0

Handout - Core Java

AtomicInteger balance = new AtomicInteger(0);

public int deposit(integer amount) {

return balance.addAndGet(amount);

}

Locks

Lock interface: More extensive locking operations than synchronized block No automatic unlocking, use try and finally to unlock Non-blocking access using tryLock()

ReentrantLock:

Concrete implementation of Lock Holding thread can call lock() multiple times and not block Useful for recursive code

ReadWriteLock

ReadWriteLock has two locks controlling read and write access: Multiple threads can acquire the read lock if no threads have a write lock. If a thread has a read lock, then others can acquire read lock but nobody can acquire

write lock. If a thread has a write lock, then nobody can have read or write lock. Methods to access locks are rwl.readLock().lock(); and rwl.writeLock().lock();

ReadWrite Lock Example

class ReadWriteMap {

final Map<String, Data> m = new TreeMap<String, Data>();

final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

final Lock r = rwl.readLock();

final Lock w = rwl.writeLock();

public Data get(String key) {

r.lock();

try { return m.get(key) }

finally { r.unlock(); }

}

public Data put(String key, Data value) {

w.lock();

try { return m.put(key, value); }

finally { w.unlock(); }

}

Page 288 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 289: Core Java Handout v1.0

Handout - Core Java

public void clear() {

w.lock();

try { m.clear(); }

finally { w.unlock(); }

}

}

Try It Out

Problem Statement: Write a program that illustrates the usage of wait() and notify() methods in controlling access to a shared resource. Code: class ThreadUsingWaitAndNotifyApp {

public static void main(String args[]) {

Resource resource = new Resource();

Thread controller = new Thread(new Controller(resource));

Thread[] user = new Thread[3];

for (int i = 0; i < user.length; ++i)

user[i] = new Thread(new User(i, resource));

controller.start();

for (int i = 0; i < user.length; ++i)

user[i].start();

boolean alive;

out: do {

alive = false;

// continued …

Refer File Name: ThreadUsingWaitAndNotifyApp.java to obtain soft copy of the program code Refer File Name : ThreadUsingWaitAndNotifyApp_output_on_two_executions.txt for the console output on two different occasions How It Works:

A Resource object is shared among a Controller object and several User objects. The Resource object provides access to the console display. The User objects execute as separate threads and use the Resource object to display

their output. The Controller object also executes as a separate thread and controls access to the

Resource object, making it available for output every 10 seconds. The displayOutput() method of the Resource object displays a message on the

console when okToSend is true.

Page 289 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 290: Core Java Handout v1.0

Handout - Core Java

If a User thread invokes displayOutput() when okToSend is false, then it enters the waiting pool.

The allowOutput() method of Resource is periodically invoked by the Controller to allow a User thread to exit the waiting pool and display output by the Resource object.

Note that the wait() method, like the sleep() method of the Thread class, throws the InterruptedException.

This exception is thrown when the interrupt() method of a thread is invoked while it is in the waiting state.

Tips and Tricks:

List out the differences between ‘blocked’ state and ‘waiting’ state. Solution:

Blocked Waiting

Thread is waiting to get a lock on the monitor. (or waiting for a blocking I/O method)

Thread has been asked to wait. (by means of wait method)

Caused by the thread tried to execute some synchronized code. (or a blocking i/o method)

The thread already acquired the lock and executed some synchronized code before coming across a wait call.

Can move to ready only when the lock is available. (or the i/o operation is complete)

Can move to ready only when it gets notified (by means of notify() or notifyAll() )

Points for complex models: o Always check the state of a monitor in a while loop, rather than in an if statement. o Always call notifyAll() , instead of notify()

wait() and sleep() must be enclosed in a try or catch block for InterruptedException. Locks on inner or outer objects are independent. Getting a lock on outer object does

not mean getting the lock on an inner object as well, that lock should be obtained separately.

wait() and notify() should be called from synchronized code. This ensures that while calling these methods the thread always has the lock on the object. If you have wait or notify in non-synchronized code, then the compiler will not catch this. At run time, if the thread does not have the lock while calling these methods, then an IllegalMonitorStateException is thrown.

Deadlocks can occur easily. For example Thread A locked Object A and waiting to get a lock on Object B, but Thread B locked Object B and waiting to get a lock on Object A. They will be in this state forever.

Summary

When a thread goes to sleep, its locks will be unavailable to other threads. All three methods namely wait(), notify(), and notifyAll() must be called from within a

synchronized context! A thread invokes wait() or notify() on a particular object, and the thread must currently hold the lock on that object.

Basically, a wait() call means “wait me in your pool,”, or “add me to your waiting list.”

Page 290 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 291: Core Java Handout v1.0

Handout - Core Java

The notify() method is used to signal to one and only one of the threads that are waiting in that same object’s waiting pool.

The notify() method can NOT specify which waiting thread to notify.

Test Your Understanding

1. Name some of the concurrency utilities. 2. Why should you use concurrency utilities?

Page 291 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 292: Core Java Handout v1.0

Handout - Core Java

Session 89: I/O operations in JAVA

Learning Objectives

After completing this session, you will be able to: Define an I/O stream Identify the types of streams Explain the Stream class hierarchy

I/O Streams

An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations like disk files,

devices, other programs, a network socket, and memory arrays. Streams support many different kinds of data like simple bytes, primitive data types,

localized characters, and objects. Some streams simply pass on data, others manipulate and transform the data in

useful ways. No matter how they work internally, all streams present the same simple model to

programs that use them. A stream is a sequence of data.

Input Stream

A program uses an input stream to read data from a source, one item at a time.

Page 292 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 293: Core Java Handout v1.0

Handout - Core Java

Page 293 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Output Stream

A program uses an output stream to write data to a destination, one item at time.

General Stream Types

The general stream types are: Character and Byte Streams: Character streams are the streams that read and write

16-bit characters whereas Byte streams are the streams that read and write 8-bit bytes.

Input and Output Streams: Based on source or destination Node and Filter Streams: Whether the data on a stream is manipulated or transformed

or not.

Character and Byte Streams

Byte streams: For binary data Root classes for byte streams: o The InputStream class o The OutputStream class o Both classes are abstract

Character streams: For Unicode characters Root classes for character streams: o The Reader class o The Writer class o Both classes are abstract

Input and Output Streams

Input or source streams: Can read from these streams Root classes of all input streams: o The InputStream class o The Reader class

Output or sink (destination) streams: Can write to these streams Root classes of all output streams: o The OutputStream class o The Writer class

Page 294: Core Java Handout v1.0

Handout - Core Java

Node and Filter Streams

Node streams (Data sink stream): Contain the basic functionality of reading or writing from a specific location

Types of node streams include files, memory, and pipes Filter streams (Processing stream): Layered onto node streams between threads or

processes For additional functionality like altering or managing data in the stream Adding layers to a node stream is called stream chaining

Streams

Streams are shown in the following diagram:

InputStream

OutputStream

Reader

Writer

Tips and Tricks:

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? What is the default character encoding of your platform?

Solution:

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

If you are running Java on English Windows platforms, then it is probably Cp1252. If you are running Java on English Solaris platforms, then it is most likely 8859_1.

Page 294 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 295: Core Java Handout v1.0

Handout - Core Java

Summary

The central building block of the Java I/O framework is the stream. “A stream is a flowing sequence of characters”.

In other words, a stream is usually considered to be an abstraction for the capability to move bytes from a source to a sink.

Input operations begin by opening a stream from the source and using a read() method to obtain the data via the stream. Similarly, output operations begin by opening a stream to the destination and using a write() method to send the data.

The package named java.io contains a set of input and output stream classes that can be used to read and write data.

The java.io package also provides specialized InputStream and OutputStream subclasses that are used for specialized types of input and output.

The InputStream class and OutputStream class are abstract superclasses that define the behavior for sequential input and output streams in Java.

Classes in java.io package are designed to be “chained” or “wrapped”. (This is a common use of the decorator design pattern.)

Test Your Understanding

1. What is a ‘stream’? 2. Name some important input and output stream classes. 3. OutputStream and InputStream classes serve as the base classes for all byte stream

classes. Comment on this statement.

Page 295 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 296: Core Java Handout v1.0

Handout - Core Java

Page 296 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Session 90: I/O operations in JAVA

Learning Objectives

After completing this session, you will be able to: Define InputStream and OutputStream abstract classes Describe Reader and Writer abstract classes

InputStream Abstract Class

Page 297: Core Java Handout v1.0

Handout - Core Java

Page 297 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Node InputStream Classes

Filter InputStream Classes

Page 298: Core Java Handout v1.0

Handout - Core Java

Page 298 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

OutputStream Abstract Class

Node OutputStream Classes

Page 299: Core Java Handout v1.0

Handout - Core Java

Filter OutputStream Classes

The Reader Class: Methods

The Reader Class: Methods

Page 299 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 300: Core Java Handout v1.0

Handout - Core Java

Node Reader Classes

Filter Reader Classes

Page 300 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 301: Core Java Handout v1.0

Handout - Core Java

The Writer Class: Methods

Node Writer Classes

Page 301 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 302: Core Java Handout v1.0

Handout - Core Java

Filter Writer Classes

Control Flow of an I/O Operation

The control flow of an I/O operation is: Create a stream object and associate it with a data-source (data-destination) Give the stream object the desired functionality through stream chaining

while (there is more information)

read(write) next data from(to) the stream

close the stream

Byte Stream

Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream. There are many byte stream classes like FileInputStream and FileOutputStream. They are implemented in much the same way. They differ mainly in the way they are

constructed.

When not to use Byte Stream

Byte Stream represents a kind of low-level I/O that you should avoid: If the data contains character data, then the best approach is to use character

streams. There are also streams for more complicated data types. Byte streams should only be used for the most primitive I/O. All other streams are based on byte stream.

Example: FileInputStream and FileOutputStream

public class CopyBytes {

public static void main(String[] args) throws IOException {

FileInputStream in = null;

FileOutputStream out = null;

try {

Page 302 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 303: Core Java Handout v1.0

Handout - Core Java

in = new FileInputStream("xanadu.txt");

out = new FileOutputStream("outagain.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);

}

}

finally { if (in != null) {

in.close();

}

if (out != null) {

out.close();

}

}

}

}

Simple Byte Stream Input and Output

Simple byte stream input and output is shown in the following diagram:

Character Stream

The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local

character set. In Western locales, the local character set is usually an 8-bit superset of ASCII.

Page 303 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 304: Core Java Handout v1.0

Handout - Core Java

All character stream classes are descended from Reader and Writer. As with byte streams, there are character stream classes of FileReader and FileWriter

that specialize in file I/O. Reader and Writer are the abstract superclasses for character streams in java.io

package. The Reader and Writer classes were added to JDK 1.1 to support internationalization. The Reader and Writer classes make it possible to work with character streams rather

than byte streams. To a large extent, these character-stream classes mirror the byte stream classes, so if

you know how to use one, it isn't too difficult to figure out how to use the other.

Example: FileReader and FileWriter

public class CopyCharacters {

public static void main(String[] args) throws IOException {

FileReader inputStream = null;

FileWriter outputStream = null;

try {

inputStream = new FileReader("xanadu.txt");

outputStream = new FileWriter("characteroutput.txt");

int c;

while ((c = inputStream.read()) != -1) {

outputStream.write(c);

}

}

finally { if (inputStream != null) {

inputStream.close();

}

if (outputStream != null) {

outputStream.close();

}

}

}

}

Character Stream and Byte Stream

Character streams are often "wrappers" for byte streams. The character stream uses the byte stream to perform the physical I/O, while the

character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.

Page 304 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 305: Core Java Handout v1.0

Handout - Core Java

Line-Oriented I/O

Character I/O usually occurs in bigger units than single characters: For the line-oriented I/O, one common single unit is the line that contains a string of

characters with a line terminator at the end. A line terminator can be a carriage-return or linefeed sequence ("\r\n"), a single

carriage-return ("\r"), or a single line-feed ("\n").

Example: Line-oriented I/O

File inputFile = new File("farrago.txt");

File outputFile = new File("outagain.txt");

FileReader in = new FileReader(inputFile);

FileWriter out = new FileWriter(outputFile);

BufferedReader inputStream = new BufferedReader(in);

PrintWriter outputStream = new PrintWriter(out);

String l;

while ((l = inputStream.readLine()) != null) {

System.out.println(l);

outputStream.println(l);

}

in.close();

out.close();

Buffered Streams

An unbuffered I/O means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, because each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

To reduce this kind of overhead, the Java platform implements buffered I/O streams: Buffered input streams read data from a memory area known as a buffer. The native

input API is called only when the buffer is empty Similarly, buffered output streams write data to a buffer, and the native output API is

called only when the buffer is full.

How to Create Buffered Streams?

A program can convert an unbuffered stream into a buffered stream using the wrapping idiom. An unbuffered stream object is passed to the constructor for a buffered stream class.

Page 305 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 306: Core Java Handout v1.0

Handout - Core Java

Example:

inputStream = new BufferedReader(new FileReader("xanadu.txt"));

outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));

Buffered Stream Classes

BufferedInputStream and BufferedOutputStream create buffered byte streams. BufferedReader and BufferedWriter create buffered character streams.

Flushing Buffered Streams

It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer.

Some buffered output classes support autoflush, specified by an optional constructor argument:

When autoflush is enabled, certain key events cause the buffer to be flushed. For example, an autoflush PrintWriter object flushes the buffer on every invocation of

println or format. To flush a stream manually, invoke its flush method. The flush method is valid on any

output stream, but has no effect unless the stream is buffered.

Standard Streams on Java Platform

Three standard streams on Java platform are: o Standard Input, accessed through System.in o Standard Output, accessed through System.out o Standard Error, accessed through System.err

These objects are defined automatically and do not need to be opened. System.out and System.err are defined as PrintStream objects.

Data Streams

Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values.

All data streams implement either the DataInput interface or the DataOutput interface. DataInputStream and DataOutputStream are the implementations that are applied

most widely of these interfaces.

DataOutputStream

DataOutputStream can only be created as a wrapper for an existing byte stream object. out = new DataOutputStream(

new BufferedOutputStream(

new FileOutputStream(dataFile)));

for (int i = 0; i < prices.length; i ++) {

out.writeDouble(prices[i]);

out.writeInt(units[i]);

Page 306 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 307: Core Java Handout v1.0

Handout - Core Java

out.writeUTF(descs[i]);

}

DataInputStream

Like DataOutputStream, DataInputStream must be constructed as a wrapper for a byte stream.

End-of-file condition is detected by catching EOFException, instead of testing for an invalid return value.

in = new DataInputStream(

new BufferedInputStream(

new FileInputStream(dataFile)));

try {

double price = in.readDouble();

int unit = in.readInt();

String desc = in.readUTF();

} catch (EOFException e){

}

Object Streams

Object streams support I/O of objects: Like Data streams support I/O of primitive data types The object has to be of Serializable type The object stream classes are ObjectInputStream and ObjectOutputStream: These classes implement ObjectInput and ObjectOutput, which are sub interfaces of

DataInput and DataOutput An object stream can contain a mixture of primitive and object values

Input and Output of Complex Object

The writeObject and readObject methods are simple to apply, but they contain some very sophisticated object management logic. This is not important for a class like Calendar, which just encapsulates primitive values. But there are many objects that contain references to other objects. The readObject method reads an object from the ObjectInputStream. The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its supertypes are read. Default deserializing for a class can be overridden using the writeObject and readObject methods.

Write Object

The writeObject traverses the entire Web of object references and writes all objects in that Web onto the stream. A single invocation of writeObject can cause a large number of objects to be written to the stream.

Page 307 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 308: Core Java Handout v1.0

Handout - Core Java

Page 308 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

I/O of Multiple Referred-to Objects

Object a contains references to objects b and c, while b contains references to d and e.

Invoking writeObject(a) writes not just a, but all the objects necessary to reconstitute a, so the other four objects in this Web are also written. When a is read back by readObject, then the other four objects are read back as well, and all the original object references are preserved.

Always Close Streams

Closing a stream when it is no longer needed is very important, so that your program should use a finally block to guarantee that both streams will be closed even if an error occurs. This practice helps to avoid serious resource leaks.

The File Class

The File class is not a stream class. The File class is important because stream classes manipulate File objects. The File class is an abstract representation of actual files and directory pathname.

The File Class: Constructors

The File class has four constructors.

Page 309: Core Java Handout v1.0

Handout - Core Java

The File Class: Methods

The File Class: Example

1 import java.io.*;

2

3 public class FileInfoClass {

4 public static void main(String args[]) {

5 String fileName = args[0];

6 File fn = new File(fileName);

7 System.out.println("Name: " + fn.getName());

8 if (!fn.exists()) {

9 System.out.println(fileName

10 + " does not exists.");

11

12 /* Create a temporary directory instead. */

13 System.out.println("Creating temp directory...");

14 fileName = "temp";

Page 309 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 310: Core Java Handout v1.0

Handout - Core Java

15 fn = new File(fileName);

16 fn.mkdir();

17 System.out.println(fileName +

18 (fn.exists()? "exists": "does not exist"));

19 System.out.println("Deleting temp directory...");

20 fn.delete();

21

24

25 System.out.println(fileName + " is a " +

26 (fn.isFile()? "file." :"directory."));

27

28 if (fn.isDirectory()) {

29 String content[] = fn.list();

30 System.out.println("The content of this directory:");

43 for (int i = 0; i < content.length; i++) {

44 System.out.println(content[i]);

45 }

46 }

35

36

36

37

38 if (!fn.canRead()) {

39 System.out.println(fileName

40 + " is not readable.");

41 return;

42 }

43

47 System.out.println(fileName + " is " + fn.length()

48 + " bytes long.");

49 System.out.println(fileName + " is " +

50 fn.lastModified() + " bytes long.");

51

52 if (!fn.canWrite()) {

53 System.out.println(fileName

54 + " is not writable.");

55 }

56 }

57 }

Page 310 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 311: Core Java Handout v1.0

Handout - Core Java

Try It Out

Problem Statement: Write a program that illustrates the usage of InputStreamReader and BufferedReader classes that are used to convert the standard input stream (System.in) from a byte stream to a character stream. Code: import java.io.*;

public class InputConversionApp {

public static void main(String args[]) throws IOException {

InputStreamReader in = new InputStreamReader(System.in);

BufferedReader inStream = new BufferedReader(in);

// Get the encoding that is in use

System.out.println("Encoding: " + in.getEncoding());

String inputLine;

do {

System.out.print(">");

System.out.flush();

inputLine = inStream.readLine();

System.out.println(inputLine);

} while (inputLine.length() != 0);

}

}

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

The InputConversionApp program converts the standard input stream (System.in) from a byte stream to a character stream.

The input characters are echoed to standard output. The program also prints out the encoding that is in effect on your system. The following is an example of the output generated when the program is run on your

local desktop: Encoding: Cp1252 >This is a test. This is a test. >

The Cp1252 encoding is the MS Windows Latin-1 character encoding. It is applied with English and Western European languages.

Page 311 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 312: Core Java Handout v1.0

Handout - Core Java

Tips and Tricks:

What is the difference between the Reader and Writer class hierarchy and the InputStream and OutputStream class hierarchy?

What class allows you to read objects directly from a stream? What value does read() return when it has reached the end of a file? What value does readLine() return when it has reached the end of a file?

Solutions:

The Reader and Writer class hierarchy is character-oriented, and the InputStream and OutputStream class hierarchy is byte-oriented.

The ObjectInputStream class supports the reading of objects from input streams. The read() method returns -1 when it has reached the end of a file. The readLine() method returns null when it has reached the end of a file.

Summary

A new File object doesn’t mean there is a new file on your hard drive. File objects can represent either a file or a directory. FileWriter and FileReader are low-level I/O classes. You can use them to write and

read files respectively, but they should usually be wrapped. The ObjectOutputStream.writeObject() method serializes objects, and

ObjectInputStream.readObject() method deserializes objects.

Test Your Understanding

1. Which one of the following statements is wrong? a) FileWriter and FileReader classes deal with character data. b) A stream gets data from a source and sends data to a destination. c) FileOutputStream class deals with binary data. d) BufferedOutputStream and BufferedInputStream classes deal with character data.

2. Which one of the following is correct? a) The write() method in FileWriter class writes a byte. b) The read() method in FileInoutStream class reads a character. c) The ‘eof’ character in the case of a file that contains character data is -1. d) PrintWriter class is a subclass of OutputStream class. e) ‘You can deal with all types of data with the help of DataOutputStream and

DataInputStream classes.’ Comment on this statement.

Page 312 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 313: Core Java Handout v1.0

Handout - Core Java

Session 92: I/O operations in JAVA

Learning Objectives

After completing this session, you will be able to: Apply Random Access Files

Random Access File

Random access files permit nonsequential, or random, access to the contents of a file.

Problem Scenario

Consider the archive format known as ZIP. A ZIP archive contains files and is typically compressed to save space. It also contain a directory entry at the end that indicates where the various files contained within the ZIP archive begin, as shown in the following figure:

A ZIP archive

Suppose that you want to extract a specific file from a ZIP archive. If you use a sequential access stream, then you have to:

Open the ZIP archive Search through the ZIP archive until you locate the file you want to extract Extract the file Close the ZIP archive

Using the procedure referred in the earlier slide, on average, you would have to read half the ZIP archive before finding the file that you want to extract. You can extract the same file from the ZIP archive more efficiently by using the seek feature of a random access file and following these steps:

Open the ZIP archive Seek to the directory entry and locate the entry for the file you want to extract from the

ZIP archive Seek (backward) within the ZIP archive to the position of the file to extract Extract the file Close the ZIP archive

Page 313 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 314: Core Java Handout v1.0

Handout - Core Java

Benefits of Random Access File

Random Access File algorithm is more efficient because you read only the directory entry and the file that you want to extract.

java.io.RandomAccessFile

The java.io.RandomAccessFile class implements both the DataInput and DataOutput interfaces.

The java.io.RandomAccessFile class can be used for both reading and writing.

Creating a Random Access File

Similar to the sequential FileInputStream and FileOutputStream classes, you specify a file to be opened by name when you instantiate an object of class RandomAccessFile. You can specify the file name either by a literal string or by passing a File object which you have previously instantiated. Unlike with the sequential classes, when you instantiate an object of RandomAccessFile, you must indicate whether you will just be reading the file, or also writing to it. You must be able to read a file before you can write to it. The syntax for instantiating a RandomAccessFile object is as follows: new RandomAccessFile(name, mode)

As mentioned earlier, the name can be specified using either a literal string or an object of type File. The mode is a literal string which can be either of two possibilities:

"r" means open for reading only "rw" means open for both reading and writing

Once the file is opened you can use the various forms of the read___() and write___() methods to read and write the data in the file. The following code creates a RandomAccessFile to read the file named xanadu.txt: new RandomAccessFile("xanadu.txt", "r");

This one opens the same file for both reading and writing: new RandomAccessFile("xanadu.txt", "rw");

After the file has been opened, you can use the common read or write methods defined in the DataInput and DataOutput interfaces to perform I/O on the file.

File Pointer

RandomAccessFile supports the notion of a file pointer. The file pointer indicates the current location in the file. When the file is first created, the file pointer is set to zero, indicating the beginning of

the file. Calls to the read and write methods adjust the file pointer by the number of bytes read

or written.

Page 314 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 315: Core Java Handout v1.0

Handout - Core Java

A ZIP file has the notion of a current file pointer

RandomAccessFile Methods

RandomAccessFile contains the normal file I/O methods for implicitly manipulating the file pointer.

RandomAccessFile also contains the following three methods for explicitly manipulating the file pointer: o int skipBytes(int) : Moves the file pointer forward the specified number of

bytes o void seek(long) : Positions the file pointer just before the specified byte o long getFilePointer() : Returns the current byte location of the file pointer

Try It Out

Problem Statement: Write a program that illustrates the usage of RandomAccessFile. Code: import java.io.*;

public class RandomIOApp {

public static void main(String args[]) throws IOException {

RandomAccessFile file = new RandomAccessFile("test.txt", "rw");

file.writeBoolean(true);

file.writeInt(123456);

file.writeChar('j');

file.writeDouble(1234.56);

// Use seek() to move to a specific file location

file.seek(1);

System.out.println(file.readInt());

System.out.println(file.readChar());

System.out.println(file.readDouble());

file.seek(0);

System.out.println(file.readBoolean());

file.close();

}

}

Refer File Name: RandomIOApp.java to obtain soft copy of the program code

Page 315 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 316: Core Java Handout v1.0

Handout - Core Java

How It Works: The RandomIOApp program provides a simple demonstration of the capabilities of

random-access I/O. It writes a boolean, int, char, and double value to a file and then uses the seek()

method to seek to offset location 1 within the file. This is the position after the first byte in the file.

It then reads the int, char, and double values from the file and displays them to the console window.

Next, it moves the file pointer to the beginning of the file and reads the boolean value that was first written to the file.

This value is also written to the console window. The output of the program is as follows:

123456

j

1234.56

True

Tips and Tricks:

What is the difference between the File and RandomAccessFile classes? Solution: The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

Summary

Random access files permit nonsequential, or random, access to the contents of a file. The RandomAccessFile class implements both the DataInput and DataOutput

interfaces and therefore can be used for both reading and writing. RandomAccessFile supports the notion of a file pointer. RandomAccessFile contains the following three methods for explicitly manipulating the

file pointer. o skipBytes: Moves the file pointer forward the specified number of bytes. o seek: Positions the file pointer just before the specified byte. o getFilePointer: Returns the current byte location of the file pointer.

Test Your Understanding

1. State true or false for the following: a) RandomAccessFile is the only bidirectional stream in Java. b) A random access file can be opened in ‘r’ mode or ‘rw’ mode.

Page 316 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 317: Core Java Handout v1.0

Handout - Core Java

Session 93: I/O operations in JAVA

Learning Objectives

After completing this session, you will be able to: Define Serialization Identify what is preserved when an object is serialized Write Transient keyword Describe the process of serialization Explain the process of deserialization Define Version control Change the default protocol Create your own protocol by Externalizable interface

Serialization

Serialization is an ability to read or write an object to a stream. It is the process of "flattening" an object. Serialization is used to save object to some permanent storage. Its state should be written in a serialized form to a file such that the object can be reconstructed at a later time from that file. Serialization is used to pass on to another object by the OutputStream class and can be sent over the network.

Streams Used for Serialization

The streams used for serialization are: ObjectOutputStream: For serializing (flattening an object) ObjectInputStream: For deserializing (reconstructing an object)

Requirement for Serialization

Serialization is required to allow an object to be serializable: Its class should implement the Serializable interface: o Serializable interface is marker interface o Its class should also provide a default constructor (a constructor with no

arguments) Serializability is inherited: o Do not have to implement Serializable on every class o Can just implement Serializable once along the class hierarchy

Page 317 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 318: Core Java Handout v1.0

Handout - Core Java

Non-Serializable Objects

Most Java classes are serializable. Objects of some system-level classes are not serializable: Because the data that they represent, changes constantly: Reconstructed object will contain different value anyway For example, thread running in your JVM would be applying the memory of your

system. Persisting it and trying to run it in your JVM would make no sense at all. A NotSerializableException is thrown if you try to serialize non-serializable objects

What is Preserved when an Object is Serialized?

When an object is serialized enough information is preserved that is needed to reconstruct the object instance at a later time:

Only the data of the object is preserved Methods and constructors are not part of the serialized stream Class information is included

The transient Keyword

The transient modifier applies only to instance variables. If you mark an instance variable as transient, you’re telling the JVM to skip (ignore)

this variable when you attempt to serialize the object containing it. In other words, the transient keyword prevents the data from being serialized. All fields that are not transient are considered part of the persistent state of an object

and are eligible for persistence.

Example: transient Keyword

1 class MyClass implements Serializable {

2

3 // Skip serialization of the transient field

4 transient Thread thread;

5 transient String fieldIdontwantSerialization;

6

7 // Serialize the rest of the fields

8 int data;

9 String x;

10

11 // More code

12 }

Page 318 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 319: Core Java Handout v1.0

Handout - Core Java

Serialization: Writing an Object Stream

To write an object stream use its writeObject method of the ObjectOutputStream class. public final void writeObject(Object obj) throws IOException

where obj is the object to be written to the stream 1 import java.io.*;

2 public class SerializeBoolean {

3 SerializeBoolean() {

4 Boolean booleanData = new Boolean("true");

5 try {

6 FileOutputStream fos = new

7 FileOutputStream("boolean.ser");

8 ObjectOutputStream oos = new

9 ObjectOutputStream(fos);

10 oos.writeObject(booleanData);

11 oos.close();

12

13 } catch (IOException ie) {

14 ie.printStackTrace();

15 }

16 }

17

18 public static void main(String args[]) {

19 SerializeBoolean sb = new SerializeBoolean();

20 }

21 }

Deserialization: Reading an Object Stream

To read an object stream use its readObject method of the ObjectInputStream class. public final Object readObject() throws IOException, ClassNotFoundException

where obj is the object to be read from the stream The Object type returned should be typecasted to the appropriate class name before methods on that class can be executed. 1 import java.io.*;

2 public class UnserializeBoolean {

3 UnserializeBoolean() {

4 Boolean booleanData = null;

5 try {

6 FileInputStream fis = new

7 FileInputStream("boolean.ser");

Page 319 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 320: Core Java Handout v1.0

Handout - Core Java

8 ObjectInputStream ois = new

9 ObjectInputStream(fis);

10 booleanData = (Boolean) ois.readObject();

11 ois.close();

12

13 } catch (Exception e) {

14 e.printStackTrace();

15 }

16 System.out.println("Unserialized Boolean from "

17 + "boolean.ser");

18 System.out.println("Boolean data: " +

19 booleanData);

20 System.out.println("Compare data with true: " +

21 booleanData.equals(new Boolean("true")));

22 }

23

24 public static void main(String args[]) {

25 UnserializeBoolean usb =

26 new UnserializeBoolean();

27 }

28 }

Version Control: Problem Scenario

Imagine that you create a class, instantiate it, and write it out to an object stream. The flattened object sits in the file system for some time. Meanwhile, you update the class file, perhaps adding a new field. What happens when you try to read in the flattened object? An exception will be thrown specifically, the java.io.InvalidClassException.

Unique Identifier

Why exception is thrown? Because all classes that are capable of persistence have a unique identifier

automatically If the identifier of the class does not equal the identifier of the flattened object, then the

exception will be thrown However, if you really think about it, why should it be thrown just because I added a field? Could not the field just be set to its default value and then written out next time? Yes, but it takes a little code manipulation. The identifier that is part of all classes is maintained in a field called serialVersionUID.

Page 320 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 321: Core Java Handout v1.0

Handout - Core Java

If you wish to control versioning, then you simply have to provide the serialVersionUID field manually and ensure that it is always the same, no matter what changes you make to the class file.

How do you Generate a Unique ID?

serialver utility is used to generate a unique ID Example: serialver MyClass

MyClass static final long serialVersionUID = 10275539472837495L;

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

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

private void writeObject(java.io.ObjectOutputStream out) throws IOException;

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

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

The most common reason to implement writeObject() and readObject() is when you have to save some part of an object’s state manually. If you choose, you can write and read ALL of the state yourself, but that’s very rare. When you want to do only a part of the serialization/deserialization yourself, you MUST invoke the defaultReadObject() and defaultWriteObject() methods to do the rest.

Externalizable Interface

The writeExternal and readExternal methods of the Externalizable interface can be implemented by a class to give the class complete control over the format and contents of the stream for an object and its super types. These methods must explicitly coordinate with the super type to save its state. These methods supersede customized implementations of writeObject() and readObject() methods.

How does Object Serialization Scheme works with Externalizable

Object Serialization applies the Serializable and Externalizable interfaces Each object to be stored is tested for the Externalizable interface:

If the object supports Externalizable, then the writeExternal() method is called. If the object does not support Externalizable and does implement Serializable, then

the object is saved using ObjectOutputStream.

Page 321 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 322: Core Java Handout v1.0

Handout - Core Java

Try It Out

Problem Statement: Write a program that illustrates the usage of ObjectInputStream and ObjectOutputStream classes in the process of serialization. Code: import java.io.*;

import java.util.*;

public class ObjectIOApp {

public static void main(String args[]) throws IOException,

ClassNotFoundException {

File file = new File("test.txt");

FileOutputStream outFile = new FileOutputStream(file);

ObjectOutputStream outStream = new ObjectOutputStream(outFile);

TestClass1 t1 = new TestClass1(true, 9, 'A', 0.0001, "java");

TestClass2 t2 = new TestClass2();

String t3 = "This is a test.";

Date t4 = new Date();

// continued …

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

ObjectIOApp creates a File object that is used to perform I/O to the test.txt file. The File object is used to create an object of class FileOutputStream. This object is then used to create an object of class ObjectOutputStream, which is

assigned to the outStream variable. Four objects are created and assigned to the t1 through t4 variables. An object of class TestClass1 is assigned to the t1 variable, and an object of class

TestClass2 is assigned to the t2 variable. A String object is assigned to t3, and a Date object is assigned to t4. The objects referenced by the t1 through t4 variables are written to outStream using

the writeObject() method. The stream and file are then closed. The test.txt file is reopened as a FileInputStream object, which is then converted to an

ObjectInputStream object and assigned to the inStream variable. Four objects are read from inStream, using the readObject() method, and they are

written to standard output. The output of the program is as follows:

true 9 A 1.0E-4 java

0 true 2 j 1.234 Java false 7 J 2.468 JAVA

Page 322 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 323: Core Java Handout v1.0

Handout - Core Java

This is a test.

Thu Mar 13 15:37:58 GMT+05:30 2008

Note that you will receive a different date value from this one. TestClass1 and TestClass2 are dummy test classes that are used to make the

example work. The toString() method is automatically invoked by the println() method to convert

objects to string values for printing.

Tips and Tricks:

1. Why will you ever write a class that was not serializable? 2. What happens if two objects in the object graph are the same object? Does this object get

saved twice during serialization? Solution:

1. There are very few reasons, but you might for example, have a security issue where you do not have a password object stored or you might have an object that makes no sense to save, because its key instance variables are themselves not serializable, so there is no useful way for you to make your class serializable.

2. Serialization is smart enough to know when two objects in the graph are the same. In that case, only one of the objects is saved, and during deserialization, any references to that single object are restored.

Summary

A class must implement the Serializable interface before its objects can be serialized. If you mark an instance variable transient, it will not be serialized even though the rest

of the object’s state will be. If a superclass implements Serializable, then its subclasses do automatically. If a superclass doesn’t implement Serializable, then when a subclass object is

deserialized, the superclass constructor will run.

Test Your Understanding

1. What is object serialization? 2. What useful purpose does serialization serve?

Page 323 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 324: Core Java Handout v1.0

Handout - Core Java

Session 96: JDBC

Learning Objectives

After completing this session, you will be able to: Define JDBC Apply JDBC API step by step

JDBC

JDBC is a standard Java API for accessing relational database and hides database specific details from application. JDBC is a part of Java SE (J2SE). Java SE 6 has JDBC 4.

JDBC API

The JDBC API is a Java API for accessing virtually any kind of tabular data. The JDBC API consists of a set of classes and interfaces written in the Java

programming language that provide a standard API for tool/database developers and makes it possible to write industrial-strength database applications entirely in the Java programming language.

The Java programming language, being robust, secure, easy to use, easy to understand, and automatically downloadable on a network, is an excellent language basis for database applications.

What is needed is a way for Java applications to talk to a variety of different data sources. The JDBC API provides the mechanism for doing this.

Majority of JDBC API is located in java.sql package, which are DriverManager, Connection, ResultSet, DatabaseMetaData, ResultSetMetaData, PreparedStatement, CallableStatement and Types

The javax.sql package provides many advanced functionalities. o Example: DataSource

For example, an alternative to the DriverManager facility, a DataSource object is the preferred means of getting a connection.

The DataSource interface is implemented by a driver vendor. With a basic implementation, the connection obtained through a DataSource object is

identical to a connection obtained through the DriverManager facility.

JDBC Driver

JDBC driver is an implementation of JDBC interfaces that is specific to database. Every database server has corresponding JDBC drivers. You can see the list of available drivers from http://industry.java.sun.com/products/jdbc/drivers

Page 324 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 325: Core Java Handout v1.0

Handout - Core Java

JDBC Driver

In simplest terms, a JDBC technology-based driver ("JDBC driver") makes it possible to do three things:

Establish a connection with a data source Send queries and update statements to the data source Process the results

The following code fragment gives a simple example of these three steps: Connection con = DriverManager.getConnection( "jdbc:myDriver:wombat", "myLogin", "myPassword");

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");

while (rs.next()) {

int x = rs.getInt("a");

String s = rs.getString("b");

float f = rs.getFloat("c");

}

Database URL

Database URL is used to make a connection to the database and can contain server, port, protocol, and so on. jdbc:subprotocol_name:driver_dependant_databasename: Oracle thin driver

jdbc:oracle:thin:@machinename:1521:dbname:Derby

jdbc:derby://localhost:1527/sample: Pointbase

jdbc:pointbase:server://localhost/sample

Steps of Applying JDBC

The steps of applying JDBC are: 1. Load the JDBC driver that is specific to DB 2. Get a Connection object 3. Get a Statement object 4. Execute queries and/or updates 5. Read results 6. Read Meta-data (optional step) 7. Close Statement and Connection objects

Load DB-Specific Database Driver

Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC–ODBC Bridge driver, the following code will load it: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Your driver documentation will give you the class name to use.

Page 325 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 326: Core Java Handout v1.0

Handout - Core Java

For instance, if the class name is jdbc.DriverXYZ, you would load the driver with the following line of code: Class.forName("jdbc.DriverXYZ");

You do not need to create an instance of a driver and register it with the DriverManager because calling the method Class.forName will do that for you automatically. If you were to create your own instance, you would be creating an unnecessary duplicate. When you have loaded a driver, it is available for making a connection with a DBMS.

Get a Connection Object

DriverManager class is responsible for selecting the database and creating the database connection. Using DataSource is a preferred means of getting a Connection object (You will talk about DataSource in the next session) Create the database connection: try {

Connection connection =

DriverManager.getConnection("jdbc:derby://localhost:1527/sample", “app"," app ");

} catch(SQLException sqle) {

System.out.println("" + sqle);

}

DriverManager and Connection

java.sql.DriverManager: getConnection(String url, String user, String password) throws SQLException java.sql.Connection:

Statement createStatement() throws SQLException

void close() throws SQLException

void setAutoCommit(boolean b) throws SQLException

void commit() throws SQLException

void rollback() throws SQLException

Get a Statement Object

Create a Statement object from Connection object: java.sql.Statement:

ResultSet executeQuery(string sql)

int executeUpdate(String sql)

Page 326 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 327: Core Java Handout v1.0

Handout - Core Java

Example: Statement statement = connection.createStatement(); The same Statement object can be used for many unrelated queries

Executing Query or Update

From the Statement object, the two most used commands are: QUERY (SELECT) :

ResultSet rs = statement.executeQuery("select * from customer_tbl");

ACTION COMMAND (UPDATE/DELETE) :

int iReturnValue = statement.executeUpdate("update manufacture_tbl set name = ‘IBM' where mfr_num = 19985678");

Reading Results

Loop through ResultSet retrieving information: java.sql.ResultSet:

boolean next()

xxx getXxx(int columnNumber)

xxx getXxx(String columnName)

void close()

The iterator is initialized to a position before the first row. You must call next() once to move it to the first row. Once you have the ResultSet, you can easily retrieve the data by looping through it while (rs.next()){

// Wrong this will generate an error

String value0 = rs.getString(0);

// Correct!

String value1 = rs.getString(1);

int value2 = rs.getInt(2);

int value3 = rs.getInt(“ADDR_LN1");

}

When retrieving data from the ResultSet, use the appropriate getXXX() method:

getString()

getInt()

getDouble()

getObject()

There is an appropriate getXXX() method of each java.sql.Types data type.

Page 327 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 328: Core Java Handout v1.0

Handout - Core Java

Read ResultSet MetaData and DatabaseMetaData (Optional)

Once you have the ResultSet or Connection objects, you can obtain the metadata about the database or the query. This gives valuable information about the data that you are retrieving or the database that you are using. ResultSetMetaData rsMeta = rs.getMetaData();

DatabaseMetaData dbmetadata = connection.getMetaData();

There are approximately 150 methods in the DatabaseMetaData class.

ResultSetMetaData Example

ResultSetMetaData meta = rs.getMetaData();

//Return the column count

int iColumnCount = meta.getColumnCount();

for (int i =1 ; i <= iColumnCount ; i++){

System.out.println(“Column Name: " + meta.getColumnName(i));

System.out.println(“Column Type" + meta.getColumnType(i));

System.out.println("Display Size: " +

meta.getColumnDisplaySize(i) );

System.out.println("Precision: " + meta.getPrecision(i));

System.out.println(“Scale: " + meta.getScale(i) );

}

Try It Out

Problem Statement: Write a program that illustrates how to connect to a database by registering the JDBC driver using the Class.forName() method. Code: import java.sql.DriverManager;

import java.sql.Connection;

import java.sql.Statement;

import java.sql.ResultSet;

import java.sql.SQLException;

public class ConnectionUsingClassForName {

final String driverClass = "oracle.jdbc.driver.OracleDriver";

public void classForName() {

Connection con = null;

Statement stmt = null;

Page 328 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 329: Core Java Handout v1.0

Handout - Core Java

ResultSet rset = null;

try {

System.out.print(" Loading JDBC Driver -> " + driverClass + "\n");

Class.forName(driverClass).newInstance();

// continued …

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

This program provides an example of how to connect to a database by registering the JDBC driver using the Class.forName() method.

This complex expression is a tool for dynamically creating an instance of a class when you have some variable representing the class name.

Because a JDBC driver is required to register itself whenever its static initializer is called, this expression has the net effect of registering your driver for you.

This method is by far the best as in that it does not require hardcoded class names and it runs well in all Java environments.

In real-world applications, you should apply this method along with a properties file from which you load the name of the driver.

Tips and Tricks:

Provide some key tips while writing SQL statements and executing it using executeUpdate() methods. Solution:

When a connection is created using JDBC, by default it is in the auto-commit mode. This means that each individual SQL statement is treated as a transaction by itself,

and will be committed as soon as its execution is finished. Notice that for the SQL statements CREATE, INSERT, UPDATE, and DELETE, the

execution of the method executeUpdate() will change the state of the database. Whenever the SQL statement will not fit on one line on the page, you have to split it

into two strings concatenated by a plus sign (+) so that it will compile. Pay special attention to the space following “INSERT INTO tablename” to separate it

in the resulting string from “VALUES”.

Summary

Advantages of Java and JDBC technologies: MIS managers like the combination of the Java platform and JDBC technology

because it makes disseminating information easy and economical. Businesses can continue to use their installed databases and access information

easily even if it is stored on different database management systems or other data sources.

Page 329 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 330: Core Java Handout v1.0

Handout - Core Java

Development time for new applications is short. Installation and version control are greatly simplified. A programmer can write an application or an update once, put it on the server, and

then everybody has access to the latest version. And for businesses selling information services, the combination of the Java and

JDBC technologies offers a better way of distributing information updates to external customers.

Test Your Understanding

1. State true or false for the following: a) Majority of JDBC API is located in java.sql package. b) DriverManager class is not responsible for selecting the database and creating the

database connection. c) In the ResultSet class, there is an appropriate getXXX() method for each

java.sql.Types data type.

Page 330 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 331: Core Java Handout v1.0

Handout - Core Java

Session 97: JDBC

Learning Objectives

After completing this session, you will be able to: Define DataSource and Connection Pooling Describe transaction

javax.sql.DataSource Interface and DataSource Object

Driver vendor implements the javax.sql.DataSource interface. DataSource object is the factory for creating database connections.

Three types of possible implementations are:

Basic implementation: Produces standard Connection object Connection pooling implementation: Produces a Connection object that will

automatically participate in connection pooling Distributed transaction implementation: Produces a Connection object that may be

used for distributed transactions and almost always participates in connection pooling

Properties of DataSource Object

A DataSource object has properties that can be modified when necessary. These are defined in the configuration file of a container:

Location of the database server Name of the database Network protocol to be used to communicate with the server

The benefit is that, because the properties of the data source can be changed, any code accessing that data source does not need to be changed. In the Sun Java System Application Server, a data source is called a JDBC resource.

Where are Properties of a DataSource Defined?

The properties of a DataSource are defined: In the configuration file of the container In Sun Java System App Server, they are defined in:

<J2EE_HOME>/domains/domain1/config/domain.xml

In Tomcat, they are defined in server.xml:

<TOMCAT_HOME>/conf/server.xml

Page 331 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 332: Core Java Handout v1.0

Handout - Core Java

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

<resources>

<jdbc-resource enabled="true" jndi-name="jdbc/BookDB" object-type=“ user” pool-name="PointBasePool"/>

<jdbc-connection-pool connection-validation-method=“auto-commit” datasource-classname="com.pointbase.xa.xaDataSource" fail-allconnections="

false" idle-timeout-in-seconds="300" is-connectionvalidation-required="false" is-isolation-level-guaranteed="true" maxpool-size="32" max-wait-time-in-millis="60000" name="PointBasePool"

pool-resize-quantity="2" res-type="javax.sql.XADataSource" steadypool-size="8">

<property name="DatabaseName"

value="jdbc:pointbase:server://localhost:9092/sun-appserv-samples"/>

<property name="Password" value="pbPublic"/>

<property name="User" value="pbPublic"/>

</jdbc-connection-pool>

</resources>

Sun Java System Application Server Admin Console

Screenshot of Sun Java System Application Server Edition 8.1 Admin Console

Page 332 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 333: Core Java Handout v1.0

Handout - Core Java

Editing a sample JDBC Resource

Sun Java System Application Server Admin Console

Screenshot of Sun Java System Application Server Edition 8.1 Admin Console

Page 333 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 334: Core Java Handout v1.0

Handout - Core Java

JNDI Registration of a DataSource Object

A driver that is accessed by a DataSource object does not register itself with the DriverManager.

Rather, a DataSource object is registered to JNDI naming service by the container and then retrieved by a client though a lookup operation.

With a basic implementation, the connection obtained through a DataSource object is identical to a connection obtained through the DriverManager facility.

JNDI Registration of a DataSource (JDBC Resource) Object

The JNDI name of a JDBC resource is expected in the java:comp/env/jdbc subcontext. For example, the JNDI name for the resource of a BookDB database could be java:comp/env/jdbc/BookDB. Because all resource JNDI names are in the java:comp/env subcontext, when you specify the JNDI name of a JDBC resource, then enter only jdbc/name. For example, for a payroll database, specify jdbc/BookDB.

Need of Connection Pooling

Database connection is an expensive and limited resource. Using connection pooling, a smaller number of connections are shared by a larger number of clients.

Creating and destroying database connections are expensive operations.

Page 334 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 335: Core Java Handout v1.0

Handout - Core Java

Using connection pooling, a set of database connections are created at firsthand and made available in the pool.

Then these connections are provided on requirement basis from the pool and finally these connections are returned back to the pool.

The important advantage of connection pooling mechanism is that it cuts down the overhead of creating and destroying database connections.

Connection Pooling and DataSource

DataSource objects that implement connection pooling also produce a connection to the particular data source that the DataSource class represents.

The Connection object that the getConnection method returns is a handle to a PooledConnection object rather than being a physical connection. The application code works in the same way.

Example: PointBasePool

The Sun Java Application Server 8 is distributed with a connection pool named PointBasePool, which handles connections to the PointBase database server.

Under Sun Java Application Server, each DataSource object is associated with a connection pool.

Retrieval and Usage of a DataSource Object

Application perform JNDI lookup operation to retrieve DataSource object. DataSource object is then used to retrieve a Connection object. In the web.xml file of the application, information on external resource, DataSource

object in this case, is provided. For Sun Java System App server, the mapping of external resource and JNDI name is

provided. This provides further flexibility.

Example: Retrieval of DataSource Object by JNDI

BookDBAO.java in bookstore1 application: public class BookDBAO {

private ArrayList books;

Connection con;

private boolean conFree = true;

public BookDBAO() throws Exception {

try {

Context initCtx = new InitialContext();

Context envCtx = (Context)initCtx.lookup("java:comp/env");

DataSource ds = (DataSource) envCtx.lookup("jdbc/BookDB");

con = ds.getConnection();

} catch (Exception ex) {

throw new Exception("Couldn't open connection to database: " ex.getMessage());

Page 335 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 336: Core Java Handout v1.0

Handout - Core Java

}

}

}

JNDI Resource Information in web.xml of bookstore1

<resource-ref>

<res-ref-name>jdbc/BookDB</res-ref-name>

<res-type>javax.sql.DataSource</res-type>

<res-auth>Container</res-auth>

<res-sharing-scope>Shareable</res-sharing-scope>

</resource-ref>

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

<sun-web-app>

<context-root>/bookstore1</context-root>

<resource-ref>

<res-ref-name>jdbc/BookDB</res-ref-name>

<jndi-name>jdbc/BookDB</jndi-name>

</resource-ref>

</sun-web-app>

Transaction

One of the main benefits of using a PreparedStatement is executing the statements in a transactional manner.

The committing of each statement when it is first executed is very time consuming. By setting AutoCommit to false, the developer can update the database more then

once and then commit the entire transaction as a whole. Also, if each statement is dependant on the other, the entire transaction can be rolled

back and the user is notified.

JDBC Transaction Methods

The JDBC transaction methods are: setAutoCommit() : If set true, every executed statement is committed immediately commit() : o Relevant only if setAutoCommit(false) o Commit operations performed because the opening of a Connection or last

commit() or rollback() calls rollback() : o Relevant only if setAutoCommit(false) o Cancels all operations performed

Page 336 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 337: Core Java Handout v1.0

Handout - Core Java

Transactions Example

Connection connection = null;

try {

connection = DriverManager.getConnection("jdbc:oracle:thin:@machinename:1521:dbname","username","password");

connection.setAutoCommit(false);

PreparedStatement updateQty =

connection.prepareStatement("UPDATE STORE_SALES SET QTY = ? WHERE ITEM_CODE = ? ");

int [][] arrValueToUpdate =

{ {123, 500} ,

{124, 250},

{125, 10},

{126, 350} };

int iRecordsUpdate = 0;

for ( int items=0 ; items < arrValueToUpdate.length ;

items++) {

int itemCode = arrValueToUpdate[items][0];

int qty = arrValueToUpdate[items][1];

updateQty.setInt(1,qty);

updateQty.setInt(2,itemCode);

iRecordsUpdate += updateQty.executeUpdate();

}

connection.commit();

System.out.println(iRecordsUpdate + " record(s) have been updated");

} catch(SQLException sqle) {

System.out.println("" + sqle);

}

try {

connection.rollback();

} catch(SQLException sqleRollback) {

System.out.println("" + sqleRollback);

} finally {

try {

connection.close();

}

catch(SQLException sqleClose) {

System.out.println("" + sqleClose);

}

}

Page 337 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 338: Core Java Handout v1.0

Handout - Core Java

Try It Out

Problem Statement: Write a program that illustrates on how the database transaction statements such as commit and rollback are handled in Java. Code: import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class TransactionExampleApp {

public static void main(String[] args) {

Connection connection = null;

try {

connection = DriverManager.getConnection(

"jdbc:oracle:thin:@machinename:1521:dbname", "username", "password");

connection.setAutoCommit(false);

PreparedStatement updateQty = connection

.prepareStatement("UPDATE STORE_SALES SET QTY = ? WHERE ITEM_CODE = ? ");

// continued …

Refer File Name: TransactionExampleApp.java to obtain soft copy of the program code How It Works: The TransactionExampleApp program is given just for referencing how the database transaction statements such as commit and rollback are handled in Java.

Tips and Tricks:

Provide some key points on the transaction isolation level namely TRANSACTION_READ_COMMITTED. Solution:

The programmer sets a property namely, the transaction isolation level, which determines the transaction isolation level given to the connection that the rowset establishes.

The owner does not want to read any data that has not been committed, so the programmer chooses the level TRANSACTION_READ_COMMITTED. crset.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

Page 338 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 339: Core Java Handout v1.0

Handout - Core Java

When you set the transaction isolation level to TRANSACTION_READ_COMMITTED, it will not allow a value to be accessed until after it has been committed, and forbids dirty read.

Now suppose that A and B both have a transaction isolation level of TRANSACTION_READ_COMMITTED.

This level prohibits reading a value that has changed until after it has been committed, so neither A nor B will be able to make a "dirty read."

In this situation, a sensitive result set open in transaction A will not show uncommitted changes that B makes, but it will reflect a value updated by B after B commits the change.

A sensitive result set open in B will likewise show changes that A makes after A commits them.

Similar to this level, the other field values for isolation levels provided in the Connection interface are TRANSACTION_READ_COMMITTED, TRANSACTION_SERIALIZABLE, TRANSACTION_NONE and TRANSACTION_REPEATABLE_READ .

By default, the isolation level is set to TRANSACTION_SERIALIZABLE.

Summary

DataSource o The DataSource interface provides methods that allow a user to get and set the

character stream to which tracing and error logging will be written. o A user can trace a specific data source on a given stream, or multiple data

sources can write log messages to the same stream provided that the stream is set for each data source.

Connection Pooling o Get the connection with a DataSource object o Always close the connection in a finally block.

Distributed Transactions: o Do not call the methods commit or rollback, and o Do not set auto-commit mode to true.

Test Your Understanding

1. State true or false for the following: a) The usage of Connection Pooling mechanism results in cutting down on the

overhead of creating and destroying database connections. b) By setting AutoCommit to false, the developer cannot update the database more

than once and then commit the entire transaction as a whole.

Page 339 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 340: Core Java Handout v1.0

Handout - Core Java

Session 98: JDBC

Learning Objectives

After completing this session, you will be able to: Identify java.sql.PreparedStatement and java.sql.CallableStatement

Prepared and Callable Statements

PreparedStatement: SQL is sent to the database and compiled or prepared beforehand

CallableStatement: Executes SQL Stored Procedures

PreparedStatement

The contained SQL is sent to the database and compiled or prepared beforehand. From this point on, the prepared SQL is sent and this step is bypassed. The more

dynamic statement requires this step on every execution. Depending on the DB engine, the SQL may be cached and reused even for a different

PreparedStatement and most of the work is done by the DB engine rather than the driver.

Instances of PreparedStatement contain an SQL statement that has already been compiled. This is what makes a statement "prepared.“

The SQL statement contained in a PreparedStatement object may have one or more IN parameters.

An IN parameter is a parameter whose value is not specified when the SQL statement is created.

Instead, the statement has a question mark (?) as a placeholder for each IN parameter.

The ? is also known as a parameter marker or parameter placeholder. An application must set a value for each parameter marker in a prepared statement

before executing the prepared statement. Because PreparedStatement objects are precompiled, their execution can be faster

than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a

PreparedStatement object to increase efficiency. Being a subclass of Statement, PreparedStatement inherits all the functionality of

Statement. In addition, it adds a set of methods that are needed for setting the values to be sent

to the database in place of the placeholders for IN parameters. Also, the three methods execute, executeQuery, and executeUpdate are modified so

that they take no argument. The Statement forms of these methods (the forms that take an SQL statement

parameter) cannot be used with a PreparedStatement object.

Page 340 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 341: Core Java Handout v1.0

Handout - Core Java

PreparedStatement Steps

The steps of PreparedStatement object are: 1. You register the drive and create the db connection in the usual manner. 2. Once you have a db connection, create the prepared statement object.

Example: PreparedStatement updateSales =

con.prepareStatement(“UPDATE OFFER_TBL SET

QUANTITY = ? WHERE ORDER_NUM = ? ");

// “?” are referred to as Parameter Markers

// Parameter Markers are referred to by number,

// starting from 1, in left to right order.

// PreparedStatement's setXXX() methods are used to set

// the IN parameters, which remain set until changed.

Bind in your variables. The binding in of variables is based on position. updateSales.setInt(1, 75);

updateSales.setInt(2, 10398001);

Once all the variables have been bound, then you execute the PreparedStatement. int iUpdatedRecords = updateSales.executeUpdate();

If AutoCommit is set to true, then once the statement is executed, the changes are committed. From this point forth, you can just re-use the PreparedStatement object. updateSales.setInt(1, 150);

updateSales.setInt(2,10398002);

If the PreparedStatement object is a select statement, then you execute it, and loop through the ResultSet object in the same way as in the basic JDBC example: PreparedStatement itemsSold =

con.prepareStatement("select o.order_num,

o.customer_num, c.name, o.quantity from order_tbl o,

customer_tbl c where o.customer_num =

c.customer_num and o.customer_num = ?;");

itemsSold.setInt(1,10398001);

ResultSet rsItemsSold = itemsSold.executeQuery();

while (rsItemsSold.next()){

System.out.println( rsItemsSold.getString(“NAME") + "sold "+ rsItemsSold.getString(“QUANTITY") + " unit(s)");

}

Page 341 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 342: Core Java Handout v1.0

Handout - Core Java

CallableStatement

CallableStatement is the interface used to execute SQL stored procedures. A stored procedure is a group of SQL statements that form a logical unit and perform a

particular task. Stored procedures are used to encapsulate a set of operations or queries to execute

on a database server. A CallableStatement object contains a call to a stored procedure. It does not contain

the stored procedure itself. The following first line of code creates a call to the stored procedure

SHOW_SUPPLIERS using the connection con . The part that is enclosed in curly braces is the escape syntax for stored procedures.

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");

ResultSet rs = cs.executeQuery();

CallableStatement Example

Here is an example using IN, OUT, and INOUT parameters. // set int IN parameter

cstmt.setInt( 1, 333 );

// register int OUT parameter

cstmt.registerOutParameter( 2, Types.INTEGER );

// set int INOUT parameter

cstmt.setInt( 3, 666 );

// register int INOUT parameter

cstmt.registerOutParameter( 3, Types.INTEGER );

//You then execute the statement with no return value

cstmt.execute(); // could use executeUpdate()

// get int OUT and INOUT

int iOUT = cstmt.getInt( 2 );

int iINOUT = cstmt.getInt( 3 );

Stored Procedure Example

FUNCTION event_list ( appl_id_in VARCHAR2,

dow_in VARCHAR2,

event_type_in VARCHAR2 OUT,

status_in VARCHAR2 INOUT)

RETURN ref_cur;

Try It Out

Problem Statement: Write a program that illustrates the usage of CallableStatement.

Page 342 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 343: Core Java Handout v1.0

Handout - Core Java

Code: import java.sql.CallableStatement;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

public class OracleCallableStmtApp {

public static void main(String[] args) {

try {

Connection connection = DriverManager.getConnection("");

CallableStatement queryreport = connection

.prepareCall("{ ? = call SRO21208_PKG.QUEUE_REPORT ( ? , ? , ? , ? , ? , ? ) }");

queryreport.registerOutParameter(1, java.sql.Types.OTHER);

queryreport.setInt(2, 10);

// continued …

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

This is an Oracle specific example of a CallableStatement. This program is given just for a reference.

Tips and Tricks:

Provide the advantages of using PreparedStatement object against Statement. Solution:

The main feature of the PreparedStatement, which distinguishes it from its super class Statement, is that unlike Statement, it gives a SQL statement right when it is created.

This SQL statement is then sent to the DBMS right away, where it is compiled. Thus, in effect, a PreparedStatement is associated as a channel with a connection and a compiled SQL statement.

The advantage offered is that if you need to apply the same, or similar query with different parameters multiple times, then the statement can be compiled and optimized by the DBMS just once.

Contrast this with an application of a normal Statement where each implementation of the same SQL statement requires a compilation all over again.

Page 343 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 344: Core Java Handout v1.0

Handout - Core Java

Summary

The SQL statement contained in a PreparedStatement object may have one or more IN parameters.

An application must set a value for each parameter marker in a prepared statement before executing the prepared statement.

Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects.

Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency.

A CallableStatement object provides a way to call stored procedures in a standard way for all RDBMSs.

A stored procedure is stored in a database; the call to the stored procedure is what a CallableStatement object contains.

This call is written in an escape syntax that may take one of two forms: one form with a result parameter and the other without a result parameter.

A result parameter, a kind of OUT parameter, is the return value for the stored procedure.

Test Your Understanding

1. Differentiate between PreparedStatement and CallableStatement. 2. What is a significance of writing a stored procedure?

Page 344 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 345: Core Java Handout v1.0

Handout - Core Java

Session 102: Garbage Collection

Learning Objectives

After completing this session, you will be able to: Define Garbage Collector Explain the GC Designs Identify the Memory Leaks

Garbage Collector

The Garbage Collector runs in a thread in the JVM. When the free memory drops under a threshold the GC begins to run to eliminate unneeded objects. Exactly when it runs and for how long, however, cannot be controlled by the user program.

Important Facts About GC

GC is unpredictable in nature, and in fact, causes serious problems for Real Time (RT) applications of Java.

The JVM does not actually require a GC and in some special situations, the GC is simply turned off or left out. In that case, the program must itself make sure that it does not run out of memory.

What Does a GC Perform?

If a section of memory earlier used by an object is no longer referenced by any variable, then the Garbage Collector (GC) will release this memory for re-use by new objects. This takes place automatically without any input from the user program.

There are no heap commands such malloc() and free() functions in C needed to allocate or de-allocate memory buffers.

Java does use a similar "new" operator as in C++ for creating objects but has no "delete" operator.

Overview of GC Designs

The JVM Specification does not in fact specify very much about the GC. It leaves considerable room for variation in implementation. Research continues in the computer science community for fast and efficient GC algorithms. A GC must meet a number of difficult challenges:

Recognize and eliminate dead (unreferenced) objects from the heap Keep the heap from becoming so fragmented that new objects do not easily fit Minimize the processing time taken away from the application Recognize circular cases where dead objects (that is, objects are no longer accessible

from the live thread processes or from static references) referencing each other and so might give them the appearance of life

Page 345 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 346: Core Java Handout v1.0

Handout - Core Java

Some of the Common Garbage Collector Designs

Some of the common GC designs are: Copying Collector: Scan through all references to determine which objects are live (referenced) and copy

them to one half of the heap When finished, free up the old half Restart the application Repeat when free memory drops under a threshold Mark and Sweep: Scan through all references and mark the objects that are live Free up the areas occupied by dead objects Mark and Compact: Similar to Mark and Sweep except after the marking phase, the

live objects are copied to a free area and all of the area earlier occupied by objects is freed up

Generational:

Most objects in most programs only last for a brief time. It is more efficient to concentrate on freeing up memory from the short-lived objects

and spend as little time as possible checking on old but stable objects. The generational GC creates at least two sub-heap areas with one for short-lived

objects and the other for old objects. A Mark and Sweep or other GC algorithm would work on the short-lived heap. Those objects that last beyond a few cycles are moved to the long-lived heap, which is

only checked occasionally. These types of algorithms (as discussed in earlier slides) must interrupt the application

threads and complete their job before returning control. There are some algorithms that work in an incremental approach, rather than

completing a full clean-up at one go, and thus interfere less with the program.

Memory Leaks

Memory leak refers to the loss of free memory in the heap to unusable data as a program runs.

This can lead to inefficient memory utilization and eventually to a crash of the program when no free memory remains.

Even with the garbage collector, memory leaks can still occur in Java.

Examples for Memory Leaks

Examples of situations that create memory leaks include: Maintaining references to unneeded objects: For example, a method might create

temporary objects in the first section of the method and then go on to do other tasks such as a loop in which the temporary objects are no longer needed.

If references to the temporary objects remain, then the objects will not be collected and take up memory. In such cases the references should explicitly be set to null.

Page 346 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 347: Core Java Handout v1.0

Handout - Core Java

Waiting for finalizer: A class can override the finalize() method and use it to do clean up tasks before the

object is reclaimed by the GC. However, there is no way to know when the finalizer will be called and if a lot of

objects with finalizers are waiting for their final invocation, a lot of memory might be used up.

Generally, it is recommended to avoid application of the finalize() method and instead create a clean up method that you call explicitly when the object is no longer needed.

Try It Out

Problem Statement: Write a program that illustrates the working of Garbage Collector. Code: public class GarbageDemo {

Garbage g;

int max;

public static void main(String[] args) {

int n = 15;

if (args.length > 0)

n = (new Integer(args[0])).intValue();

GarbageDemo app = new GarbageDemo(n);

app.run();

}

public GarbageDemo(int n) {

max = n;

}

// continued …

Refer Files: Garbage.java, GarbageDemo.java to obtain soft copy of the program code How It Works:

This program is designed to quickly use up all of your memory resources by creating increasingly longer arrays of increasingly longer String objects.

The program takes an integer command-line argument, which you can use to specify the amount of resources it applies.

You set the default to 15, which allows the program to execute to completion when you run it under Windows XP Professional on a desktop with 2 GB of RAM.

If your computer has less RAM, then you may need to run the program with a value less than 15. Start at 14 and work backwards until your program is able to execute without running out of memory.

When you run the program on your desktop, it displays the following output: 11 is being collected.

Page 347 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 348: Core Java Handout v1.0

Handout - Core Java

10 is being collected. 9 is being collected. 8 is being collected. 7 is being collected. 6 is being collected. 5 is being collected. 4 is being collected. 3 is being collected. 2 is being collected. 1 is being collected. 12 is being collected.

This output is displayed by the finalize() method of each Garbage object, indicating that the Garbage Collector has determined that the object has become unreachable. (The finalize() method is invoked on an object by the Garbage Collector so that the object may perform cleanup before it is reclaimed by the Garbage Collector.)

The earlier output indicates that 12 Garbage objects were being finalized by the Garbage Collector.

These objects had become unreachable because they no longer were referenced by the g field variable of the GarbageDemo class.

To get an idea how this happened, look at the run() method:

void run() {

for(int i=1;i<max;++i) {

g = new Garbage(i);

}

}

With each iteration of the for statement, a new Garbage object is created and assigned to the g variable. When a new object is assigned to the g variable, the earlier object that was referenced by the g variable is no longer accessible by g or any other variable or object. Hence, that object becomes subject to Garbage Collection.

Tips and Tricks:

When will an object is eligible for garbage collection? Solution: An object becomes eligible for Garbage Collection when its last live reference disappears. Three ways to get rid of the reference:

The reference goes out of scope, permanently.

void go() {

Life z = new Life();

}

Here, the reference ‘z’ dies at the end of method The reference is assigned another object.

Life z = new Life();

z = new Life();

Page 348 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 349: Core Java Handout v1.0

Handout - Core Java

Here, the first object is abandoned when z is ‘reprogrammed’ to a new object. The reference is explicitly set to null.

Life z = new Life();

z = null;

Here, the first object is abandoned when z is ‘deprogrammed’.

Summary

In Java, garbage collection (GC) provides automated memory management. The purpose of GC is to delete objects that can’t be reached. Only the JVM decides when to run the GC, you can only suggest it. You can’t know the GC algorithm for sure. Objects must be considered eligible before they can be garbage collected. An object is eligible when no live thread can reach it. To reach an object, you must have a live, reachable reference to that object.

Test Your Understanding

1. State true or false for the following: a) Garbage Collection is a mechanism for reclaiming memory from objects that are

no longer in application, making the memory available for new objects. b) An object being no longer in application means that it still can be referenced by

any ‘active’ part of the program. c) Garbage Collection runs in a high priority thread. It will never kick in when memory

is too low.

Page 349 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 350: Core Java Handout v1.0

Handout - Core Java

Session 103: Garbage Collection

Learning Objectives

After completing this session, you will be able to: Describe the important GC Performance Metrics Identify the types of Garbage Collectors

Important GC Performance Metrics

Throughput: The percentage of total time not spent in garbage collection is considered over long periods of time.

Pause time: The length of time during which application execution is stopped while garbage collection is being performed is called the pause time.

Application Requirement: Different applications have different requirements: Higher throughput is more important for Web application: Pauses during Garbage

Collection may be tolerable, or simply obscured by network latencies. Shorter pause time is more important to an interactive graphics application

Types of Garbage Collector

The types of Garbage Collector are: Serial Collector Parallel Collector Parallel Compacting Collector Concurrent Mark-Sweep (CMS) Collector

Serial Collector

Serial Collector is used for most applications that are running on client-style machines, which do not have low pause time requirement.

Serial Collector is the default for client-style machines in Java SE 5. Serial Collector can be explicitly requested with XX:+UseSerialGC.

Parallel Collector

Parallel Collector is also known as Throughput Collector. This is applied for Java applications, which run on machines with a lot of physical

memory and multiple CPUs and do not have low pause time requirement: Infrequent but potentially long old generation GC can still occur Examples: Batch applications, billing, payroll, scientific computing, and so on Parallel Collector can be explicitly requested with XX:+UseParallelGC.

Page 350 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 351: Core Java Handout v1.0

Handout - Core Java

Parallel Compact Collector

Parallel Compact Collector is used for Java applications, which run on machines with a lot of physical memory and multiple CPUs and do have low pause time requirement. Parallel operations of old generation collection reduces pause time.

Parallel Compact Collector can be explicitly requested with XX:+UseParallelOldGC.

Concurrent Mark Sweep Collector

Concurrent Mark Sweep Collector is used when an application needs shorter pause time and can afford to share processor resources with GC when application is running Applications with relatively large set of long-lived data (a large old generation) and run multi-CPU machines Example: Web server Can be explicitly requested with:

-XX:+UseConcMarkSweepGC -XX:ParallelCMSThreads=<n>

Scheduling of collection handled by GC: Based on statistics in JVM Occupancy level of tenured generation:

-XX:CMSTriggerRatio -XX:CMSInitiatingOccupancyFraction

CMS Collector in Incremental Mode

CMS Collector can be used in a mode in which the concurrent phases are done incrementally:

Meant to lesson the impact of long concurrent phases by periodically stopping the concurrent phase to yield back processing to the application

Can be explicitly requested with XX:+CMSIncrementalMode.

Other Incremental CMS Options

Other incremental CMS options are: -XX:CMSIncrementalDutyCycle=<n%> (default: 50) -XX:CMSIncrementalDutyCycleMin=<n%> (default: 10) -XX:+CMSIncrementalPacing (default: true)

DutyCycle of 10 and DutyCycleMin of 0 can help certain applications

Page 351 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 352: Core Java Handout v1.0

Handout - Core Java

Tips and Tricks:

Provide some key points on Garbage Collection. Solution:

It is not possible to force Garbage Collection. Invoking System.gc may start garbage process.

Circular references do not prevent objects from being garbage collected. All objects have a finalize() method. It is inherited from the Object class. finalize() method is used to release system resources other than memory. finalize() method is called only once for an object. If an exception is thrown in finalize

(), then the object is still eligible for Garbage Collection (at the discretion of gc). gc keeps track of unreachable objects and garbage-collects them, but an unreachable

object can become reachable again by letting know other objects of its existence from its finalize() method (when called by gc). This ‘resurrection’ can be done only once, since finalize() is called only once for an object.

finalize() can be called explicitly, but it does not garbage collect the object.

Summary

Java applications can run out of memory. Islands of objects can be garbage collected, even though they refer to each other. Request garbage collection with System.gc(); (recommended). Class Object has a finalize() method. The finalize() method is guaranteed to run once and only once before the garbage

collector deletes an object. The garbage collector makes no guarantees, fianlize() may never run. You can uneligibilize an object for GC from within finalize().

Test Your Understanding

1. State true or false for the following: a) There is no guarantee on the order in which the objects will be garbage collected

or on the order in which the finalizers are called. Therefore the program should not make any decisions based on this assumption.

Page 352 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 353: Core Java Handout v1.0

Handout - Core Java

Session 105: Overview of Annotation

Learning Objectives

After completing this session, you will be able to: Define Annotation Explain the importance of Annotation Identify Built-in Annotations

How Annotations are Used?

Annotations are used to affect the way programs are treated by tools and libraries. Annotations are used by tools to produce derived files: Tools: Compiler, IDE, and Run-time tools Derived files: New Java code, deployment descriptor, and class files

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

Ad-hoc Annotation-like examples in pre-J2SE 5.0 platform: Transient Serializable interface @deprecated javadoc comments Xdoclet

J2SE 5.0 Annotation provides a standard, general purpose, and more powerful annotation scheme.

Need of Annotation

Annotation enables “declarative programming” style: Less coding because tool will generate the boiler plate code from annotations in the

source code Easier to change

Annotation eliminates the need for maintaining "side files" that must be kept up to date with changes in source files:

Information is kept in the source file (example) Eliminate the need of deployment descriptor

Page 353 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 354: Core Java Handout v1.0

Handout - Core Java

Built-in Annotations

Java defines seven built-in annotations. The following four are imported from java.lang.annotation:

@Retention @Documented @Target @Inherited

The following three are included in java.lang:

@Override @Deprecated @SuppressWarnings

Annotation Retention Policy

A retention policy determines at what point an annotation is discarded. Java defines three such policies of SOURCE, CLASS, and RUNTIME. The earlier policies are encapsulated within the java.lang.annotation.RetentionPolicy

enumeration. An annotation with a retention policy of SOURCE is retained only in the source file and

is discarded during compilation. An annotation with a retention policy of CLASS is stored in the .class file during

compilation. However, it is not available through the JVM during run time. An annotation with a retention policy of RUNTIME is stored in the .class file during

compilation and is available through the JVM during run time. RUNTIME retention offers the greatest annotation persistence.

@Retention

@Retention is designed to be used only as an annotation to another annotation. Its general form is as follows:

@Retention(retention-policy)

Here, retention-policy must be one of the earlier discussed enumeration constants. If no retention policy is specified for an annotation, then the default policy of CLASS is used.

The following example uses @Retention to specify the RUNTIME retention policy. Thus, the following annotation (MyAnno) will be available to the JVM during program execution.

@Retention(RetentionPolicy.RUNTIME)

@interface MyAnno {

String str();

int val();

}

Page 354 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 355: Core Java Handout v1.0

Handout - Core Java

@Documented

The @Documented annotation is a marker interface, which tells a tool that an annotation is to be documented.

It is designed to be used only as an annotation to an annotation declaration.

@Target

The @Target annotation specifies the types of declarations to which an annotation can be applied.

It is designed to be used only as an annotation to another annotation. @Target takes one argument, which must be a constant from the ElementType

enumeration. This argument specifies the types of declarations to which the annotation can be applied.

The following table shows the constants and the type of declaration to which they correspond:

Target Constant Annotation Can Be Applied To

ANNOTATION_TYPE Another annotation

CONSTRUCTOR Constructor

FIELD Field

LOCAL_VARIABLE Local variable

METHOD Method

PACKAGE Package

PARAMETER Parameter

TYPE Class, interface, or enumeration

You can specify one or more of the values (as shown in the earlier slide) in a @Target

annotation. To specify multiple values, you must specify them within a braces-delimited list. For example, to specify that an annotation applies only to fields and local variables,

you can use this @Target annotation:

@Target( { ElementType.FIELD,ElementType.LOCAL_VARIABLE } )

@Inherited

@Inherited is a marker annotation that can be applied only on another annotation declaration.

It affects only annotations that will be applied on class declarations. @Inherited causes the annotation for a super class to be inherited by a subclass.

Page 355 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 356: Core Java Handout v1.0

Handout - Core Java

@Override

@Override is a marker annotation that can be applied only on methods. A method annotated with @Override must override a method from a super class. If it

does not, then a compile-time error will result. It is used to ensure that a super class method is actually overridden, and not simply

overloaded.

@Deprecated

@Deprecated is a marker annotation. It indicates that a declaration is obsolete and has been replaced by a new form.

@SuppressWarnings

@SuppressWarnings specifies that one or more warnings that might be issued by the compiler are to be suppressed.

The warnings to suppress are specified by name, in string form. This annotation can be applied to any type of declaration.

Tips and Tricks:

Does the new feature in Java 2, v5.0 called ‘metadata’ is same as the ‘annotation’ feature? Solution:

Java 2, v5.0 adds a powerful new facility called metadata, which enables you to embed supplemental information into a source file.

This information, called an annotation, does not change the actions of a program. An annotation leaves the semantics of a program unchanged. However, this information can be applied by various tools, during both development

and deployment. For example, an annotation might be processed by a source-code generator. Although Sun refers to this feature as metadata, the term program annotation facility is

also applied, and is more descriptive.

Summary

All annotation types automatically extend the Annotation interface. Thus Annotation is a super-interface of all annotations. The Annotation interface is declared within the java.lang.annotation package. It overrides hashCode(), equals(), and toString(), which are defined by Object. It also specifies annotationType(), which returns a Class object that represents the

invoking annotation.

Page 356 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 357: Core Java Handout v1.0

Handout - Core Java

Test Your Understanding

1. State true or false for the following: a) There are totally seven of built-in annotations defined in Java. b) All built-in annotations are defined directly in the java.lang package. c) @Documented is one of the built-in annotations defined in java.lang.annotation

package. d) The target constant ANNOTATION_TYPE is available in the @Target built-in

annotation. e) RUNTIME retention offers the least annotation persistence.

Page 357 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 358: Core Java Handout v1.0

Handout - Core Java

Session 106: Overview of Annotation

Learning Objectives

After completing this session, you will be able to: Define an annotation Apply an annotation

How to “Define” Annotation Type?

Annotation type definitions are similar to normal Java interface definitions: An at-sign (@) precedes the interface keyword Each method declaration defines an element of the annotation type Method declarations must not have any parameters or a throws clause Return types are restricted to primitives, String, Class, enums, annotations, and arrays

of the preceding types Methods can have default values

Example: Annotation Type Definition

/**

* Describes the Request-For-Enhancement(RFE) that led to the presence of the annotated API element.

*/

public @interface RequestForEnhancement {

int id();

String synopsis();

String engineer() default "[unassigned]";

String date() default "[unimplemented]";

}

How To “Use” Annotation

Once an annotation type is defined, you can use it to annotate declarations like classes, methods, fields, parameters, and enum constant declarations.

An annotation is a special kind of modifier. It can be used anywhere in the statement whenever the other modifiers such as

public, static, or final are used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a

parenthesized list of element-value pairs.

Page 358 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 359: Core Java Handout v1.0

Handout - Core Java

Example: Usage of Annotation

Here is the declaration for an annotation called MyAnno: // A simple annotation type.

@interface MyAnno {

String str();

int val();

}

Here is an example of MyAnno being applied to a method.

// Annotate a method.

@MyAnno (str = “Annotation Example”, val = 100)

public static void myMeth() { // …

Three Different Kinds of Annotations

The three kinds of different annotations are: Marker annotation Single member (or value) annotation Normal annotation

Marker Annotation

A marker annotation is a special kind of annotation that contains no members. Because a marker annotation contains no members, determining the existence of the

marker annotation is sufficient. The best way to determine whether a marker annotation exists is to use the method

isAnnotationPresent(), which is defined by the AnnotatedElement interface. This interface is available in Class, Field, Method, Constructor, and Package.

Example:

import java.lang.annotation.*;

// A marker annotation.

@Retention(RetentionPolicy.RUNTIME)

@interface MyMarker { }

class Marker {

// Annotate a method using a marker.

// Notice that no parentheses ‘( )’ is needed.

@MyMarker

Single Member (or Value) Annotation

An annotation type with a single element where the element should be named “value” is called a single member annotation. Definition

Page 359 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 360: Core Java Handout v1.0

Handout - Core Java

/** * Associates a copyright notice with the annotated API element.

*/

public @interface Copyright {

String value();

}

Usage: Can omit the element name and equals sign (=). @Copyright("2008 Cognizant Technology Solutions")

public class SomeClass { ... }

Normal Annotation

Definition: public @interface RequestForEnhancement {

int id();

String synopsis();

String engineer() default "[unassigned]";

String date(); default "[unimplemented]";

}

Usage: @RequestForEnhancement(

id = 2868724,

synopsis = "Enable time-travel",

engineer = "Mr. Peabody",

date = "4/1/3007"

)

public static void travelThroughTime(Date destination) { ... }

Example: Definition and Usage of a User-defined Annotation

Definition of ‘Accessor’ annotation (user-defined): @Target(ElementType.FIELD)

@Retention(RetentionPolicy.CLASS)

public @interface Accessor {

String variableName();

String variableType() default "String";

}

Usage Example of the Accessor annotation: @Accessor(variableName = "name")

public String myVariable;

Page 360 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 361: Core Java Handout v1.0

Handout - Core Java

Note: The preceding annotation (Accessor) has a member with default value. The default value can be given for an annotation member if no value is specified when the annotation is applied.

Reflection

Reflection is a feature that enables information about a class to be obtained at run time.

The reflection API is contained in the java.lang.reflect package. There are a number of a ways to apply reflection. The first step for applying a reflection is to obtain a Class object that represents the

class whose annotation you want to obtain. If you want to obtain the annotations associated with a specific item declared within a

class, then you must first obtain an object that represents that item. From a Class, Method, Field, Constructor, or Package object, you can obtain a

specific annotation associated with that object by calling getAnnotation() as shown in the following code:

<T extends Annotation> T getAnnotation(Class<T> annoType)

Here, annoType is a Class object that represents the annotation in which you are interested. It returns a reference to the annotation. Using the reference, you can obtain the values associated with the members of the annotation.

The AnnotatedElement Interface

The methods such as getAnnotation() and getAnnotations() are defined by the AnnotatedElement interface, which is defined in java.lang.reflect package. This interface supports reflection for annotations and is implemented by the classes Method, Field, Constructor, Class, and Package. AnnotatedElement defines the methods as shown in the following slide. Therefore, these methods are available to any object to which annotations can be applied.

Methods Defined by AnnotatedElement

Method Description

<T extends Annotation> T getAnnotation(Class<T> annoType)

Returns the annotation of type annoType associated with the invoking object.

Annotation[ ] getAnnotations() Returns an array containing all annotations associated with the invoking object.

Annotation[ ] getDeclaredAnnotations()

Returns an array containing all noninherited annotations associated with the invoking object.

boolean isAnnotationPresent Class<? extends Annotation> annoType)

Returns true if an annotation specified by annoType is associated with the invoking object. It returns false otherwise.

Page 361 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 362: Core Java Handout v1.0

Handout - Core Java

Usage of Reflection in Annotations

Marker annotation:

boolean isBeta = MyClass.class.isAnnotationPresent(BetaVersion.class);

Single value annotation:

String copyright = MyClass.class.getAnnotation(Copyright.class).value();

Normal annotation:

Name author = MyClass.class.getAnnotation(Author.class).value();

String first = author.first();

String last = author.last();

Try It Out

Problem Statement: Write a program that applies a Marker annotation. Code: import java.lang.annotation.*;

import java.lang.reflect.*;

// A marker annotation

@Retention(RetentionPolicy.RUNTIME)

@interface MyMarker { }

class Marker {

// Annotate a method using a marker.

// Notice that no ( ) is needed.

@MyMarker

public static void myMeth() {

Marker ob = new Marker();

// continued …

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

The preceding example applies a marker annotation. It implements isAnnotationPresent() to determine if the marker is present.

Because a marker interface contains no members, simply determining its existence is sufficient.

The following output confirms that @MyMarker is present:

Page 362 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 363: Core Java Handout v1.0

Handout - Core Java

MyMarker is present.

In the program, notice that you do not need to follow @MyMarker with parentheses when it is applied. Thus MyMarker is applied simply by applying its name like this:

@MyMarker

It is not wrong to supply an empty set of parentheses, but they are not needed.

Tips and Tricks:

List out some of the restrictions that are applied to annotation declarations. Solution:

There are a number of restrictions that apply to annotation declarations. First, no annotation can inherit another. Second, all methods declared by an annotation must be without parameters. Furthermore, they must return one of the following: A simple type, such as int or double An object of type String or Class An enum type Another annotation type An array of one the preceding types Annotations cannot be generic. In other words, they cannot take parameters. Finally, they cannot specify a throws clause.

Summary

Java 2, v5.0 adds a powerful new facility called metadata, which enables you to embed supplemental information into a source file. This information called an annotation, does not change the actions of a program.

Metadata is created through a mechanism based on the interface. You can give annotation members default values that will be used if no value is

specified when the annotation is applied. A default value is specified by adding a default clause to a member’s declaration.

A marker annotation is a special kind of annotation that contains no members and its sole purpose is to mark a declaration.

A single-member annotation is another special kind of annotation that contains only one member.

Java defines seven built-in annotations. They are: @Retention, @Documented, @Target, @Inherited, @Override, @Deprecated and @SuppressWarnings.

Test Your Understanding

1. State true or false for the following: a) In the single-member or single value annotation, the name of the member must be

element. b) A marker annotation is a special kind of annotation that contains no members.

Page 363 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 364: Core Java Handout v1.0

Handout - Core Java

Session 108: Updates in JDK 1.6

Learning Objectives

After completing this session, you will be able to: Describe the key features of Java SE (Standard Edition) 6 (JDK 1.6)

The Java SE 6 (JDK 1.6) Top 10 Features

The top 10 features of JDK 1.6 are: Scripting Web Services Database (JDBC 4.0, Java DB) More Desktop APIs Monitoring and Management Compiler Access Pluggable Annotations Desktop Deployment Security Quality, Compatibility, and Stability

Motivation for Scripting Support

Scripting support provides developers an opportunity to leverage the advantages of different languages in the same application.

It extends scripting languages applying the powerful Java technology libraries. It provides reuse of code modules in other programming languages. It produces an environment in which developers and end users can collaborate to

create more useful and dynamic applications. You can now mix in JavaScript technology with your Java technology source code,

useful for prototyping. Also useful when you have teams with a variety of skill sets. o Scripting for the Java Platform (JSR 223): o Mechanism for configuring script engines into Java SE o APIs for mixing script fragments into Java applications o A JavaScript engine is included in the implementation of Java SE 6 of Sun: o Mozilla Rhino engine o Conformant scripting engines: scripting.java.net

Page 364 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 365: Core Java Handout v1.0

Handout - Core Java

Scripting: Developer Example

// create a ScriptEngineManager

ScriptEngineManager m = new ScriptEngineManager();

// get an instance of JavaScript script engine

ScriptEngine engine = m.getEngineByName("js");

// evaluate a script

engine.eval("alert(\"Hello World!\")");

Web Services Support on Java SE 6 Platform

JAX-WS Data binding using JAXB 2.0 Updates to the JAXP, which includes StaX

Standards supported are:

SOAP 1.2 WS-I Basic Profile 1.1 XML-binary Optimized Packaging (XOP) and SOAP Message Transmission

Optimization Mechanism (MTOM) Representational State Transfer (REST) Totally on XML schema

API Support

Java SE 6 provides support for the JAX- WS Web services stack. For the client side: Service class for creating proxy For the server side: Endpoint class for publication

Database: JDBC 4.0 Support

Developers will get the updated JDBC 4.0, which focuses on ease of use. It contains many feature additions like support for XML as an SQL datatype and better

integration of Binary Large OBjects (BLOBs) and Character Large OBjects (CLOBs) into the APIs.

Additional features that improve ease of use include removal of some JDBC boilerplate and some of the new annotations that make SQL strings embed better into your JDBC application – like decorating your getAllUsers() method with an @Query(sql=”select * from user”) annotation, and that being all you need.

Page 365 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 366: Core Java Handout v1.0

Handout - Core Java

Java DB

Java DB is based on Apache Derby: JDBC conformant all-Java relational database Bundled and pre-configured in JDK

Desktop APIs

AWT (Abstract Window Toolkit) improvements are: Tray icon Splash screen Desktop class Dialog Modality enhancements and API Text printing

Swing improvement: GroupLayout: Basis for NetBeans GUI Builder (Matisse) JTable sorting and filtering SwingWorker

Tray Icon

Tray icon lets you to access the system tray in your Java application:

SystemTray TrayIcon

Tray icon gives you the ability to add graphics, popup menus, and floating tip functionality to the system tray.

Tray Icon: Usage

// Construct a TrayIcon

TrayIcon trayIcon = new TrayIcon(image, "Tray Demo", popupMenu);

// Add event listener

trayIcon.addActionListener(actionListener);

// Add the tray icon to the System tray

SystemTray.getSystemTray().add(trayIcon);

Page 366 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 367: Core Java Handout v1.0

Handout - Core Java

Splash Screen: Overview

Before Java SE 6, Java run time needs to be fully loaded and initialized before a visual image can be displayed.

Splash screen allows displaying a splash screen for the application instantly before the Java runtime software starts:

GIF (Graphic Interchange Format), PNG (Portable Network Graphics), and JPEG (Joint Photographic Experts Group) images supported

Transparency, translucency, and animation supported Closed automatically when first top-level window displays

Splash Screen: Usage

Display from command line: java -splash:image.gif TheApp

Display from MANIFEST.MF (in a jar file): Splashscreen-Image: image.gif

Painting: You can change the image shown after the splash screen is loaded, but before the application starts. SplashScreen splash = SplashScreen.getSplashScreen();

Graphics2D g = splash.createGraphics();

// your painting code here

splash.update();

Desktop APIs

GUI developers get a large number of new tricks to play like the ever popular yet newly incorporated SwingWorker utility to help you with threading in GUI apps, JTable sorting and filtering, and a new facility for quick splash screens to quiet impatient users.

Desktop class has an enumeration of actions that may be supported for a file or URI like BROWSE, EDIT, MAIL, OPEN, and PRINT.

File processing: Opening, editing, and printing files with applications registered in native system

Browsing: Opening a URL with the default browser Email: Sending a message with the default mail client

Dialog Modality Enhancement

New modality model is introduced: This new model allows the developer to scope, or limit the modality blocking of a

dialog box, based on the modality type that the developer chooses. This new model allows windows and dialog boxes to be truly parentless. This new model solves the problem of interacting with JavaHelp in J2SE 1.5 when

modal dialog box is on the front.

Page 367 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 368: Core Java Handout v1.0

Handout - Core Java

Modality Types

The modality types are: modeless: Does not block any other window document-modal: Blocks input to all top-level windows from the same document application-modal: Blocks all windows from the same application toolkit-modal: Blocks all windows that run in the same toolkit

New Dialog Modality API

Sample dialog boxes

Text Printing

Text printing easily print a Swing text component: o Prints the entire contents of the text component o Does not have to be visible o javax.swing.text.JTextComponent.print();

Text printing reformats for printed page. It optionally displays print dialog and progress box. It supports optional header or footer. It will not split lines in half!

Page 368 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 369: Core Java Handout v1.0

Handout - Core Java

SwingWorker

SwingWorker makes it easy to offload work to separate threads. It makes use of concurrency package. It makes it more generic. It supports partial results. It supports PropertyChangeListener. More information: http://java.sun.com/docs/books/tutorial/uiswing/concurrency/

javax.swing.GroupLayout Class

This class is a new layout manager to support new Matisse GUI builder that is NetBeans™ IDE ships with Matisse

Can also apply GroupLayout in J2SE 1.5 software implementing stand-alone library This has more capabilities for relative positioning of components. This works with horizontal and vertical layout separately.

JTable Sorting and Filtering

JTable sorting and filtering add sorting to your JTable with one method call: setAutoCreateRowSorter(true)

This specify your own comparators This supports secondary and tertiary sort columns

Monitoring and Management

The potential problems that can be detected are: o Memory leaks o Thread deadlocks o Dirty references o Infinite loops

jps: Lists JVMs jconsole: Can connect to applications that did not start up with the JMX (Java

Management Extensions) agent jmap: Takes a detailed 'photograph' of what is going on in memory at any one point in

time jhat: Forensic expert that will help you to interpret the result of jmap jstack: Takes a 'photograph' of all the threads and what they are up to in their own

stack frames Compiler Access:

Compiler access opens up programmatic access to javac for in process compilation of dynamically generated Java code.

This is really aimed at people who create tools for Java development and for frameworks:

Page 369 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 370: Core Java Handout v1.0

Handout - Core Java

JavaServer Pages (JSP) or PHP construction kit engines that need to generate a bunch of classes on demand

Average developers will benefit indirectly from faster performing tool The compiler API is not directly intended for the everyday developer, but for those of

you deafened by your screaming inner geek, roll up your sleeves and give it a try.

Pluggable Annotations

JSR 175 of JDK 5 standardized how annotations are declared in Java code but annotation processing details were relegated as an implementation detail. Java tool and framework vendors (and you) can define annotations and have core API support for plugging in and executing the processors that do the heavy lifting. It seamlessly integrates your custom annotations. Processing API standardizes annotation processing as well. The annotation processors act as plug-ins to the compiler, hence "pluggable annotation processing”.

Desktop Deployment

Desktop deployment improved actual performance: Graphics hardware acceleration on Windows

It perceived performance: True double buffering It improved the native look and feels: o Updated Swing Look and Feel Windows/Unix o LCD text rendering

It revamped Java Web Start and JRE installations: No more scary security dialog

Windows Look and Feel Improvements SwingSet on Vista with 5.0

Windows look and feel improvements SwingSet on Vista with 5.0 is shown in the following screenshot:

Page 370 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 371: Core Java Handout v1.0

Handout - Core Java

Sample screen shot on Vista with Java 2, v5.0

Windows Look and Feel Improvements SwingSet on Vista with 6

Windows look and feel improvements SwingSet on Vista with 6 is shown in the following screenshot:

Page 371 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 372: Core Java Handout v1.0

Handout - Core Java

Sample screen shot on Vista with Java 2, v6

Security

Security added important new APIs: XML Digital Signature (XMLDSig) API (JSR 105) Smart Card I/O API (JSR 268)

Security improved authentication schemes:

JAAS-based authentication using LDAP Native Platform Java GSSAPI (Generic Security Services Application Programming

Interface) Java SE 6 has simplified the job of its security administrators by providing various new ways to access platform-native security services, such as native Public Key Infrastructure (PKI) and cryptographic services on Microsoft Windows for secure authentication and communication, Java Generic Security Services (Java GSS) and Kerberos services for authentication, and access to LDAP servers for authenticating users.

Page 372 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 373: Core Java Handout v1.0

Handout - Core Java

Quality, Stability, and Compatibility

Sun has around 80,000 test cases and several million lines of code testing conformance.

People have been downloading (and testing) snapshots of Java SE 6 (Mustang) for the last 15 months and filing bugs.

So even before beta release, several quality and regression issues were fixed. Performance is claimed to be better than J2SE 5.

Performance Improvement

Client Benchmark: SwingMark

Server Benchmark: SPECjbb2000

Page 373 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 374: Core Java Handout v1.0

Handout - Core Java

Running Applications on Java SE 6

Applications run faster on the desktop and servers. New 'Dynamic Attach' diagnostics simplify troubleshooting. Expanded Solaris DTrace support provides additional value on Solaris. The Swing Look&Feel of the applications deployed in Windows/Unix is greatly

enhanced.

Building Applications on Java SE 6

This JSR 223 specification introduces the basic technical background to bridge the scripting and the Java community.

The JSR 223 specification is concerned with how to write and package Java classes that will be accessible from different scripting engines.

The Java classes may be part of a Servlet application or may be in a standard Java VM.

Scripting languages framework extends support for Ruby, Python, and other languages.

With Java SE 6, applications can use JAX-WS to build web applications and web services, incorporating the newer XML-based web services functionality.

JDK 6 uses: (i) the host desktop's font smoothing settings to ensure consistent text rendering, (ii) the new desktop integration features, and (iii) the new Dialog modality options.

Building Applications on Java SE 6

The JDBC 4.0 API specification seeks to improve Java application access to SQL data stores by the provision of ease-of-development focused features and improvements at both the utility and API level.

Java DB is ideal for: o Departmental Java client-server applications that need up to 24 x 7 support and

the sophistication of a standards-based, transactional SQL database that protects against data corruption or systems crashes without also requiring a database administrator.

o Multi-platform use due to Java portability. And, because Java DB is fully standards-compliant and 100% Java, it is easy to migrate an application using Java DB to other open standard databases.

The NetBeans IDE fully supports Java SE v5.5, v5.5.1 and v6.0

Summary

The key features of Java SE 6 (Mustang) (JDK 1.6) are: o Scripting o Web Services o Database (JDBC 4.0, Java DB) o More Desktop APIs o Monitoring and Management o Compiler Access o Pluggable Annotations

Page 374 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 375: Core Java Handout v1.0

Handout - Core Java

o Desktop Deployment o Security o Quality, Compatibility, and Stability

Test Your Understanding

1. State true or false for the following: a) JDBC 4.0 is available with Java SE v5 (Tiger). b) With Java SE 6, applications can use JAX-WS to build web applications and web

services, incorporating the newer XML-based web services functionality. c) A JavaScript engine named as Mozilla Rhino engine is included in the Sun’s

implementation of Java SE 6.

Page 375 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 376: Core Java Handout v1.0

Handout - Core Java

Glossary

ANT Another Neat Tool

API Application Programming Interface

ASCII American Standard Code for Information Interchange

AWT Abstract Windows Toolkit

BLOB Binary Large OBject

CLOB Character Large OBject

CMS Concurrent Mark Sweep

DB DataBase

EJB Enterpise Java Bean

GC Garbage Collection

GIF Graphic Interchage Format

GSSAPI Generic Security Services Application Programming Interface

GUI Graphical User Interface

HTML HyperText Markup Language

I/O Input/Output

IDE Integrated Development Environment

J2SE Java 2 Standard Edition

JAAS Java Authentication and Authorization Service

JAR Java Archive

Java SE Java Standard Edition

JAX Java API for XML

JAXB Java Architecture for XML Binding

JAXP Java API for XML Processing

JAX-WS Java API for XML Web Services

JDBC Java DataBase Connectivity

JDK Java Development Kit

JMX Java Management eXtensions

JPEG Joint Photographic Experts Group

JRE Java Runtime Environment

JSP Java Server Pages

JSR Java Specification Request

JVM Java Virtual Machine

LCD Liquid Crystal Display

LDAP Lightweight Directory Access Protocol

MTOM Message Transmission Optimization Mechanism

Page 376 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 377: Core Java Handout v1.0

Handout - Core Java

PHP PHP: Hypertext Preprocessor (HTML-embedded scripting language)

PKI Public Key Infrastructure

PNG Portable Network Graphics

REST Representational State Transfer

SDE Standard Development Environment

SOAP Simple Object Access Protocol

SQL Structured Query Language

URL Uniform Resource Locator

WS Web Service

XML eXtensible Markup Language

XMLDSig XML Digital Signature

XOP XML-binary Optimized Packaging

XSLT eXtensible Stylesheet Language Transformation

Page 377 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 378: Core Java Handout v1.0

Handout - Core Java

References

Websites

http://java.sun.com http://www.javapassion.com http://www.jspwiki.org/wiki/ExternalClassProblemInJUnit http://www.stanford.edu/class/cs193j/slidesSummer2003/ http://www.particle.kth.se/~lindsey/JavaCourse/Book/courseMap.html

Books

Head First Java – 2nd edition – Kathy Sierra & Bert Bates Java 2, v5.0 (Tiger) New Features – Herbert Schildt Essentials of Java Programming – C.Muthu Sun Certified Programmer for Java 5 - Exam Study Guide - Kathy Sierra & Bert Bates

Page 378 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 379: Core Java Handout v1.0

Handout - Core Java

Page 379 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

STUDENT NOTES: