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

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

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

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

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

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

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

..................................113  Tips and Tricks: ..........................................................................................................................................121  Autoboxing .........................122  Method Arguments ..........................................................................................117  Converting Primitive Types to Objects (Wrapper) and the Reverse ..................................................................................................................................... All Rights Reserved C3: Protected .............123  Autoboxing With Switch Statement .................................................113  Try It Out ..............................................................116  Learning Objectives .........................................................................................................................................................................................................................................................116  Why Should You Use Wrapper Classes? ..................................................................................117  Wrappers are Immutable .........................................................................120  Learning Objectives ........121  Converting Primitive Types to Strings (Example) ....................................112  Detailed Example.................... Selection Statements and Iteration Blocks .................123  Boolean Expressions .....Core Java Key Points on enum and its Constructor ..........................................112  Output .............................114  Summary ..............................................................................................................................................................................................................................................124  Try It Out .......................................122  With Autoboxing (Java versions 5.................................................120  Primitive Types: Wrapper Classes ......................................................................................................................................................................124  Tips and Tricks: ....................................................................................................................................................................................119  Session 27: Wrapper Classes.........118  Tips and Tricks: ..........................................................................................................................................................................................................123  Return Values .........................................................................................................119  Summary ........................115  Session 26: Wrapper Classes.....................................................................................................122  Without Autoboxing (Java versions before 5......................................................................................................................0 or greater) ....................................................................................................................................................126  Page 8 ©Copyright 2007...................................126  Test Your Understanding.......................................................................................................................114  Test Your Understanding..........................................................116  The Wrapper Classes ..............................................................................................................123  Assignments ............122  Autoboxing Illustrations ............... Cognizant Technology Solutions...........................................................125  Summary ..........................................................................................................................................................................................................................................120  Converting Strings to Primitive Types .........................................................................................................................Handout ......................................120  Converting Primitive Types to Strings ...................................................119  Test Your Understanding............................................................................................... Selection Statements and Iteration Blocks ..................................0) .........................................118  Try It Out ....................................................................................................................................................................................................................................123  Operations on Numbers .....................................................................

............................................................... Cognizant Technology Solutions.....................................................135  Summary .................................................................................................................................................................................138  Coding Guidelines ........................................................................................... All Rights Reserved C3: Protected ........................................................................140  Labeled Break Statement .....................................................................................................................................139  Example of for-loop .........................................................................................................................................132  Flowchart of switch Statement................138  Examples of do-while-loop ...............................................................................................................................................129  if-else Flowchart.................... Selection Statements and Iteration Blocks ...........................................................131  Sample Program ........................................131  Common Errors ..........................140  Example of Unlabelled Break Statement .................................134  Tips and Tricks: ....................................................................................................139  for-loop........................................................................................................135  Session 31: Wrapper Classes.............................130  if-else-else if Statement ....................................................................................128  Coding Guidelines .137  Repetition Control Structures ................................................................................................................................................................................................................................................................................................................................................139  Branching Statements ....................................................Handout ..................................................127  if-statement .................................................................................................................................................................................................................................................................................................129  Coding Guidelines ..130  Example of if-else-else if Statement ................................................................128  if-else Statement .............................................................................................134  Try It Out ................................Core Java Session 30: Wrapper Classes..........................................................................................................................................................137  while-loop.............................. Selection Statements and Iteration Blocks ........137  Learning Objectives .............................................................135  Test Your Understanding..................................................................................................................................................................................................................................................................................................................127  Learning Objectives .........................................................................................133  Coding Guidelines ...................................................................................................................................................127  if-statement Flowchart ..............................................................................................................127  Control Structures .....130  if-else-else if Flowchart ........................................140  Unlabelled Break Statement ....................................................................................................................................................129  Examples of if-else Statement ....................................................................................................................................127  Decision Control Structures ...................................................................................................................................................................................................................132  switch Statement ..............................................................140  Page 9 ©Copyright 2007.....................................137  do-while-loop ........................................................................................................................................................128  Examples of if-statement ...............................................................................137  Examples of while-loop ....................................

................150  Sample Source Code that uses StudentRecord Class............................................................................................................. Constructors and Methods..........................................................................................146  Applying Constructors .......................................................................................................... All Rights Reserved C3: Protected ......................................................................................................................................................................................................................149  Example: Multiple Return Statements .146  Example of “this()” Constructor Call ..........................................................................................................147  Declaring Methods .....................................................148  Accessor (Getter) Methods...........................................145  Constructors ...................................................................................................................................................142  Tips and Tricks: ........................................150  Source Code for StudentRecord Class .............................................150  When to Define Static Method? . Cognizant Technology Solutions............................................145  Overloading Constructor Methods .142  Try It Out ................................................................................................155  Method Overloading ........141  Return Statement .................................................................................................................................................................................................147  Example of “this” Reference ...........................................................................................................148  Example 2: Accessor (Getter) Method ..........................................................................................................................................................................................................................149  Static Methods ...........................................153  Test Your Understanding..........................................................................................................................................................................................................................................................................................................................................143  Summary ...........................................................................................................................................................................................................................................................150  Coding Guidelines ...............145  Default Constructor (Method) .........................................................................Core Java Example of Labeled Break Statement ...........................................................................................................147  “this” Reference .....153  Summary ...............................................................................................146  “this()” Constructor Call .....152  Tips and Tricks: .............................................................................................................................................................................................................. Constructors and Methods.....154  Session 38: Access Specifiers........................................143  Test Your Understanding......................................................148  Example 1: Accessor (Getter) Method ..........148  Mutator (Setter) Methods ...................................................................................................151  Try It Out ....................................................................................................................................................................................................................................................................................................................................................155  Learning Objectives ..................................149  Multiple Return Statements .....................................143  Session 35: Access Specifiers......................................................141  Labeled Continue Statement ..........Handout ...............................141  Unlabelled Continue Statement ..................155  Page 10 ©Copyright 2007......................................................................................................................................................................................................145  Learning Objectives ................................................................................................................................

......................................................................................................166  How Constructor Method of a Super Class gets Called ................158  Session 39: Access Specifiers................................................................................... Constructors and Methods.....................................................................................................................................................................................................................................................................................................................163  Session 42: Inheritance..............................................................................................................162  Summary .....................................................161  Try It Out .............................166  Superclass and Subclass .....................................................................................................................................................................................................................................................................................................................164  Deriving a Subclass ....................165  What you can do in a Sub-class Regarding Methods ..........................................................................................................................................................................................................................................................164  extends Keyword .......................................................166  Page 11 ©Copyright 2007..................................159  protected Accessibility ............................................159  Example: “public” Access Modifier ...............................................................................165  What you can do in a Sub-class Regarding Fields.................................................................................................................................................................................................................................166  Class Hierarchy ..............................................................................................................................................157  Summary .....................................163  Test Your Understanding.......................................................................................................................................................................................................................................................................................165  What you can do in a Subclass ......................................................................................................158  Test Your Understanding.......161  Java Program Structure: The Access Modifiers .............160  default Accessibility ..............................160  Example: “private” Access Modifier .............................160  Example: “protected” Access Modifier ................155  Program Output ................................165  Object Class ..................................................... Cognizant Technology Solutions........................................................................160  Example: “default” Access Modifier ......................................................................................................................................................................156  Tips and Tricks: .............................164  Learning Objectives ..............164  Inheritance ...................................161  Coding Guidelines ..............................Handout ........................................................................................................................................................................164  Importance of Inheritance ..........160  private Accessibility ..................... Interfaces and Abstract Classes ................................................................................159  Learning Objectives ...............................................................................................................................................Core Java Example of Method Overloading ......................................................................................................................................................................................159  Access Modifiers................................................................................................................ All Rights Reserved C3: Protected .............................................................................................156  Try It Out ...............................................................................161  Tips and Tricks: .....................................................................................................166  Example: Constructor Calling Chain....................159  public Accessibility ................

...................................................................................................................................................................................................................172  Session 46: Inheritance.....................................................170  Hiding Fields ..........................174  Sample Abstract Class ......................................169  Example: Coding of Hiding Static Method ................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................177  Interface as a Type .....................................................................................................................175  What is an Interface? ..........176  Example 2: OperatorCar Interface........................177  Interface versus Class: Commonality ............177  Example: Interface as a Type ................175  Example 1: Interface ...................................................................................169  Example: Run-time Polymorphism .....177  Interface versus Class: Differences ...............167  The “super” Keyword .............................................................................................................................................................................................167  Overriding Methods ....................................................................170  Example: Overriding Method Versus Hiding Method During Runtime .....................................................................................178  Defining Interface..................................................175  When to use Abstract Methods and Abstract Class ..........174  Extending An Abstract Class ...........................................................................................................176  Why do you use Interfaces? Reason #2 ..................168  Modifiers in the Overriding Methods .........................................................................................................................................................................................172  Test Your Understanding.......................174  Abstract Methods ..........................................................168  Example: Overriding Methods ...............................................176  Why do you use Interfaces? Reason #3 ................................................................................................................................................................................................................177  Interface versus Abstract Class ................................................................................................................................................169  Overriding Method Versus Hiding Method ........170  Tips and Tricks: ..................174  Abstract Class.....................................................................................................................................................................................................................169  Hiding Methods .......... All Rights Reserved C3: Protected ................................... Interfaces and Abstract Classes ............................................................. Cognizant Technology Solutions.....................................................................................................................179  Relationship of an Interface to a Class .....................................................169  Run-time Polymorphism with Overriding Methods ................................................................................................................................................................................................178  Implementing Interfaces ..................................................170  Try It Out ........................................................179  Page 12 ©Copyright 2007..........................................................................................................................178  Implementing Class .................................................174  Learning Objectives ............................................................................................................................................................176  Why do you use Interfaces? Reason #1 ........................................................................................................................................................................................172  Summary .................Core Java Example: Constructor Calling Chain............................Handout ..................................................................................................

................................................................................................................................................................................................188  Casting Objects .........................................187  Significance of Type .............................................................................................................................................................................................................184  Using IS-A and HAS-A ...........................................................181  When to use an Abstract Class Over Interface? ...............................187  Implicit Casting .........................................................................................................................191  Summary ........................................189  Explicit Type Casting .............................................187  Learning Objectives ...187  What is a “Type”? ..............................180  Inheritance among Interfaces ........190  Runtime Type Mismatch Exception ............................ All Rights Reserved C3: Protected ......................................................................................................................................................................................................................................................................................................................................................................................................................................................188  Explicit Casting: Example .................................................182  Summary ...................................................................................................................................186  Test Your Understanding.....................................................................................................................................188  Explicit Casting .....................................................................183  Session 48: Inheritance............................................................................................................188  Implicit Casting: Example .....185  Summary ....................180  Interface and Polymorphism ..........................189  Implicit Type Casting .....................................................................180  Problem of Rewriting an Existing Interface ....................................................190  Use instanceof Operator To Prevent Runtime Type Mismatch Error ....................182  Test Your Understanding............................192  Page 13 ©Copyright 2007..........................................................................................................................................................................................185  Tips and Tricks: .......................................................................................................................................................................................................................................................................................................................................181  Tips and Tricks: .....................................................................................................................................................................................................186  Session 49: Inheritance..................................................................................................................................................................................................................................................................181  Try It Out ......................................Core Java Example: Implementing Multiple Interfaces .......................................................................................................................................................184  IS-A Relationship Test ...........180  Solution of Rewriting an Existing Interface ...............................Handout ............................................................... Interfaces and Abstract Classes ..............................................................................................184  Try It Out ....................................................................188  Casting Objects: Example ................................................................................................................................................................................................................................184  Learning Objectives .........187  Casting Primitive Types ..................................................... Cognizant Technology Solutions.....................................................190  Tips and Tricks: .. Interfaces and Abstract Classes ...............................................................................190  Try It Out ..........................................................................189  Type Casting Between Objects ...........

...........................204  Separating Error Handling Code from Regular Code ...........................................................................................................................200  Expressions View .........................................................194  Nested Classes versus Inner Classes ........................................................................................................................... Cognizant Technology Solutions......................................................................................200  Display View ........................................................195  Tips and Tricks: ....................................204  Benefits of Java Exception Handling Framework .........................................................................199  Debug View ............ Interfaces and Abstract Classes .....193  Java Program Structure: Inner Classes .....................................................................................................................................................................................................................................................................................................................194  Static Nested Class: Example .................................................................................................................200  Tips and Tricks: .........................200  Registers View .......................................................................................................202  Example: Default Exception Handling .....................................................................193  Inner Class...........................................................199  Breakpoint View ....................................................................202  Learning Objectives .....................................204  Page 14 ©Copyright 2007.........................193  Static Nested Classes ...............................................................................................................................................................................195  Try It Out ...........................................................................................202  Exception .....................................194  Anonymous Classes .................................202  Exception Example ...........................................................................................................................195  Anonymous Inner Class: Example .................................................................................................................................................197  Test Your Understanding.........................................................................................193  Accessing Members of Outer Class Within an Inner Class ........................................................................................................... Interfaces and Abstract Classes ............................................... All Rights Reserved C3: Protected ........................................................................Core Java Test Your Understanding.................................................................................................................................203  Searching the Call Stack for an Exception Handler ..............................................................................................................................200  Summary .................201  Test Your Understanding.............................................196  Summary .............................................................................................................................................................................................Handout ............................................................................................................................................................199  Learning Objectives ..........................198  Session 52: Inheritance................................................................................................................................................................195  Anonymous Inner Class: Example .................................................................................................201  Session 54: Exception Handling .........................193  Learning Objectives .............................................................................................................................199  Console View ..............................................................................................192  Session 50: Inheritance.............................................................................................202  What Happens when an Exception Occurs? .................................................................................

............................................219  Checked and Unchecked Exceptions ................................................................................................................................214  Traditional Way of Propagating Errors ..................................................................................................................................................................Core Java Traditional Programming: No Separation of Error Handling Code .......................................................................................217  Summary ..............................214  Example: Throwing Exceptions ..................................................................................................................................................................................................................................212  Summary ............223  The String Class ...........................................................................208  Catching Exceptions: Nested trys..........................................................218  Test Your Understanding............................................................220  Tips and Tricks: ........................................................................207  Catching Exceptions: Multiple catch .................................................................................................................................................................................................................................................................................................. and its Functions ................................................... All Rights Reserved C3: Protected ............................................................................................................................222  Summary .................................219  How to use Your own Exceptions ............................219  Try It Out ........................................................................................................223  Page 15 ©Copyright 2007... Cognizant Technology Solutions.....................................................................................................................210  Tips and Tricks: ........................................213  Session 55: Exception Handling ...................219  Learning Objectives ..............Handout ...................................................................214  Throwing Exceptions: The throw Keyword .................................................................................................................216  Try It Out .......................................... String Buffer......................................................................................................................................................................................................................................................................................................................................................................................................................208  Catching Exceptions: Nested trys with Methods .......................................................205  Separating Error Handling Code from Regular Code .....................214  Propagating Errors up the Call Stack .......................................................222  Session 61: Strings.......................215  Using Java Exception Handling .......................................................................................................................................................223  Learning Objectives .....214  Learning Objectives .........................................................................................................................................205  Exception Class Hierarchy ....................................219  Creating Your Own Exception Class ...........................216  Grouping and Differentiating Error Types ..........................................................................................................................................222  Test Your Understanding..........208  Catching Exceptions: The finally Keyword .218  Session 58: Exception Handling .............................206  Catching Exceptions: The try-catch Statements ............................................................................................................................................212  Test Your Understanding.....................................................................................................................................................217  Tips and Tricks: ..............................................................................................................................................209  Try It Out ........................................................

....................................................................................231  Tips and Tricks: ................................................................234  The StringBuffer Class: Example .................................................................225  Summary ...................Core Java The String Class: Constructors........................................229  Test Your Understanding...............................................................................................................................................................................226  Session 62: Strings.......................................228  Tips and Tricks: .......................................................... and its Functions ........................................................................................................................................................................ String Buffer.............................................................................................237  Test Your Understanding...............................231  Learning Objectives ......................................................................................................239  Collection .............. String Buffer................................................224  Tips and Tricks: ..234  Learning Objectives .............................................................................................................................................................................................................................................................................................................................................................................235  Try It Out ..........238  Session 69: Collections and Util package ...............................................................................................................................................................................................................................lang.......................................... and its Functions ..............................................................................................................229  Summary ..........................................232  Summary .............................................233  Session 66: Strings...........................233  Test Your Understanding..........................................................................................................................................................................224  Try It Out ..... Cognizant Technology Solutions..... String Buffer........................................................231  Java Object Law for equals() and hashCode() Methods ..........................................................234  The StringBuffer Class ......................................................................................................................................................................................................................................................227  Learning Objectives ..........................................................226  Test Your Understanding............................................................................................................................................ All Rights Reserved C3: Protected ................................................................................239  Collection Framework ................................................................................................................239  Benefits of Collection Framework ...............................................................................................................................................................................................................................................230  Session 65: Strings...................................................................................................................................................223  The String Class: Methods ..........227  The String Class: Example .........................................227  Try It Out ................................................................231  Try It Out ....Handout ..............................239  Learning Objectives .............................234  The StringBuffer Class: Methods............... and its Functions ...........................................234  The java.............237  Summary ................................................................................236  Tips and Tricks: .....StringBuilder Class ..................................................................................................................................................239  Page 16 ©Copyright 2007................................................................................................

...........................................240  General Purpose Implementations ...........................................................246  Learning Objectives .................................................................................................................................................................................................................249  Example: Set Interface and LinkedHashSet ....................................................................................................................................250  Implementations of “List” Interface .................................241  “Collection” Interface (Java SE 5)...................................................................................243  Try It Out ...............................................................................................................................................................................................................246  “equals” Operation of Set Interface ........................................241  Core Collection Interfaces ...........247  Caveats of Using HashSet .....................................................................................................................................................................242  add() and remove() Methods of Collection Interface ......................................................Core Java Collection Interfaces ..........................................................................................................240  Core Collection Interfaces Hierarchy ......................................................................243  Tips and Tricks: ...............................................................................................................241  “Collection” Interface .............................................242  Bulk Operations .....................................250  “Map” Interface .................................................................................242  Example: removeAll() .............................................................................................................248  LinkedHashSet ..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................243  Array Operations..................246  “Set” Interface ..247  Implementations of “Set” Interface ....................................................................................................247  Example: Set Interface and HashSet ..............................241  Example: Usage “Collection” Interface as a Type ............................240  Implementations .................................................................................................................................................................250  Page 17 ©Copyright 2007.....................................................Handout ...........................................................................................................................243  Example: Array Operations ................................................................................................................................................................. Cognizant Technology Solutions....247  TreeSet ..................................................249  “List” Interface ....240  Types of Implementations .......................................................................................248  Example: Set Interface and TreeSet ...........................................247  “SortedSet” Interface ......244  Summary ..............246  “Set” Interface (Java SE 5) ................................................................................................................................................................................................................................................................................................................................................247  HashSet ...........................................................................................................................................................................................................................................................................................................................................................................245  Session 70: Collections and Util package .................................................................249  Additional Operations Supported by “List” Interface over “Collection” ...........240  Algorithms ............................................... All Rights Reserved C3: Protected ................................................245  Test Your Understanding................................249  “List” Interface .

....................................................................................................................................254  Summary .................................................255  Test Your Understanding..............................................................................260  The Date Class: Example ..............................................................................................................256  Iterator Interface .............................................................................................................................................261  Tips and Tricks: .................................260  Learning Objectives .................................262  Summary ............................................................................................................................................................................................................................................................................253  Composition ........................................................260  The Properties Class: Example ............................................................................................................................................................................................................................255  Session 73: Collections and Util package ............................................252  Implementations of Queue Interface .............258  Summary ...256  Two Schemes of Traversing Collections ...................252  Abstract Classes ..................................................................................................................................................................................................................................................................................260  The Properties Class ........................................256  Use Iterator Over for-each .................................... All Rights Reserved C3: Protected ....................................................................... Cognizant Technology Solutions...........................................................................252  Searching.......................................................................................................................................................................................................................................262  Test Your Understanding......................................................................................................................................................................................................................................................................................................251  Implementations of “Map” Interface ..............................................................259  Test Your Understanding.............256  The Iterable Interface .....263  Page 18 ©Copyright 2007......260  The Date Class ....257  Try It Out ................262  Session 81: Threads...............................................................................................................................................................................................................................................................................263  Learning Objectives ...................................................................................................................................................................................................................................251  “Queue” Interface..............252  Implementations of Queue Interface ..............................................................................................................................................................................253  Tips and Tricks: .........................................259  Session 75: Collections and Util package ......Handout .............................................................................................................................................................................................260  Try It Out ....................256  Learning Objectives .......251  “SortedMap” Interface ...........................................................................................................................................................................................................................................................Core Java “Map” Interface (Java SE 5) ................................................................................................................................................................................................................................257  Tips and Tricks: .............................................................................................252  Routine Data Manipulation .......................................................................................................................................................253  Try It Out ..........

..................................................................270  Scheme 2: Thread Object is Created and Started Within a Constructor...............273  Summary .............................................................................................................................................................................277  Inter-thread Communication: Methods from Object Class ...........................................................................................................................................................................277  Option 2: Use Synchronized Statement on a Common Object .................................................278  Page 19 ©Copyright 2007.................268  Two Ways of Creating and Starting a Thread ......264  Tips and Tricks : .......................................................Handout ...........................................................275  Learning Objectives .................267  The Thread Class: Constructor ........................................272  ThreadGroup Class .............................................................................................................................................................................Core Java Threads.........................................................263  Try It Out .........270  Two Ways of Starting a Thread for a Class that Implements Runnable ..274  Test Your Understanding....................................................................................... Cognizant Technology Solutions..................................................................................................276  Option 1: Executing Synchronized Method ..................................................................................................................................................................................................268  Scheme 2: start() Method is in a Constructor of the Subclass .......................................................269  Runnable Interface ............................................................................268  Extending Thread Class ...............................................................................................263  Thread Priorities ..................................................................................................................................................................................................................................................................276  Option 1: Use Synchronized Method .........................268  Two Schemes of Starting a Thread from a Subclass .....................267  Learning Objectives ........................................275  Synchronization: Locking an Object ........................272  Try It Out ...............268  Scheme 1: start() Method is not in the Constructor of Subclass ...............................................................................................267  The Thread Class: Constants .................................................................................................................................................275  Race Condition and How to Solve it ................................................275  An Unsynchronized Example ......................................................................272  Example: ThreadGroup ...265  Test Your Understanding.......................................................................................271  Extending Thread versus Implementing Runnable Interface ..............................................................................................................................................................265  Summary ............................................................................................................................................................................................................................................................................................................................................................................... All Rights Reserved C3: Protected .................................................................................................................................................................................................274  Session 84: Threads....................................................................................................................................................................................266  Session 82: Threads..........................................................267  The Thread Class: Methods .............273  Tips and Tricks: ................................................................270  Scheme 1: Caller Thread Creates a Thread Object and Starts it Explicitly..............................................................263  Multi-Threading in Java Platform ........

.....................................284  Callable's and Future's: Problem (pre-J2SE 5.................................................286  Blocking Queue Example 1 .............288  Try It Out ...........................................................................................................................................................................................................................................280  Test Your Understanding........................................... Cognizant Technology Solutions...........................................................................................................................................283  Code example of poor resource management (pre-J2SE 5..........................................................................................................................................284  Code example for better resource management (Using Executors of Java2...............................................................................................................................................................................................................................................................................................................................................................282  Concurrency Utilities .......................................................................................................................................292  I/O Streams........................................................................................................................282  Concurrency Utilities: JSR-166..............................................................0 code).....................................................282  Task Scheduling Framework ...........................................292  Learning Objectives .............283  Creating ExecutorService From Executors ...............291  Session 89: I/O operations in JAVA ...............................283  Executor and ExecutorService .........................................279  Tips and Tricks: .............................................................................................................................................................................................................................282  Learning Objectives .......................................................................................................................278  notify() Method ..........................................................Handout ........................282  Executor Interface ...................289  Tips and Tricks: ........................................................................................................285  Semaphores ................................................................................285  Callables and Futures ...v5......................................0) .......................................................288  ReadWriteLock ...................................................................................Core Java wait() Method of Object Class ................................................................................................................................................................................................................................................................................................................285  Future Example (Caller) .....292  Page 20 ©Copyright 2007..............285  Build CallableExample (This is Callee) ................................................................................................................................................................................................................287  Blocking Queue Example 2 ... All Rights Reserved C3: Protected ...................................................286  Semaphore Example ........287  Atomics ..........................................................................................282  Why Use Concurrency Utilities? ..................................0) ...............279  Try It Out ....................290  Summary ...................................................................................................................................................290  Test Your Understanding............................................................................................................................................................................................................................................286  BlockingQueue Interface ...................................................................................281  Session 86: Threads.....................................................................................................287  Locks ...............................................................................................................280  Summary .........................................................................................................................................................................288  ReadWrite Lock Example .....

.......................293  Character and Byte Streams ......................................................................................................................................................................................294  Streams .........................................................................................306  Page 21 ©Copyright 2007......................................................................296  Learning Objectives ..........................................................................................301  Node Writer Classes ........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................295  Session 90: I/O operations in JAVA .........................................304  Character Stream and Byte Stream ......................................................................................................302  Simple Byte Stream Input and Output .............................................................................................................296  InputStream Abstract Class .......................294  Summary .................................................................................................................................... All Rights Reserved C3: Protected .............................302  Example: FileInputStream and FileOutputStream ...........................................................................................................305  How to Create Buffered Streams?.......................................Handout ..................................................................................................................................................................................................................................................................................300  Filter Reader Classes .......................................................................................................................................................................................................................................297  OutputStream Abstract Class ....................................................................297  Filter InputStream Classes ......................................................................................................................................................................................................................................................................................................302  When not to use Byte Stream........................................................................301  Filter Writer Classes ...................................292  Output Stream ............................................302  Byte Stream ............................................................................................................................................................................................................................. Cognizant Technology Solutions.............................................................................................................................................................................................................................................................................................................................................................................................................................296  Node InputStream Classes ..............................................................299  The Reader Class: Methods .....299  Node Reader Classes ...........302  Control Flow of an I/O Operation ...................................................................305  Example: Line-oriented I/O .........................................................304  Line-Oriented I/O ................................298  Filter OutputStream Classes ............................299  The Reader Class: Methods .................................................................305  Buffered Streams .....................Core Java Input Stream ...........................................................................293  General Stream Types ........300  The Writer Class: Methods ...................................298  Node OutputStream Classes ............................................................294  Tips and Tricks: ...............................................295  Test Your Understanding.....................293  Node and Filter Streams ............................................................................303  Character Stream .............293  Input and Output Streams ....................................305  Buffered Stream Classes...........................................................................303  Example: FileReader and FileWriter........................................................................

...........................312  Test Your Understanding..............................................................................................314  Creating a Random Access File ............................................306  Data Streams ...................................................................................................................................................................................................................307  I/O of Multiple Referred-to Objects ..........................................................311  Tips and Tricks: ...................................................................................................................309  Try It Out .......................... Cognizant Technology Solutions...313  Problem Scenario .................................................................317  Learning Objectives .............................................................................................................................312  Session 92: I/O operations in JAVA ................................................................................................................................................................307  Write Object ...............................................308  The File Class: Constructors .......................................................................................313  Random Access File .........Core Java Flushing Buffered Streams .........................................................................................316  Test Your Understanding.......................317  Requirement for Serialization .............................................................................................................................314  File Pointer..............................................................................................................................................................312  Summary .........................................................................................................................................................308  Always Close Streams ...................................................................................................................................................................................................317  Non-Serializable Objects .......................................................................................................315  Try It Out .............................RandomAccessFile ...........................................................................................306  DataOutputStream ......................................................................316  Session 93: I/O operations in JAVA ...................................................................................313  Learning Objectives ........................................................Handout ....................................................................313  Benefits of Random Access File.....................................................................316  Summary ....................................................................306  DataInputStream.........................................308  The File Class: Methods ......................................................314  java..............................................................................315  Tips and Tricks: ................................................................................................................................................................................................................318  Page 22 ©Copyright 2007..................314  RandomAccessFile Methods .........................................................................................................................................................................................................................................308  The File Class ............io................317  Serialization ..........................................................................................................................306  Standard Streams on Java Platform.......................................................................................................................................................................................................................................307  Object Streams ......................................................... All Rights Reserved C3: Protected .....................................................................................................................................317  Streams Used for Serialization ...................................................307  Input and Output of Complex Object ....................................................................................................309  The File Class: Example ............................................................................................................................................................................................................................................................................................

...................326  Executing Query or Update ....................327  Read ResultSet MetaData and DatabaseMetaData (Optional) ................................................329  Summary ........................................325  Database URL .....................................................................................324  JDBC Driver ....324  JDBC API..............................................................325  Get a Connection Object ..............321  Provide your own implementation for readObject() and writeObject() methods ......................323  Summary ....................................................................331  Page 23 ©Copyright 2007..............................................................................................................................................324  Learning Objectives ........................................................................322  Tips and Tricks: ..............324  JDBC ........318  The transient Keyword ..................................... Cognizant Technology Solutions.....................................................................................................................................................................................................................................................319  Deserialization: Reading an Object Stream ......................................................................................................................................................................................................................................................320  How do you Generate a Unique ID?...330  Session 97: JDBC ....................................................................................325  Steps of Applying JDBC ................324  JDBC Driver ................320  Unique Identifier.............................................................................................................................................................Handout ..............................................................................................................328  Tips and Tricks: ..............................Core Java What is Preserved when an Object is Serialized?..............................323  Session 96: JDBC ..........................................................................................................................................................................................................................................................328  ResultSetMetaData Example .............................................................................................................................................................................................................................................................................................................................319  Version Control: Problem Scenario .........................................................................................327  Reading Results ................................................................................................................................................................................................................................................................................................................325  Load DB-Specific Database Driver ........................328  Try It Out ....................................................................................................................................321  Externalizable Interface ................................................326  Get a Statement Object .........................................................................................................................................................................................................................................................................................................................................................................................................................................................326  DriverManager and Connection...................... All Rights Reserved C3: Protected ..........................................318  Serialization: Writing an Object Stream ....................318  Example: transient Keyword ........................................321  How does Object Serialization Scheme works with Externalizable...................................323  Test Your Understanding....321  Try It Out .............................................................329  Test Your Understanding...................................................................................................................................................................................321  Provide your own implementation for readObject() and writeObject() methods ...................................................................................................................................................................................

...340  PreparedStatement Steps .......................................................................336  JNDI and Resource Mapping in sun-web.................................................344  Test Your Understanding............................................................................................................331  javax...................332  Sun Java System Application Server Admin Console ........................Core Java Learning Objectives ..................................................335  Example: PointBasePool .........xml of Sun Java System AppServer....................................................................332  Sun Java System Application Server Admin Console ........................................................................................................................................................xml of bookstore1 ....................................342  Try It Out ............331  DataSource (JDBC Resource) Definition in domain.....342  Tips and Tricks: .................................................340  PreparedStatement ........................................................338  Tips and Tricks: ................................................................................................................................................336  Transaction .................................................. Cognizant Technology Solutions....................................................................................................................sql....................................................................................................345  Learning Objectives .....................................................339  Session 98: JDBC ..............................................................................................................................................335  Retrieval and Usage of a DataSource Object .............................................................................................................331  Properties of DataSource Object ............................................................................................................................................................................................................................................................................................................................ All Rights Reserved C3: Protected .................................331  Where are Properties of a DataSource Defined? ................336  JDBC Transaction Methods....................................................................333  JNDI Registration of a DataSource Object ............DataSource Interface and DataSource Object ......................335  JNDI Resource Information in web............................................335  Example: Retrieval of DataSource Object by JNDI ..........................................345  Page 24 ©Copyright 2007.........334  Connection Pooling and DataSource .......................................................................................................................344  Session 102: Garbage Collection .................................................................................................................341  CallableStatement ...................................334  Need of Connection Pooling ..........................................................................................................................................................................................................................................................................................................................343  Summary ...............................................................................................Handout ........340  Prepared and Callable Statements..........................................................................................................................................................................................336  Transactions Example ......................................................................334  JNDI Registration of a DataSource (JDBC Resource) Object ....................................................................................................................................337  Try It Out ........................................................................................................342  Stored Procedure Example .............xml of bookstore1 ...338  Summary ......................................................................................................................................................................................339  Test Your Understanding........342  CallableStatement Example .............................340  Learning Objectives ....................................................................................................................................

..346  Memory Leaks ............................................................................................................352  Summary ...............................................................................................................................352  Test Your Understanding.....................................................................................................350  Important GC Performance Metrics ...............................346  Examples for Memory Leaks ..............................................................................353  How Annotations are Used? .......................................345  What Does a GC Perform?...........350  Parallel Collector.......................................................................................................................................................................Handout ...........................................................................................356  Page 25 ©Copyright 2007.......................................354  @Retention .........................................................................353  Learning Objectives ..............................................351  Concurrent Mark Sweep Collector.............345  Overview of GC Designs .........................350  Parallel Compact Collector ..........................................................................................................................................................................................356  @Deprecated ...............................353  Built-in Annotations .....................................................................354  Annotation Retention Policy ....................349  Session 103: Garbage Collection .....................................................................................................................................................................................................................347  Tips and Tricks: ...............................................................................................................................................................................355  @Target .......................Core Java Garbage Collector .......................................................................................................................................................0 Platform ................................................................................348  Summary ...............350  Types of Garbage Collector..........................................................................350  Serial Collector ................................................................................................................................................................................................................353  Need of Annotation ..................................................................346  Try It Out ............355  @Inherited ..345  Important Facts About GC .................................................................351  Tips and Tricks: ..............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................349  Test Your Understanding...........................................................................................................................................................................................................................................................353  Ad-hoc Annotation-like Examples in pre-J2SE 5..............................351  CMS Collector in Incremental Mode ......................................351  Other Incremental CMS Options ............................................................................354  @Documented .................. Cognizant Technology Solutions..............................................................................................................................................................................................................................................345  Some of the Common Garbage Collector Designs ........................................................................352  Session 105: Overview of Annotation .....................................................................................................................................................355  @Override ........................................................................ All Rights Reserved C3: Protected .....................350  Learning Objectives ..................................................................................................................................................................

...................................................................................................................363  Test Your Understanding........................................362  Try It Out ............................Core Java @SuppressWarnings.........................................362  Tips and Tricks: ..............................................................................................................366  Desktop APIs .......................................................................................................................................................................................................................................................................................356  Test Your Understanding.................................................................................................................360  Example: Definition and Usage of a User-defined Annotation ........................................................ Cognizant Technology Solutions....................................................................................... All Rights Reserved C3: Protected .........................................................364  Motivation for Scripting Support ......................................................................................................................................................................6 ...................................................365  API Support ..............................................................363  Session 108: Updates in JDK 1..............359  Marker Annotation ................................................................................................................................365  Java DB .......................................................................................................358  Example: Annotation Type Definition .......................................358  Learning Objectives .................................................367  Splash Screen: Usage .............................................................................................................................................................................................................365  Database: JDBC 4....................................................366  Splash Screen: Overview .....................................356  Tips and Tricks: .........................................................................................359  Normal Annotation ...............................................................................................................................................................358  How To “Use” Annotation .................................................................................................................................................................................................................................................................................................................................................................................................................Handout .................................................................................................361  Methods Defined by AnnotatedElement .............358  How to “Define” Annotation Type? ....................................364  The Java SE 6 (JDK 1...................................367  Page 26 ©Copyright 2007.........................364  Learning Objectives .................................364  Scripting: Developer Example .................................................................................................................................................................................................................................................................................................................................................................359  Single Member (or Value) Annotation ......366  Tray Icon: Usage ...........................................................................................................................................................................6) Top 10 Features .............357  Session 106: Overview of Annotation ...........................363  Summary ...................................358  Example: Usage of Annotation .................361  The AnnotatedElement Interface ........356  Summary ....359  Three Different Kinds of Annotations ...........................................360  Reflection ..........................................................................................................................0 Support ....................................................................361  Usage of Reflection in Annotations ..............................................................................................................................................366  Tray Icon ...........................................................................................................................................................365  Web Services Support on Java SE 6 Platform ......

.....................................378  Books .....................................................................................................................................369  Monitoring and Management ... Stability...................................................373  Performance Improvement ................................369  Pluggable Annotations .............. Cognizant Technology Solutions.......................................374  Test Your Understanding...............................................................375  Glossary ..................................................................................................................................................................................................................................................................................................................................................367  Dialog Modality Enhancement .......................................................374  Summary ........370  Windows Look and Feel Improvements SwingSet on Vista with 5..................374  Building Applications on Java SE 6 ......................................369  javax.................................................................................................GroupLayout Class .............................378  STUDENT NOTES: .368  SwingWorker ....................................376  References ................................................................................................374  Building Applications on Java SE 6 ............................................................................................................................................................................................................................................................................................................................................................................................................................................................................swing..............................................................................................................................369  JTable Sorting and Filtering.................................................................................................... All Rights Reserved C3: Protected ................................................................................................Core Java Desktop APIs .......................................373  Running Applications on Java SE 6 ..........................................................................................................................................0 ...............372  Quality......................................................................................................................................368  Text Printing......................................................................370  Desktop Deployment .........368  New Dialog Modality API ...............367  Modality Types...................................................................................................................................... and Compatibility ..............................371  Security ...................................................379  Page 27 ©Copyright 2007...........................................................................................................Handout ................................................................370  Windows Look and Feel Improvements SwingSet on Vista with 6 ..........................................................................378  Websites .......................................

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. arrays and Enum Write Java programs using Control Flow statements. operators.Handout .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. Page 28 ©Copyright 2007. wrapper classes and autoboxing Write Java programs using access specifiers. StringBuffer.0). Module Objectives After completing this module handout. interfaces. you will be able to: Describe the characteristics of Java language Define Java platform Explain the concepts of packages. and methods Write Java programs using the concepts of inheritance. objects. constructors. and abstract classes Write Java programs implementing exceptions handling Write Java programs using Strings.out. Target Audience This module is designed for beginners of Java who are expected to know the basic concepts of Object Oriented Programming. 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. main method and System. variable declaration. version 2.6 Pre-requisite The prerequisite of Core Java is knowledge in concepts of Object Oriented Programming. Cognizant Technology Solutions. data types. All Rights Reserved C3: Protected . classes. StringBuilder.

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. 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. Cognizant Technology Solutions. 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).Core Java Session 02: Introduction to OOPS Learning Objectives After completing this session. 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. which can either do something or have something done to them. OOP defines “things” (objects).Handout . All Rights Reserved C3: Protected . 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). Examples of class: Classroom Car Person Procedural Versus OOP “Nouns” refer to data and “Verbs” refer to operations.

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. Book book2 = new Book(). But it is used to construct objects.Handout . 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.println(“Getting the chapters list”). Each object made from the class can have its own values for the instance variables of that class. void getChaptersList() { System. } } Page 30 ©Copyright 2007.out.getChaptersList(). It tells the virtual machine how to make an object of that particular type. } public static void main(String[] args) { Book book1 = new Book().getChaptersList(). A class is a blueprint for an object. All Rights Reserved C3: Protected . book1. Class Book { String id. book2. String author. String title. Cognizant Technology Solutions.

void playDisc() { System. Test Your Understanding Find out who am I from the following: 1.playDisc(). I am compiled from a . All Rights Reserved C3: Protected .out. you have used the Book class to make different books. This error will be fixed by adding DiskDeck dd = new DiscDeck().recordDisc(). if (dd. statement in the main method. Cognizant Technology Solutions. and author. and each book has its own id.println(“disc playing”). dd. They represent the state of an object. I have behaviors ____ Page 31 ©Copyright 2007. The things an object does are called methods.println(“disc recording”).java file ____ 2. title. They represent the behavior of an object. An object knows things and does things. Tips and Tricks Please tell whether the following file could be compiled: Class DiscDeck { boolean canRecord = false. Summary Object-oriented programming lets you to extend a program without having to touch the working code that is tested earlier. The things an object knows about itself are called instance variables.out. A class is like a blueprint. A class describes how to make an object of that class type.canRecord = true.Handout .java to obtain soft copy of the program code How It Works: In the example provided. } public static void main(String[] args) { dd.canRecord == true) { dd. I behave like a template or blueprint ____ 3. } } } Solution: The preceding file will result in compilation error since object is not created for the DiscDeck class.Core Java Refer File Name: Book. } void recordDisc() { System.

____ Page 32 ©Copyright 2007.Handout . 5. All Rights Reserved C3: Protected . I declare methods ____ I represent ‘state’ ____ I am used to create object instances ____ I am located in objects ____. Cognizant Technology Solutions. 7. 6.Core Java 4.

Cognizant Technology Solutions. public variables and methods A Class private variables and methods public variables are not recommended Page 33 ©Copyright 2007. They are: flexibility and maintainability. Make public accessor methods. encapsulation. All Rights Reserved C3: Protected . and keeps both safe from outside interference and misuse. You have to write your classes and code in a way that supports flexibility and maintainability. The Object Orientation has two major promises/benefits.Handout . If you want maintainability. The following are some of the ways to include encapsulation: o o o Keep instance variables protected (with an access modifier. Encapsulation Abstraction in OOP is closely related to a concept called encapsulation. 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.Core Java Session 03: Introduction to OOPS Learning Objectives After completing this session. often private). For the methods. 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. flexibility and extensibility your design must include encapsulation. 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. and force calling code to use those methods rather than directly accessing the instance variable. This concept is called abstraction. you will be able to: Describe abstraction.

Inheritance is the process by which one object acquires the properties of another object. Animal Bird .. By use of inheritance. it can inherit its general attributes from its parent. Moreover the inheriting class can define its own attributes and behaviors. . 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..Core Java Encapsulation: Example Bank machine Hidden data Account balance Personal information Interface Deposit. The inheriting class contains all the attributes and behaviors of its parent class..Handout .. Page 34 ©Copyright 2007. 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 . Withdraw.... Duck Inheritance One of the main tenets of OOP is inheritance.. an object needs only to define all of its characteristics that make it unique within its class. All Rights Reserved C3: Protected . . Cognizant Technology Solutions.

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 BankAccount int acctNum Client acctHolder double balance bankAccount(Client info) void deposit(double amt) boolean withdraw(double amt) void printStatement() SavingsAccount double interestRate double accruedInterest Time lastBalanceChange CurrentAccount double minBalance currentAccount(…) boolean withdraw(double amt) double calcServiceFee() savingsAccount(.Handout .) void updateIntRate(double rate) void deposit(double amt) boolean withdraw(double amt) Try It Out Problem Statement: Design a class inheritance class diagram (tree structure) for the following: Class Clothing Shirt Superclasses --Clothing Subclasses Shirt.Core Java The inheriting class can override the definition of existing methods by providing its own implementation. All Rights Reserved C3: Protected .. Trouser Page 35 ©Copyright 2007. 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. Cognizant Technology Solutions.

Clothing is the superclass and its subclasses are Shirt and Trouser that is a Shirt extends Clothing and also a Trouser extends Clothing. All Rights Reserved C3: Protected . Fill in the blanks for the following: a) A sub class ______ all the public instance variables and methods of the super class. Using Java.java. b) If the base class or super class has functionality.java. The typical problems include real-time problems and challenges: 2.java to obtain soft copy of the program code How It Works: In the given example. Are there any practical limits on the level of subclassing using Java? 3. Cognizant Technology Solutions. Shirt. you cannot extend any class as such. Tips and Tricks 1. Summary A class can inherit instance variables and methods from a more abstract superclass. Test Your Understanding 1.Handout . State true or false for the following: a) Guitar extends Instrument b) Animal extends Cat Page 36 ©Copyright 2007. 2. there is no hard limit for the limits on the level of subclassing. Trouser. The factors like access control and access modifier determine whether a class can be subclassed.Core Java Class Trouser Superclasses Clothing Subclasses Answer: Inheritance Class Diagram Clothing Shirt Trouser Refer File Name: Clothing. Can you extend any class in Java? Solution: With regard to Java API. then its ______ automatically gets the same functionality.

Cognizant Technology Solutions.com/definition/Polymorphism_%28computer_science%29 Generally. 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. rather than overloading the method.Handout . or method overloading. o The actual method executed is determined by the type of the object and not the type of the reference. Method Overloading This is called ad hoc polymorphism. the call signature is matched to the correct method version. float b) public static float max(float a. int b) When a method is called. refer the following url: http://www.wordiq. All Rights Reserved C3: Protected . float c) public static int max(int a. you will be able to: Describe polymorphism Explain the relationship between objects Polymorphism Polymorphism (from Greek. float b. Page 37 ©Copyright 2007. it is instead overriding the method: For subclass objects.Core Java Session 04: Introduction to OOPS Learning Objectives After completing this session. Idea of polymorphism: See internet definition: On Google type “definition polymorphism” and see the results Moreover. Dynamic (or late) binding: o The code executed for a method call is associated with the call during run-time. polymorphism allows you to mix methods and objects of different types in a consistent way. the definition in the subclass replaces the version in the superclass. Note: This is done during program compilation Subclassing Polymorphism Subclassing polymorphism is sometimes called “true polymorphism”. 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. It consists basically of two ideas: Method overriding: o o o A method defined in a superclass is redefined in a subclass with an identical method signature. As the signatures are identical. In this case.

but objects are not.move(). References are all the same. A[2] = new Fish(). Cognizant Technology Solutions.Core Java o o o Allows superclass and subclass objects to be accessed in a regular and consistent way: Array or collection of superclass references can be used to access a mixture of superclass and subclass objects 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. i < A. A[0] = new Bird(). 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.Handout .length. All Rights Reserved C3: Protected . Page 38 ©Copyright 2007. i++) A[i]. for (int i = 0. The method invoked is associated with the object and not with the reference. Animal [] A = new Animal[3]. A[1] = new Person().

Wheels can exist independently from the car and are not necessarily destroyed when the car is wrecked. This is a great feature of Object Oriented approach. and sometimes it saves you from having to rewrite the class from scratch. They represent the behavior of an object. you may also want to create a separate test class. All Rights Reserved C3: Protected . Composition: Composition is the relation in which the objects cannot exist independently from the whole. a Java program is nothing more than objects ‘talking’ to other objects. Summary Object-oriented programming lets you to extend a program without having to touch the working code that is tested earlier. The relation may be referred alternatively as “contains”. A class is like a blueprint. State true or false for the following: a) Polymorphism means many forms. A class describes how to make an object of that class type. Example: The car registration cannot exist without a car. b) An overloaded method is not the same as overridden method. When you create a class. or “is part of”.Handout . Page 39 ©Copyright 2007. Cognizant Technology Solutions. At run-time. All Java code is defined in a class. Example: A car contains wheels. which you will use to create objects of your new class type. They represent the state of an object. The things an object knows about itself are called instance variables. The things an object does are called methods.Core Java Aggregation: Aggregation is a special form of association. Test Your Understanding 1. or track down the programmer who is hiding the source code. A class can inherit instance variables and methods from a more abstract superclass. “is composed of”. An object can take care of itself. 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. but you want to change the way a method of that class works. you do not have to know or care how the object does it. 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. An object knows things and does things.

Page 40 ©Copyright 2007. Patrick Naughton. Sun formally announced the Java SunWorld in 1995. which affect the robustness of the code. Ed Frank. such as pointer arithmetic and memory management. and so on. interpreter. had requirements such as reliability. security.Core Java Session 05: Introduction to Java and SDE Learning Objectives After completing this session. Cognizant Technology Solutions. Java Technology Java is a programming language. by nature. Java is a deployment environment that supplies Java2 Software Development Kit (J2SDK) with complete set of Application Programming Interface (APIs) as packages. Chris Warth. Java is an application environment to run standalone programs that run on any machine where the Java Runtime Environment (JRE) is installed. regardless of the CPU The World Wide Web (WWW). 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. and architecture independence. which were fully compatible with the design patterns of Java. and it was developed as a part of the Green project at Sun Microsystems. documentation generator. Java provides an easy-to-use language by avoiding pitfalls of other languages. All Rights Reserved C3: Protected . Java was conceived by James Gosling. and Mike Sheridon at Sun Microsystems in 1991.Handout . 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. Java is a development environment that provides tools such as compiler.

Bytecode: Bytecode is a highly optimized set of instructions designed to be executed by the JVM. All Rights Reserved C3: Protected . The key that allows Java to solve both the security and the portability problem is the output of Java compiler. Java SE or J2SE Runtime Environment J2SE stands for Java 2 Standard Edition. Because applets are executed in the client machine. JVM needs to be implemented for each platform. An applet can react to user input dynamically. each of which contains code for at most one public class.5 onwards. and other components necessarily for you to run applets and applications written in Java. The JVM is ported to different platforms to provide hardware and operating system independence. Page 41 ©Copyright 2007. The JRE provides the libraries. which is not an executable code rather it is the bytecode. Code for the JVM is stored in . JVM is implemented in a Java technology development tool or in a Web browser. Java enforces a lot of restriction on applets. An applet is designed to be transmitted over the Internet and is executed by a Java compatible Web browser. The specification enables the Java language to be platform independent. much in the same way an image is included in a page.class files. this is referred to as Java SE (Java Standard Edition). Cognizant Technology Solutions.Handout . 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. Java Interpreter. JVM. From Java SDK API version 1. which is environment independent of hardware and operating system.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.

and other components necessary for you to run applets and applications written in Java. In a Java application. and it is a part of JDK libraries. JRE appropriate to that OS must be available. The Java API is a code that is written earlier. such as compilers and debuggers that are necessary or useful for developing applets and applications. Java language has been developed: o o Security Reliability Completely platform independent and functions seamlessly regardless of the type of CPU Java is a development environment. then you will also need to include that with the classes of your application. e) A Java source file (*. verifying. object oriented. you write one or more classes. Java Interpreter.Handout . robust. Summary Keeping the following objectives in mind. so that they can run your program. one of the classes must have a main method. Page 42 ©Copyright 2007. for different platforms). The JDK includes the JRE as well as command-line development tools. and put it all on a CD-ROM. and executing the bytecodes. Test Your Understanding 1. If the end-user does not have a JVM. Secure. organized into packages of similar topics. There are a number of installer programs that lets you to bundle your classes with a variety of JVMs (say. So as a programmer. multithreaded are some of the salient features of Java. All Rights Reserved C3: Protected . Then the end-user can install the correct version of JVM (assuming they do not already have it on their machine.). and so on. An applet is a program. State true or false for the following: a) Java is an Object Oriented Programming language. Cognizant Technology Solutions. d) Java is platform dependent.Core Java JRE is responsible for loading. f) To run a Java program on any Operating System. documentation generator.class file. The JRE provides the libraries. and multi-threaded. b) Java is developed at Microsoft. portable. which provides tools like compiler. 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). JVM. used to start-up the program. interpreter. which you deliver.java) is compiled and the corresponding bytecode is available in the *. robust. which is downloaded in the client machine and executed by the JVM of the client machine. c) Java is secure. Bytecode is a highly optimized set of instructions designed to be executed by the JVM. platform independent.

the particular name and address for a given Person object is declared as an instance variable. There is only one copy of each of these variables no matter how many objects are created for the class. Examples of class: Classroom Car Person The following Java program defines a class Person with data member name: Class Person private String name. Class variable: o o o The data that is shared by all the objects are declared as class variables. Cognizant Technology Solutions. o An instance variable relates to an instance (object) of its class. } } The data members in a class can be defined as follows: Instance variable: o This differentiates one object from another. These variables exist even if no object of the class has been created.Handout . Page 43 ©Copyright 2007. giving an object its individuality. you will be able to: Define a class Create objects Identify packages. } public String getName() { return name. For example. import statement. public void setName(String aName) { name = aName. All Rights Reserved C3: Protected .Core Java Session 06: Introduction to Java and SDE Learning Objectives After completing this session. A class is a template that describes the data and the methods that manipulate the data. and Object class Explain object messaging Defining a Class A class is a basic building block of an object oriented language.

mypack. the class ArrayList is actually java.ArrayList. they help in the overall organization of a project or library. All Rights Reserved C3: Protected . To put a class in a package. The constructor will contain code that initializes the new object to the desired values.. To use a class in a package other than java.util. if you preponed your reverse domain name on to the front of a class name.Book. Person EdmundHillary Instantiation: The new keyword is a Java operator that creates the object.lang. you must tell Java the full name of the class. Page 44 ©Copyright 2007. because you can restrict the code. import java. For example. A class has a full name. com. Data members of the class are normally declared as instance variables using the keyword private. packages provide a level of security. The following statement creates an object: Person EdmundHillary = new Person(). put a package statement at the top of the source code file. In the Java API. EdmundHillary = new Person() Initialization: The new operator is followed by a call to a constructor. Packages Every class in the Java library belong to a package. which is a combination of the package name and the class name. The preceding statement has three parts: Declaration: This notifies the compiler that you will use name to refer to data whose type is type.Core Java o o These variables are also referred to as static fields because they are declared with the keyword static. which you write so that only other classes in the same package can access it. To be in a package.Handout .ArrayList.mypack. Packages are important for three main reasons: o Firstly. a class must be in a directory structure that exactly matches the package structure. to help to prevent collisions if many programmers in a company decide to make a class with the same name. Cognizant Technology Solutions. which is in a directory named com. Organizing your classes into packages prevents naming collisions with other classes.util. classes are grouped into packages. before any import statement like package com.io. Creating Objects An object is created from a class. For a class. the Book class must be in a directory named mypack. o Thirdly. Import Statement A typical set of import statements might look like the following: import java. packages give you a name-scoping. o Secondly.*.

util. import java. or sending an email). It is the superclass of everything. After performing the operation.Date. implicitly extends Object class. returning a value. this keyword: o o Used to represent the object that invokes the method: Used within the member methods of the class those are not static Page 45 ©Copyright 2007.setName(“EdmundHillary”). When an object invokes a method on itself or on the method of another object. Purpose of import statement: Because of the rigid source code naming convention.util.ArrayList myList = new java. This can be illustrated with the following example: java.ArrayList.Properties.util. Example: person. before the class statement. is to use import statements like the following: import java. it is said to pass a message to the object that contains the target method. The alternative to this long-winded style of coding (as shown earlier). The required arguments for a method are defined by a parameter list of the method. you must first import the superclass using the import statement.util.Handout . To derive a class from an external superclass. 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. Cognizant Technology Solutions. Data that are passed to a method are known as arguments. … ArrayList myList = new ArrayList(50).Core Java import java. All Rights Reserved C3: Protected .util. the body of the method uses the return statement to return the value to the calling object.ArrayList(50). the Java compiler can easily find the corresponding source or class files just from the fully qualified name of a package and class. The import statements must come right after the package statement. Object Class Every class in Java extends class Object that is the Object class is the mother of all classes. Any class that does not explicitly extend another class. The message contains the name of the method and any data that the method requires.

Handout .Core Java this keyword this keyword refers to the object that is currently executing. 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.and so on). but each card knows things unique to that particular card. So. } Page 46 ©Copyright 2007. All Rights Reserved C3: Protected .name = name. Each card has the same blank fields (the instance variables). changeName(String aName) . public void getName() { } public String setName(String aName) { } public String changeName(String aName) { } Refer File Name: AddressBook. Person(String name) { this. and the entries you make on that card represent its state. like the following code: Class Person { String name. } Try It Out Problem Statement: Illustrate the importance of the objects with relevant to entries in the address book. and setName(String aName) could all be the methods for the class AddressBook. getName() . this keyword also allows one constructor to explicitly invoke another constructor in the same class. The methods of the class are the things you do to a particular card.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. setName(String aName) . you are creating an instance (object). Code: class AddressBook { String id. Cognizant Technology Solutions. } ……. each card can do the same things (getName() . When you fill out a card. int telephoneNumber.

Test Your Understanding 1. b) The import statement can be placed next to the package statement in a Java program.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. State true or false for the following: a) The package statement in a Java program. The things an object knows about itself are called instance variables. You can put all of your application files into a Java Archive or a . All Rights Reserved C3: Protected . can be written anywhere in the code. Page 47 ©Copyright 2007. They represent the behaviour of an object. you can include a simple text file formatted as something called a manifest. Cognizant Technology Solutions. it would be a big pain to deliver a huge bunch of individual files to your end-users.Handout . They represent the state of an object. if available. The things an object does are called methods. d) Every class in Java does not extend the Object class. In the jar file. but you will not have to. A class describes how to make an object of that class type. c) A Java class is made up of data members and methods. 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 is like a blueprint.jar file that is based on the pkzip format. An object knows things and does things.

Typically this stream corresponds to display output or another output destination specified by the host environment or user. Cognizant Technology Solutions. This is then compiled into a new class file (with a .println inserts a new line while System.lang package.print keeps printing to the same line.class extension) When you run your program.out. The “out” is a field of the System class representing the “standard” output stream. Running a program means telling the Java Virtual Machine (JVM) to “Load the class” (Book class for example).println(data) . then starting to execute its main() method. you will be able to explain the following: The main() method and SOP (System. The main() method is where a Java application starts running.out. everything goes in a class.out. a typical way to write a line of output data is System. you are really running a class.out.println method) Code structure in Java The main Method In Java.out.Core Java Session 07: Introduction to Java and SDE Learning Objectives After completing this session. System. and at least one main() method. Keep running till all the code in main() method is finished. 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. Every Java application has to have at least one class.Handout .java extension). For simple stand-alone Java applications. 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 o To test your real class To launch or start your Java application The System.println (SOP) Method The System class is available in the java. All Rights Reserved C3: Protected . The source code is typed into a file (with a .

java source file in a MS-DOS prompt. 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. } } Save the preceding contents in a file called MyFirstProgram.displayMessage(). All Rights Reserved C3: Protected . Run: To run the earlier Java program in a MS-DOS prompt.Core Java Example /** * * Sample program to print This is my first Java program * */ class MyFirstProgram { // Declare class MyFirstProgram void displayMessage() { System. which is made up of bytecodes.out.java After successfully compiling the earlier source file. } public static void main(String[] args) { MyFirstProgram myFirstProgram = new MyFirstProgram(). the compiler generates MyFirstProgram. */ Page 49 ©Copyright 2007.println(“This is my first Java program”).Handout .java Compile and Run a Java Program Compile: To compile MyFirstProgram. Cognizant Technology Solutions. myFirstProgram.class file. The compiled bytecode is platform independent. give the following command: java MyFirstProgram The JVM translates the bytecode into something that the underlying platform understands. and runs your program. give the following command: javac MyFirstProgram. Code: /** * A Simple application.

println("Simple program"). Page 50 ©Copyright 2007. Describe the purpose of the keyword void when used as the return type for the main method. but you might have only one with a main() method. Tips and Tricks Does a Java program need to have a main() method in every class written? Solution: No. The keyword public indicates that the method can be called by any object. 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. You might write test classes. They also bracket the code of a method. System.*/ : 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.Core Java public class SimpleApp1 { public static void main(String args[]) { // A method to output to the console. Cognizant Technology Solutions.java to obtain soft copy of the program code How It Works: /** * A Simple application.println("Simple program"). : Print to console }: Curly braces span the code for a class.Handout . a Java program might use dozens of classes (even hundreds). } } Refer File Name: SimpleApp1.out. All Rights Reserved C3: Protected . that have main methods for testing your other classes. Explain the reason that the main method in a Java application must be declared static. : Comment using two slashes System. 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.out. the one that starts the running of the program. though. The void keyword when used as the return type for any Java methods indicates that the method does not return anything.

Handout .Core Java Test Your Understanding 1.println methods in displaying the output. State true or false for the following: a) The execution of a Java Program always starts with the main() method. All Rights Reserved C3: Protected . Cognizant Technology Solutions.out. c) javac and java are the tools available in Java Development Kit (JDK). d) A bytecode is platform dependent.out. Page 51 ©Copyright 2007. b) There is no difference between System.print and System.

0 (Europa) Features of SDE 4.Core Java Session 08: Introduction to Java and SDE Learning Objectives After completing this session.Handout . 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.0 support Business Tier Tech: Spring tools Advanced Spring JPA EJB 3.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.3 & Struts 2. All Rights Reserved C3: Protected .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.x was built on top of Eclipse 3.3.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.1-2.0 * Page 52 ©Copyright 2007. Cognizant Technology Solutions.

Tomcat Launcher. Code Management and Metrics Plugins Lomboz STRUTS. STAN Page 53 ©Copyright 2007. Commonclipse.5GB minimum for installing SDE 4. 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. OC4J XDoclet. Cognizant Technology Solutions.x.0. Web. All Rights Reserved C3: Protected . CodeSugar Jalopy.0 support JBoss seam support MyLyn support Portlet support Cheatsheet Support (ongoing updates) Tools Purpose J2EE Development Tools Server Plug-ins Code/Descriptor Generation Code Analysis & Formatting Automated Testing Profiler. Apache Tomcat 6. Spring IDE.Handout . Weblogic. AspectJ Dev Tools JBoss IDE. WASCE.x Software: Windows XP and Linux Testing tool and Profiling tool Reporting tool SHRIMP 2. and MySQL 5.Core Java Hibernate support Database tools Others: o o o o o o o CTS Project: Designed for the Application Development Projects of CTS You can build Java. Checkstyle JUnit TPTP (Test and Performance Tool Platform).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. Metrics plugin.

x was built on top of Eclipse 2.x was built on top of Eclipse 3. Summary SDE 4.1-2.5.0) and Spring MVC J2EE Applications (Web applications + EJB and Web Services). edit. b) Jalopy and Checkstyle plugins are available in SDE for doing the code analysis and formatting work. Page 54 ©Copyright 2007.0 SDE is easy to install The following applications can be built using SDE: o o o o Simple Java Application Java Applets Dynamic web applications using different frameworks such as Struts (1.exe command.0.3. If the JDK version is lesser than 1. c) The Java Perspective in SDE supports developers who create. Test Your Understanding 1. The JRE version needs to be 1. Please check the version of java by running java –version command.exe -vm %JAVA_HOME%\bin\javaw.Handout . then please update the path settings to have %JAVA_HOME%\bin in the path before all other entries or run eclipse using eclipse. State true or false for the following: a) SDE 4.5.5 configured in your path. and build Java code.0. All Rights Reserved C3: Protected .Core Java Tips and Tricks Problem: Eclipse does not startup Solution: If Eclipse does not startup by clicking on short cut on desktop.3. then you do not have JDK 1. Cognizant Technology Solutions.

you will be able to: Create Java classes and packages Creating New Java Project Java projects contain the resources needed for Java applications. select File > New > Project. All Rights Reserved C3: Protected .Core Java Session 09: Introduction to Java and SDE Learning Objectives After completing this session. Page 55 ©Copyright 2007. Java projects are used to create Java packages. including Java files and class files. Cognizant Technology Solutions.Handout . 1. To create a new Java project. Select Java Project from this page and click Next.

The project is configured with default options. All Rights Reserved C3: Protected . Name the Java project and specify the directory. Click Finish. Select the project in the Package Explorer view and New > Package from the context menu. where the project files should be stored. 4. enter the fully qualified name of the package. 3. Creating Java Package Once the Java project has been created. Click Finish to create the package. Cognizant Technology Solutions. you can add Java packages to it. Page 56 ©Copyright 2007.Handout . In the dialog window.Core Java 2.

select the package that has been created in the preceding step and select New > Class. the name of the super class.Core Java Creating Java Classes After you have created the new package. Cognizant Technology Solutions. All Rights Reserved C3: Protected .Handout . add interfaces which should be implemented. Page 57 ©Copyright 2007. In the Name field of the new Java class dialog. To create a new class. and create method stubs for the new class. you have to enter the name of the new class. you can add classes to it. You can also set the modifiers.

To manually build a project.Handout . In automatic build. click on Project > Build Automatically. select the project and click on Project > Build Project. Page 58 ©Copyright 2007. All the files in the java project are compiled in one shot when the build process is invoked. click Finish to create the class. To enable automatic build for a project. SDE provides facilities for both automatically building a java file and building it manually. all the java files are recompiled when a resource is saved. Cognizant Technology Solutions. Building Java Classes The java files are compiled by the build process in SDE.Core Java After all the settings have been made. All Rights Reserved C3: Protected .

and classpath settings for your launch configuration. A new launch configuration with the appropriate settings for the selected class is created.Core Java Running Java Programs After the code has been completed and is free of compile errors.Handout . If you launch the program for the first time. JRE. All Rights Reserved C3: Protected . Cognizant Technology Solutions. You can also specify arguments. you click the Run icon from the toolbar. In the Launch Configuration dialog box. To launch the program. then the Launch Configuration dialog opens. Page 59 ©Copyright 2007. Select Java Application from the list and right click New or simply double-click. Clicking Run invokes the main method of the class. it can be executed using the Workbench Java Application Launcher. you can select the type of configuration you would like to create to run the program.

when the error was detected. Page 60 ©Copyright 2007. Cognizant Technology Solutions.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.Handout . Fix the errors highlighted by SDE and go on saving the work. All Rights Reserved C3: Protected .

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.Core Java Summary When a new Java project is created in SDE. Cognizant Technology Solutions. the following can be performed: Create new packages Create new Java classes Build the Java classes Run the Java programs Test Your Understanding 1. All Rights Reserved C3: Protected .Handout .

Handout . You cannot use keywords as names for your variables. and primitive data types Java Keywords Keywords are predefined identifiers reserved by Java for a specific purpose. All Rights Reserved C3: Protected . Java literals. A list of Java keywords are as follows: Java Literals Literals are tokens that do not change. methods. you will be able to: Identify Java keywords. 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.Core Java Session 14: Language Fundamentals and Operators Learning Objectives After completing this session. Cognizant Technology Solutions. classes. and so on. They are constant in value.

All Rights Reserved C3: Protected . a backslash is used followed by the character code. For example. “Hello World”. Java Literals: Character Character Literals represent single Unicode characters. enclose the character in single quote delimiter. Cognizant Technology Solutions. Page 63 ©Copyright 2007.45 (standard). Java Literals: String String literals represent multiple characters and are enclosed by double quotes.8345e2 (scientific) Java Literals: Boolean Boolean literals have only two values. Special characters such as a newline character. ‘\n’ for the newline character. and ‘\b’ for backspace. An example of a string literal is.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. For example: The letter a. 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. 5. is represented as ‘a’. ‘\r’ for the carriage return.1416 Can be expressed in standard or scientific notation: Example: 583. true or false.Handout .

and. long Integral data types in Java uses three forms of decimal. All Rights Reserved C3: Protected . It has its literal enclosed in double quotes(“”). Primitive Data Types: Textual-char A character data type (char). 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. rather it is a class. For example the following code: ‘a’ ‘\t’ //The letter a //A tab To represent special characters like ' (single quotes) or " (double quotes). Cognizant Technology Solutions. The earlier example shown.Handout . represents a single Unicode character. It is not a primitive data type. Examples are: 2 077 0xBACC // The decimal value 2 // The leading 0 indicates an octal value // The leading 0x indicates a hex value Integral types has int as default data type. Page 64 ©Copyright 2007. It must have its literal enclosed in single quotes(’ ’). Primitive Data Types: Integral – byte. short. or hexadecimal.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. octal. For example. An example is boolean result = true. int. declares a variable named result as boolean type and assigns it a value of true. String message=“Hello world!”. use the escape character \.

Declare double named d and assign it the value 456.709 4. Cognizant Technology Solutions.718F 123. Floating-point literal includes either a decimal point or one of the following.4E+306D //A simple floating-point value (a double) //A large floating-point value //A simple float size value //A large double value with redundant D //(add exponential value) //(float) //(double) 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.Core Java You can define its long value by appending the letter l or L. Page 65 ©Copyright 2007. Declare an int named y. 3.14 6. Declare a boolean named isAvailable(no assignment) 5. For example: 10L Integral data type have the following ranges: Integer Length 8 bits 16 bits 32 bits 64 bits Name or Type byte short int long Range -27 to 27-1 -215 to 215-1 -231 to 231-1 -263 to 263-1 Coding Guidelines: In defining a long value. and assign it the value that is the sum of whatever x and 456. E or e F or f D or d Examples are: 3. Declare an int named size and assign it the value 32 2. a lowercase L is not recommended because it is hard to distinguish from the digit 1. Declare a char named initial and assign it the value ‘j’.Handout .02E23 2. All Rights Reserved C3: Protected . Assign the value true to the isAvailable that is declared earlier 6. Primitive Data Types: Floating Point-float and double Floating point types has double as default data type.

Cognizant Technology Solutions. const and goto are reserved words. boolean isAvailable. A number is by default an int literal. or digits. int y = size + 456. All Rights Reserved C3: Protected . literals. the literal values are shown in bold italics: int size = 32.709. but they cannot be used as identifiers as well.709. isAvailable = true. but not used. Solution: An identifier must begin with a letter. isGood = true. char initial = ‘j’. false. Page 66 ©Copyright 2007. and null are literals (not keywords). double d = 456. $. 1E-5d is a valid double literal and E2d is not (since it starts with a letter. and keywords in Java. dollar sign($). Tips and Tricks List out few important points while using identifiers.Core Java Code: class LiteralValues { public static void main(String[] args) { int size = 32.Handout . or underscore (_). An identifier cannot have a name of a Java keyword. boolean isAvailable. double d = 456. Subsequent characters may be letters. All numeric data types are signed.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. 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. int y = x + 456. char initial = 'j'. true. _ (underscore). char is the only unsigned integral type. compiler thinks that it’s an identifier). Embedded keywords are accepted. } } Refer File Name: LiteralValues. A decimal number is by default a double literal. isAvailable = true.

Literals for chars are single character inside single quotes: ‘d’. 0x3d). All Rights Reserved C3: Protected . Cognizant Technology Solutions. Which one of the following is not a valid identifier? total a) _count b) sum c) 2root 3. octal (e. Float literals end in F or f.Handout . Literals for longs end in L or l (lowercase of the alphabet L).g. Test Your Understanding 1. 013). The boolean literals are true and false. double literals end in a digit D or d. Which one of the following is not a token? a) keyword b) identifier c) method d) literal 2.g. 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.Core Java Summary Integer literals can be decimal. or hexadecimal (e.

Cognizant Technology Solutions.Handout .Core Java Session 15: Language Fundamentals and Operators Learning Objectives After completing this session. Note: Values enclosed in <> are required values. All Rights Reserved C3: Protected . 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. 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. 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. Declaring and Initializing Variables Declare a variable as follows: <data type> <name> [=initial value]. while those values in [] are optional. 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.

as the data type (double) of the destination variable holds a larger value than the data type (int) of the value.Core Java Example of a reference variable and primitive variable Suppose you have two variables with data types int and String. String name = "Hello". int num = 10. the variable name. wherein you have the address of the memory cells. int numInt = 10.Handout . Page 69 ©Copyright 2007. 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 o Implicit Casting Explicit Casting Implicit Casting Suppose you want to store a value of int data type to a variable of data type double. the data is implicitly casted to the data type double of the destination variable. Type Casting Type Casting is the mapping type of an object to another. Cognizant Technology Solutions. and the data they hold. // primitive type // reference type Example of memory handling of a reference variable and a primitive variable The following picture is the actual memory of your computer. double numDouble = numInt. //implicit cast In this example. All Rights Reserved C3: Protected .

2. int numInt2 = 2. VicePresident is a subclass of Employee with more information. Explicit Casting Examples double valDouble = 10. int result = (int)(x/y). Explicit Casting When you convert a data that has a large type to a smaller type. Cognizant Technology Solutions. All Rights Reserved C3: Protected . Cast. int valInt = (int)valDouble.Handout .Core Java Example of implicit casting: int numInt1 = 1. Explicit casts take the following form: (Type)value where. Type is the name of the type you are converting to value. int y = 2. Some objects might not need to be cast explicitly. //typecast result of operation to int Casting Objects Instances of classes also can be cast into instances of other classes. classname is the name of the destination class and object is a reference to the source object. The source and destination classes must be related by inheritance.12. with one restriction. Employee emp = new Employee(). VicePresident vp = new VicePresident(). //convert valDouble to int type double x = 10. One class must be a subclass of the other. which here defines that the VicePresident has executive washroom privileges. //result is implicitly cast to type double double numDouble = numInt1/numInt2. you must use an explicit cast. // no cast needed for upward use Page 70 ©Copyright 2007. Casting Objects Example The following example casts an instance of the class VicePresident to an instance of the class Employee. It is an expression that results in the value of the source type. Casting objects is analogous to converting a primitive value to a larger type. (classname)object where.

Handout . Try It Out Problem Statement: Write a program that illustrates the implementation of the automatic initialization of member variables.0 double: 0. Cognizant Technology Solutions. float f. char c.run().Core Java emp = vp. double d. app. public static void main(String[] args) { Initialization app = new Initialization(). int i. short s. byte by. All Rights Reserved C3: Protected . Code: class Initialization { boolean bo. Object o. // must cast explicitly vp = (VicePresident)emp.0 Object: null Page 71 ©Copyright 2007. It displays the following output: boolean: false byte: 0 char: short: 0 int: 0 long: 0 float: 0.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. } // continued … Refer File Name: Initialization. long l.

} 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. public String testMethod(int a) { String tmp.) Object references can be initialized to null to make the compiler happy The following code will not compile.g. Arithmetic with boolean is not allowed.. the compiler will catch it. return tmp. 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). the integer type is automatically converted (sometimes called promoted) to a floating type and floating arithmetic is performed. All Rights Reserved C3: Protected . Cognizant Technology Solutions. The default value for a boolean member variable is false. if you fail to initialize a local variable. they are automatically initialized to a default value. whenever division is performed between a floating type and an integer type.Handout . For e. Specify else part or initialize the local variable explicitly. Variables can be initialized when declared All Java variables can be initialized when they are declared. if (a > 0) tmp = “Positive”.Core Java Tips and Tricks List out the key points related to ‘instance’ (or member) variables and ‘local’ variables. Local variables are not automatically initialized Unlike instance (or member) variables. Must initialize or assign value to all local variables Page 72 ©Copyright 2007. the variable is not automatically initialized. 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 o Must be initialized explicitly and (Or.

Handout . b) Different types of variables can be declared in a single Type declaration statement. 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.Core Java Thus. Cognizant Technology Solutions. 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. All Rights Reserved C3: Protected . or assigning a value to them before attempting to access their value with code later in the program. Test Your Understanding 1. c) The list of variables in a Type declaration statement should be separated by commas. Page 73 ©Copyright 2007. the programmer is responsible for either initializing all local variables. d) The Type declaration statement can be used to declare as well as initialize a variable.

the variable name can be given as “grade” or “studentGrade” instead of giving any other names. Page 74 ©Copyright 2007.0 15 double grade = 0. Cognizant Technology Solutions. double grade = 0. //assign 'C' to option 11 12 //declare a data type with variable name 13 //grade. double data type and initialized 14 //to 0. All Rights Reserved C3: Protected . For example.0. grade=0. 16 } 17 } Declaring and Initializing Variables: Coding Guidelines It is always good to initialize your variables as you declare them.Handout . Declare one variable in each line of code. For example. double quiz = 10. is preferred over the declaration double exam=0. for a student’s grade. quiz=10. 6 7 //declare a data type with variable name 8 // option and char data type 9 char option. 10 option = 'C'. Apply descriptive names for your variables. the variable declarations: double exam = 0. 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.Core Java Session 16: Language Fundamentals and Operators Learning Objectives After completing this session.

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. convert the other operand to double. but as soon as you try to use it. Arithmetic promotion: Unary operators: If the operand is byte. byte and short. no conversion needed. and arithmetic promotion. } else if one operand is float { Page 75 ©Copyright 2007. method call conversion. short or char { convert it to int. You can declare k without a value. All Rights Reserved C3: Protected . } } Refer File Name: Digit. } Binary operators: If the operand is double { all double. 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. cannot be converted to char and char cannot be converted to byte and short. boolean may not be converted to or from any type that is not boolean. int s = k + 3. } else { do nothing. Cognizant Technology Solutions.java to obtain soft copy of the program code How It Works: The preceding code will not compile.

} else if one operand is float { all double. short or char as provided in the following example) byte b = 10. convert the other operand to double. Page 76 ©Copyright 2007. There are four basic scopes: Static variables live basically as long as their class lives. b += 10. (Useful when applied to byte. } Summary Local variables (method variables) live on the stack.Handout . however.g. Block variables (e. All Rights Reserved C3: Protected . Scope of a variable refers to the lifetime of variable. in a for or an if) live until the block completes.Core Java all double. State true or false for the following: a) Extended assignment operators (for example +=) do an implicit cast. Objects and their instance variables live on the heap. convert all to int. Instance variables live as long as their object lives. they are temporarily unavailable. Test Your Understanding 1.. } else { all int. if their method invokes another method. Local variables live as long as their method is on the stack. convert the other operand to double. Cognizant Technology Solutions.

Core Java Session 18: Language Fundamentals and Operators Learning Objectives After completing this session. 10 System. 19 System.println(" i . 12 System.22. 5 int j = 42.y = " + (x – y)). 16 //subtracting numbers 17 System.println("Variable values. 13 System.println(" i + j = " + (i + j)).println("Adding. 15 System. 18 System.. All Rights Reserved C3: Protected . in case multiple operators are used in one statement.out. 20 21 //multiplying numbers Page 77 ©Copyright 2007. 9 System.println(" j = " + j). Cognizant Technology Solutions.j = " + (i – j)).out.").").println(" x .out...out.out.out. 11 System.out.println(" i = " + i).out...out.println(" x = " + x).println(" x + y = " + (x + y)). 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. 7 double y = 7..println(" y = " + y). 14 System.out. 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.out.println("Subtracting.Handout .").475. 8 System. 6 double x = 27.

.. i % j = 37 x % y = 5.. Cognizant Technology Solutions..println("Mixing types.695 Subtracting.println("Dividing. i * j = 1554 x * y = 198.println(" j + y = " + (j + y))....out.").58 Arithmetic Operators Note: When an integer and a floating-point number are used as operands to a single arithmetic operation.out.out. Page 78 ©Copyright 2007.37 Dividing.println(" i * j = " + (i * j)). //mixing types System. System.out. System.815 Mixing types..println(" x % y = " + (x % y)).. System.255 Multiplying.."). i = 37 j = 42 x = 27. j + y = 49. the result is a floating point..").println(" i * x = " + (i * x)).. i + j = 79 x + y = 34.Core Java 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 } System.println("Multiplying. All Rights Reserved C3: Protected .out. Arithmetic Operators: Sample Program Output Variable values. //dividing numbers System.j = -5 x . The integer is implicitly converted to a floating-point number before the operation takes place.out. //computing the remainder resulting from dividing // numbers System. System.println(" x * y = " + (x * y)).. i ..Handout . System.out. i / j = 0 x / y = 3.out.8054 Computing the remainder...22 i * x = 1016.").22 Adding..println("Computing the remainder.out.println(" x / y = " + (x / y)). System.println(" i / j = " + (i / j)).475 y = 7.y = 20.println(" i % j = " + (i % j)).out. System.... System...out.out.

Handout . For example: int i = 10. it causes the variable to be incremented or decremented by 1. evaluates to the value of op before it was incremented op---op Decrements op by 1. Increment and decrement operators increase and decrease a value stored in a number variable 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. //will result to k = 4+10 = 14 When the increment and decrement operators are placed after the operand.Core Java Increment and Decrement Operators unary increment operator (++) and unary decrement operator (--) are the two increment and decrement operators. 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. int j = 3. the old value of the variable will be used in the expression where it appears. count=count + 1. All Rights Reserved C3: Protected . For example the expression. //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. evaluates to the value of op before it was incremented ++op Increments op by 1. Page 79 ©Copyright 2007. int j = 3. k = ++j + i. int k = 0. For example: int i = 10. //increment the value of count by 1 is equivalent to count++.. and then the new value is used in the expression in which it appears. evaluates to the value of op before it was decremented Decrements op by 1. Operator Use ++ ++ --Description op++ Increments op by 1. int k = 0. Cognizant Technology Solutions. k = j++ + i.

println("Variable values.println("Less than or equal to.out.. 7 System.. evaluates to the value of op before it was incremented Decrements op by 1.out.out.out. 23 System..println("Greater than or equal to")..println(" j >= i = "+(j>=i)).println(" j <= i = "+(j<=i))..println(" k <= j = "+(k<=j)).println(" i > j = "+(i>j)).println(" i <= j = "+(i<=j)).//true Page 80 ©Copyright 2007.").out. 18 System.println("Greater than.//false 14 System..out.//false 25 System.out.out.//false 19 System.out.").//true 21 //less than 22 System. 13 System.println(" k = " +k).out.out.//true 24 System.println(" i < j = "+(i<j)).. 6 int k = 42. 5 int j = 42.out. 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.//true 20 System.//false 30 System. All Rights Reserved C3: Protected .println(" j > i = "+(j>i)). evaluates to the value of op before it was incremented Increments op by 1.println(" i == j = " + (i==j))..println("Equal to.println(" i = " +i). evaluates to the value of op before it was decremented Decrements op by 1.out.out.//true 29 System.out. 9 System.println(" j < i = "+(j<i)). 8 System.Core Java Operator ++ ++ --- Use op++ ++op op---op Description Increments op by 1.//true 15 System.//false 26 //less than or equal to 27 System.out.out. 10 System.println(" k >= j = "+(k>=j)).//true 31 //equal to 32 System. 11 //greater than 12 System.println(" i >= j = "+(i>=j)).out..println(" j = " +j).Handout .out.println(" k == j = " + (k==j)).").println(" k < j = "+(k<j)). Cognizant Technology Solutions.out.out. 33 System..//false 34 System.").out.").//false 16 //greater than or equal to 17 System.println(" k > j = "+(k>j)).out. 28 System.println("Less than.

out.. System. All Rights Reserved C3: Protected ..out.println(" i != j = " + (i!=j)).").//false } 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. There are six logical operators: && (logical AND) & (boolean logical AND) || (logical OR) Page 81 ©Copyright 2007. Cognizant Technology Solutions.Handout .//true System.out.. i != j = true k != j = false Logical Operators Logical operators have one or two boolean operands that yield a boolean result.println("Not equal to.Core Java 35 36 37 38 39 40 } //not equal to System.println(" k != j = " + (k!=j))..

out. If exp1 is false. Given an expression exp1 && exp2 where: && will evaluate the expression exp1. &. 5 boolean test= false. summarize the result of each operation for all possible combinations of x1 and x2. the & operator always evaluates both exp1 and exp2 before returning an answer.println(test). 9 System. 11 //demonstrate & 12 test = (i > 10) & (j++ > 9). The truth tables that will be shown next.Core Java | (boolean logical inclusive OR) ^ (boolean logical exclusive OR) ! (logical NOT) The basic expression for a logical operation is. while & does not. Logical Operators: &&(logical) and &(boolean logical) AND Here is the truth table for && and &: x1 TRUE TRUE FALSE FALSE x2 TRUE FALSE TRUE FALSE Result TRUE FALSE FALSE FALSE The basic difference between && and & operators is that && supports short-circuit evaluations (or partial evaluations). x1 op x2 where. 10 System. variables or constants. 13 System. 6 //demonstrate && 7 test = (i > 10) && (j++ > 9). and immediately return a false value 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. Cognizant Technology Solutions.out.println(j). x1.println(i). x2 can be boolean expressions.out. 14 System. 8 System. 1 public class TestAND { 2 public static void main( String[] args ){ 3 int i = 0. All Rights Reserved C3: Protected .println(i).out.out. op is either &&.Handout . | or ^ operator.println(j). In contrast. 4 int j = 10. Page 82 ©Copyright 2007.

All Rights Reserved C3: Protected .println(j). If exp1 is true. Page 83 ©Copyright 2007. that the j++ on the line containing the && operator is not evaluated because the first expression (i>10) is already equal to false System. } Logical Operators: || (logical) and | (boolean logical) inclusive OR Here is the truth table for || and |: x1 TRUE TRUE FALSE FALSE x2 TRUE FALSE TRUE FALSE Result TRUE FALSE FALSE FALSE The basic difference between || and I operators is that || supports short-circuit evaluations (or partial evaluations).Handout . 9 System. while | does not. 1 public class TestOR { 2 public static void main( String[] args ){ 3 int i = 0. 5 boolean test= false. 8 System. 6 //demonstrate || 7 test = (i < 10) || (j++ > 9).println(test). the | operator always evaluates both exp1 and exp2 before returning an answer.out.println(i). Cognizant Technology Solutions. 4 int j = 10.println(test).out.out.out. In contrast. 10 System.Core Java 15 16 17 } The output of the program is: 0 10 false 0 11 false Note. then the operator never evaluates exp2 because the result of the operator will be true regardless of the value of exp2. Given an expression exp1 || exp2 where: || will evaluate the expression exp1 and immediately return a true value if exp1 is true.

1 public class TestXOR { 2 public static void main( String[] args ){ 3 boolean val1 = true.out.println(i). Note that both operands must always be evaluated in order to calculate the result of an exclusive OR. 5 System. that the j++ on the line containing the || operator is not evaluated because the first expression (i<10) is already equal to true //demonstrate | test = (i < 10) | (j++ > 9). 7 System. val2 = false.Handout .out. if and only if one operand is true and the other is false. System. System.Core Java 11 12 13 14 15 16 17 } The output of the program is: 0 10 true 0 11 true Note. 9 System.println(val1 ^ val2).out.println(val1 ^ val2). All Rights Reserved C3: Protected . } Logical Operators: ^ (boolean logical exclusive OR) Here is the truth table for ^: x1 TRUE TRUE x2 TRUE FALSE Result TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE The result of an exclusive OR operation is TRUE.out. Page 84 ©Copyright 2007.println(val1 ^ val2).println(test). val2 = false. 8 val1 = false. 10 val1 = true.out.out. Cognizant Technology Solutions. val2 = true.println(j). System. 6 val1 = false. 4 boolean val2 = true.

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. 5 System.println(val1 ^ val2). } Logical Operators: ! ( logical NOT) The logical NOT takes in one argument. All Rights Reserved C3: Protected .out.println(!val2). Cognizant Technology Solutions. 4 boolean val2 = false.Handout . 6 System. variable. wherein that argument can be an expression.Core Java 11 12 13 } The output of the program is: false true false true System.println(!val1). 7 } 8 } The output of the program is: false true Logical Operators: Conditional Operator (?:) The conditional operator ? is a ternary operator.out. Here is the truth table for !. x1 TRUE FALSE Result FALSE TRUE 1 public class TestNOT { 2 public static void main( String[] args ){ 3 boolean val1 = true. or constant.out.

Core Java Result: If exp1 is true. All Rights Reserved C3: Protected . The instanceof operator cannot be used with primitive types (this results in a compilation error). then exp2 is the value returned If it is false.out. then exp3 is returned 1 public class ConditionalOperator { 2 public static void main( String[] args ){ 3 String status = "". 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'.println( status ). and C implements I. 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). and T is a subclass or subinterface of T' or equal to T'. interface. or array type specified by the right operand. 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.Handout . 5 //get status of the student 6 status = (grade >= 60)?"Passed":"Fail". The right operand is an interface name I. the left operand is an array of type T. 4 int grade = 80. 7 //print status 8 System. Page 86 ©Copyright 2007. Cognizant Technology Solutions. The right operand is an array of type T‘ .

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.Core Java The instanceof operator returns false if none of the preceding conditions are met or if the left operand is null.elementAt(0). keep your expressions simple and use parentheses.println(s instanceof Object). Try It Out Problem Statement: Write a program that illustrates the use of the instanceof operator.println(s instanceof String). Operator Precedence: Coding Guidelines To avoid confusion in evaluating mathematical operations. v.out. System.out.*. Page 87 ©Copyright 2007. class Instance { public static void main(String args[]) { String s = "abcd". Vector v = new Vector(). Cognizant Technology Solutions.add(s).. like ((6%2)*5)+(4/2)+88-10. Code: import java. All Rights Reserved C3: Protected . System. Object o = v.Handout .util.

Core Java System. (which means they refer to the same object on the heap) use the == operator. Foo b = new Foo().out.println(o instanceof String). Cognizant Technology Solutions. Tips and Tricks On what situations can you use the ‘==‘ operator? Solution: To compare two primitives. int b = 3. if (a == b) { // true} To see if two references are the same. use the equals() method. System. System. 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. Example: Foo a = new Foo(). use the == operator. All Rights Reserved C3: Protected . Page 88 ©Copyright 2007. if (a == b) { // false } if (a == c) { // true } if (b == c) { // false } To compare if two different objects are equal. } } Refer File Name: Instance.java to obtain soft copy of the program code How It Works: When you run the program.out.println(o instanceof Vector). Foo c = a.Handout .out. Example: int a = 3.println(o instanceof Object).

keep your expressions simple and use parentheses. Test Your Understanding 1. Cognizant Technology Solutions. State true or false for the following: a) The character pair ?: is called the relational operator. All Rights Reserved C3: Protected . Page 89 ©Copyright 2007. 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.Handout .Core Java Summary The different types of operators are: o o o o o Arithmetic operators Increment and decrement operators Relational operators Conditional operators Logical operators To avoid confusion in evaluating mathematical operations. b) In a mixed expression.

function. and so on while in object-oriented programming. 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)). Web page. All Rights Reserved C3: Protected . Cognizant Technology Solutions. menu. which may be a base or super class. JUnit is used by developers to implement unit tests in Java (de-facto standard) Page 90 ©Copyright 2007. Code quality is improved since the code is tested against the test cases at various stages. TDD gives rapid feedback. In procedural programming a unit may be an individual program. A unit is the smallest testable part of an application. procedure. JUnit JUnit is a regression testing framework.Core Java Session 21: Language Fundamentals and Operators Learning Objectives After completing this session. Unit Testing Unit testing is a procedure used to validate that individual units of source code are working properly.Handout . 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. abstract class or derived or child class. Write test cases first and then code it. the smallest unit is always a class.

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. Test methods must have no arguments. All Rights Reserved C3: Protected .Handout . Test methods are type of void. Xxx reflects the method of the target class. Page 91 ©Copyright 2007. Cognizant Technology Solutions.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.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().

} // Test code public void testSomething() { System.textui. String s2 = new String(“abcd”).framework.class)."). } Page 92 ©Copyright 2007.out. Cognizant Technology Solutions. All Rights Reserved C3: Protected .run(SimpleTest.Core Java Example 1: Very Simple Test import junit.. assertTrue(“Strings not equal”.println("About to call assertTrue() method. assertTrue(4 == (2 * 2)). } } 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”). s1.TestRunner. public class SimpleTest extends TestCase { public SimpleTest(String name) { super(name).equals(s2)).TestCase.Handout . } // You don't have to have main() method.. use Test runner public static void main(String[] args){ junit.

nextToken())).Core Java // Could run the test in batch mode public static void main(String[] args){ junit. boolean condition) assertFalse() statement asserts that the given condition is false o o assertFalse(boolean condition) assertFalse(String message. Object actual) Page 93 ©Copyright 2007.) o assertXxx(String message..TestRunner.class)).addTest(new StringTest((String)tokens. if (tests == null){ suite. ". All Rights Reserved C3: Protected . } } return suite..Handout .textui. actual) assertSame() statement asserts that the expected result is same as the actual behavior o assertSame(Object expected. actual) o assertEquals(String message. } else { StringTokenizer tokens = new StringTokenizer(tests. Cognizant Technology Solutions.."). boolean condition) assertEquals() statement asserts that the expected result is equal to the actual behavior o assertEquals(expected. expected. } Assert Statements JUnit assertions are methods starting with the keyword assert. assertTrue() statement asserts that the given condition is true: o assertTrue(boolean condition) o assertTrue(String message.getProperty("tests"). Object expected.run (suite ()).addTest(new TestSuite(StringTest. String tests = System. } // continued … // Create TestSuite object public static Test suite (){ suite = new TestSuite ("StringTest"). 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.) The message is displayed when assertXxx() fails. Object actual) o assertSame(String message.hasMoreTokens()){ suite. while (tokens. Two variants are: o assertXxx(. .

Class testClass) Test Suites can have hierarchy Page 94 ©Copyright 2007.String name>) addTest(Test test) or addTestSuite(java. assertTrue(result == 5. Object obj) assertNotNull() statement asserts that the object reference is not null o assertNotNull(Object obj) o assertNotNull(String message.lang. <java.0).Class theClass.Core Java assertNull() statement asserts that the object reference is null o o assertNull(Object obj) assertNull(String message. } public void testMultiply() { double result= fValue1 * fValue2.0. } public void testAdd() { double result= fValue1 + fValue2. } } Test Suites Test Suites are used to collect all the test cases Test Suites can contain testCases and testSuites: TestSuite(java. fValue2= 3. Example: setUp public class MathTest extends TestCase { protected double fValue1.0).Handout .lang. All Rights Reserved C3: Protected . protected void setUp() { fValue1= 2. assertTrue(result == 6. Cognizant Technology Solutions.0. The setUp() method is run before every test invocation and the tearDown() method is run after every test method. fValue2.lang. 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.

class)). suite.05 Tests run: 7.TestRunner... Time: 0. quick quiet Run from command line Example: java StringTest .. All Rights Reserved C3: Protected .Handout ..addTest(new TestSuite(FloatTest.run (suite ()).addTest(StringTest. } TestRunners Highlights of the Test Runner in text mode: Lightweight.swingui. Cognizant Technology Solutions.. Errors: 0 TestRunners: Swing Run with java junit.TestRunner: Page 95 ©Copyright 2007.. suite.addTest(new TestSuite (AllTests. suite.suite()).class). Failures: 0.class)). return suite. suite.addTest(new TestSuite(BoolTest. } public static Test suite() { TestSuite suite = new TestSuite(IntTest.textui.Core Java Example: Test Suites public static void main (String [] args){ junit.class)). } public void testAllTests () throws Exception{ assertTrue (suite != null). } public static Test suite (){ suite = new TestSuite("AllTests").

All Rights Reserved C3: Protected . 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.Handout . Cognizant Technology Solutions.dir}" /> Page 96 ©Copyright 2007.Core Java The swingui TestRunner provides the summary of test runs in GUI mode.

which could break Write test case methods such that the testing should succeed quietly What should not you test Do not write test case methods for the setter or getter methods Do not write test case methods for the compiler Page 97 ©Copyright 2007. All Rights Reserved C3: Protected .Handout .dir}"> <include name="**/*Test.dir}/test" /> </classpath> <formatter type="plain" usefile="yes"/> <batchtest fork="yes" todir=""> <fileset dir="${test.Core Java <pathelement location="${build.java" /> </fileset> </batchtest> </junit> </target> JUnit Class Diagram Class diagram of JUnit framework API Best Practices: What Should You Test? Tests things. Cognizant Technology Solutions.

Cognizant Technology Solutions. implementations are pluggable. The test cases should be written keeping the following factors in mind are performance. } catch(NullPointerException ex) { assertTrue(true). Obviously.. fix the bug and watch the bar go green!! Your tests assure that the bug will not reappear. this test is needed. Now. code a little. code a little. Page 98 ©Copyright 2007.toString(). 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. maintainability. Write a 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. All Rights Reserved C3: Protected . } } Test Then Fix Bugs occasionally slip through (gasp!).. Test then Refactor Once the code is written you will want to improve it. fail("Should see null pointer"). try { s1. test a little.Handout . Test a little.Core Java Test First and What to Test Key points on Testing Write your test first. Tests help you to make sure that you do not break it while improving it. which demonstrates the error. String s2 = new String("abcd"). and readability.

Cognizant Technology Solutions. JUnit Extensions The extensions of JUnit are: JUnitReport Cactus JWebUnit XMLUnit MockObjects StrutsTestCase JUnitReport JUnitReport is an Apache Ant extension task. which can be used across multiple implementations Promotes frequent testing by writing tests. All Rights Reserved C3: Protected . the external system or database can be simulated. which factory is used.Core Java Design for Testing: Factories Allows writing tests. 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. 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. For example. the testing gets continued with the mock objects. using the mock objects concept. Testing with Resources (EJB or DB) Testing with resources use fixtures to request resource connection by factory pattern. Data initialization or clearing is handled by fixtures to preserve order independence of tests. This uses XML and XSLT to generate HTML.Handout . In these cases. Page 99 ©Copyright 2007. Testing with resources also use vm args or resource bundle to drive. The mock objects mock the functionality of the desired resource.

XMLUnit XMLUnit provides a XMLTestCase class.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. All Rights Reserved C3: Protected . Cognizant Technology Solutions. 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.

class).java. Mock object: "double agent" used to test the behavior of other objects Dummy object. import junit. protected void setUp() throws Exception { super.TestRunner. public class HelloTest extends TestCase { public static void main(String[] args) { junit.run(HelloTest. Code: package com. } // continued … Refer Files: Hello. 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.textui.setUp(). All Rights Reserved C3: Protected .TestCase.testing.java to obtain soft copy of the program code Page 101 ©Copyright 2007. } Hello hello = new Hello().Core Java Mock Objects The goal of generic unit testing framework is to facilitate developing unit tests in the mock object style. HelloTest.framework. Cognizant Technology Solutions. 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.Handout .

The class only contains getters and setters for the string ‘str’. which is to be. create a new JUnit test case by clicking NEW > JUnit Test Case.Core Java How It Works: To test a file using JUnit tool in SDE. which all methods you need to test in the Hello class. All Rights Reserved C3: Protected . tested using JUnit.Handout . 1. Page 102 ©Copyright 2007. Hello is the class. Like in this case. There you can also give the name of the class you are intending to test. Click Next to go the next page where you can specify. Cognizant Technology Solutions.

Click Finish to create the JUnit test case. All Rights Reserved C3: Protected . 3. To run the JUnit test. right click on the test case class created and click on RUN > JUnit Test. Cognizant Technology Solutions.Core Java 2. The JUnit window will be opened indicating which were the tests that failed and which all passed. Write your logic in the test method that is automatically generated. 5. 4.Handout . Page 103 ©Copyright 2007.

In this case. You can also see the expected and the actual result by clicking the ‘Compare actual with the expected result’ button. All Rights Reserved C3: Protected .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. the expected result was ‘Hello world” but the actual result was ‘Hello world!”.Handout . Cognizant Technology Solutions. Page 104 ©Copyright 2007.

out.sun. Test a little.3=javax. The latter is probably more sensible.* excluded. javax. which classes are never reloaded. which classes should never be reloaded. This class loader uses a special list.Core Java Tips and Tricks You have got really strange ClassNotFoundExceptions with JUnit 3. so you will not have unpacked jars cluttering your directory structure.properties file to add packages like org. test a little. and edit the excluded.println().xml. then the following explanation is probably correct: The graphical test runners apply a different class loader than the text version. Run all the tests in the system at least once per day (or night).2=org.*. code a little.8=org.* excluded.* Summary Testing Idioms: Keep the following things in mind when writing JUnit tests: o o o o o o o The software does well those things that the tests check.. code a little.Handout . write a test to automatically check the result instead.* and org.4=sunw.0=sun.* .1=com. Write tests that have the highest possible return on your testing investment. you need to either unpack your external jar. All Rights Reserved C3: Protected . If you find yourself debugging using System.5=java. and it typically contains classes such as sun.properties to define.6=junit.* excluded. and as most of the external libraries are distributed as such.jar file and apply that. Then repack the junit.* excluded.apache.properties file: # # The list of excluded package paths for the TestCaseClassLoader # excluded..* excluded.jar file. com. The class loader does not load files from a jar-file. Here is an example of excluded.* excluded. junit/runner/excluded.omg.* excluded.* .apache. or tell the JUnit class loader. Page 105 ©Copyright 2007.sun.7=oracle. You need to unpack the junit.* . Make sure all tests always run at 100%.* excluded. Write tests for the areas of code with the highest probability of breakage. and so on.7 Solution: Does your class work fine if you run the test cases using the TextRunner? If yes. Cognizant Technology Solutions.

All Rights Reserved C3: Protected . The next time someone asks you for help debugging. help them write a test. Page 106 ©Copyright 2007.Handout . b) setUp() is run before every test invocation and tearDown() is run after every test method. Test Your Understanding 1.Core Java o o o When a bug is reported. write a test to expose the bug. Write unit tests before writing the code and only write new code when a test is failing. State true or false for the following: a) JUnit is a regression testing framework. Cognizant Technology Solutions.

number2 = 2. int []ages. Page 107 ©Copyright 2007. int number3. array of multiple dimension.Core Java Session 23: Language Fundamentals and Operators Learning Objectives After completing this session. divided into a number of slots. Declaring Arrays To declare an array. in a contiguous block of memory. int number1. All Rights Reserved C3: Protected . An array stores multiple data items of the same data type. followed by the identifier name. Cognizant Technology Solutions. For example.Handout . In Java and other programming languages. you will be able to: Define an array Declare an array Instantiatiate an array Access array element Identify array length. it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose. number1 = 1. int number2. or int ages[]. and Enum Introduction to Arrays Suppose you have here three variables of type int with different identifiers for each variable. followed by a set of square brackets[]. write the data type. As you can see. This type of variable is called an array. there is one capability wherein you can apply one variable to store a list of data and manipulate them more efficiently. number3 = 3.

int arr[] = {1. you need to use a constructor for this. //instantiate object ages = new int[100]. For example. This statement declares and instantiates an array of integers with five elements (initialized to the values 1. 4. Page 108 ©Copyright 2007. and 5). 2. 2. or. 3. //declaration int ages[]. 5}. You will cover more about instantiating objects and constructors later. followed by the square brackets containing the number of elements you want the array to have.Core Java Array Instantiation After declaring. 4. All Rights Reserved C3: Protected . this means creation Constructor: In order to instantiate an object.Handout . //declare and instantiate object int ages[] = new int[100]. A constructor is a method that is called to create a certain object. Cognizant Technology Solutions. can also be written as. To instantiate (or create) an array. Definitions: Instantiation: In Java. For example. write the new keyword. 3. Sample diagram illustrating array instantiation You can also instantiate an array by directly initializing it with data. you must create the array and specify its length with a constructor statement.

9 10 double []grades = {100. 90. “Thu”. “Sat”. “Sun”}. //prints the last element in the array System. This array contains 7 elements 14 15 String days[] = { “Mon”. the stored value of each member of the array will be initialized to zero for number data. 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). 75}.print(ages[99]). 80. “Fri”. 90. 80.out. you have: //assigns 10 to the first element in the array ages[0] = 10. “Tue”. Index number or subscript: Assigned to each member of the array. 11 12 //creates an array of Strings with identifier days and 13 //initialized. 75}. false }. 6 7 //creates an array of 4 double variables initialized 8 //to the values {100. “Wed”. false} 4 5 boolean results[] = { true. false. in the given array you have declared a while ago (see slide 10). you must populate the String arrays explicitly. or a part of the array.Core Java Sample Program 1 //creates an array of boolean variables with identifier 2 //results. Accessing an Array Element To access an array element. true. This array contains 4 elements that are 3 //initialized to values {true. you use a number called an index or a subscript. Therefore.Handout . false. For reference data types such as Strings. All Rights Reserved C3: Protected . true. Cognizant Technology Solutions. they are not initialized to blanks or an empty string “”. Page 109 ©Copyright 2007. For example. Note: Once an array is declared and constructed.

This uses a for loop. you can use the length field of an array. Page 110 ©Copyright 2007. 7 } 8 } 9 } Coding Guidelines When creating for loops to process the elements of an array. 1 public class ArraySample{ 2 public static void main( String[] args ){ 3 int[] ages = new int[100]. Remember you cannot resize an array. so your code is shorter. int []arr. The elements of an n-element array have indexes from zero to n-1. This will allow the loop to adjust automatically for different-sized arrays. use the length field of the array object in the condition statement of the for loop. i++ ){ 6 System. i++ ){ 5 System. arr = new int[100]. It can be applied by writing. arrayName. Cognizant Technology Solutions. Note that there is no array element arr[n]! This will result in an array-index-out-of-bounds exception. For example. int []arr = new int[100].Handout . All Rights Reserved C3: Protected .print( ages[i] ).out. The length field of an array returns the size of the array. 6 } 7 } 8 } Coding Guidelines It is usually better to initialize or instantiate the array right away after you declare it.length 1 public class ArraySample { 2 public static void main( String[] args ){ 3 int[] ages = new int[100]. 4 5 for( int i=0. the declaration.Core Java The following is a sample code on how to print all the elements in the array. Array Length In order to get the number of elements in an array. 4 for( int i=0.length. is preferred over. i<ages.out.print( ages[i] ). i<100.

{ "Kristin". For example.Core Java Declare the sizes of arrays in a Java program using named constants to make them easy to change. you write. you define an enum type by using the enum keyword. . //declare a constant . Multidimensional Arrays Multidimensional arrays are implemented as arrays of arrays. This will print the String "terry" on the screen. // character array 8 x 16 x 24 char[][][] threeD = new char[8][16][24]. final int ARRAY_SIZE = 1000. For example. // String array 4 rows x 2 columns String[][] dogs = {{ "terry". To access an element in a multidimensional array is just the same as accessing the elements in an one dimensional array. "white" }. EAST. For example: // integer array 512 x 128 elements int[][] twoD = new int[512][128]. "black"} }. Page 111 ©Copyright 2007. Cognizant Technology Solutions. enum Keyword In the Java programming language. SOUTH. { "toby". the names of the fields of an enum type are in uppercase letters. int[] ages = new int[ARRAY_SIZE]. and WEST) and the days of the week.out.Handout . As they are constants. Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name. Enum An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH. "brown" }. "gray"}.print( dogs[0][0] ). System. { "fido". to access the first element in the first row of the array dogs. All Rights Reserved C3: Protected . .

SATURDAY } enum Type You should use enum types any time you need to represent a fixed set of constants. public EnumTest(Day day) { this. The compiler automatically adds some special methods when it creates an enum.Handout .lang. As Java does not support multiple inheritance. You cannot invoke an enum constructor on yourself. command line flags. WEDNESDAY. It automatically creates the constants that are defined at the beginning of the enum body. the following code iterates over all the planets in the solar system. Detailed Example Here is some code that shows you how to apply the Day enum defined earlier: public class EnumTest { Day day. 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). + p. the choices on a menu. All Rights Reserved C3: Protected . for (Planet p : Planet. THURSDAY. they have a static values method that returns an array containing all of the values of the enum in the order they are declared. an enum cannot extend anything else. FRIDAY.Enum. TUESDAY.out. The constructor for an enum type must be package-private or private access. Cognizant Technology Solutions.println(“Your weight on ” + p + “ is : ”. The enum class body can include methods and other fields. Example: enum in for Loop For example.day = day. you would specify a days-of-the-week enum type as: public enum Day { SUNDAY. } Key Points on enum and its Constructor All enums implicitly extend java. 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. For example.Core Java For example. } public void tellItLikeItIs() { Page 112 ©Copyright 2007. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. MONDAY.values()) { System.surfaceWeight(mass)).

Core Java switch (day) { case MONDAY: System. } } public static void main(String[] args) { EnumTest firstDay = new EnumTest(Day. break.tellItLikeItIs().tellItLikeItIs(). firstDay. fifthDay.println("Midweek days are so-so.out.").").WEDNESDAY). EnumTest thirdDay = new EnumTest(Day. break.println("Mondays are bad. case FRIDAY: System. myBird. Midweek days are so-so. sixthDay. Weekends are best.FRIDAY). All Rights Reserved C3: Protected . Try It Out Problem Statement: Consider the following : Bird myBird = new Bird().SATURDAY).println("Weekends are best.out. EnumTest seventhDay = new EnumTest(Day.MONDAY). EnumTest sixthDay = new EnumTest(Day.SUNDAY). seventhDay.").tellItLikeItIs().tellItLikeItIs().out.name = “Parrot”. Page 113 ©Copyright 2007. } } Output The output is: Mondays are bad.Handout . Cognizant Technology Solutions.tellItLikeItIs().out. thirdDay. EnumTest fifthDay = new EnumTest(Day. case SATURDAY: case SUNDAY: System."). break. Fridays are better.println("Fridays are better. break. default: System. Weekends are best.

fly(). public void sing() { }.sing().name = “Parrot”. You must include the size of an array when you construct it (using new) unless you are creating an anonymous array.name = “Parrot”.sing(). Stuff those ints into the array. myBirds[0].Handout . public static void main(String[] args) { Bird[] myBirds = new Bird[3]. Summary Arrays can hold primitives or objects. All Rights Reserved C3: Protected . but the array itself is always an object. cuckoo. the square brackets can be placed left side or right side of its name. Instead. but on what? Code: class Bird { String name. Page 114 ©Copyright 2007. you have created a Bird object and used the dot operator on the reference variable myBird to access the name variable. then the declared return type can be an int array. 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. if you want to return.java to obtain soft copy of the program code How It Works: When the Bird is in an array. } } Refer File Name: Bird. myBirds[0]. For example myBirds[0]. you do not have an actual variable name (like “myBird”). What happens if the Bird is in a Bird array? You can access the instance variables of Bird and methods using the dot operator.Core Java From the preceding code. myBirds[0] = new Bird(). You can further use the myBird reference to get the bird to sing() or fly()as given below: cuckoo. three int values. say. Cognizant Technology Solutions. but. you apply array notation and the dot operator on an object at a particular index (position) in the array. and pass it on back. When you declare a array.

Which one of the following is true? a) All elements of an array should be of the same type. Test Your Understanding 1. Arrays are indexed beginning with zero. Page 115 ©Copyright 2007. An ArrayIndexOutOfBoundsException occurs if you use a bad index value. Multidimensional arrays are just arrays of arrays. Which one of the following is true? a) A two-dimensional array is stored internally as a one-dimensional array. The dimensions in a multidimensional array can have different lengths. Cognizant Technology Solutions.Handout . d) All the earlier options are true. 2. b) The ‘for’ loop shall be used to initialize the elements of an array. d) All the earlier options are true.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. c) More than two dimensions are allowed in Java. b) The range of an array index is checked in Java. The last index you can access is always one less than the length of the array. c) You cannot create a larger array and supply fewer values. All Rights Reserved C3: Protected .

Character class has the method charValue() . Selection Statements and Iteration Blocks Learning Objectives After completing this session. and so on Example: int unWrapped = iWrap. 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. or wraps. All Rights Reserved C3: Protected .Handout . Boolean class has the method booleanValue().lang package that extend the Object superclass like all Java classes. Integer iWrap = new Integer(i).intValue(). Cognizant Technology Solutions. The wrappers are normal classes in the java. An instance of a wrapper contains. the wrappers come with the same name as the corresponding primitive type except that the first letter is capitalized: o o o Integer is a wrapper class of the primitive int Character is a wrapper class of the primitive char 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. UnWrapping a value: Each wrapper class has its own method for unwrapping a value. a primitive value of the corresponding type.Core Java Session 26: Wrapper Classes. For example. Page 116 ©Copyright 2007. Other than for the primitive type int.

The elements of a Vector instance are object references. String pennsylvania = "65000". The wrapper classes also provide various tools such as constants (the smallest and largest possible int value. a very useful tool is as the Vector class. Each wrapper has a similar method to access the primitive value: intValue() for Integer. For example.Core Java Why Should You Use Wrapper Classes? Wrappers allow for situations where numerical values are needed but objects instead of primitives are required.0. The following statement converts an Integer object to its primitive data type int. For example. Converting Primitive Types to Objects (Wrapper) and the Reverse The wrapper constructors create class objects from the primitive types. If one wants to use a Vector to hold a list of numbers. Page 117 ©Copyright 2007. In turn. Double aDouble = new Double(d). booleanValue() for Boolean. each wrapper provides a method to return the primitive value like: double r = aDouble. The result is an int with value 7801. int penn = Integer. which is a list that that can grow or shrink. Cognizant Technology Solutions. then the numbers must be wrapped in instances of their corresponding type. A common translation you need in programs is converting a String to a numeric type.Handout . such as an int (Object->primitive). int newCount = dataCount. All Rights Reserved C3: Protected .doubleValue(). Here a Double wrapper object is created by passing the double value in the Double constructor argument. for example) and static methods.intValue(). You will often use wrapper methods to convert a number type value to a string or a string to a number type. Integer dataCount = new Integer(7801).parseInt(pennsylvania). for a double floating point number "d" : double d = 5. and so forth The following statement creates an instance of the Integer class with the integer value 7801. unlike an array.

Example: If you create a wrapper object like: Integer iWrap = new Integer(25). then. System. Boolean booleanObj = new Boolean("True"). but then you will have two objects. Applying the static utility methods (for example. System. The value of iWrap will always be 25 You can.booleanValue(). There is no setter method for a wrapper object. /* object to primitive */ booleanVar = booleanObj.out.println("booleanVar = " + booleanVar). Try It Out Problem Statement: Write a program that illustrates the use of Boolean Wrapper class.println("compare 2 wrapper objects: " + booleanObj. System.println("booleanVar = " + booleanVar). refer iWrap to a different wrapper object. Integer.out. of course. /* * primitive to object. can also use valueOf method */ Boolean booleanObj2 = new Boolean(booleanVar). System.parseInt()). Once you create a wrapper object.out.println("booleanObj = " + booleanObj). } } Refer File Name: BooleanWrapper. System. there is no way to change the value of that object.java to obtain soft copy of the program code Page 118 ©Copyright 2007.Core Java Wrappers are Immutable The two main applications of wrapper classes are: Wrapping a primitive so it can pretend to be an object.Handout .out. All Rights Reserved C3: Protected .println("booleanObj2 = " + booleanObj2).equals(booleanObj2)). Code: class BooleanWrapper { public static void main(String args[]) { boolean booleanVar = 1 > 2.out. Cognizant Technology Solutions.

Core Java How It Works: When you run the program. returns a wrapped object.parseInt() works only on Strings that represent the ASCII values for digits (0.parseInt() is used to get the int value of a String Integer. b) The isNaN() method is made available by the Double class. All Rights Reserved C3: Protected .9).7.8. Test Your Understanding 1. and throws NumberFormatException o valueOf() takes a String.2. Summary The wrapper classes correlate to the primitive types. then the code will throw an exception.lang package. d) The Runtime class encapsulates the java run time environment. c) A number cannot be converted to and from Strings. throws NumberFormatException Wrapper constructors can take a String or a primitive.4. 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.5.6. Which one of the following is wrong? a) All the type wrappers are defined in java. Cognizant Technology Solutions. e) ‘Like the String class. returns a primitive o parseXxx() takes a String. which can only take a char.3.parseInt() if the thing you pass is not a number? And does it recognize spelled-out numbers like “three”? Solution: Integer.Handout . the wrapper classes are immutable’. except for Character. If you try to parse something like “two” or “real”. Wrappers have two main functions: o o To wrap primitives so that they can be handled like objects. To provide utility methods for primitives (usually conversions) The three most important methods available in the wrapper classes are: o xxxValue() takes no argument. Page 119 ©Copyright 2007. returns a primitive.1. Comment on this statement.

Short java.lang. All Rights Reserved C3: Protected .Long java.lang.Character java.lang.Boolean byte char double float int long short void java.lang. 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.Integer java. Cognizant Technology Solutions. You occasionally want to pass values to an applet.lang.Float java.lang.lang.Core Java Session 27: Wrapper Classes..> <param name = "string_name" value = "string_value" > </applet> Page 120 ©Copyright 2007.Byte java.lang.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.Handout .. The applet hypertext tag includes the param sub-tag for this like the following: <applet . Selection Statements and Iteration Blocks Learning Objectives After completing this session.Double java.

…… shows the use of the parseDouble method in Double and the parseInt method in Integer.45"> <param name="intNumber" value="10"> </applet> In the applet code. For example. String intStr = getParameter ("intNumber"). Cognizant Technology Solutions. 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.Handout . String iStr = String. you could pass two strings with numbers like the following: <applet code="myApplet" codebase="Java" width=100 height=50> <param name="fpNumber" value="12. You now have the parameter values in string form and need to convert them to numbers. Page 121 ©Copyright 2007. double d = 5.0. The String class provides the static valueOf methods (there is one for each primitive type). it is the only overloaded operator) as a string concatenator. For example. Anything added to a string is also a string.valueOf(i). String dStr = String. 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.parseInt (intStr). int intNum = Integer. the following code: public void init () { string fpStr= getParameter ("fpNumber"). The parameter has a name and corresponding value. The wrapper classes provide tools for this in the form of static methods.Core Java for passing strings to the applet program. All Rights Reserved C3: Protected . you then use the getParameter(String) method from the applet class to obtain a given parameter.parseDouble (fpStr). Converting Primitive Types to Strings You can convert a primitive type to a string in several ways. as in the following code: String fpStr = getParameter ("fpNumber").valueOf(d). usually in the init() method. double fpNum = Double. String intStr = getParameter ("intNumber").

Handout .get(0). } Autoboxing Illustrations The general rule is that boxing and unboxing work wherever you can normally use a primitive or a wrapped 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. Cognizant Technology Solutions.Core Java In the following code. Without Autoboxing (Java versions before 5.0 and 1. } With Autoboxing (Java versions 5. int intOne = one.0 does the conversion (wrapping) from primitive to wrapper object.0) Example: An ArrayList of primitive ints public void doNumsOldWay() { ArrayList listOfNumbers = new ArrayList listOfNumbers.add(new Integer(3)).add(3). while aStr holds "d = 5.0" and bStr holds "i = 1“. Integer one = (Integer) listOfNumbers. Autoboxing The autoboxing feature added to Java 5. listOfNumbers. All Rights Reserved C3: Protected .get(0). String bStr = "i = " + i. int num = listOfNumbers. you convert numerical values to strings using the "+" operator: String aStr = "d = " + d.0 or greater) Example: An ArrayList of primitive ints public void doNumsNewWay() { ArrayList<Integer> listOfNumbers = new ArrayList<Integer>. Now dStr and iStr objects hold string representations of 5. It can be illustrated in the following: Method arguments Return values Boolean expressions Operations on numbers Assignments Page 122 ©Copyright 2007.intValue().

Short. int.Handout . Boolean Expressions Any place a boolean value is expected. while. If a method takes a primitive. Integer. All Rights Reserved C3: Protected .4. the if. Operations on Numbers This is probably the strangest one. If a method declares a wrapper return type. or char type in Java 1. Example: int giveNumber() { return x. or a primitive boolean.4 and earlier to Java 1.Core Java Method Arguments If a method takes a wrapper type.0. those flow control statements now also accept expressions that evaluate to Boolean types. Example: boolean one = true. you can use either an expression that evaluates to a boolean (4 > 2). then you can pass in either a compatible primitive or a reference to a wrapper of that primitive type. short. Cognizant Technology Solutions. } In the preceding example. the old switch statement expects a byte. then you can return either a compatible primitive or a reference to the wrapper of that primitive type. Through the use of unboxing. You can now use a wrapper type as an operand in operations where the primitive type is expected.0. and do-while statements are all expected as boolean expressions. and Character types. x can be either a reference to Integer wrapper or int primitive type. Boolean type if (one && two) // nothing new here // autoboxing of primitive 'true' to // auto unboxing do_something (). Page 123 ©Copyright 2007. or a reference to a Boolean wrapper. Example: void takeNumber(Integer i) { } Return Values If a method declares a primitive return type. then you can return either a reference to the wrapper type or a primitive of the matching type. switch now also accepts Byte. Boolean two = true. Before Java 5. then you can pass a reference to a wrapper or a primitive of the matching type. Autoboxing With Switch Statement Similarly. With the addition of autoboxing in Java 5.

the increment operator against a reference to an Integer object! Examples: Integer i = new Integer(56).java to obtain soft copy of the program code Page 124 ©Copyright 2007. i++. } } Refer File Name: WrappedClassApp.toString(m.out.println(Long.forDigit(j. In the preceding example. 8)).println(). Code: public class WrappedClassApp { public static void main(String args[]) { Boolean b1 = new Boolean("TRUE"). for (int j = 0. For example. Boolean b2 = new Boolean("FALSE"). say.print(Character. and boolean. System.MAX_VALUE). long m = l. ++j) System. long.toString()).parseLong("abcd". System. System. float.MIN_VALUE).out.println(b1. Long l = new Long(Long.toString() + " or " + b2.println(Float.out. j < 16.out.longValue() * i. Example: Double d = x. System.println(Double. Integer j = new Integer(4). 16)). double.longValue().Handout .Core Java That means you can apply.parseInt("ef".out. char. All Rights Reserved C3: Protected . Cognizant Technology Solutions. 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. Integer i = new Integer(Integer. 16)). Integer k = j + 3. 16)). Assignments You can assign either a wrapper or primitive to a variable declared as a matching wrapper or primitive. System. 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.out.

They are displayed in lowercase.println(“Hypotenuse is “ + c). Cognizant Technology Solutions. they are used to convert strings representing hexadecimal numbers into Integer and Long values. c = Math. In the example. The static parseInt() and parseLong() methods are used to parse strings according to different radices.0.Core Java How It Works: The program examines some of the more useful methods provided by the wrapped classes. It assigns these objects to b1 and b2 and then converts them back to String objects when it displays them. it is possible to write code like this: // A bad use of autoboxing/unboxing! Double a.5 and further) includes autoboxing and auto-unboxing.Handout .7976931348623157E308 Tips and Tricks: Typical problems include real-time problems or challenges: Java 5 (JDK 1. These values are then multiplied together and converted to a string that represents the resulting value in base 8. abandoning primitives altogether. System. All Rights Reserved C3: Protected . c. b.4E-45 1. Page 125 ©Copyright 2007.0. The program then executes a for loop that prints out the character corresponding to each of the hexadecimal digits. a = 10. This is accomplished using an overloaded version of the toString() method. b = 4.out. The sample program concludes by displaying the minimum float value and the maximum double value. A developer might be tempted to apply objects such Integer or Double exclusively. 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. It creates two objects of class Boolean from string arguments passed to their constructors. The output of the program is as follows: true or false 0123456789abcdef 50062143 1. as boolean values are traditionally represented.sqrt(a*a + b*b). For example. using the predefined class constants of the Float and Double classes.

objects of type Double hold values that are used to calculate the hypotenuse of a right triangle.Core Java Solution: In this example. and in fact. There is no way for the process to produce the wrong type of object or value. Summary As of Java 5.Handout . Page 126 ©Copyright 2007. b) Using Java 5 (JDK 1. All Rights Reserved C3: Protected . and auto-unboxing always produces the proper value. Test Your Understanding 1. wrappers with the same small values (typically lower than 127).5 and furhter). Although this code is technically correct. In general. the method calls such as intValue() or doubleValue() are very much needed in the code. It is far less efficient than the equivalent code written applying the primitive double. Cognizant Technology Solutions. you should restrict your use of the type wrappers to only those cases in which the object representation of a primitive type is required. work properly. State true or false for the following: a) Autoboxing always creates the proper object. The reason is that each autobox and auto-unbox adds overhead that is not present if the primitive type is used. Using the == with wrappers is tricky. autoboxing / unboxing allow you to convert primitives to wrappers or to convert wrappers to primitives automatically. it is a very bad use of autoboxing or unboxing. will be ==. larger values will not be ==.

you will be able to: Use decision control structures (if. Selection Statements and Iteration Blocks Learning Objectives After completing this session. which allows selection of specific sections of code to be executed. if-statement has the form: if( boolean_expression ) statement or if( boolean_expression ){ statement1. switch). All Rights Reserved C3: Protected . 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. } where boolean_expression is either a boolean expression or boolean variable. 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. if-else.Core Java Session 30: Wrapper Classes.Handout . statement2. Page 127 ©Copyright 2007. Cognizant Technology Solutions.

For example.out. which means that the execution of the condition should either result to a value of true or a false. Example 2: int grade = 68. } Coding Guidelines The boolean_expression part of a statement should evaluate to a boolean value.Handout . if( grade > 60 ) System.println("You passed!"). //statement2. if( boolean_expression ) { //statement1. Cognizant Technology Solutions.Core Java if-statement Flowchart The following figure shows the flowchart of an if statement: Examples of if-statement Example 1: int grade = 68.println("Congratulations!").out.println("Congratulations!"). All Rights Reserved C3: Protected . if( grade > 60 ) { System. } Page 128 ©Copyright 2007. Indent the statements inside the if-block. System.out.

out.out.println("Sorry you failed").println("Congratulations!"). All Rights Reserved C3: Protected .Handout . Example 2: int grade = 68. .println(“You passed!"). statement4. . if( grade > 60 ){ System. System.out. } if-else Flowchart The following figure shows the flowchart of an if-else statement: Examples of if-else Statement Example 1: int grade = 68. statement2. } else { statement3. Cognizant Technology Solutions. if-else statement has the form: if( boolean_expression ) { statement1. . . else System. . if( grade > 60 ) System.out. and a different statement if the condition is false. } Page 129 ©Copyright 2007.Core Java if-else Statement if-else statement is used when you want to execute a certain statement if a condition is true. .println("Congratulations!").

Handout . All Rights Reserved C3: Protected .out. } Coding Guidelines To avoid confusion. The statement has the form: if( boolean_expression1 ) statement1. else statement3. For example. You can have nested if-else blocks.Core Java else{ System. 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.println("Sorry you failed"). This cascading of structures allows you to make more complex selections. if-else-else if Flowchart The following figure shows the flowchart of an if-else-else if statement: Page 130 ©Copyright 2007. always place the statement or statements of an if or if-else block inside brackets {}. This means that you can have other if-else blocks inside another if-else block. Cognizant Technology Solutions. else if( boolean_expression2 ) statement2.

println("Sorry you failed").out.Core Java Example of if-else-else if Statement Example: int grade = 68.Handout . for example. } Common Errors The condition inside the if-statement does not evaluate to a boolean value.println("Good"). Cognizant Technology Solutions.out. All Rights Reserved C3: Protected . } else if (grade > 60){ System. if( grade > 90 ){ System. } else{ System. //WRONG int number = 0. if( number ) { //some statements here } The variable number does not hold a boolean value.println("Very good!"). Page 131 ©Copyright 2007. Writing elseif instead of else if Using = instead of == for comparison.out.

Core Java For example.out. 5 if( grade >= 90 ){ 6 System. 10 } 11 else if( (grade < 80) && (grade >= 60)){ 12 System.println("Good job!" ). //CORRECT int number = 0.println( "Excellent!" ). All Rights Reserved C3: Protected . 7 } 8 else if( (grade < 90) && (grade >= 80)){ 9 System. if( number == 0 ){ //some statements here } Sample Program 1 public class Grade { public static void main( String[] args ) { 4 double grade = 92. Cognizant Technology Solutions.// statement2.out. 13 } 14 else{ 15 System.out.out.Handout .//block 1 break.0.println("Sorry. //WRONG int number = 0. 16 } 17 } 18 } switch Statement switch allows branching on multiple outcomes switch statement has the form: switch( switch_expression ){ case case_selector1: statement1.println("Study harder!" ). if( number = 0 ){ //some statements here } This should be written as. you failed. case case_selector2: Page 132 ©Copyright 2007.").

8 break.//block 2 break. the multiple statements are executed in the switch statement without needing the curly braces. and jumps to the case whose selector matches the value of the expression. 14 break.out. the statements associated with the succeeding cases are also executed. 11 break. : default: statement1. then the default block is executed. Flowchart of switch Statement Sample Program: 1 public class Grade { 2 public static void main( String[] args ) 3 { 4 int grade = 92.out. When a case in a switch statement has been matched. you use a break statement as your last statement. Cognizant Technology Solutions.println("Study harder!" ). Take note however.Core Java statement1. Note: Unlike with the if statement. 9 case 90: 10 System. Page 133 ©Copyright 2007.// statement2.Handout . case_selector2 and so on. All Rights Reserved C3: Protected . are unique integer or character constants When a switch is encountered: Java first evaluates the switch_expression.//block n } where: switch_expression is an integer or character expression case_selector1. 5 switch(grade){ 6 case 100: 7 System.out.println( "Excellent!" ).// statement2. To prevent the program from executing statements in the subsequent cases. that the default part is optional. Not only that. skipping then to the first statement after the end of the switch structure. all the statements associated with that case are executed.println("Good job!" ). If none of the cases are satisfied. The program executes the statements in order from that point on until a break statement is encountered. 12 case 80: 13 System.

out. is a judgment call. This program displays the following single line of output: 3 Page 134 ©Copyright 2007. case 3: System. break.println(2). Also. whereas a switch statement can make decisions based only on a single integer or character value. the value provided to each case statement must be unique. switch (n) { case 1: System.out.println(1).println(3).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. You can decide which to use. case 2: System. } } Coding Guidelines Deciding whether to use an if statement or a switch statement. break.out. Cognizant Technology Solutions.Handout .println("Sorry. All Rights Reserved C3: Protected . // continued … Refer File Name: SwitchWithBreak. 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. break. An if statement can be used to make decisions based on ranges of values or conditions.Core Java 15 16 17 18 19 } default: System. based on readability and other factors.out."). you failed.

else part is optional. int. Watch out for boolean assignments (=) that can be mistaken for boolean equality (==) tests. // 200 not in the range of byte Summary The only legal expression in an if statement is a boolean expression. The if statement takes boolean arguments. Cognizant Technology Solutions. including an enum. You cannot have a case that includes a non-final variable. b) The test condition may be a logical expression or an arithmetic expression. to provide the ability to conditionally compile the code. Solution: if (false) { x = 3}. Parenthesis is required.Core Java Tips and Tricks: List out the few important tips on selection statements.Handout . Curly braces are optional for if blocks that have only one conditional statement. Empty switch construct is a valid construct. switch statements can evaluate only to enums or the byte. It will be executed only if none of the case values match. The case constant must be a literal or final variable. or a range of values. and char data types. But watch out for misleading indentations. or a constant expression. // will compile. The compiler checks each case value against the range of the data type of switch expression. The following code will not compile. But any statement within the switch block should come under a case label or the default case label. All Rights Reserved C3: Protected . 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. c) The else part is optional. Default case can be placed anywhere. The default keyword can be located anywhere in the switch block. Page 135 ©Copyright 2007. in other words an expression that resolves to a boolean or a Boolean variable. d) More than one statement may be present in the if block and else block statements. byte b. Test Your Understanding 1. short. But this is not a part of switch statement and not enforced by the compiler. switch (b) { case 200: default: } You need to place a break statement in each case block to prevent the execution to fall through other case blocks.

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.Handout .Core Java 2. b) The body of a case may be empty. Page 136 ©Copyright 2007. Cognizant Technology Solutions. d) The default part is optional. c) The body of a case should have the break statement. All Rights Reserved C3: Protected .

while (x<10) { System. . x++. Cognizant Technology Solutions.Handout . you will be able to: Use repetition control structures (while. 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. } Page 137 ©Copyright 2007. do-while.Core Java Session 31: Wrapper Classes. for). } The statements inside the while loop are executed as long as the boolean_expression evaluates to true. .println(x). 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. Selection Statements and Iteration Blocks Learning Objectives After completing this session. . All Rights Reserved C3: Protected . return). statement2. Examples of while-loop Example 1: int x = 0.out. continue. which allow executing specific sections of code a number of times Use branching statements (break. while loop has the following form: while( boolean_expression ){ statement1.

x++. . Examples of do-while-loop Example 1: int x = 0. All Rights Reserved C3: Protected .out. }while( boolean_expression ). ] while(true). 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. . Cognizant Technology Solutions.println(“hello”). Page 138 ©Copyright 2007.println(x).println(“hello”). Example 2: //infinite loop do { System. } while (x<10). .Core Java Example 2: //infinite loop while(true) System.Handout .out. Example 3: //no loops // statement is not even executed while (false) System. do { System.out.println(“hello”).out.

. } Where: InitializationExpression initializes the loop variable. } while (false)...Handout .println(i). i++ ){ System.out. All Rights Reserved C3: Protected . StepExpression updates the loop variable.LoopCondition.Core Java Example 3: //one loop // statement is not executed only once do { System. . LoopCondition compares the loop variable to some limit value. } The preceding code shown is equivalent to the following while loop: int i = 0. Coding Guidelines Common programming mistakes when using the do-while loop is forgetting to write the semi-colon after the while expression. for loop has the following form: for(InitializationExpression. Cognizant Technology Solutions. do{ .println(i). for( i = 0. i < 10. } Page 139 ©Copyright 2007.out. Just like in while loops.println(“hello”). i++. }while(boolean_expression)//WRONG->forgot semicolon. for-loop for loop allows execution of the same code a number of times. statement2. Example of for-loop int i. make sure that your do-while loops will terminate at some point. while( i < 10 ){ System. .StepExpression) { statement1.out.

"Gem".Core Java Branching Statements Branching statements allows you to redirect the flow of program execution. Labeled Break Statement Labeled break statement: This terminates an outer statement. for( int i=0. Cognizant Technology Solutions."Ethan"}.Handout . i++ ){ if( names[i]. The sample program in the following slide searches for a value in a two dimensional array. String searchName = "Yza". Java offers three branching statements: break continue return Unlabelled Break Statement Unlabelled break: Terminates the enclosing switch statement. i< names. which is the outer for loop. 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." ). Two nested for loops traverse the array.out."Nico".println( searchName + " found!" ). while. break. All Rights Reserved C3: Protected . a labeled break terminates the statement labeled search.length."Yza". and flow of control transfers to the statement immediately following the switch This can also be used to terminate a for.equals( searchName )){ foundName = true."Lance". When the value is found. } } if( foundName ) else System. System.out."Belle". or do-while loop Example of Unlabelled Break Statement String names[]={"Beah". boolean foundName = false."Bianca". Page 140 ©Copyright 2007.println( searchName + " not found.

3}. 6}. {4. Cognizant Technology Solutions. "Bianca". //message1 Page 141 ©Copyright 2007. j<5. i++ ){ for( int j=0.length. Labeled Continue Statement Labeled continue statement skips the current iteration of an outer loop marked with the given label. i<numbers. } } } if( foundNum ) else System.println("There are "+count+" Beahs in the list"). j<numbers[i]. "Beah"}.out.length.println(searchNum + " found!" ). int searchNum = 5. i<5. i++ ){ if( !names[i]. System. 5.{7.out. Example of Unlabelled Continue Statement String names[] = {"Beah". break searchLabel. 9}}. int count = 0. 2. j++ ){ if( searchNum == numbers[i][j] ){ foundNum = true.println(searchNum + " not found!").Core Java Example of Labeled Break Statement int[][] numbers = {{1. boolean foundNum = false. searchLabel: for( int i=0. Example of Labeled Continue Statement outerLoop: for( int i=0.Handout .equals("Beah") ){ continue. for( int i=0. //skip next statement } count++.out. } System. basically skipping the remainder of this iteration of the loop. 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. 8. i++ ){ for( int j=0.out.length. "Lance". i<names. All Rights Reserved C3: Protected . j++ ){ System.println("Inside for(j) loop").

println("Inside for(i) loop"). for (i = 0. then you cannot declare variables within the initialization block.println(i + j). Code: class ForLoop { public static void main(String[] args) { int i. For example: return ++count. if you apply a comma separator in the initialization block. which skips the iteration. For example: return.Core Java if( j == 2 ) continue outerLoop. The data type of the value returned by return must match the type of the declared return value of the method. //message2 } In this example. use the form of return that does not return a value. All Rights Reserved C3: Protected . 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.Handout .out.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. j += i) { System. Try It Out Problem Statement: Write a program that illustrates the use of for loop. } } } Refer File Name: ForLoop. or return "Hello". j = 0. j. message 2 never gets printed since you have the statement continue outerLoop. ++i. When a method is declared void. Page 142 ©Copyright 2007. } System. Cognizant Technology Solutions.out. i + j < 20.

println(i+j). the following for statement results in a compilation error: for(int i=0. ++i.Core Java For example. parameter. as long as they do not enclose one another. method. or local variable. Solution: break statement can be used with any kind of loop or a switch statement or just a labeled block.int j=0. Labels can have the same name. it produces the following output: 0 2 5 9 14 Tips and Tricks: Provide few important tips on branching statements. class. All Rights Reserved C3: Protected . Names of the labels follow the same rules as the name of the variables (Identifiers). continue statement can be used with only a loop.Handout .java program. 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.out. You can use break and continue statements to branch out of multiple levels of nested loops using labels. (any kind of loop). interface. Loops can have labels. There is no restriction against applying the same identifier as a label and as the name of a package. field. } When you run ForLoop. j += i) { System. i+j < 20. Cognizant Technology Solutions. 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.

Handout . 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.Core Java 2. All Rights Reserved C3: Protected . Cognizant Technology Solutions.

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. Cognizant Technology Solutions.Handout . then an implicit default constructor is created Example: Default Constructor Method of StudentRecord Class public StudentRecord() { //some code here } Page 145 ©Copyright 2007.Core Java Session 35: Access Specifiers. To declare a constructor. It is generally declared as public. <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. Constructors and Methods Learning Objectives After completing this session. you write. Constructors should have the same name as the name of the class. You cannot invoke a constructor on an existing object. It does not have any return type and not even void. It may have optional list of arguments. All Rights Reserved C3: Protected . You can use a constructor only in combination with the new operator.

//some code here } “this()” Constructor Call Constructor calls can be chained. "Philippines"). There are a few things to remember when using the this() method constructor call: When using this constructor call. double sGrade) { mathGrade = mGrade. scienceGrade = sGrade. Page 146 ©Copyright 2007.address = address. 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". which means that you can call another constructor from inside another constructor. The this call can then be followed by any other relevant statements. double eGrade. You use the this() method call for this. All Rights Reserved C3: Protected .100).Core Java Overloading Constructor Methods public StudentRecord() //some initialization code here } public StudentRecord(String temp) { this.90.Handout . It can only be used in a constructor definition. } public StudentRecord(String name. this. Cognizant Technology Solutions.name = name. } Applying Constructors To apply these constructors.name = temp. it must occur as the first statement in a constructor. String address { this. englishGrade = eGrade. StudentRecord crisRecord=new StudentRecord(80. } public StudentRecord(double mGrade.

Handout . 3: 4: } 5: 6: public StudentRecord(String temp){ 7: this.age = age. } void anotherMethod() { // method definition here. 8: } 9: 10: public static void main( String[] args ) 11: { 12: 13: StudentRecord annaRecord = new StudentRecord(). Cognizant Technology Solutions.anotherMethod() anotherMethod().name = temp. All Rights Reserved C3: Protected .Core Java Example of “this()” Constructor Call 1: public StudentRecord(){ 2: this("some string"). this. } Page 147 ©Copyright 2007. you type. public class MyClass { void aMethod() { // same thing as 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. 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. } } Example of “this” Reference public void setAge( int age ){ this..

Each <parameter> is associated with a parameter type (primitive or object) and a parameter name. Cognizant Technology Solutions. getName is the name of the method. Example 2: Accessor (Getter) Method public class StudentRecord { private String name. All Rights Reserved C3: Protected . () means that your method does not have any parameters. 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. } } where: public means that the method can be called from objects outside the class.Core Java Declaring Methods To declare methods you write. // some code // An example in which the business logic is Page 148 ©Copyright 2007.Handout . : public String getName(){ return name. <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. This means that the method should return a value of type String. String is the return type of the method.

Core Java // used to return a value on an accessor method public double getAverage(){ double result = 0. You can also use constants to return values instead of variables. Cognizant Technology Solutions. Multiple Return Statements You can have multiple return statements for a method as long as they are not on the same block. //return a constant } //return a variable Page 149 ©Copyright 2007. } } Where: public means that the method can be called from objects outside the class. Example: Multiple Return Statements public String getNumberInWords( int num ){ String defaultNum = "zero". return result. void means that the method does not return any value. (String temp) is a parameter that will be used inside your method. setName is the name of the method. } } 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.Handout . All Rights Reserved C3: Protected . result=(mathGrade+englishGrade+scienceGrade)/3. : public void setName( String temp ){ name = temp. if( num == 1 ){ return "one". //return a constant } else if( num == 2){ return "two".

public static int getStudentCount(){ return studentCount. private String address.Core Java return defaultNum. Cognizant Technology Solutions. } Static Methods Example: public class StudentRecord { private static int studentCount.getStudentCount() int is the return type of the method. Source Code for StudentRecord Class public class StudentRecord { // Instance variables private String name.[methodName. public means that the method can be called from objects outside the class. Page 150 ©Copyright 2007. () means that your method does not have any parameters. private double englishGrade. [ClassName]. private int age. For example. 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. private double mathGrade.Handout .parseInt(). This means that the method should return a value of type int. int y) method When the logic is a convenience without creating an object instance: Integer. private double scienceGrade. you call the method StudentRecord. getStudentCount is the name of the method. in this case. static means that the method is static and should be called by typing. All Rights Reserved C3: Protected . } } where.

new StudentRecord(). } /** * returns the number of instances of StudentRecords * (Accessor method) */ public static int getStudentCount(){ return studentCount. result = ( mathGrade+englishGrade+scienceGrade )/3. new StudentRecord(). All Rights Reserved C3: Protected . Page 151 ©Copyright 2007. } /** * Changes the name of the student (Mutator method) */ public void setName( String temp ){ name = temp. private static int studentCount. } Sample Source Code that uses StudentRecord Class public class StudentRecordExample { public static void main( String[] args ){ //create three objects for StudentRecord annaRecord = StudentRecord beahRecord = StudentRecord crisRecord = Student record new StudentRecord(). } /** * Computes the average of the english.Handout . //set the name of the students annaRecord. return result. /** * Returns the name of the student (Accessor method) */ public String getName(){ return name.Core Java private double average.setName("Anna"). math and science * grades (Accessor method) */ public double getAverage(){ double result = 0. Cognizant Technology Solutions.

public Box(double x.getName() ). this. this. this. y. 10. width.setName("Beah"). double height) { this. 10).x = x. //print anna's name System. height. and height and assigns them to the appropriate field variables. width.out. double y) { this(x.out. y.y = y.setName("Cris"). //print number of students System.width = width.java to obtain soft copy of the program code How It Works: The first Box() constructor takes the arguments x.println("Count="+StudentRecord. double y.getStudentCount()).Handout . Cognizant Technology Solutions.Core Java beahRecord.println( annaRecord. y. } public Box(double x. All Rights Reserved C3: Protected . } } Program Output Anna Student Count = 0 Try It Out Problem Statement: Write a program that illustrate the use of ‘this’ statement in constructor overloading. double width.height = height. Page 152 ©Copyright 2007. Code: public class Box { double x. } // continued … Refer File Name: Box. crisRecord.

The this(x.Handout . Calls to this() and super() cannot be in the same constructor.10) and this(1. but constructors cannot have a return type and not even void. All Rights Reserved C3: Protected . which does not make it a constructor. The thing that separates a method from a constructor is the return type.Core Java The second Box() constructor takes just the coordinates of the box as arguments and invokes the first constructor. has at least one constructor. Summary A constructor is always invoked when a new object is created. Note: If this() appears in a constructor.then do you get the superclass constructor instead of the default? A static method cannot access a variable that is not static. there must be a constructor whose argument list matches those supplied with this() . Constructors can use any access modifier (even private!) The default constructor is a no-arg constructor with a no-arg call to super(). In order to use a constructor call statement. but never both. constructors are not inherited. then it must appear as the first statement in the constructor. 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. even an abstract class. Page 153 ©Copyright 2007. passing 10 as the default value for the height and width of the box. 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. Interfaces do not have constructors. It is referred to as a constructor call statement. though.y.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. you can have one or the other. Cognizant Technology Solutions. Methods must have a return type. 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. The first statement of every constructor must be a call to either this() (an overloaded constructor) or super(). No. 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. Every class. Constructors must have the same name as the class.10.

All Rights Reserved C3: Protected . What is the advantage of using the ‘this’ keyword? Page 154 ©Copyright 2007. How many constructors can a class have? 3.Handout . Cognizant Technology Solutions.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.

Core Java Session 38: Access Specifiers.out. System. System. System.println("Name:" + name). Cognizant Technology Solutions.println("Science Grade:" + sGrade). Page 155 ©Copyright 2007.5).out.setName("Anna").out.println("Address:" + address). } public static void main( String[] args ) { StudentRecord annaRecord = new StudentRecord().setAddress("Philippines").println("Age:" + age). annaRecord. Constructors and Methods Learning Objectives After completing this session. annaRecord. annaRecord. All Rights Reserved C3: Protected .setMathGrade(80).out.out.setAge(15). double sGrade) System. } public void print(double eGrade. System. double mGrade.out.println("Math Grade:" + mGrade). 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. System.out.setScienceGrade(100).println("Name:" + name).setEnglishGrade(95.Handout .println("English Grade:" + eGrade). annaRecord. annaRecord. annaRecord.

} // Overload the addThem method to add doubles instead of ints public double addThem(double x. return x + y. } 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 Try It Out Problem Statement: Write a program that illustrates invoking overloaded methods.").print( annaRecord.. All Rights Reserved C3: Protected . double y) { System. int y) { System. Page 156 ©Copyright 2007.Core Java //overloaded methods annaRecord. Code: class TestAdder { public int addThem(int x. annaRecord.println("Inside addThem(int x.getMathGrade(). int y) method.getEnglishGrade(). invoke the addThem() method public class TestAdder { public static void main(String[] args) { Adder a = new Adder().println("Inside addThem(double x.out. double y) method. return x + y.Handout . annaRecord.getName() ).5 Science Grade:100. annaRecord.getScienceGrade()). } } //From another class.0 English Grade:95.out.print( annaRecord. int b = 27.... Cognizant Technology Solutions.").

Cognizant Technology Solutions. (including the return in return type is not enough.methodName() . If two methods have the same signature.5. Tips and Tricks: Differentiate between Overloading methods and Overriding methods. for the above call. Overrides the parent class method. Methods are independent methods. Methods can be static or non-static. Also.super will not work. the first version of addThem() – the overloaded method that contains two int arguments – is done. 9.3).addThem(22. the second version of addThem() – the overloaded method that contains two double arguments – is done. The second call to a. since they are resolved at compile time based on the type of reference variable.addThem(22.5. Just a difference Signature has to be the same. Resolved at run-time based on type of the object. Overriding methods cannot be more private than the overridden methods. Overriding method can call overridden method by super. static methods do not participate in overriding. Page 157 ©Copyright 2007. c). Can call each other by providing appropriate argument list. It’s a compile time error. declaring one as static and another as non-static does not provide a valid overload. 9. All Rights Reserved C3: Protected .addThem(b. a class outside the inheritance hierarchy cannot use this technique. Solution: Overloading Overriding Signature has to be different. // which addThem? } } Refer File Name: TestAdder. A static method cannot be overridden to be non-static and vice-versa. super. type) Accessibility may vary freely. Resolved at compiletime based on method signature. Each parent class method may be overridden at most once in any sub-class. for the above call. this can be used only to access the immediate method of superclass. the first call to a. There is no limit on number of overloaded methods a class can have. So.Handout . Related directly to sub-classing. // which addThem is invoked? double doubleResult = a.java to obtain soft copy of the program code How It Works: In the TestAdder program. So.c) passes two ints to the method.addThem(b. A static method in a sub-class cannot use super. Just the name is reused.Core Java int c = 3.3) passes two doubles to the method. int result = a.

Handout . Overloading means reusing a method name. Reference type determines which overloaded method will be used at compile time. Page 158 ©Copyright 2007. 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. but with different arguments. What is meant by method overloading’? 2. Cognizant Technology Solutions. Differentiate between constructor overloading and method overloading. Test Your Understanding 1. Overloaded methods: o Must have different argument lists o May have different return types.Core Java Summary Methods can be overridden or overloaded. constructors can be overloaded but not overridden. All Rights Reserved C3: Protected .

All Rights Reserved C3: Protected . public Accessibility Public access: Specifies that class members (variables or methods) are accessible to anyone. 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. } } Page 159 ©Copyright 2007. 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.Core Java Session 39: Access Specifiers. //default access to method public String getName(){ return name.Handout . which is default. Constructors and Methods Learning Objectives After completing this session. Cognizant Technology Solutions. 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. no keyword is used.

//default access to method protected String getName(){ return name. All Rights Reserved C3: Protected . //default access to method String getName(){ return name.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.Handout . } } 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. Cognizant Technology Solutions. } } 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.

out.println(“OtherClass”).Handout .OtherClass. All Rights Reserved C3: Protected . } } 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.Core Java Example: “private” Access Modifier public class StudentRecord { //default access to instance variable private int name. Page 161 ©Copyright 2007. you have the following: package somethingElse. Try It Out Problem Statement: Write a program that illustrates about access modifiers. //default access to method private String getName(){ return name. import learn. Cognizant Technology Solutions. } } -----------------------------------------------------------------------In another source code. Code: package learn. public class OtherClass { void testIt() { // No modifier means method has default access System.

If no access modifier is specified. protected. Only the direction shown in following figure is permitted from parent classes to sub-classes. it will cause access denial to the variable or method of the sub class. All Rights Reserved C3: Protected . All classes in the same package can access the feature. will AccessClass be able to apply the method testIt() ? Will it cause a compiler error? No method matching testIt()is found in class learn. So. you can see that AccessClass cannot use the OtherClass method testIt() because testIt() has default access. This ensures that classes from other packages are accessing only the members that are part of their inheritance hierarchy.java. An instance of a class can access the private features of another instance of the same class.testIt().testIt(). From the preceding results.OtherClass. ‘private’ means only the class can access it and not even sub-classes. and private. } } Refer Files : OtherClass. then the accessibility is default package visibility. Same directory is same package in consideration of Java. and AccessClass is not in the same package as OtherClass. Methods cannot be overridden to be more private. But friendly is not a Java keyword. which classes can access the features. Now the question is. These modifiers dictate. Notice also that class OtherClass is in a different package from the AccessClass. private --> friendly (default) --> protected --> public Parent classes Sub-classes Page 162 ©Copyright 2007. o. Tips and Tricks: Provide the key tips on access modifiers in Java. But a subclass in another package can access the protected members in the super-class by only the references of subclass or its subclasses. and hence the compiler complains.java to obtain soft copy of the program code How It Works: In the OtherClass program. It is called as friendly access.. AccessClass. o. ‘protected’ means all classes in the same package (like default) and sub-classes in any package can access the features. A subclass in the same package does not have this restriction. Cognizant Technology Solutions. Solution: Access modifiers can be public. So AccessClass cannot see it.Core Java class AccessClass { static public void main(String[] args) { OtherClass o = new OtherClass().Handout . the testIt() method has default (think: package-level) access.

and protected.Handout .Core Java Summary The different access modifiers in Java are default. public. Cognizant Technology Solutions. State true or false for the following: a) For the default (or package-level access). All Rights Reserved C3: Protected . Page 163 ©Copyright 2007. the keyword default is used. Test Your Understanding 1. private. b) protected variables and methods can be accessed by all members of subclasses in different packages.

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). protected String address. Cognizant Technology Solutions. Once a behavior (method) is defined in a super class. the same set of properties are inherited by all subclasses. Deriving a Subclass To derive a child class. Suppose you have a parent class called Person. A class and its children share common set of properties A subclass only needs to implement the differences between itself and the parent. public class Person { protected String name. that behavior is automatically inherited by all subclasses Thus. All Rights Reserved C3: Protected . Interfaces and Abstract Classes Learning Objectives After completing this session. 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 primary features of object-oriented programming are encapsulation and polymorphism. /** * Default constructor */ Page 164 ©Copyright 2007.Core Java Session 42: Inheritance. you use the extends keyword.Handout . Importance of Inheritance The benefit of inheritance in OOP is reusability.

address = "". you want to create another class named Student. } extends Keyword Now.out. You can declare new fields in the subclass that are not in the super class. .Core Java public Person(){ System.println(“Inside Person:Constructor”). just like any other fields. What you can do in a Sub-class Regarding Methods The inherited methods can be used directly as they are. . . you write. You can declare new methods in the subclass that are not in the super class.Handout . public class Student extends Person { public Student(){ System. . . } . thus hiding it (not recommended). All Rights Reserved C3: Protected . However. thus hiding it. . A subclass does not inherit the private members of its parent class. so that you can inherit all the properties and methods of the existing class Person. What you can do in a Sub-class Regarding Fields The inherited fields can be used directly.println(“Inside Student:Constructor”).out. } What you can do in a Subclass A subclass inherits all of the “public” and “protected” members (fields or methods) of its parent. Cognizant Technology Solutions. } . you decide to just extend the class Person. Page 165 ©Copyright 2007. thus overriding it. if the super class has public or protected methods for accessing its private fields. You can write a new instance method in the subclass that has the same signature as the one in the super class. these can also be applied by the subclass. no matter what package the subclass is in. Since a student is also a person. then it also inherits the packageprivate members (fields or methods) of the parent. To do this. name = "". You can declare a field in the subclass with the same name as the one in the super class. If the subclass is in the same package as its parent. You can write a new static method in the subclass that has the same signature as the one in the 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. you create an object of class Student. All Rights Reserved C3: Protected . 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. Page 166 ©Copyright 2007. the default constructor of its super class (parent class). In Java language.Core Java Object Class Object class is mother of all classes. a subclass (child class). } In the code. consider the following code: public static void main( String[] args ){ Student anna = new Student(). Person class. is invoked implicitly before the constructor method of the subclass is invoked. When a Student object.Handout . Cognizant Technology Solutions. all classes are subclassed (extended) from the Object super class. is instantiated. 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.

Another use of super is to refer to members of the super class (just like the this reference ). The super() call can only be used in a constructor (not in ordinary methods). } Few things to remember when using the super constructor call: The super() call must occur as the first statement in a constructor.Handout . All Rights Reserved C3: Protected .out. This is done by using the super constructor call. System. In the given the following code for Student: public Student(){ super( "SomeName". Cognizant Technology Solutions.println("Inside Student:Constructor"). based on the arguments passed. A super constructor call in the constructor of a subclass will result in the execution of relevant constructor from the super class. For example. Page 167 ©Copyright 2007. "SomeAddress" ). in your preceding example classes Person and Student.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. you show an example of a super constructor call.

and the output would be: Student: getName Page 168 ©Copyright 2007. The overriding method has the same name.out. public class Student extends Person{ : public String getName(){ System.println("Student: getName"). super.address = “some address”. number and type of parameters. } Overriding Methods If a derived class needs to have a different implementation of a certain instance method from that of the super class. Cognizant Technology Solutions. } : } Now. the getName() method of the Student class would be called. All Rights Reserved C3: Protected .println("Parent: getName"). then override that instance method in the sub class: Note that the scheme of overriding applies only to instance methods. and return type as the method it overrides.name = “somename”. return name. The overriding method can also return a subtype of the type returned by the overridden method This is called a covariant return type. reimplement the method with the same signature.out.Handout .Core Java For example: public Student() { super. return name. when you invoke the getName() method of an object of the subclass Student. 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. it is called hiding methods. } } To override the getName() method of the superclass Person in the subclass Student. For static methods.

Hiding Methods If a subclass defines a class method (static method) with the same signature as a class method in the super class.myMethod("test5"). in the subclass. 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(). Result: myMethod(test4) in Student class is called myMethod(test5) in InternationalStudent class is called. 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."). Person person3 = new InternationalStudent().Handout . person3.out. } } // The testClassMethod() of the child class hides the one of // the super class – it looks like overriding. person2. Cognizant Technology Solutions.Core Java Modifiers in the Overriding Methods The access specifier for an overriding method can allow more. then the method in the subclass “hides” the one in the super class. For example. but not private. a protected instance method in the super class can be made public. but not less. 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. access than the overridden method. Example: Coding of Hiding Static Method class Animal { public static void testClassMethod() { System.println("The class method in Animal. doesn't it? class Cat extends Animal { Page 169 ©Copyright 2007. All Rights Reserved C3: Protected .myMethod("test4").

Cognizant Technology Solutions. // The object instance is Cat type // and assigned to Animal type variable. instead. This is run-time polymorphism. When you override a static method. Animal myAnimal2 = myCat.Core Java public static void testClassMethod() { System. the static method of // the super class gets called. Example: Overriding Method Versus Hiding Method During Runtime // Create object instance of Cat. Page 170 ©Copyright 2007. Cat myCat = new Cat(). The difference comes during run time: When you override an instance method. Animal. hides the super class' field. // // // // For instance method. the field in the super class cannot be referenced by its simple name. even if their types are different.testInstanceMethod().Handout .out."). Generally speaking. Within the subclass. myAnimal2. Try It Out Problem Statement: Write a program that illustrate the use of ‘this’ and ‘super’. you get the benefit of run-time polymorphism. there is no runt-time polymorphism. the field must be accessed through super keyword. Hiding Fields Within a sub class.println("The class method in Cat. All Rights Reserved C3: Protected . hiding fields is not a recommended programming practice as it makes code difficult to read. } } Overriding Method Versus Hiding Method Hiding a static method of a super class looks like overriding an instance method of a super class. // For static method. the instance method of the subclass is called even though myAnimal2 is a super class type. a field that has the same name as a field in the super class.testClassMethod().

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

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

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

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 { } For example, // Note that there is no body public abstract void someMethod(); Please make this point that there are no parentheses will be available.

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

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

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

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

you write: public interface [InterfaceName] { //some methods without the body } As an example. this. Defining Interface To define an interface.Handout .Core Java Interface versus Class: Differences The methods of an interface are all abstract methods.y2 = y2. double x2.x1 = x1. //ERROR! An interface can only be implemented by classes or extended by other interfaces. public interface Relation { public boolean isGreater( Object a. private double x2. Object b). /** * Line class implements Relation interface */ public class Line implements Relation { private double x1. use the implements keyword. public boolean isLess( Object a.y1 = y1. They cannot have bodies. private double y1. double y2){ this. } Implementing Interfaces To create a concrete class that implements an interface. this.x2 = x2. public Line(double x1. create an interface that defines relationships between two objects according to the “natural order” of the objects. All Rights Reserved C3: Protected . Cognizant Technology Solutions. this. For example: PersonInterface pi = new PersonInterface(). } public double getLength(){ double length = Math. Page 178 ©Copyright 2007. return length. private double y2. Object b).sqrt((x2-x1)*(x2-x1) + (y2-y1)* (y2-y1)). public boolean isEqual( Object a. Object b). double y1. You cannot create an instance from an interface.

return (aLen > bLen). Object b){ double aLen = ((Line)a). Cognizant Technology Solutions. } } When your class tries to implement an interface. always make sure that you implement all the methods of that interface. return (aLen == bLen).getLength(). Object b){ double aLen = ((Line)a). } public boolean isLess( Object a. double bLen = ((Line)b). or else. double bLen = ((Line)b). All Rights Reserved C3: Protected .Core Java } public boolean isGreater( Object a. } public boolean isEqual( Object a.Object) in Relation public class Line implements Relation ^ 1 error Implementing Class Implementing class can have its own methods.java:4: Line is not abstract and does not override abstract method isGreater(java. Relationship of an Interface to a Class A concrete class can only extend one super class.getLength(). The Java programming language does not permit multiple inheritance (inheritance is discussed later in this lesson). All abstract methods of all interfaces have to be implemented by the concrete class Page 179 ©Copyright 2007.lang. Implementing class extend a single super class or abstract class.Object. but it can implement multiple Interfaces. but interfaces provide an alternative.java.Handout .lang.getLength().getLength(). double bLen = ((Line)b). you would encounter the following error: Line. return (aLen < bLen). Object b){ double aLen = ((Line)a).getLength().getLength().

} Suppose that. and the proper version of that method will be executed depending on the type of object instance passed to the interface method call. because program may call an interface method.Core Java Example: Implementing Multiple Interfaces A concrete class extends one super class but multiple Interfaces: public class ComputerScienceStudent extends Student implements PersonInterface. } Interface and Polymorphism Interfaces exhibit polymorphism as well. you want to add a third method to DoIt. String s). } Page 180 ©Copyright 2007. double x. All Rights Reserved C3: Protected . int doSomethingElse(String s). boolean didItWork(int i. at a later time. However. } public interface StudentInterface extends PersonInterface { void doExtraSomething(). Problem of Rewriting an Existing Interface Consider an interface that you have developed called DoIt: public interface DoIt { void doSomething(int i. } Inheritance among Interfaces Interfaces are not part of the class hierarchy.Handout . AnotherInterface. double x). interfaces can have inheritance relationship among themselves. ThirdInterface{ // All abstract methods of all interfaces // need to be implemented. Cognizant Technology Solutions. public interface PersonInterface { void doSomething(). so that the interface now becomes: public interface DoIt { void doSomething(int i. int doSomethingElse(String s). double x).

you want to use them when you want to provide common implementation code for all subclasses: Reducing the duplication For abstract methods.Core Java If you make this change. String s). Solution of Rewriting an Existing Interface Create more interfaces later For example. public void doCarThings() { // special car code goes here } } public class Mini extends Car { public void goUpHill() { Page 181 ©Copyright 2007. } } public abstract class Car extends Vehicle { public abstract void goUpHill(). then all classes that implement the old DoIt interface will break because they do not implement all methods of the interface anymore. double x. public abstract void goUpHill(). 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. All Rights Reserved C3: Protected . public String getType() { return type. 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. Code: public abstract class Vehicle { private String type. } 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 could create a DoItPlus interface that extends DoIt: public interface DoItPlus extends DoIt { boolean didItWork(int i.Handout . Cognizant Technology Solutions.

and is implicitly abstract whether you type the abstract modifier in the declaration or not. if you wrote your code to use interfaces. it leads to polymorphism. Mini. An interface can have only abstract methods.java. and is never implemented in the Car class (so it remains abstract). Summary Interfaces can be implemented by any class. because Car like Vehicle. class Mini cannot pass the buck (of abstract method implementation) to the next class down the inheritance tree. It means the class Mini as the first concrete class below Vehicle must implement the goUpHill() method. You could just give them the interface. Page 182 ©Copyright 2007. no concrete methods allowed. which are always implicitly public. Cognizant Technology Solutions.java to obtain soft copy of the program code How It Works: The class Mini have three methods. Moreover. Interfaces are really flexible. It inherits both the getType() and doCarThings() methods. from any inheritance tree. goUpHill() is abstract in the super class Vehicle. you will not even have to give anyone a super class that they has to extend. A class can extend one class. The fact that you cannot put in implementation code turns out not to be a problem for most good object oriented designs. and implement an interface. because they are public and concrete (nonabstract). Car. but class Car can.Core Java // Mini-specific going uphill code } } Refer File Name: Vehicle. But another class might implement the same interface. Interface methods are by default public and abstract – explicit declaration of these modifiers is optional. yet coming from a different inheritance tree! In fact. Interfaces can have constants. A class implementing an interface can itself be abstract.java. Most interface methods need to be overridden even if the methods were not forced to be abstract. All Rights Reserved C3: Protected . In other words.Handout . static and final. because you cannot put any implementation code in them. An interface is like a 100-percent abstract class. 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). If all the methods of an interface are abstract. is abstract. Tips and Tricks: Interfaces do not really give you multiple inheritance. then what does an interface really buy you? Solution: When all the methods of an interface are abstract.

d) An interface cannot contain method definitions. Test Your Understanding 1. b) A class can extend any number of classes but it can implement only one interface. Interfaces cannot extend a class. All Rights Reserved C3: Protected . Interfaces can extend one or more interfaces. c) An interface can be implemented in different ways by different classes. Differentiate between an abstract class and an interface. Cognizant Technology Solutions. or implement a class or interface. but it can implement many interfaces. Page 183 ©Copyright 2007.Core Java A class can extend only one class (no multiple inheritance).Handout . Which one of the following statements is wrong? a) A class can extend only one class but it can implement any number of interfaces. 2.

Cognizant Technology Solutions. you say that the subclass extends the super class. use the IS-A test. The IS-A relationship works only in one direction. Page 184 ©Copyright 2007. you will be able to: Define IS-A and HAS-A relationship Using IS-A and HAS-A When one class inherits from another. Examples: If class B extends class A. Example: Tea IS-A beverage makes sense. then class C passes the IS-A test for both B and A. Do not apply inheritance if the subclass and super class do not pass the IS-A test. The IS-A relationship implies that if X IS-A Y. Interfaces and Abstract Classes Learning Objectives After completing this session. Shape IS-A Triangle does not make sense. so Shape should not extend Triangle. then X can do anything a Y can do (and possibly more). When you want to know if one thing should extend another. so you can have Triangle extends Shape. then class B IS-A class A. (for example.Handout . All Rights Reserved C3: Protected . but not through inheritance.Core Java Session 48: Inheritance. 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. one class has a reference to another class) then you say that the two classes are joined by HAS-A relationship. Triangle IS-A Shape makes sense. But the reverse. If class C extends class B. Always ask yourself if the subclass IS-A more specific type of the super class. Beverage IS-A tea does not make sense. Examples for IS-A relationship: Triangle IS-A Shape Green IS-A Color When two classes are related.

Cognizant Technology Solutions. Code: public class Animal { } public class Horse extends Animal { private Halter myHalter. 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. Horse class has a Halter. Halter.java. Page 185 ©Copyright 2007. Tips and Tricks: How do you know whether to make class. The following point summarizes the HAS-A relationship between Horse and Halter. Use an abstract class when you want to define a template for a group of subclasses.java to obtain soft copy of the program code How It Works: A Horse IS-A Animal. All Rights Reserved C3: Protected . Make a subclass (in other words. Horse. // Delegate tie behavior to the Halter object } } public class Halter { public void tie(LeadRope aRope) { // Do the actual tie work here } } Refer Files: Animal. an abstract class. a subclass. A Horse HAS-A Halter. public void tie (LeadRope rope) { myHalter.Core Java Try It Out Problem Statement: Write a program that illustrates the HAS-A relationship between Horse and Halter. because Horse declares an instance variable of type Halter. the Horse invokes tie() on the Halter instance variable of the Horse object. and you have at least some implementation code that all subclasses could use.java. Make the class abstract when you want to guarantee that nobody can make objects of that type. When code invokes tie() on a Horse instance. extend a class) only when you need to make a more specific version of a class and need to override or add new behaviors.tie(rope).Handout .

regardless of where those classes are in the inheritance tree. one can check whether a class has a reference to another class. “inherits from” and “is a subtype of” are all equivalent expressions. b) Using HAS-A test. Test Your Understanding 1. 2. HAS-A means an instance of one class “has a” reference to an instance of another class or another instance of the same class. IS-A is expressed with the keyword extends.Handout . State true or false for the following: a) The IS-A test is applied to check whether one class inherits from another class. 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. All Rights Reserved C3: Protected . Summary IS-A refers to inheritance.Core Java Use an interface when you want to define a role that other classes can play. IS-A. Cognizant Technology Solutions.

Student. and that is the boolean data type Types of Casting: Implicit Casting Explicit Casting Page 187 ©Copyright 2007. and Person student1 object can be used in any place where object instance of the type of TuftsStudent.Core Java Session 49: Inheritance.Handout . Cognizant Technology Solutions. Casting Primitive Types Casting between primitive types enables you to convert the value of one data from one type to another primitive type. Example: Student student1 = new Student(). There is one primitive data type that you cannot do casting though. All Rights Reserved C3: Protected . Student. 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. Interfaces and Abstract Classes Learning Objectives After completing this session. 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. Commonly occurs between numeric types. or Person is called for This enables polymorphism. you say the object instance is “type” of the class and its super classes.

int numInt = 10. as the data type (double) of the destination variable holds a larger value than the data type (int) of the value. //typecast result of operation to int Casting Objects Instances of classes also can be cast into instances of other classes.12. int valInt = (int)valDouble. //implicit cast In this example. the data is implicitly casted to the data type double of the destination variable. int y = 2. some objects might not need to be cast explicitly. Explicit Casting When you convert a data that has a large type to a smaller type.Core Java Implicit Casting Suppose you want to store a value of int data type to a variable of data type double. numInt2 = 2.2. Casting objects is analogous to converting a primitive value to a larger type. //convert valDouble to int type double x = 10. //result is implicitly casted to type double double numDouble = numInt1/numInt2. Implicit Casting: Example Another example: int int numInt1 = 1.Handout . Explicit Casting: Example double valDouble = 10. double numDouble = numInt. One class must be a subclass of the other. Page 188 ©Copyright 2007. Explicit casts take the following form: (Type)value where. All Rights Reserved C3: Protected . 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. with one restriction. int result = (int)(x/y). Cognizant Technology Solutions. you must use an explicit cast. The source and destination classes must be related by inheritance.

VicePresident is a subclass of Employee with more information. All Rights Reserved C3: Protected . Person person = collegeStudent. Cognizant Technology Solutions. Object object = collegeStudent. This is safe because an object instance of a subclass “is” also the type of the super class.Handout . // Implicit type casting // Implicit type casting // Implicit type casting Type Casting Between Objects Type casting between objects is shown in the following figure: collegeStudent CollegeStudent student Object instance person Page 189 ©Copyright 2007. // must cast explicitly veep = (VicePresident)emp. // no cast needed for upward use emp = veep. VicePresident veep = new VicePresident(). 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().Core Java Cast (classname)object where. Student student = collegeStudent. Employee emp = new Employee(). Implicit Type Casting An object instance of a subclass can be assigned to a variable (reference) of a parent class through implicit type casting. 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. which here defines that the VicePresident has executive washroom privileges.

} Try It Out Problem Statement: Write a program that illustrates the use of Casting Object References.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(). but runtime type mismatch exception Student student2 = (Student) person2. Person person2 = new Teacher(). // 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(). Cognizant Technology Solutions.Handout . Example: Person person1 = new Student(). Page 190 ©Copyright 2007. Student student1 = (Student) person1. Student student1 = (Student) person1. // Do the casting only when the type is verified if (person2 instanceof Student) { Student student2 = (Student) person2. Person person2 = new Teacher(). All Rights Reserved C3: Protected . 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. // Explicit type casting // No compile error.

then a ClassCastException is thrown. it produces the following result: abc Without the (String) cast operator.Handout . class of the object may not be known.java to obtain soft copy of the program code How It Works: When you run the program. The compiler recognizes this inconsistency and generates an error message. You cannot cast or apply instanceof or compare unrelated references. At compile time. When the (String) cast operator is used. so at runtime if checks fail. } } Refer File Name: CastObjRef.println(s2).util. Cast operator.elementAt(0) is an object of the Object class. sibling references or any incompatible references. s2 = (String) v. Page 191 ©Copyright 2007.*. the compiler recognizes that you are casting the reference to an Object object into a String object and proceeds with the compilation. All Rights Reserved C3: Protected . Tips and Tricks: Provide some key tips on casting of primitives. Object references.out.Core Java Code: import java. Cognizant Technology Solutions. instanceof operator and the == operator behave in the same way in allowing references to be the operands of them. 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. v. Solution: Casting of Primitives: Explicit type casting is required for the narrow conversion of primitive data types. the result returned by v. System.elementAt(0). Extensive checks done both at compile and runtime. String s2 = "def".add(s1). Vector v = new Vector(). class CastObjRef { public static void main(String args[]) { String s1 = "abc". and rules that are followed during compile-time and Run-time.

You must make an explicit cast to do this. Run-time rules: If new type is a class. one class must be the subclass of the other. and the result is that you can access the subtype’s members with this new reference variable.Core Java Compile-time rules: When old and new types are classes. This is an inherently safe operation because the assignment restricts the access capabilities of the new variable. o Downcasting: If you have a reference variable that refers to a subtype object. both must contain reference types and it must be legal to cast between those types (primitive arrays cannot be cast. All Rights Reserved C3: Protected . Test Your Understanding 1. b) Differentiate between Implicit type casting and Explicit type casting.Handout . Summary Reference Variable Casting: There are two types of reference variable casting: downcasting and upcasting. Page 192 ©Copyright 2007. When old and new types are arrays. then the class of the expression being converted must be new type or extend new type. you can assign it to a reference variable of the subtype. State true or false for the following: a) Casting cannot be done for the boolean primitive type. You can always cast between an interface and an object that is not final. o Upcasting: You can assign a reference variable to a supertype reference variable explicitly or implicitly. then the class of the expression being converted must implement the interface. Cognizant Technology Solutions. conversion possible only between same type of primitive arrays). If new type is an interface.

and. 3 class In { 4 void inMeth() { 5 outData = 10.println(data2). Page 193 ©Copyright 2007.println(data). Interfaces and Abstract Classes Learning Objectives After completing this session.Handout . static nested classes. 6 } 7 } 8 } Java Program Structure: Inner Classes 1 class OuterClass { 2 int data = 5.innerMember = 5.out.. //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.out. 3 class InnerClass { 4 int data2 = 10. 7 System. you will be able to: Identify inner classes. 5 void method() { 6 System.. All Rights Reserved C3: Protected . 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. 8 } 9 } 10 11 //continued.Core Java Session 50: Inheritance. Cognizant Technology Solutions.

Handout .println(“method of a static inner class”). If it is inside another class. but not all nested classes are inner classes. System. } } Nested Classes versus Inner Classes Any Java class that is defined within the scope of another class is known as a nested class. Static nested class cannot access the variables that are not static and methods of the outer class.Core Java 9 10 11 12 13 14 15 16 } public static void main(String args[]) { OuterClass oc = new OuterClass(). It does not matter if it is anonymous. } } } class Test { public static void main(String[] args) { OuterClass.out. InnerClass ic = oc.data2). Static nested classes can access only the private static members of the outer class.new InnerClass().InnerClass().method(). } Static Nested Classes A static nested class is just a class enclosed within another class. inner.sayIt(). Static nested class is not connected to an instance of the outer class. ic. then it is technically considered as a nested class. and marked with the keyword static.out.InnerClass inner = new OuterClass. All inner classes are nested classes.data).println(ic. All Rights Reserved C3: Protected . Cognizant Technology Solutions. Nested classes that are not static. often referred to as inner classes. normal.out. Page 194 ©Copyright 2007. static. or whatever. System. Static nested classes are considered a member of the enclosing or outer class. Static Nested Class: Example public class OuterClass { static class InnerClass void sayIt() { System.println(oc.

This is called as an anonymous class. in this case "1". System.addActionListener ( // The argument is the object created by the following: new ActionListener () // no name given to this object { public void actionPerformed (ActionEvent e) { i++. Cognizant Technology Solutions.class where a number.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. is used to identify the class files for anonymous inner classes. Page 195 ©Copyright 2007..Handout . All Rights Reserved C3: Protected . With the inner classes you can take this to another level by creating and instantiating a class without bothering to give it a name. add(fBt). Now the compiler will create a class file name AnOuterClass$1.println ("Pressed "+i+" times"). Try It Out Problem Statement: Write a program that illustrates the use of an instance of an inner class and an outer class.out. fBt. public AnOuterClass () { int i = 0. in one step you have created an implementation of the ActionListener interface and created an instance of it for application by the button. public class AnOuterClass extends Applet { Button fBt = new Button("OK"). } } ). Anonymous Inner Class: Example In the following code an instance of the ActionListener class is created in the argument of the addActionListener method: . This anonymity eliminates a lot unnecessary named objects and makes the code more readable. } } // class AnOuterClass Anonymous Inner Class: Example In this example.

} } } Refer File Name: Outer.Core Java Code: class Outer { String s = "Outer". anonymous class (static and nonstatic) Solution: Declaration context As package member As static class member Accessibility Modifiers public or default Outer instance Direct access to enclosing context N/A static members in enclosing context All members in enclosing context Defines static or nonstatic members Both static and non-static Both static and non-static Entity Package level Top level nested class (static) Non static inner class No All No As non-static class member All Yes Only nonstatic Page 196 ©Copyright 2007.java to obtain soft copy of the program code How It Works: The program displays the line Inner followed by the line Outer.s refers to the s variable of the Outer class. All Rights Reserved C3: Protected . System. } class Inner { String s = "Inner". Inner() { System. this.out. Cognizant Technology Solutions.out. public static void main(String[] args) { new Outer().this. Tips and Tricks: List out the key points on local class (static and non-static).Handout .new Inner().s). To refer to the instance of an outer class preponed the outer class name and a period to this.this.println(this. yields the value of the s variable corresponding to the Inner class and Outer.println(Outer.s).s. In the Inner() constructor.

Page 197 ©Copyright 2007. To instantiate an inner class. you must have a reference to an instance of the outer class. Cognizant Technology Solutions.Handout .Core Java Direct access to enclosing context All members in enclosing context + local final variables Static members in enclosing context + local final variables All members in enclosing context All members in enclosing context + local final variables Static members in enclosing context + local final variables Defines static or nonstatic members Entity Declaration context Accessibility Modifiers Outer instance Local class (non-static) In block with non-static context None Yes Only nonstatic Local class (static) In block with static context None No Only nonstatic Non static inner class As non-static class member All Yes Only nonstatic Anonymous class (nonstatic) In block with non-static context None Yes Only nonstatic Anonymous class (static) In block with static context None No Only nonstatic Package level interface As package member public or default No N/A static variables and non-static prototypes static variables and non-static method prototypes Top level nested interface (static) As static class member All No Static members in enclosing context Summary Inner Classes: A “regular” inner class is declared inside the curly braces of another class. but outside any method or other code block. All Rights Reserved C3: Protected .

An anonymous inner class is always created as part of a statement.Handout . An anonymous inner class can extend one subclass or implement one interface. A static nested class is not an inner class. and their type must be either a subclass of the named type or an implementer of the named interface. Anonymous Inner Classes: Anonymous inner classes have no name. Page 198 ©Copyright 2007. and automatically instantiated as part of a method invocation. and anonymous class. don’t forget to close the statement after the class definition with a curly brace. All Rights Reserved C3: Protected . defined.Core Java Static Nested Classes Static nested classes are inner classes marked with the static modifier. Cognizant Technology Solutions. You don’t need an instance of the outer class to instantiate a static nested class. An anonymous-local inner class is declared. it’s a top-level nested class. Test Your Understanding Differentiate between static class. inner class.

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. and let you step through it.Handout . (Window > Preferences > Run/Debug > Console). The Breakpoints view lists Java exception breakpoints.Core Java Session 52: Inheritance. delete them. You can also enable or disable breakpoints. You can add or remove exceptions. Breakpoints view lists all the breakpoints you have set in the workbench projects. which suspend execution at the point where the exception is thrown. All Rights Reserved C3: Protected . A breakpoint causes the execution of a thread to suspend at the location where the breakpoint is set. Page 199 ©Copyright 2007. Interfaces and Abstract Classes Learning Objectives After completing this session. The console shows three kinds of text. 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. 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. Breakpoints can be set to trigger always or when a certain condition has been met. or add new ones. In this view. Cognizant Technology Solutions. you can double-click a breakpoint to display its location in the editor. To add a breakpoint in the code.

For all nodes that are visible in this view. It displays the process for each target you are running. The Expressions view opens automatically when the Inspect command is activated. All Rights Reserved C3: Protected . It displays the stack frame for the suspended threads for each target you are debugging. and other places. how the execution of a Java program is stepped through line by line using SDE? Page 200 ©Copyright 2007. Tips and Tricks: When a thread is suspended.Handout . you can jump to a specific node by typing the first letter of the node. then its stack frames are shown as child elements. You can evaluate and display a selection either from the editor or directly from the Display view. If necessary. If the thread is suspended. Each thread in your program appears as a node in the tree.Core Java Debug View This view allows you to manage the debugging or running of a program in the workbench. Registers View You can view the contents of a register from the Registers view. In the Registers view. The view will jump to the next node that begins with that letter. Nodes in the Registers view are visible if they are at the top level of the tree structure. To view the contents of a register in the Register view: In the Debug view. Display View This view displays the result of evaluating an expression in the context of the current stack frame. Cognizant Technology Solutions. a stack frame of a suspended thread. select the thread for which you want to view the registers. use the scroll bars or PageUp and PageDown keys to scroll the Register view until the register is visible. expand the register group that you want to view. Expressions View Data can be inspected in the Expressions view. or if the nodes at a level higher have been expanded. You can inspect data from a scrapbook page.

Debug view allows you to manage the debugging or running of a program in the workbench. and execution suspends at the next executable line in the method that is invoked. Click on Run > Step Over in the tool bar or press F6 key to perform this operation. What is a Breakpoint? a) Breakpoints are indicators to the debugger that it should stop execution at specific places. and execution suspends on the next executable line. Data can be inspected in the Expressions view. Step Into: The next expression on the currently selected line to be executed is invoked. the step controls can be used to step through the execution of the program line-by-line.Core Java Solution: When a thread is suspended. Step Over: The currently selected line is executed and suspends on the next executable line. All Rights Reserved C3: Protected . Test Your Understanding 1. 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. c) Breakpoints are used to exit from code abruptly during execution.Handout . Registers view displays the contents of a register. Cognizant Technology Solutions. Display view displays the result of evaluating an expression in the context of the current stack frame. 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. b) Breakpoints display variables applied in the code. Console view shows the output of the execution of your program and allows you to enter input for the program. 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.

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.println(3/0).”). 5 } 6 } Example: Default Exception Handling Displays this error message: Exception in thread "main“ java.println(“Pls.out.lang. 4 System. 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. print me.ArithmeticException: / by zero at DivByZero.Handout .Core Java Session 54: Exception Handling Learning Objectives After completing this session.out. Cognizant Technology Solutions.main(DivByZero. All Rights Reserved C3: Protected .

The exception handler chosen is said to catch the exception. consequently. including its type and the state of the program when the error occurred. 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”.Core Java What Happens when an Exception Occurs? When an exception occurs within a method. Cognizant Technology Solutions. then the run-time system (and. All Rights Reserved C3: Protected . The run time system searches the call stack for a method that contains an exception handler.Handout . When an appropriate handler is found. Page 203 ©Copyright 2007. the program) terminates and uses the default exception handler. Exception object contains information about the error. 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. If the run-time system exhaustively searches all the methods on the call stack without finding an appropriate exception handler.

} Page 204 ©Copyright 2007.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. read the file into memory. and handling often lead to confusing spaghetti code.Handout . Consider the pseudo code method here that reads an entire file into memory: readFile { open the file. All Rights Reserved C3: Protected . determine its size. reporting. Cognizant Technology Solutions. allocate that much memory. error detection. close the file.

} return errorCode.Handout . and handling. determine its size. allocate that much memory. All Rights Reserved C3: Protected . } } else { errorCode = -2. } } else { errorCode = -3.Core Java Traditional Programming: No Separation of Error Handling Code In traditional programming. if (gotEnoughMemory) { read the file into memory. Page 205 ©Copyright 2007. readFile { try { open the file. } 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. if (readFailed) { errorCode = -1. read the file into memory. reporting. errorCodeType readFile { initialize errorCode = 0. if (theFileIsOpen) { determine the length of the file. if (theFileDidntClose && errorCode == 0) { errorCode = -4. } close the file. } } else { errorCode = -5. Cognizant Technology Solutions. } else { errorCode = errorCode and -4. if (gotTheFileLength) { allocate that much memory. to handle such cases. the readFile function must have more code to do error detection. open the file.

catch (fileCloseFailed) { doSomething.Core Java close the file. All Rights Reserved C3: Protected .Handout . 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 o 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 Division by zero error Array out-of-bounds error Page 206 ©Copyright 2007. catch (readFailed) { doSomething. Exception. Exception Class Hierarchy The Throwable. reporting. but they help you to organize the work more effectively. catch (sizeDeterminationFailed) { doSomething. Cognizant Technology Solutions. } } } } } } } Note that exceptions do not spare your effort of doing the work of detecting. and handling errors. catch (memoryAllocationFailed) { doSomething. catch (fileOpenFailed) { doSomething.

out.out. 11 } 12 } Page 207 ©Copyright 2007.out. 5 System. All Rights Reserved C3: Protected ..Handout . } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs> } 1 class DivByZero { 2 public static void main(String args[]) { 3 try { 4 System..println(3/0). 9 } 10 System.”). 6 } catch (ArithmeticException exc) { 7 //Division by zero is an ArithmeticException 8 System.println(exc).println(“After exception.”). Cognizant Technology Solutions.println(“Please print me.out.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> } .

parseInt(args[0]). 5 System.parseInt(args[1]).println(a/b). } } } Catching Exceptions: Nested trys with Methods 1 class NestedTryDemo2 { 2 static void nestedTry(String args[]) { 3 try { 4 int a = Integer.out.out. 9 } 10 } Page 208 ©Copyright 2007.println(a/b). 7 } catch (ArithmeticException e) { 8 System.”).out.”). Cognizant Technology Solutions.println(“Missing argument.out.out. 8 } catch (ArrayIndexOutOfBoundsException exc2) { 9 System. 5 int b = Integer. 12 } 13 } Catching Exceptions: Nested trys class NestedTryDemo { public static void main(String args[]){ try { int a = Integer. } } catch (ArrayIndexOutOfBoundsException) { System. 6 } catch (ArithmeticException exc) { 7 System. System.parseInt(args[0]).out.println("Div by zero error!").out.println(“Divisor was 0.out.parseInt(args[0]). 10 } 11 System.Core Java Catching Exceptions: Multiple catch 1 class MultipleCatch { 2 public static void main(String args[]) { 3 try { 4 int den = Integer.Handout .”).parseInt(args[1]). All Rights Reserved C3: Protected .println(“After exception. try { int b = Integer. } catch (ArithmeticException e) { System.out. 6 System.println(3/den).println(“Div by zero error!").println(“Need 2 parameters!").

. 9 case 4: System. 6 return. Cognizant Technology Solutions.out. } } Catching Exceptions: The finally Keyword Syntax: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } . 10 throw new Exception("4!").println("3rd case").out.println("Need 2 parameters!"). } finally { <code to be executed before the try block } 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. 8 throw new RuntimeException("3!"). All Rights Reserved C3: Protected . 16 System.out. 17 } finally { ends> Page 209 ©Copyright 2007.println("2nd case").out. 11 case 2: System.print("RuntimeException: ").Core Java 11 12 13 14 15 16 17 18 } public static void main(String args[]){ try { nestedTry(args).out..println("4th case").println("1st case"). 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. 12 } 13 } catch (RuntimeException e) { 15 System.out.getMessage()).Handout .println(e. a continue.out. } catch (ArrayIndexOutOfBoundsException e) { System. 7 case 3: System.

println("IO Error"). i++) { 24 try { 25 FinallyDemo.printStackTrace(). ioe. public class ExceptionHierarchyApp { public static void main(String[] args) { try { RandomAccessFile raf = new RandomAccessFile("myfile.println(e.toString()).err. } catch (IOException ioe) { System. 0. byte b[] = new byte[1000].println(fnfe. System.err. Cognizant Technology Solutions.out. } catch (FileNotFoundException fnfe) { System.out.readFully(b.Handout . 28 System.printStackTrace().getMessage()).println(ioe.err.java to obtain soft copy of the program code Page 210 ©Copyright 2007. } } } Refer File Name: ExceptionHierarchyApp.out.txt".myMethod(i). fnfe.println("try-block entered.out.println()."). All Rights Reserved C3: Protected . 1000).println("File not found").err. raf. 19 } 20 } 21 //continued 22 public static void main(String args[]){ 23 for (int i=1.*. 31 } 32 } 33 } Try It Out Problem Statement: Write a program that illustrates the importance of handling classes in the Exception Hierarchy.print("Exception caught: "). i<=4. 29 } 30 System. Code: import java.getMessage()). "r"). 26 } catch (Exception e){ 27 System.Core Java 18 System. System.io.

Core Java How It Works: When you run the program. but then you will have to test the exception to determine whether it was a FileNotFoundException. then the program will not compile. most of which are some type of IOException.main(ExceptionHierarchyApp. If you do it in the opposite way.<init>(Unknown Source) at ExceptionHierarchyApp.open(Native Method) at java.txt (The system cannot find the file specified) at java. The handlers for the most specific exceptions must always be placed before those for more general exceptions. If some other exception is generated. If it generates another IOException perhaps EOFException.java:6) This program attempts to open a file and read some data from it. which is a subclass of IOException. Imagine that in this program you are interested in knowing only whether the exact exception is a FileNotFoundException.RandomAccessFile. FileNotFoundException is a subclass of IOException. All Rights Reserved C3: Protected . It is already handled by the catch block for IOException. it produces the following result: File not found myfile.txt (The system cannot find the file specified) java.io. If this code generates a FileNotFoundException.<init>(Unknown Source) at java. You can handle it in the catch clause that catches all subtypes of IOException. then it will be handled by the catch clause related to IOException.io. Page 211 ©Copyright 2007.io. Opening and reading files can generate many exceptions. Cognizant Technology Solutions. then neither catch clause will be executed nor the exception will be propagated down the call stack. such as a run time exception of some type. 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. Notice that the catch clause for the FileNotFoundException has been placed before the handler for the IOException. you have coded a special exception handler for the FileNotFoundException and a separate exception handler for all other IOException subtypes. then it will be handled by the catch clause related to FileNotFoundException. This is really important.RandomAccessFile. Instead.Handout .FileNotFoundException: myfile.io.RandomAccessFile.

try { x. } finally { } } Summary Exceptions come in two flavours: checked and unchecked. } finally { // cleanup } A try with only a finally (no catch) must still declare the exception. If you use an optional finally block. any method that might throw a checked exception must either declare the exception using throws. } catch(FooException fe) { } A try must be followed by either a catch or a finally. regardless of whether an exception in the corresponding try is thrown or not. excluding classes that extend RuntimeException. or handle the exception with an appropriate try/catch. catch(FooException fe) { } } You cannot put code between the try and the catch.Core Java Tips and Tricks: List out some of the key exception rules that need to be followed while writing a Java program. Checked exceptions include all subtypes of Exception. void go() { Foo f = new Foo(). try { x.Handout .doStuff(). Solution: You cannot have a catch or finally without a try. and regardless of whether a thrown exception is caught or not. Checked exceptions are subject to the handle or declare rule.foof().doStuff(). Page 212 ©Copyright 2007. Subtypes of Error or RuntimeException are unchecked. } int y = 50. it will always be invoked. All Rights Reserved C3: Protected . void go() throws FooException { try { x. f.doStuff(). Cognizant Technology Solutions.

Page 213 ©Copyright 2007. d) When the try…catch mechanism is used. Cognizant Technology Solutions. 2. All Rights Reserved C3: Protected .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. b) The try…catch mechanism can be used only once in a Java program. Which one of the following statements is correct? a) The ‘try’ block should be followed by a ‘catch’ block. d) The ‘try’ block should be followed by at least two ‘catch’ blocks. execution will resume even after an error is detected and reported. b) The ‘try’ block should be followed by a ‘finally’ block. c) Error messages defined by user can be displayed by using the try…catch mechanism. Test Your Understanding 1. That could happen if code from the try or catch blocks calls System.Handout .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. c) The ‘try’ block should be followed by either a ‘catch’ block or a ‘finally’ block.exit(). Which one of the following statements is wrong? a) An exception is an abnormal condition that is caused by a run-time error.

You have to create an exception object in the same way you create any other object. Cognizant Technology Solutions.. 11 } catch (RuntimeException e) { 12 System.out..Handout .println("Exception caught:" + e).out. 9 } 10 System. which calls method3 that finally calls readFile. 7 } else { 8 System. 4 try { 5 if (input.println("After throwing"). method1 calls method2. Example: Throwing Exceptions 1 class ThrowDemo { 2 public static void main(String args[]){ 3 String input = “invalid input”. Page 214 ©Copyright 2007.println(input). throw <exception object>.equals(“invalid input”)) { 6 throw new RuntimeException("throw demo"). 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). Example: throw new ArithmeticException(“testing.Core Java Session 55: Exception Handling Learning Objectives After completing this session. All Rights Reserved C3: Protected .out. 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.”). An exception you throw is an object.

else proceed. } method2 { call method3. which is the only method that is interested in them. } Page 215 ©Copyright 2007. method1 { errorCodeType error. else proceed. } 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. } method3 { call readFile. } errorCodeType method2 { errorCodeType error. if (error) return error. error = call method3.Handout .Core Java Suppose also that method1 is the only method interested in the errors that might occur within readFile. All Rights Reserved C3: Protected . if (error) doErrorProcessing. else proceed. error = call readFile. if (error) return error. method1 { call method2. Cognizant Technology Solutions. } errorCodeType method3 { errorCodeType error. error = call method2.

An example of a group of related exception classes in the Java platform are those defined in java. The FileNotFoundException class has no descendants. method1 { try { call method2. For example. Its descendants represent more specific errors. FileNotFoundException means that a file could not be located on disk. All Rights Reserved C3: Protected . Cognizant Technology Solutions. including // FileNotFoundException. A method can write specific handlers that can handle a very specific exception.Core Java Using Java Exception Handling A method can duck any exception thrown within it. the grouping or categorizing of exceptions is a natural outcome of the class hierarchy. } Page 216 ©Copyright 2007. to catch all I/O exceptions. an exception handler specifies an IOException argument... Any checked exceptions that can be thrown within a method must be specified in its throws clause. Hence.io IOException and its descendants: IOException is the most general and represents any type of error that can occur when performing I/O. so the following handler can handle only one type of exception. } } method2 throws Exception { call method3. catch (IOException e) { .. } method3 throws Exception { call readFile. For example. } Grouping and Differentiating Error Types Because all exceptions thrown within a program are objects. } 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. catch (FileNotFoundException e) { .Handout . regardless of their specific type. only the methods that care about errors have to worry about detecting errors. // Catch all I/O exceptions.. EOFException. } catch (Exception ex) { doErrorProcessing. and so on. thereby allowing a method farther up the call stack to catch it.

Handout .java to obtain soft copy of the program code How It Works: First. where the calling method does not handle or declare the checked exception.IOException.io. } void doMore() { throw new IOException().Core Java Try It Out Problem Statement: Write a program that looks for code that invokes a method declaring an exception. but does not declare it. the doMore() method throws a checked exception. All Rights Reserved C3: Protected . must declare the IOException. then you must declare it using the throws keyword in your method declaration. because it. Code: import java. Cognizant Technology Solutions. If you call a method that throws an exception (in other words. a method that declares it throws an exception). Page 217 ©Copyright 2007. } } Refer File Name: ExceptionThrowApp. But suppose you fix the doMore() method like the following: void doMore() throws IOException { … } The doStuff() method is still in trouble. One way to satisfy the compiler is to wrap the call in a try or catch. then you must acknowledge that you are aware of the exception possibility. 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. public class ExceptionThrowApp { void doStuff() { doMore(). too. unless it handles it by providing a try or catch.

Test Your Understanding Differentiate between ‘throws’ and ‘throw’ keywords. 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. You are free to handle them.Handout .Core Java Summary Uncaught exceptions propagate back through the call stack. so the compiler does not enforce the handle or declare rule. Page 218 ©Copyright 2007. Subtypes of Error or RuntimeException are unchecked. but the compiler does not care one way or the other. All Rights Reserved C3: Protected . Cognizant Technology Solutions. or to declare them.

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. Create a class that extends the RuntimeException or the Exception class 2. All Rights Reserved C3: Protected . 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". 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 o o Error RuntimeException 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. 7 } Page 219 ©Copyright 2007.Handout . 4 try { 5 if (input.Core Java Session 58: Exception Handling Learning Objectives After completing this session.equals("invalid input")) { 6 throw new HateStringExp(). Cognizant Technology Solutions.

io. Code: import java.").\n"). Cognizant Technology Solutions. } } while (!finished). } finally { System. } catch (ExitException x) { System.println("An exit occurred.java to obtain soft copy of the program code How It Works: The ExceptionTest program reads a character entered by the user. } catch (VowelException x) { System.println("A blank occurred. or ExitException based on the input of the user."). } } Try It Out Problem Statement: Write a program that illustrates the creation and usage of your own exceptions. It then throws and catches a VowelException. } } Refer File Name: ExceptionTest. BlankException.*.println("Hate string!”).println("A vowel occurred.println("This is clause.out.out. finished = true.println("Accept string.out.Handout . } catch (BlankException x) { System.out. do { try { processUserInput().").out. exception exception exception the finally Page 220 ©Copyright 2007. All Rights Reserved C3: Protected .out.Core Java 8 9 10 11 12 13 } System. public class ExceptionTest { public static void main(String args[]) { boolean finished = false. } catch (HateStringExp e) { System.").

The main() method consists of a simple do statement that repeatedly tries to invoke processUserInput() . but the finally clause is executed. The processUserInput() method prompts the user to enter a character. The finally clause always executes no matter whether processUserInput() throws an exception or not. When you run ExceptionTest. and the following is displayed: Enter a character: j This is the finally clause. then BlankException is thrown. This is the finally clause.Core Java ExceptionTest provides two static methods. it produces the following prompt: o o o o o Enter a character: Enter a blank line. The catch clause with an ExitException parameter causes the do statement and the program to terminate by setting finished to true. and the following output is displayed: A blank exception occurred. Cognizant Technology Solutions. throws the BlankException. All Rights Reserved C3: Protected . The three catch clauses notify the user of the type of exception they catch. If the user enters a line beginning with a character that cannot be printed. Enter a character: No exceptions are thrown for the j character. upon encountering a space character returned by getChar() . o o o o Enter j. 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. eliminating the need to declare the exception in the processUserInput() throws clause. If the user enters a vowel. The processUserInput() method throws one of the three exceptions based upon the character entered by the user. The IOException is handled by notifying the user that the exception occurred and continuing with program execution. and the following output appears: o o o o Enter a character: a A vowel exception occurred. Enter a at the program prompt. then VowelException is thrown. The try statement has three catch clauses and a finally clause. Enter a character: Here the program notifies you that a VowelException has occurred. IOException is caught by the try statement. main() and processUserInput() . The processUserInput() method. Page 221 ©Copyright 2007. then ExitException is thrown. The processing of the VowelException is similar to the blank exception. which is caught by the main() method. The finally clause just displays the fact that it has been executed. This is the finally clause.Handout . If the user enters x or X. The actual reading of the character occurs within a try statement.

Handout . normally by extending Exception or one of its subtypes. The compiler will stop you from defining catch clauses that can never be reached.length attribute is for). you must put the catch for IOException first in your code. This is the finally clause. You cannot guarantee the server is up. Test Your Understanding 1. exceptions are divided into two categories. All Rights Reserved C3: Protected . Use your catch blocks to try to recover from situations that you cannot guarantee will succeed. State true or false for the following: a) In Java. The program displays the output as shown below: o o o Enter a character: x An exit exception occurred. A try or catch is for handling exceptional situations and not flaws in your code. print out a message to the use and a stack trace. Your exception will then be considered a checked exception. If you have a catch clause for both IOException and Exception. You want run time exceptions to happen at development and testing time. no matter what happens during the execution of a try statement. you must put the catch for IOException and Exception. so that somebody can figure out what had happened. But you can make sure your code does not index off the end of an array (that is what the . The output acknowledges the fact that the Exit Exception was thrown by processUserInput() and caught by main(). rather than conditions that fails at run time in ways that you cannot predict or prevent. Some exceptions are created by programmers. You do not want to code in a try or catch. All catch blocks must be ordered from most specific to most general. namely checked and unchecked exceptions. Cognizant Technology Solutions. Or at the very least. 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. b) All subclasses of the RuntimeException and Error classes are unchecked exceptions. The program then returns you to the command prompt. Summary You can create your own exceptions. Go ahead and type x to exit the ExceptionTest program. and the compiler will enforce the handle or declare rule for that exception.Core Java The finally clause is always executed. Page 222 ©Copyright 2007. some by the JVM. You cannot guarantee that the file is there.

All Rights Reserved C3: Protected . 12 System. you will be able to: Identify the String class and its methods The String Class Definition: Represents combinations of character literals Using Java.println(s6).println(s1).Handout . 5 String s2 = new String(chars).out. 15 System. 9 String s5 = new String(s2). 1. 3).out. 14 System.0. 16 System.println(s5). 'l'. 6 byte bytes[] = { 'w'. //empty string 4 char chars[] = { 'h'. 'l'. 'o'}. 'd' }.out. 'l'. String Buffer.println(s2). 'r'. strings can be represented using: o o Array of characters 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. 'o'. 10 String s6 = s2. //s3="world" 8 String s4 = new String(chars.println(s4). and its Functions Learning Objectives After completing this session. 11 System.out. 7 String s3 = new String(bytes). //s2="hello". 'e'.out.out. Cognizant Technology Solutions. The String Class: Constructors 1 class StringConstructorsDemo { 2 public static void main(String args[]) { 3 String s1 = new String(). 13 System. v5.Core Java Session 61: Strings. 17 } 18 } Page 223 ©Copyright 2007.println(s3).

Handout . or it takes in an object as a parameter and returns the String equivalent of the specified parameter. Code: class StringConstructors { public static void main(String args[]) { String s1 = new String(). // s2="hello". All Rights Reserved C3: Protected . then the method will return false. public int compareToIgnoreCase (String str): Like compareTo but ignores the case used in this string and the specified string. byte bytes[] = { 'w'. 'o' }. public boolean equals (Object anObject): Returns true if this string has the same sequence of characters as that of the Object specified. public int compareTo (String anotherString): Compares this string with the specified parameter. int srcEnd. char[] dst. public boolean equalsIgnoreCase (String anotherString): Like equals but ignores the case used in this string and the specified string. public static String valueOf(-): Takes in a simple data type such as boolean. public int length() :Returns a length of this string. Cognizant Technology Solutions. 'e'. public char[] toCharArray() :Returns the character array equivalent of this string. int endIndex): Returns the substring of this string starting at the specified beginIndex up to the endIndex index. zero if both of the strings have the same value and a positive value if this string comes after the other string lexicographically. char newChar): Returns the string wherein all occurences of the oldChar in this string is replaced with newChar. 'l'.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. Page 224 ©Copyright 2007. String s2 = new String(chars). integer. which should be a String object. 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 String substring (int beginIndex. 'l'. // empty string char chars[] = { 'h'. public void getChars (int srcBegin. public String trim(): Returns a modified copy of the string wherein the leading and trailing white space are removed. 'l'. public String replace (char oldChar. 'r'. Try It Out Problem Statement: Write a program that illustrates the usage of String constructors. Otherwise if the specified parameter is not a String object or it does not match the sequence of symbols in this string. Returns a negative value if this string comes lexicographically before the outer string. 'o'. or character. 'd' }.

even if it is created from a literal. White spaces means. reverse. passing empty string returns zero. and passing a string that is not in the target string returns -1.println(s1).println(s3). append. String class is final.out. System. Page 225 ©Copyright 2007. String s5 = new String(s2). Passing null to indexOf or lastIndexOf will throw NullPointerrException.out.out.println(s2).Handout . System. all characters with values less than or equal to the space character – ‘\u0020’. System.out.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.out.println(s4). } } Refer File Name: StringConstructors.println(s5). substring. toUpperCase and toLowerCase will return the same string if no case conversion was needed.Core Java String s3 = new String(bytes). trim method removes all leading and trailing white-space from a String and returns a new String. a char array. A String created by a new operator is always a different new object. All Rights Reserved C3: Protected . = and += operators are overloaded for Strings.out. Cognizant Technology Solutions. 3). System. They can be created from a literal. replace. or a string buffer. and insert are not String methods. String s6 = s2. Solution: Strings are immutable. trim. All string operations (concat. System. and so on) construct and return new strings. 1. a byte array. // s3="world" String s4 = new String(chars.println(s6). System.

Core Java Summary String objects are immutable. Test Your Understanding 1. 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.n) and substring(m) formats. All Rights Reserved C3: Protected . Differentiate between indexOf() and lastIndexOf() methods. 2.Handout . String methods use zero-based indexes. Cognizant Technology Solutions. Differentiate between substring(m. the old String can be lost. and String reference variables are not. The String class is final – its methods can’t be overridden. Page 226 ©Copyright 2007. except for the second argument of substring().

.equals("Jonathan")).out. 34 /* Need to add 1 to the endIndex parameter of Page 227 ©Copyright 2007. 16 System. 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".println("name: " + name). and its Functions Learning Objectives After completing this session.compareToIgnoreCase("jonathan")). 'e')). 25 char charArr[] = "Hi XX".out. charArr. 29 System.out.println("Is Jonathan equal to jonathan? " + 22 name.equalsIgnoreCase("jonathan")).println("3rd character of name: " + 6 name. 23 System. String Buffer..println("Length of name: " + 31 name. 32 System.println("Is Jonathan equal to Jonathan? " + name.out.println("Solomon compared to Jonathan: " 12 + "Solomon".println("Jonathan compared to jonathan 17 (ignore case): " + name.compareTo("Solomon")).getChars(0.out.out.charAt(2)). 21 System.out.println("Is Jonathan equal to jonathan (ignore case)? " + name.out.Core Java Session 62: Strings.compareTo("Jonathan")). 2. 18 System. 13 /* 'J' has lower unicode value compared to 'j' */ 14 System.Handout . All Rights Reserved C3: Protected . 26 /* Need to add 1 to the endSrc index of getChars */ 27 "Jonathan".toCharArray(). 5 System. 20 //continued.print("getChars method: ").out.replace('a'.compareTo("jonathan")).out. Cognizant Technology Solutions. 28 System. 4 System.println("Jonathan compared to Solomon: " 10 + name. 30 System.println("Jonathan compared to jonathan: " + 15 name.out.println(charArr).out.println("Replace a's with e's in name: " + 33 name. 7 /* character that first appears alphabetically 8 has lower unicode value */ 9 System.length()).out. 11 System. 3).equals("jonathan")).

out. /* Note there's no change in the String object name even after applying all these methods.Core Java 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 substring*/ System.out. */ System. s = s. //continued. s = s.println(s). All Rights Reserved C3: Protected . 'Z'). 'X').println("Trim \" a b c d e f \": \"" + " a b c d e f ".valueOf(10>10)). // continued … Refer File Name: StringApp.Handout . System.out.trim() + "\"").println("String representation of boolean expression 10>10: " + String. 2)).out. System.out.println(s).out.println("[" + s + "]"). System. System.replace('J'.out.out.println("name: " + name).replace('C'.println("[" + s + "]"). 'Y'). s = s.trim().java to obtain soft copy of the program code Page 228 ©Copyright 2007.replace('2'. /* toString method is implicitly called in the println method*/ System.toLowerCase()).println("String representation of boolean expression 10<10: " + (10<10)).substring(0. System. s = s.out..println("A substring of name: " + name.println(s..out. Code: public class StringApp { public static void main(String args[]) { String s = " Java 2 Certification ". System.toUpperCase()). } 51 } Try It Out Problem Statement: Write a program that illustrates the usage of various methods available in the String class.println(s. System. System.out. Cognizant Technology Solutions.

Page 229 ©Copyright 2007. The new string is assigned to s and is printed. 'Y'. length(). if an object reference is null and that object is appearing in a concatenation expression by itself.Handout . 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”. 'C'. When the JVM finds a String literal. and 'Z'. It then uses the indices to put 'J'. It uses the toCharArray() to convert the string to a char array. toLowerCase(). arrays have an attribute named length. toString(). it is added to the String literal pool. Cognizant Technology Solutions. 'Y'. toUpperCase(). which is initially set to " Java 2 Certification ". The same is true for arrays. But if you try to access its members or methods. It prints the string enclosed between two braces to show that it contains leading and trailing spaces. The String() constructor is used to construct a new string from the character array. Summary String methods to remember are charAt(). Strings have a method: length(). 'C‘ . substring(). equalsIgnoreCase(). but trying to index it when the null of it throws a NullPointerException. It uses the indexOf() method to get the indices of 'X'. and 'Z' within s. Array name is replaced with null. Remember that chained methods are evaluated from left to right. The program uses the replace() method to replace 'J‘ .Core Java How It Works: This program performs several manipulations of a string s. concat(). then a NullPointerException is thrown. and '2' back in their proper locations within the character array. and prints out the string to show the changes. The replace() method is case sensitive. It then trims away these spaces using the trim() method and reprints the string to show that these spaces were removed. It prints the original string and then prints uppercase and lowercase versions of it. replace(). and '2' with 'X'. illustrating the use of the toUpperCase() and toLowerCase() methods. and trim(). All Rights Reserved C3: Protected .

Page 230 ©Copyright 2007. Cognizant Technology Solutions. equals(). and equalsIgnoreCase().Core Java Test Your Understanding Differentiate the methods compareTo(). All Rights Reserved C3: Protected .Handout .

} public boolean equals(Object obj) { HashHash h = (HashHash) obj. they must have the same hashcode value. Page 231 ©Copyright 2007.equals(b) must also mean that a.Core Java Session 65: Strings. then no two objects can ever be considered equal because references to two different objects will always contain a different bit pattern.hashCode() == b. public HashHash(int xVal) { x = xVal.equals(b)).) If two objects have the same hashcode value. But if they are equal. and its Functions Learning Objectives After completing this session. then calling equals() on the other object must return true. Java Object Law for equals() and hashCode() Methods (Contd.hashCode() == b. a. So.hashCode().equals(a)) . So if you do not override hashCode() in a class. Code: class HashHash { public int x.equals(b). then they must have matching hashcodes.hashCode() does not have to mean a. All Rights Reserved C3: Protected . a. Cognizant Technology Solutions. In other words. The default behavior of equals() is to do a == comparison. if you override equals() . then (b. In other words. the default behavior of equals() is to test whether the two references refer to a single object on the heap. 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. Try It Out Problem Statement: Write a program that illustrates the usage of equals() and hashCode() methods. So if you do not override equals() in a class. you must override hashCode() . then no two objects of that type can ever be considered equal.Handout . But. The default behavior of hashCode() is to generate a unique integer for each object on the heap. If two objects are equal. String Buffer. then they are not required to be equal. if (a.

Hashcodes can be the same without necessarily guaranteeing that the objects are equal. Cognizant Technology Solutions. But a HashSet can find an object more quickly. 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).x == this. } else { return false. 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. because it uses the hashcode as a kind of label on the “bucket” where it stored the element. Page 232 ©Copyright 2007. } // continued … Refer File Name: HashHash. but to find the one exact match. because the “hashing algorithm” applied in the hashCode() method might happen to return the same value for multiple Objects.Core Java if (h. looking at each element in the list to see if it matches. All Rights Reserved C3: Protected .x) { return true. 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. 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. Notice that in order for an object to be located. then the ArrayList has to start searching from the beginning.java to obtain soft copy of the program code How It Works: This program has overridden both the equals() and hashCode() methods.Handout . } } public int hashCode() { return (x * 17). Hashcode values are sometimes used to narrow down the search. This means that multiple objects would all land in the same bucket in the HashSet. the search object and the object in the collection must have both identical hashcode values and return true for the equals() method.

equals(y) is false.equals(x) is true. then x. hashCode(). and toString() are public.equals(y) is true.hashCode() is true. If x.hashCode() return the same integer. Test Your Understanding 1. o If you override equals().hashCode() == b. o Consistent: Multiple calls to x.equals(x) must be true. and y. o Null: If x. Cognizant Technology Solutions. then z. then y.hashCode() == y. transient variables are not appropriate for equals() and hashCode(). b) a.hashCode() must also mean that a.equals(y) is true.equals(y) will return the same result.hashCode() c) a. Highlights of the equals() contract: o Reflexive: x. State true or false for the following: a) If two objects are equal. override hashCode(). When overridding equals(). then x.equals(y) is true.hashCode() == y.equals(b) must also mean that a. Highlights of the hashCode() contract: o o o o Consistent: multiple calls to x.hashcode() == y. o Transitive: if x.Handout .hashCode() == b.equals(x) is true. x.equals(z) is true. All Rights Reserved C3: Protected . o Symmetric: if x. then they must have matching hashcodes.hashCode() can be either true or false.equals(b) Page 233 ©Copyright 2007. If x.equals(y) is true.hashCode() is true. use the instanceof operator to be sure you are evaluating an appropriate class.Core Java Summary equals(). but false will tend to create better efficiency.

All Rights Reserved C3: Protected .Core Java Session 66: Strings. you will be able to: Define StringBuffer and StringBuilder The StringBuffer Class Problem with String objects: Once created.println("sb = " + sb).Handout . String Buffer. Cognizant Technology Solutions. 4 System. and its Functions Learning Objectives After completing this session. Page 234 ©Copyright 2007. can no longer be modified (It is a final class) A StringBuffer object: Similar to a String object But.out. 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").

} The java. However. All the methods available on StringBuffer are also available on StringBuilder.println("capacity of sb: "+sb.StringBuilder Class J2SE5.insert(2. All Rights Reserved C3: Protected . 3)). System. The advantage of using StrignBuilder is faster performance. 2.out.out.0 javac compiler normally uses StringBuilder instead of StringBuffer whenever you perform string concatenation as in System.println("3rd character of sb: " + sb. Because StringBuilder is not synchronized. you should apply StringBuilder in preference over StringBuffer.out. System.println("implicit toString(): " + sb).lang. which means it is not thread-safe.out. System.println("replace: " + sb. System.out.println("append \'O\' to sb: " + sb.replace(3.out.println("substring (1st two characters): " + sb. /* Need to add 1 to the endIndex parameter of substring*/ System. " Ong")). System.out.0 added the StringBuilder class. which is a drop-in replacement for StringBuffer in cases where thread safety is not an issue. /* Need to add 1 to the endSrc index of getChars */ sb. 9.delete(2.out.println("The result is " + result).print("getChars method: "). "jo")).out. System. Page 235 ©Copyright 2007. the J2SE 5.substring(0.getChars(0. StringBuilder is identical to the well-known StringBuffer class of Java except for one important difference it is not synchronized.println("length of sb: " + sb. In general.out.println("Insert \'jo\' at the 3rd cell: " + sb.4)). System. Cognizant Technology Solutions.Handout .toCharArray().Core Java 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 } /* initial capacity is 16 */ System. charArr.out. System. you must apply StringBuffer rather than StringBuilder. System. In fact.println(charArr).append('O')). in cases in which you are applying multithreading.out.out.length()).capacity()). it offers faster performance than StringBuffer. char charArr[] = "Hi XX". System. 3).println("Delete \'jo\' at the 3rd cell: " + sb. so it really is a drop-in replacement.charAt(2)).println("sb = " + sb).

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.toString(). sb. "Java"). sb. } } Refer File Name: StringBufferApp. another newline character is appended to sb. All Rights Reserved C3: Protected .java to obtain soft copy of the program code How It Works: The program creates a StringBuffer object using the string " is ".out. insert() . sb. sb. and setCharAt() methods. sb.append("Hot").append(1).println(s).append('\n'). The charAt() and setCharAt() methods allow StringBuffer objects to be treated as arrays of characters.append('\n'). The setCharAt() method is used to replace the letter 't' at index 21 with the letter 'T‘ . sb. System. followed by the string "Java is #" and the int value 1.setCharAt(21. Cognizant Technology Solutions. Code: public class StringBufferApp { public static void main(String args[]) { StringBuffer sb = new StringBuffer(" is "). Page 236 ©Copyright 2007.append(true).Handout . Finally. The insert() method is used to insert the string "Java" at the beginning of the string buffer. the string "This is ". sb.insert(0.append('!'). sb. 'T'). sb.append("This is ").append("Java is #"). sb. It appends the string "Hot" using the append() method and the character '!' using an overloaded version of the same method. Three append methods are used respectively to tack on the following: o A new line character (\n). String s = sb.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() .

As they can grow dynamically in size without bounds. Page 237 ©Copyright 2007. reverse(). 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. StringBuilder methods should run faster than StringBuffer methods. trim is not a StringBuffer method.Handout . StringBuffer created with the specified capacity has the exact capacity specified. All operands are appended by calling toString method. capacity does not have much effect. Do not use it to test content equality. insert(). setCharAt. A StringBuffer created from a String has the capacity of the length of String + 16. All of the following apply to both StringBuffer and StringBuilder: They are mutable – they can change without creating a new object. This method does not affect the capacity. Finally a string is returned by calling toString on the StringBuffer. StringBuffer methods act on the invoking object. StringBuffer methods to remember: append(). Cognizant Technology Solutions. then nulls are padded. from a string or with a capacity. it doesn’t compare values. Both extend Object class. An empty StringBuffer is created with 16-character capacity. setLength changes the length. If it is smaller than the specified length. and toString(). ‘+’ operator appearing with one String operand. and reverse are used to manipulate the string buffer. and objects can change without an explicit assignment in the statement. String context means. except that StringBuilder’s methods are not synchronized for thread safety. insert. All Rights Reserved C3: Protected . delete(). They can be created empty. Summary The StringBuffer’s API is the same as the new StringBuilder’s API. A new StringBuffer is created. StringBuffer equals() is not overridden. If the current content is larger than specified length. append. equals on StringBuffer does a shallow comparison (same like ==) and will return true only if the objects are same. if needed. There is no relationship between String and StringBuffer. StringBuffer is a final class. String concatenation cannot be applied to StringBuffer.Core Java The StringBuffer object is then converted to a string and displayed to the console window. then it is truncated. Solution: String Buffers are mutable strings.

Cognizant Technology Solutions.Handout . All Rights Reserved C3: Protected .Core Java Test Your Understanding Differentiate between length() and capacity() methods of the StringBuffer class. Page 238 ©Copyright 2007.

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

Handout - Core Java

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 240 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Handout - Core Java
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 241 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

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

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

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

Handout - Core Java Summary
Common collection activities include adding objects, removing objects, verifying object inclusion, retrieving objects, and iterating. Three meanings for “collection”: o o o Collection: Represents the data structure in which objects are stored Collection: java.util interface from which Set and List extend 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

//optional Page 246 ©Copyright 2007. Cognizant Technology Solutions. //optional Iterator<E> iterator(). boolean isEmpty(). “Set” Interface (Java SE 5) public interface Set<E> extends Collection<E> { // Basic operations int size(). //optional void clear(). //optional removeAll(Collection<?> c). addAll(Collection<? extends E> c). boolean contains(Object element). boolean add(E element). All Rights Reserved C3: Protected .Handout . 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. 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. //optional boolean remove(Object element). // Bulk boolean boolean boolean boolean operations containsAll(Collection<?> c). //optional retainAll(Collection<?> c).Core Java Session 70: Collections and Util package Learning Objectives After completing this session.

Core Java // Array Operations Object[] toArray(). allowing Set instances to be compared meaningfully even if their implementation types differ. 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. such as word lists and membership roll. All Rights Reserved C3: Protected . Several additional operations are provided to take advantage of the ordering. 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. 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. 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. can waste both space and time Choosing an initial capacity that is too low. <T> T[] toArray(T[] a). HashSet is the mostly commonly used implementation. Cognizant Technology Solutions. Sorted sets are used for naturally ordered sets. “SortedSet” Interface Sorted Set interface is a set that maintains its elements in ascending order.Handout . Two Set instances are equal if they contain the same elements. } “equals” Operation of Set Interface Set also adds a stronger contract on the behavior of the equals and hashCode operations.

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

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

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

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

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

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

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

This field is blank. duplicates not allowed. Sets. (Nulls OK) Vector (Nulls OK) TreeSet This field is blank. May or may not be ordered and/or sorted. Test Your Understanding 1. Resizable Array This field is blank. May or may not be ordered and/or sorted. (Nulls OK) This field is blank. Ordered by FIFO or by priority. HashMap (Nulls This field is blank. Queues: Lists of things Sets of things Maps of things with keys Queues of things to process Ordered. 2.Handout . This field is blank. All Rights Reserved C3: Protected .Core Java Data structures used to Set implement HashTable HashSet (Nulls OK) Interfaces SortedSet List Map SortedMap This field is This field is blank. OK) HashTable (No Nulls) This field is blank. TreeMap Linked List This field is LinkedList blank. This field is blank. d) HashMap class implements the Map interface. Summary The four basic flavors of collections include Lists. Maps. blank. Cognizant Technology Solutions. Which one of the following statements is wrong? a) All classes in collection framework implement the Collection interface. This field is blank. When will the search() method return -1? Page 255 ©Copyright 2007. with an index. c) Hashtable class is a concrete class. Duplicate keys are not allowed. duplicates allowed. b) HashSet class implements the Map interface. This field is ArrayList blank. Balanced Tree This field is blank.

Handout .iterator(). Iterator: An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively.out. } Iterating over multiple collections in parallel Page 256 ©Copyright 2007. remove() is the only safe way to modify a collection during iteration. 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. it. void remove(). All Rights Reserved C3: Protected . static void filter(Collection<?> c) { for (Iterator<?> it = c.next())) it. next() method returns the next element in the iteration. Iterator Interface public interface Iterator { boolean hasNext(). //optional } hasNext() method returns true if the iteration has more elements.remove(). 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.hasNext(). Object next().Core Java Session 73: Collections and Util package Learning Objectives After completing this session. The behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress. ) if (!cond(it.println(o). if desired. Cognizant Technology Solutions. the for-each construct is not usable for filtering.

v5.next(). Cognizant Technology Solutions. In other words. Although the for-each form of the for loop was designed with arrays and collections in mind.Core Java The Iterable Interface Iterable is a generic interface that was added by Java 2.*. d. as shown here: Iterator<T> iterator() It returns an iterator to the set of elements contained in the invoking object.hasNext()) { Dog d2 = itr. Dog dog = new Dog("aiko").println(d2.name).util.add(new Dog("magnolia")). d. a class must implement Iterable whenever an object needs to be used within a for-each style for loop in that class. All Rights Reserved C3: Protected .out.add(dog). } } class IteratorTest { public static void main(String[] args) { List<Dog> d = new ArrayList<Dog>(). Iterator<Dog> itr = d. } Page 257 ©Copyright 2007.Handout . // cast not required System. This enables you to create classes whose objects can be applied with the for-each form of the for loop. // make an iterator while (itr.0. Try It Out Problem Statement: Write a program that illustrates the usage of List and an Iterator. Code: import java. This is a powerful feature that substantially increases the types of programming situations to which the for can be applied. Dog(String n) { name = n. The Iterable interface must be implemented by any class whose objects will be applied by the for-each version of the for loop. iterator() . class Dog { public String name. d.iterator(). Iterable has the following declaration: interface Iterable<T> It defines one method.add(new Dog("clover")). it can be used to cycle through the contents of any object that implements the Iterable interface.

Because of this. you have used generics syntax to create the Iterator (an Iterator of type Dog). Cognizant Technology Solutions. you did not have to cast the object returned by next() to a Dog. Iterators that do this are known as fail-fast iterators.Handout . Dog d2 = (Dog)itr. and toArray() methods. For example.java to obtain soft copy of the program code How It Works: When you run IteratorTest.Core Java Refer File Name: IteratorTest. indexOf() . Page 258 ©Copyright 2007. Note: Invoking hasNext() does not move the iterator to the next element of the collection. it displays the following results: aiko clover magnolia size 3 get1 clover aiko 0 oa aiko oa clover Firstly. the results are undefined under these circumstances. In general. as they fail quickly and cleanly. You could have declared the Iterator like this (on using JDK1. get() . // make an Iterator But then you would have had to cast the following returned value: Tips and Tricks: Explain briefly about the ConcurrentModificationException related to Iterators. 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. when you have used the next() method. All Rights Reserved C3: Protected .iterator. 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. it is not permissible for one thread to modify a Collection while another thread is iterating over it. rather that risking arbitrary behavior that is not deterministic at an undetermined time in the future.4 or lesser version): Iterator itr = d.next(). The rest of the code demonstrates using the size() .

when the entire Collections Framework was retrofitted for generics. Because the iterator() method of Iterable returns an Iterator. v5.Core Java Summary Iterable is a generic interface that was added by Java 2. State true or false for the following: a) An interface. often a class that implements Iterable will also implement Iterator. v5. Earlier versions of Iterator were not generic. All Rights Reserved C3: Protected . which provides you a standardized way of accessing the elements within a collection applied for general purpose. Test Your Understanding 1.Handout . is also defined in the collections framework. 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.0. Page 259 ©Copyright 2007. Cognizant Technology Solutions. This interface is known as Iterator interface. Iterator is a generic class in Java 2.0.

This second property list is searched if the property key is not found in the original property list. The Properties Class The Properties class represents a persistent set of properties.} Date d2 = new Date(). Cognizant Technology Solutions.util.getTime().load(propFile). System.d1. Properties p = new Properties(System. The Properties Class: Example // set up new properties object // from file "myProperties.Properties classes The Date Class Date class represents a precise moment in time. Greenwich Mean Time.println("That took " + elapsed_time + " milliseconds"). i++) { int j = i. p.out.getTime() . 1970. 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. down to the millisecond. The Date Class: Example // Return the number of milliseconds in the Date // as a long.Core Java Session 75: Collections and Util package Learning Objectives After completing this session.Handout . Dates are represented as a long type that counts the number of milliseconds since midnight.getProperties()).Date and java. All Rights Reserved C3: Protected .util. Page 260 ©Copyright 2007. January 1. // timed code goes here for (int i=0. i<1000000. using the getTime() method Date d1 = new Date(). you will be able to: Identify java.txt"). A property list can contain another property list as its "defaults“.txt" FileInputStream propFile = new FileInputStream("myProperties. long elapsed_time = d2.

The displayDateInfo() method is then invoked to display date and time information about the cal variable.setTime(today). There are several versions of the set() method. // display new properties System.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. All Rights Reserved C3: Protected . displayDateInfo(cal).out). 1). The Date object is assigned to the today variable.util. Cognizant Technology Solutions. System. The cal variable is updated with the current date by invoking its setTime() method with the Date object stored in today.println("\nNew Years Day 2000: "). public class DateApp { public static void main(String args[]) { Date today = new Date().TimeZone classes in order to access date and time information. } // continued … Refer File Name: DateApp. 0. Try It Out Problem Statement: Write a program that illustrates the usage of java.out. cal.setProperties(p).Core Java // set the system properties System. System.println("Today: "). Page 261 ©Copyright 2007.Date class along with java.clear().util. The set() method is used to set its date to New Year's 2000. displayDateInfo(cal). Code: import java. each of which takes a different set of parameters.list(System.util. cal. and the GregorianCalendar object is assigned to the cal variable.GregorianCalendar and java. The clear() method of the Calendar class is invoked to reset the date of the GregorianCalendar object stored in cal.set(2000.getProperties().out.*.Handout . GregorianCalendar cal = new GregorianCalendar(). cal.util.

months. Note that the month value ranges from zero to 12. Which methods do you use to add and retrieve data in a Properties object? Page 262 ©Copyright 2007. The Locale class is used in conjunction with DateFormat and NumberFormat.m. The getID() method of the TimeZone class is used to retrieve the local time zone ID string. The Calendar provides a powerful set of methods to manipulate dates. These values are retrieved using the get() method of the Calendar class and the Calendar constants corresponding to date and time values. Cognizant Technology Solutions. java. The DateFormat. the number of milliseconds since January 1. java.Date. and am_pm arrays to define string values corresponding to the days of the week.Core Java The version used in DateApp takes the year. The value corresponds to the difference between the current time and midnight. Most of the Date class’s methods have been deprecated. java. It then prints a line corresponding to date and time values./p.text. and a. The displayDateInfo() method is invoked again to display information about the new calendar date. where the year and date values begin at one. performing tasks such as getting days of the week. the catch is that the time is provided in milliseconds.util.util. Summary The classes you need to understand are java. what is the alternate way to get the current time? Solution: To get the current time use System. Test Your Understanding 1. 1970 UTC. Tips and Tricks: Instead of using Date class. All Rights Reserved C3: Protected .currentTimeMillis().Locale. and date as parameters. The getTimeZone() method of Calendar is invoked to retrieve the local TimeZone object.format() method is used to create Strings containing properly formatted dates. and java. A Date is stored as a long.NumberFormat. months of the year. Properties class is a subclass of the Hashtable class. 1970.util.Calendar. The displayDateInfo() method creates the days. January 1. Do you agree with this statement? 2. or adding some number of months or years to a date. However. Date objects are go-betweens the Calendar and Locale classes.m.text.Handout .DateFormat. month. This method is useful for program timing studies.

which thread receives CPU control and gets to be executed first. you start with just one thread. 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.Core Java Session 81: Threads Learning Objectives After completing this session. All Rights Reserved C3: Protected . called the main thread. 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. But from the point of view of application programmer. This thread has the ability to create additional threads. Thread Priorities Priorities determine. if you count "system" threads that do things like memory management and signal handling. comes in while first thread is running Context switch: Occurs when a thread snatches the control of CPU from another Page 263 ©Copyright 2007. Cognizant Technology Solutions.Handout . Definition of threads: Single sequential flow of control within a program For simplicity. you will be able to: Define a thread Identify the thread priorities Threads Threads are required to handle concurrent processes. already running Second thread = priority of 10.

Handout .start(). t2. All Rights Reserved C3: Protected . } // continued … Refer File Name: ThreadPriorityApp.println(s).out. Code: class ThreadPriorityApp { public static void main(String args[]) { MyThread t1 = new MyThread("t1"). } } class MyThread extends Thread { public void displayOutput(String s) { System.start(). Cognizant Technology Solutions. t1. 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. The decision that which of the highest priority threads receives the CPU control is dependent on the operating system.Core Java When does it occur? o o Running thread voluntarily relinquishes CPU control 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.java to obtain soft copy of the program code Page 264 ©Copyright 2007. MyThread t2 = new MyThread("t2").

Handout . although priorities are not guaranteed. Thread priorities are numerical values that tell the scheduler (if it cares) how important a thread is to you. If not explicitly set. Summary Once a thread is started. Cognizant Technology Solutions. the scheduler will kick a lower priority out of the running state if a higher priority thread suddenly becomes runnable. It is recommended that you use priorities only if you want to influence performance. Also. there is no guarantee. The setPriority() method is use don Thread objects to give threads a priority of between 1 (low) and 10 (high). the output differs between each and every run. Still.Core Java How It Works: When you run the program. and not all JVMs recognize 10 distinct priority levels. but they still do not offer any guarantee. the output sequence will vary from computer to computer. 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. it will always enter the runnable state. All Rights Reserved C3: Protected . Page 265 ©Copyright 2007. a thread’s priority will have the same priority as the priority of the thread that created it. ever rely on them for program correctness. In general. but never.

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. All Rights Reserved C3: Protected . Name the different states in the life cycle of a thread. Cognizant Technology Solutions.Handout . 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. 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. Test Your Understanding 1. If a lowpriority thread is running when a high priority thread enters runnable. 3. Page 266 ©Copyright 2007.Core Java The yield() method may cause a running thread to back out if there are runnable threads of the same priority. the JVM will usually preempt the running low-priority thread and put the high-priority thread in.

Core Java Session 82: Threads Learning Objectives After completing this session.Handout . All Rights Reserved C3: Protected . Some of the important constructors are as follows: The Thread Class: Constants The Thread class contains fields for priority values. Page 267 ©Copyright 2007. Cognizant Technology Solutions. 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.

An object instance of the subclass can then be created. The start() method is in the constructor of the subclass. 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. Java runtime starts the execution of the thread by calling run() method of object instance. The start() method needs to be explicitly invoked after object instance of the subclass is created in order to start the thread. The subclass overrides the run() method of Thread class.Handout . All Rights Reserved C3: Protected . Scheme 1: start() Method is not in the Constructor of Subclass 1 class PrintNameThread extends Thread { 2 PrintNameThread(String name) { 3 super(name). Cognizant Technology Solutions. Creating an object instance of the subclass will start the thread.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. 4 } Page 268 ©Copyright 2007. Calling the start() method of the object instance starts the execution of the thread.

i < 100. 7 for (int i = 0.out. i < 100. 18 pnt1.Core Java 5 public void run() { 6 String name = getName(). 21 pnt2. 18 PrintNameThread pnt2 = 19 new PrintNameThread("B").out. // Start the first thread 19 PrintNameThread pnt2 = 20 new PrintNameThread("B").print(name). 10 } 11 } 12 } 13 14 class ExtendThreadClassTest2 { 15 public static void main(String args[]) { 16 PrintNameThread pnt1 = 17 new PrintNameThread("A"). 20 21 } 22 } Page 269 ©Copyright 2007. Cognizant Technology Solutions.Handout .print(name).start(). All Rights Reserved C3: Protected . //runs the thread once instantiated 5 } 6 public void run() { 7 String name = getName(). // 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).start(). i++) { 8 System. 8 for (int i = 0. 9 } 10 } 11 } 12 13 14 class ExtendThreadClassTest1 { 15 public static void main(String args[]) { 16 PrintNameThread pnt1 = 17 new PrintNameThread("A"). 4 start(). i++) { 9 System.

name = name.out. } Page 270 ©Copyright 2007. All Rights Reserved C3: Protected . The class must define run() method of no arguments. Scheme 1: Caller Thread Creates a Thread Object and Starts it Explicitly // PrintNameRunnable implements Runnable interface class PrintNameRunnable implements Runnable { String name. Cognizant Technology Solutions. The Thread object is created and started within the constructor method of the class that implements Runnable interface. The run() method is like main() for the new thread. 17 new PrintNameThread("B"). A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. i++) { System. 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.print(name). PrintNameRunnable(String name) { this. The start() method of the Thread object needs to be explicitly invoked after object instance is created. The caller thread just needs to create object instances of the Runnable class. public void run() { for (int i = 0. i < 10.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").Handout . } // Implementation of the run() defined in the // Runnable interface. 18 } 19 } Runnable Interface The Runnable interface should be implemented by any class whose instances are intended to be executed as a thread. The Runnable interface provides the means for a class to be active while not subclassing Thread.

getName(). new PrintNameRunnable("B").Core Java } } public class RunnableThreadTest1 { public static void main(String args[]) { PrintNameRunnable pnt1 = new PrintNameRunnable("A"). new PrintNameRunnable("C"). Thread t1 = new Thread(pnt1). } } } public class RunnableThreadTest2 { public static void main(String args[]) { // Since the constructor of the PrintNameRunnable // object creates a Thread object and starts it. t1. // there is no need to do it here. name). PrintNameRunnable(String name) { thread = new Thread(this. Cognizant Technology Solutions.print(name).out. All Rights Reserved C3: Protected . for (int i = 0. } } Scheme 2: Thread Object is Created and Started Within a Constructor // PrintNameRunnable implements Runnable interface class PrintNameRunnable implements Runnable { Thread thread.start().Handout .start(). } // Implementation of the run() defined in the // Runnable interface. i++) { System. public void run() { String name = thread. new PrintNameRunnable("A"). thread. i < 10. } } Page 271 ©Copyright 2007.

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.start(). Example: ThreadGroup 1 // Start three threads 2 new SimpleThread("Jamaica"). 15 } Page 272 ©Copyright 2007.i++){ 12 System.Handout . In addition.getName() + " in thread group " 14 + group. 10 int actualSize = group.start(). Cognizant Technology Solutions.currentThread().println("Thread " + 13 tarray[i]. i<actualSize. but not to access information about the parent thread group of the thread group or any other thread groups. 3 new SimpleThread("Fiji"). 8 9 Thread[] tarray = new Thread[10].start(). a thread group can also include other thread groups.getName()).getThreadGroup(). 4 new SimpleThread("Bora Bora"). All Rights Reserved C3: Protected .enumerate(tarray). 5 6 ThreadGroup group 7 = Thread. 11 for (int i=0.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.out.

println("Thread 1 is dead. 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. The only disadvantage to this approach is that you have to do a little more work to create and execute your threads. All Rights Reserved C3: Protected . Remember that there are two things to be noticed.out. From an OO view.Handout .isAlive()) { thread1IsAlive = false. do { if (thread1IsAlive && !thread1. Code: class ThreadUsingRunnableApp { public static void main(String args[]) { Thread thread1 = new Thread(new MyClass("thread1: ")). thread1. In other words."). Cognizant Technology Solutions. 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(). that is another way of making your own thread. your class can extend some other required class. Instead. } Refer File Name: ThreadUsingRunnableApp. if you think of the Thread as the worker. boolean thread2IsAlive = true. This is a very helpful feature when you create multithreaded applets. boolean thread1IsAlive = true. if desired. // no Runnable] Solution: Yes.start(). then do not extend the Thread class unless you need more specific worker behaviors.start(). Page 273 ©Copyright 2007.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. which are the Thread and the job of the thread. Thread thread2 = new Thread(new MyClass("thread2: ")).Core Java Try It Out Problem Statement: Write a program that illustrates the usage of Runnable interface in the creation of threads. thread2. System. and belong to separate classes.java to obtain soft copy of the program code Refer File Name: ThreadUsingRunnableApp_output_on_two_executions. those two are very separate activities.

When a Thread object is created. How can you assign priority to a thread? Does the priority value always lie between one and 10? Page 274 ©Copyright 2007. Summary Threads can be created by extending Thread and overriding the public void run() method.Handout . It is legal to create many Thread objects using the same Runnable object as the target. it will throw a RuntimeException. Write the different forms of constructor of the Thread class. it does not become a thread of execution until its start() method is invoked. If start() is called more than once on a Thread object.Core Java But if all you need is a new job to be run by a Thread or worker. It is perfectly legal to subclass Thread and override then run() method. The Runnable object is said to be the target of the thread. You can call start() on a Thread object only once. This is a design issue and not a performance or language issue. but it is rarely a good idea. Thread objects can also be created by calling the Thread constructor that takes a Runnable argument. Test Your Understanding 1. then implement Runnable in a separate class that is specific to job and not specific to worker. it is in the new state and is not considered alive. What useful purpose does the isAlive() method of the Thread class serve? 3. When a Thread object exists but hasn’t been started. Cognizant Technology Solutions. All Rights Reserved C3: Protected . 2.

with one thread reading from the file while another thread writes to the file.println(str2). Example: Threads often need to share a common resource that is a file.out. str2). 15 PrintStringsThread(String str1.print(str1. String str2) { 16 this. They can be avoided by synchronizing the threads. String str2) { 3 System. 23 } 24 } Page 275 ©Copyright 2007.out.str2 = str2. 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.sleep(500).print(str1). 19 thread. 6 } catch (InterruptedException ie) { 7 } 8 System.start(). asynchronously executing threads access the same object (called a shared resource) returning unexpected (wrong) results. which access the shared resource. str2. 20 } 21 public void run() { 22 TwoStrings. All Rights Reserved C3: Protected . 14 String str1. An Unsynchronized Example 1 class TwoStrings { 2 static void print(String str1. 18 thread = new Thread(this). 4 try { 5 Thread. 17 this.str1 = str1.Core Java Session 84: Threads Learning Objectives After completing this session. 9 } 10 } 11 12 class PrintStringsThread implements Runnable { 13 Thread thread. Cognizant Technology Solutions.Handout .

Cognizant Technology Solutions.out. str2. "there. 5 try { 6 Thread. All Rights Reserved C3: Protected . 29 new PrintStringsThread("How are ".Handout . 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.sleep(500). 19 thread = new Thread(this). 30 new PrintStringsThread("Thank you ". 31 "very much!"). 18 this. String str2) { 17 this.str1 = str1. 16 PrintStringsThread(String str1. 10 } 11 } 12 13 class PrintStringsThread implements Runnable { 14 Thread thread. Page 276 ©Copyright 2007.Core Java 25 26 class TestThread { 27 public static void main(String args[]) { 28 new PrintStringsThread("Hello ". "you?"). 15 String str1. 3 String str2) { 4 System. 32 } 33 } Sample output: Hello How are Thank you there.str2 = str2.out.print(str1).println(str2)."). 7 } catch (InterruptedException ie) { 8 } 9 System.

32 "very much!").str1 = str1. 21 } 22 public void run() { 23 TwoStrings. 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. Cognizant Technology Solutions. All Rights Reserved C3: Protected . 33 } 34 } Option 1: Executing Synchronized Method Sample output: Hello there. 16 PrintStringsThread(String str1. String str2.println(str2). str2). 9 } 10 } 11 12 class PrintStringsThread implements Runnable { 13 Thread thread. "there. String str2) { 3 System. 19 this.out. 24 } 25 } 26 27 class TestThread { 28 public static void main(String args[]) { 29 new PrintStringsThread("Hello ". 6 } catch (InterruptedException ie) { 7 } 8 System.str2 = str2. 31 new PrintStringsThread("Thank you ". 30 new PrintStringsThread("How are ". 15 TwoStrings ts. str2.").start().out.print(str1. 14 String str1.ts = ts. "you?"). 17 TwoStrings ts) { 18 this.print(str1). 4 try { 5 Thread.Core Java 20 thread. Page 277 ©Copyright 2007.Handout . 20 this.sleep(500).

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. wait() can only be invoked from within synchronized code. 36 new PrintStringsThread("Thank you ". wait() method is defined in the Object class. 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. All Rights Reserved C3: Protected . str2). 23 } 24 25 public void run() { 26 synchronized (ts) { 27 ts. Page 278 ©Copyright 2007.Handout . 37 "very much!". ts). ts). It should always be wrapped in a try block as it throws IOException.print(str1. Another thread invokes the notifyAll() method for this object. "you?". wait() can only be invoked by the thread that owns the lock on the object. 28 } 29 } 30 } 31 class TestThread { 32 public static void main(String args[]) { 33 TwoStrings ts = new TwoStrings(). When wait() is called. ts). Cognizant Technology Solutions. 22 thread.Core Java 21 thread = new Thread(this). "there. 35 new PrintStringsThread("How are ".start().". 34 new PrintStringsThread("Hello ".

The choice is arbitrary and occurs at the discretion of the implementation. notify() method can only be used within synchronized code.txt for the console output on two different occasions Page 279 ©Copyright 2007.". 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. ThreadSynchronizedStmtApp thread2 = new ThreadSynchronizedStmtApp("thread2: ")." }.java to obtain soft copy of the program code Refer File Name : ThreadSynchronizedStmtApp_output_on_two_executions. boolean thread1IsAlive = true. "hot. "is". When one of the earlier occurs. All Rights Reserved C3: Protected . thread1. "invigorating. public static void main(String args[]) { ThreadSynchronizedStmtApp thread1 = new ThreadSynchronizedStmtApp("thread1: "). thread2. The specified wait() time elapses.Core Java Another thread interrupts this thread. Code: class ThreadSynchronizedStmtApp extends Thread { static String message[] = { "Java". 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. Cognizant Technology Solutions.Handout .start().start(). "aromatic. Refer File Name: ThreadSynchronizedStmtApp. boolean thread2IsAlive = true. The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. then one of them is chosen to be awakened. "and".". Try It Out Problem Statement: Write a program that illustrates the usage of synchronized statement in thread synchronization.

Summary Synchronized methods prevent more than one thread from accessing an object’s critical method code simultaneously. But. It is used to acquire a lock on an object before performing an action.Handout . multiple threads can still access the same object’s unsynchronized code. the Thread object is no longer a thread. 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. for making a pool of threads that you can keep using to perform different jobs. To synchronize a block of code. It is just an object. the thread can never be restarted. you must specify an argument that is the object whose lock you want to synchronize on. at that point. All Rights Reserved C3: Protected . using the lock from the java. In fact. It can be used with the lock of any object. the thread has finished its run() method and can never be restarted.Class instance representing that class. at that point the thread moves into the dead state. or to start a synchronized block of code. rather than an entire method. In other words. Page 280 ©Copyright 2007. The Thread object might still be on the heap. like all other objects. The synchronized method can only be used with the lock of object or class. there are design patterns. Cognizant Technology Solutions. It also differs in a way that it applies to a statement block. as a living object that you can call other methods on (if appropriate). Static methods can be synchronized. but the Thread object has permanently lost its ‘threadness’. The synchronized statement differs from a synchronized method in that.lang.Core Java How It Works: The synchronized statement is similar to a synchronized method in that. 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. But you do not do it by restarting a dead thread. You can use the synchronized keyword as a method modifier. While only one thread can be accessing synchronized code of particular instance. In the dead state. Once the run() method of a thread has completed.

4. All Rights Reserved C3: Protected . 2. What do you mean by ‘Synchronization’? Why do you need it? What is ‘deadlock’? What harmful effect does it have? Differentiate between notify() and notifyAll() methods.Core Java Test Your Understanding 1. Why do you need join() method? Page 281 ©Copyright 2007. 3. Cognizant Technology Solutions.Handout .

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 o o Standardizing invocation Scheduling Execution

Page 282 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

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

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

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

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 o o Returns immediately if semaphore count is greater than zero Blocks if count is zero until release() is called by different thread 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

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

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

java to obtain soft copy of the program code Refer File Name : ThreadUsingWaitAndNotifyApp_output_on_two_executions. All Rights Reserved C3: Protected . making it available for output every 10 seconds. ++i) user[i]. i < user.Handout .length.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. out: do { alive = false. Thread controller = new Thread(new Controller(resource)). try { m. ++i) user[i] = new Thread(new User(i. // continued … Refer File Name: ThreadUsingWaitAndNotifyApp. The Controller object also executes as a separate thread and controls access to the Resource object. The User objects execute as separate threads and use the Resource object to display their output. controller. Page 289 ©Copyright 2007. Thread[] user = new Thread[3].clear().unlock(). for (int i = 0.length. The Resource object provides access to the console display.start().lock(). Cognizant Technology Solutions. } finally { w. i < user. } } } 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(). boolean alive. resource)).Core Java public void clear() { w.start(). The displayOutput() method of the Resource object displays a message on the console when okToSend is true. for (int i = 0.

and the thread must currently hold the lock on that object. At run time. Deadlocks can occur easily. Note that the wait() method. o Always call notifyAll() . Getting a lock on outer object does not mean getting the lock on an inner object as well.Core Java If a User thread invokes displayOutput() when okToSend is false. This ensures that while calling these methods the thread always has the lock on the object. Cognizant Technology Solutions. like the sleep() method of the Thread class. wait() and notify() should be called from synchronized code. Basically. rather than in an if statement. They will be in this state forever. Can move to ready only when the lock is available. Summary When a thread goes to sleep.”. Thread has been asked to wait. For example Thread A locked Object A and waiting to get a lock on Object B. or “add me to your waiting list. a wait() call means “wait me in your pool. instead of notify() wait() and sleep() must be enclosed in a try or catch block for InterruptedException. If you have wait or notify in non-synchronized code. Locks on inner or outer objects are independent.Handout . then the compiler will not catch this.” Page 290 ©Copyright 2007. Tips and Tricks: List out the differences between ‘blocked’ state and ‘waiting’ state. (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. (by means of wait (or waiting for a blocking I/O method) method) The thread already acquired the lock and executed Caused by the thread tried to execute some some synchronized code before coming across a synchronized code. notify(). This exception is thrown when the interrupt() method of a thread is invoked while it is in the waiting state. (or a blocking i/o method) wait call. if the thread does not have the lock while calling these methods. that lock should be obtained separately. and notifyAll() must be called from within a synchronized context! A thread invokes wait() or notify() on a particular object. its locks will be unavailable to other threads. but Thread B locked Object B and waiting to get a lock on Object A. throws the InterruptedException. Solution: Blocked Waiting Thread is waiting to get a lock on the monitor. All Rights Reserved C3: Protected . All three methods namely wait(). then an IllegalMonitorStateException is thrown. 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. then it enters the waiting pool.

Handout . Test Your Understanding 1. The notify() method can NOT specify which waiting thread to notify. Name some of the concurrency utilities.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. All Rights Reserved C3: Protected . 2. Cognizant Technology Solutions. Why should you use concurrency utilities? Page 291 ©Copyright 2007.

Handout . A stream can represent many different kinds of sources and destinations like disk files. Streams support many different kinds of data like simple bytes. primitive data types. and objects. All Rights Reserved C3: Protected . Page 292 ©Copyright 2007. other programs. Input Stream A program uses an input stream to read data from a source. 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. one item at a time. localized characters. Some streams simply pass on data. others manipulate and transform the data in useful ways. a network socket. and memory arrays. Cognizant Technology Solutions. No matter how they work internally.Core Java Session 89: I/O operations in JAVA Learning Objectives After completing this session. devices. A stream is a sequence of data. all streams present the same simple model to programs that use them.

Handout . one item at time. 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 o o The Reader class The Writer class Both classes are abstract Input and Output Streams Input or source streams: Can read from these streams Root classes of all input streams: o o The InputStream class The Reader class Output or sink (destination) streams: Can write to these streams Root classes of all output streams: o o The OutputStream class The Writer class Page 293 ©Copyright 2007. 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. Cognizant Technology Solutions. 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.Core Java Output Stream A program uses an output stream to write data to a destination. All Rights Reserved C3: Protected .

it is usually represented as 8 bits. Page 294 ©Copyright 2007. ASCII. and 18 bit patterns.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.Handout . then it is probably Cp1252. and UTF-8 characters? What is the default character encoding of your platform? Solution: Unicode requires 16 bits and ASCII require 7 bits. UTF-8 represents characters using 8. Cognizant Technology Solutions. 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. If you are running Java on English Windows platforms. then it is most likely 8859_1. 16. UTF-16 uses 16-bit and larger bit patterns. If you are running Java on English Solaris platforms. All Rights Reserved C3: Protected . Although the ASCII character set uses only 7 bits. UTF-16. memory.

What is a ‘stream’? 2. Name some important input and output stream classes.Handout . In other words. Cognizant Technology Solutions. “A stream is a flowing sequence of characters”.) Test Your Understanding 1. (This is a common use of the decorator design pattern. Comment on this statement. Classes in java. 3. a stream is usually considered to be an abstraction for the capability to move bytes from a source to a sink. The package named java. output operations begin by opening a stream to the destination and using a write() method to send the data. Page 295 ©Copyright 2007.io package also provides specialized InputStream and OutputStream subclasses that are used for specialized types of input and output. The java. All Rights Reserved C3: Protected . Input operations begin by opening a stream from the source and using a read() method to obtain the data via the stream.io contains a set of input and output stream classes that can be used to read and write data.Core Java Summary The central building block of the Java I/O framework is the stream. Similarly. OutputStream and InputStream classes serve as the base classes for all byte stream classes. The InputStream class and OutputStream class are abstract superclasses that define the behavior for sequential input and output streams in Java.io package are designed to be “chained” or “wrapped”.

All Rights Reserved C3: Protected .Core Java 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 296 ©Copyright 2007.Handout . Cognizant Technology Solutions.

All Rights Reserved C3: Protected . Cognizant Technology Solutions.Core Java Node InputStream Classes Filter InputStream Classes Page 297 ©Copyright 2007.Handout .

All Rights Reserved C3: Protected .Handout .Core Java OutputStream Abstract Class Node OutputStream Classes Page 298 ©Copyright 2007. Cognizant Technology Solutions.

All Rights Reserved C3: Protected .Core Java Filter OutputStream Classes The Reader Class: Methods The Reader Class: Methods Page 299 ©Copyright 2007.Handout . Cognizant Technology Solutions.

All Rights Reserved C3: Protected .Handout .Core Java Node Reader Classes Filter Reader Classes Page 300 ©Copyright 2007. Cognizant Technology Solutions.

Handout .Core Java The Writer Class: Methods Node Writer Classes Page 301 ©Copyright 2007. All Rights Reserved C3: Protected . Cognizant Technology Solutions.

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. All byte stream classes are descended from InputStream and OutputStream. There are also streams for more complicated data types. FileOutputStream out = null.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. There are many byte stream classes like FileInputStream and FileOutputStream. Example: FileInputStream and FileOutputStream public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null. Cognizant Technology Solutions. They differ mainly in the way they are constructed.Handout . They are implemented in much the same way. Byte streams should only be used for the most primitive I/O. try { Page 302 ©Copyright 2007. All Rights Reserved C3: Protected . All other streams are based on byte stream. then the best approach is to use character streams.

Page 303 ©Copyright 2007.Core Java in = new FileInputStream("xanadu.read()) != -1) { out. } } finally { if (in != null) { in. Character stream I/O automatically translates this internal format to and from the local character set. In Western locales. Cognizant Technology Solutions.txt"). All Rights Reserved C3: Protected .write(c).close(). out = new FileOutputStream("outagain.txt").Handout . } if (out != null) { out. int c.close(). the local character set is usually an 8-bit superset of ASCII. while ((c = in. } } } } 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.

while ((c = inputStream.Core Java All character stream classes are descended from Reader and Writer. Example: FileReader and FileWriter public class CopyCharacters { public static void main(String[] args) throws IOException { FileReader inputStream = null. } if (outputStream != null) { outputStream. Cognizant Technology Solutions. these character-stream classes mirror the byte stream classes. FileWriter outputStream = null.txt").write(c). } } finally { if (inputStream != null) { inputStream. FileReader.txt"). Reader and Writer are the abstract superclasses for character streams in java. int c. Page 304 ©Copyright 2007. The Reader and Writer classes were added to JDK 1.close(). while the character stream handles translation between characters and bytes. so if you know how to use one.Handout . The character stream uses the byte stream to perform the physical I/O. while FileWriter uses FileOutputStream. there are character stream classes of FileReader and FileWriter that specialize in file I/O. To a large extent.1 to support internationalization. The Reader and Writer classes make it possible to work with character streams rather than byte streams. it isn't too difficult to figure out how to use the other. } } } } Character Stream and Byte Stream Character streams are often "wrappers" for byte streams. for example.io package. try { inputStream = new FileReader("xanadu. As with byte streams. uses FileInputStream.read()) != -1) { outputStream.close(). outputStream = new FileWriter("characteroutput. All Rights Reserved C3: Protected .

out. How to Create Buffered Streams? A program can convert an unbuffered stream into a buffered stream using the wrapping idiom. out. Example: Line-oriented I/O File inputFile = new File("farrago. network activity. All Rights Reserved C3: Protected . } in.println(l). FileReader in = new FileReader(inputFile).Core Java Line-Oriented I/O Character I/O usually occurs in bigger units than single characters: For the line-oriented I/O. Cognizant Technology Solutions. or a single line-feed ("\n").Handout .txt"). the Java platform implements buffered I/O streams: Buffered input streams read data from a memory area known as a buffer. because each such request often triggers disk access. buffered output streams write data to a buffer. Buffered Streams An unbuffered I/O means each read or write request is handled directly by the underlying OS. while ((l = inputStream. String l. a single carriage-return ("\r"). The native input API is called only when the buffer is empty Similarly.close().readLine()) != null) { System. PrintWriter outputStream = new PrintWriter(out). An unbuffered stream object is passed to the constructor for a buffered stream class. or some other operation that is relatively expensive. BufferedReader inputStream = new BufferedReader(in). FileWriter out = new FileWriter(outputFile). To reduce this kind of overhead. File outputFile = new File("outagain. and the native output API is called only when the buffer is full.close().println(l). Page 305 ©Copyright 2007. outputStream. This can make a program much less efficient. one common single unit is the line that contains a string of characters with a line terminator at the end.txt"). A line terminator can be a carriage-return or linefeed sequence ("\r\n").

writeDouble(prices[i]). long. char.Core Java Example: inputStream = new BufferedReader(new FileReader("xanadu. int.in Standard Output. float. accessed through System.out and System. certain key events cause the buffer to be flushed. This is known as flushing the buffer. For example. Flushing Buffered Streams It often makes sense to write out a buffer at critical points. Some buffered output classes support autoflush.writeInt(units[i]). but has no effect unless the stream is buffered.txt")). accessed through System.txt")). All Rights Reserved C3: Protected . The flush method is valid on any output stream. specified by an optional constructor argument: When autoflush is enabled. System. Standard Streams on Java Platform Three standard streams on Java platform are: o o o Standard Input. DataOutputStream DataOutputStream can only be created as a wrapper for an existing byte stream object.Handout . and double) as well as String values. Page 306 ©Copyright 2007. All data streams implement either the DataInput interface or the DataOutput interface. Cognizant Technology Solutions. out. Buffered Stream Classes BufferedInputStream and BufferedOutputStream create buffered byte streams. invoke its flush method.err These objects are defined automatically and do not need to be opened. To flush a stream manually. i < prices. DataInputStream and DataOutputStream are the implementations that are applied most widely of these interfaces.length.err are defined as PrintStream objects. short. out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(dataFile))). i ++) { out. byte. BufferedReader and BufferedWriter create buffered character streams. accessed through System. Data Streams Data streams support binary I/O of primitive data type values (boolean.out Standard Error. outputStream = new BufferedWriter(new FileWriter("characteroutput. an autoflush PrintWriter object flushes the buffer on every invocation of println or format. for (int i = 0. without waiting for it to fill.

} DataInputStream Like DataOutputStream. and the values of the non-transient and non-static fields of the class and all of its supertypes are read. try { double price = in.writeUTF(descs[i]).readDouble().Handout . This is not important for a class like Calendar. } 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. but they contain some very sophisticated object management logic. String desc = in. Cognizant Technology Solutions. which just encapsulates primitive values. Write Object The writeObject traverses the entire Web of object references and writes all objects in that Web onto the stream. Page 307 ©Copyright 2007. int unit = in.readInt(). in = new DataInputStream( new BufferedInputStream( new FileInputStream(dataFile))). A single invocation of writeObject can cause a large number of objects to be written to the stream.Core Java out. the signature of the class. End-of-file condition is detected by catching EOFException. Default deserializing for a class can be overridden using the writeObject and readObject methods. 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 there are many objects that contain references to other objects. DataInputStream must be constructed as a wrapper for a byte stream. instead of testing for an invalid return value. The class of the object. The readObject method reads an object from the ObjectInputStream.readUTF(). All Rights Reserved C3: Protected .

The File Class: Constructors The File class has four constructors. and all the original object references are preserved.Core Java I/O of Multiple Referred-to Objects Object a contains references to objects b and c. When a is read back by readObject. The File Class The File class is not a stream class. Cognizant Technology Solutions. The File class is an abstract representation of actual files and directory pathname. then the other four objects are read back as well. All Rights Reserved C3: Protected . This practice helps to avoid serious resource leaks. Page 308 ©Copyright 2007. Always Close Streams Closing a stream when it is no longer needed is very important.Handout . but all the objects necessary to reconstitute a. while b contains references to d and e. so that your program should use a finally block to guarantee that both streams will be closed even if an error occurs. so the other four objects in this Web are also written. Invoking writeObject(a) writes not just a. The File class is important because stream classes manipulate File objects.

println(fileName 10 + " does not exists. 6 File fn = new File(fileName).out.out.Handout . Cognizant Technology Solutions. */ 13 System.exists()) { 9 System.. 8 if (!fn.out.*.io.").Core Java The File Class: Methods The File Class: Example 1 import java.println("Name: " + fn."). 14 fileName = "temp". 11 12 /* Create a temporary directory instead.getName()).. All Rights Reserved C3: Protected .println("Creating temp directory. Page 309 ©Copyright 2007. 2 3 public class FileInfoClass { 4 public static void main(String args[]) { 5 String fileName = args[0]. 7 System.

out.isFile()? "file. System.println("Deleting temp directory. System. for (int i = 0."). i++) { System. fn.out.println("The content of this directory:"). if (!fn.out.Core Java 15 16 17 18 19 20 21 24 25 26 27 28 29 30 43 44 45 46 35 36 36 37 38 39 40 41 42 43 47 48 49 50 51 52 53 54 55 56 57 } fn = new File(fileName).").").delete().mkdir(). } System.exists()? "exists": "does not exist")). Cognizant Technology Solutions.println(fileName + " is " + fn.out.canWrite()) { System. if (fn. System. } } Page 310 ©Copyright 2007.isDirectory()) { String content[] = fn. } } if (!fn.. i < content. System.out. return.println(fileName + " is not writable.out.")).Handout ." :"directory.println(fileName + (fn.println(fileName + " is not readable.out. fn. System. All Rights Reserved C3: Protected .println(fileName + " is " + fn.canRead()) { System.out.length() + " bytes long.println(fileName + " is a " + (fn.list().")..length.lastModified() + " bytes long.out.println(content[i]).").

The program also prints out the encoding that is in effect on your system. do { System. inputLine = inStream.length() != 0).in) from a byte stream to a character stream. This is a test.in) from a byte stream to a character stream. System.Handout . > The Cp1252 encoding is the MS Windows Latin-1 character encoding.out.*. System. public class InputConversionApp { public static void main(String args[]) throws IOException { InputStreamReader in = new InputStreamReader(System.readLine(). } } Refer File Name: InputConversionApp. Code: import java. } while (inputLine. Page 311 ©Copyright 2007.io. All Rights Reserved C3: Protected .println("Encoding: " + in.out.getEncoding()). Cognizant Technology Solutions.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. BufferedReader inStream = new BufferedReader(in). The following is an example of the output generated when the program is run on your local desktop: Encoding: Cp1252 >This is a test. It is applied with English and Western European languages.out. The input characters are echoed to standard output.println(inputLine).out. String inputLine.in).print(">").flush(). // Get the encoding that is in use System.java to obtain soft copy of the program code How It Works: The InputConversionApp program converts the standard input stream (System.

The ObjectOutputStream. c) The ‘eof’ character in the case of a file that contains character data is -1. and ObjectInputStream. Page 312 ©Copyright 2007. File objects can represent either a file or a directory. but they should usually be wrapped. and the InputStream and OutputStream class hierarchy is byte-oriented. e) ‘You can deal with all types of data with the help of DataOutputStream and DataInputStream classes. You can use them to write and read files respectively.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. FileWriter and FileReader are low-level I/O classes. b) A stream gets data from a source and sends data to a destination.readObject() method deserializes objects. d) PrintWriter class is a subclass of OutputStream class.’ Comment on this statement. The read() method returns -1 when it has reached the end of a file. Test Your Understanding 1. All Rights Reserved C3: Protected . Summary A new File object doesn’t mean there is a new file on your hard drive. b) The read() method in FileInoutStream class reads a character. Which one of the following statements is wrong? a) FileWriter and FileReader classes deal with character data. Cognizant Technology Solutions. Which one of the following is correct? a) The write() method in FileWriter class writes a byte. c) FileOutputStream class deals with binary data. The ObjectInputStream class supports the reading of objects from input streams. 2.writeObject() method serializes objects.Handout . d) BufferedOutputStream and BufferedInputStream classes deal with character data. The readLine() method returns null when it has reached the end of a file.

access to the contents of a file. If you use a sequential access stream. 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.Handout .Core Java Session 92: I/O operations in JAVA Learning Objectives After completing this session. All Rights Reserved C3: Protected . Cognizant Technology Solutions. It also contain a directory entry at the end that indicates where the various files contained within the ZIP archive begin. or random. A ZIP archive contains files and is typically compressed to save space. Problem Scenario Consider the archive format known as ZIP. you will be able to: Apply Random Access Files Random Access File Random access files permit nonsequential. you would have to read half the ZIP archive before finding the file that you want to extract. on average. 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. as shown in the following figure: A ZIP archive Suppose that you want to extract a specific file from a ZIP archive.

you specify a file to be opened by name when you instantiate an object of class RandomAccessFile.Handout . Unlike with the sequential classes.txt". you can use the common read or write methods defined in the DataInput and DataOutput interfaces to perform I/O on the file. You must be able to read a file before you can write to it. The following code creates a RandomAccessFile to read the file named xanadu. The java. File Pointer RandomAccessFile supports the notion of a file pointer. This one opens the same file for both reading and writing: new RandomAccessFile("xanadu. mode) As mentioned earlier. "rw"). When the file is first created.RandomAccessFile class can be used for both reading and writing. indicating the beginning of the file. java.RandomAccessFile The java. Calls to the read and write methods adjust the file pointer by the number of bytes read or written.txt". you must indicate whether you will just be reading the file. Creating a Random Access File Similar to the sequential FileInputStream and FileOutputStream classes.io. You can specify the file name either by a literal string or by passing a File object which you have previously instantiated.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. "r"). Cognizant Technology Solutions.txt: new RandomAccessFile("xanadu. 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. After the file has been opened.io. Page 314 ©Copyright 2007.RandomAccessFile class implements both the DataInput and DataOutput interfaces. the name can be specified using either a literal string or an object of type File. when you instantiate an object of RandomAccessFile.io. All Rights Reserved C3: Protected . The file pointer indicates the current location in the file. or also writing to it. The syntax for instantiating a RandomAccessFile object is as follows: new RandomAccessFile(name. the file pointer is set to zero.

} } Refer File Name: RandomIOApp. Code: import java. Cognizant Technology Solutions.java to obtain soft copy of the program code Page 315 ©Copyright 2007. All Rights Reserved C3: Protected . public class RandomIOApp { public static void main(String args[]) throws IOException { RandomAccessFile file = new RandomAccessFile("test.seek(1). "rw").writeDouble(1234. System.close().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.println(file.out.56). file.println(file. file.readBoolean()). System. file. file.writeBoolean(true).io. System. System. file.out. 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.writeInt(123456). file.println(file.out.seek(0).Handout .txt".writeChar('j').readChar()).readDouble()). // Use seek() to move to a specific file location file.*.out.readInt()).println(file.

Page 316 ©Copyright 2007. char. State true or false for the following: a) RandomAccessFile is the only bidirectional stream in Java. Cognizant Technology Solutions. access to the contents of a file. char. It writes a boolean. Test Your Understanding 1. or random. b) A random access file can be opened in ‘r’ mode or ‘rw’ mode. RandomAccessFile contains the following three methods for explicitly manipulating the file pointer. Next. RandomAccessFile supports the notion of a file pointer. and double value to a file and then uses the seek() method to seek to offset location 1 within the file. The output of the program is as follows: 123456 j 1234. Summary Random access files permit nonsequential. The RandomAccessFile class implements both the DataInput and DataOutput interfaces and therefore can be used for both reading and writing. and double values from the file and displays them to the console window. o skipBytes: Moves the file pointer forward the specified number of bytes. it moves the file pointer to the beginning of the file and reads the boolean value that was first written to the file. It then reads the int.Core Java How It Works: The RandomIOApp program provides a simple demonstration of the capabilities of random-access I/O. This value is also written to the console window.Handout . All Rights Reserved C3: Protected . getFilePointer: Returns the current byte location of the file pointer. This is the position after the first byte in the file. o o seek: Positions the file pointer just before the specified byte.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. int. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

Handout . Serialization is used to save object to some permanent storage. 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. All Rights Reserved C3: Protected . 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. 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 o Serializable interface is marker interface 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.Core Java Session 93: I/O operations in JAVA Learning Objectives After completing this session. Cognizant Technology Solutions. It is the process of "flattening" an object. Serialization is used to pass on to another object by the OutputStream class and can be sent over the network.

If you mark an instance variable as transient. Persisting it and trying to run it in your JVM would make no sense at all. 6 7 // Serialize the rest of the fields 8 int data. Objects of some system-level classes are not serializable: Because the data that they represent. Cognizant Technology Solutions.Core Java Non-Serializable Objects Most Java classes are serializable. the transient keyword prevents the data from being serialized. thread running in your JVM would be applying the memory of your system. 10 11 // More code 12 } Page 318 ©Copyright 2007. 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. 5 transient String fieldIdontwantSerialization.Handout . All Rights Reserved C3: Protected . All fields that are not transient are considered part of the persistent state of an object and are eligible for persistence. you’re telling the JVM to skip (ignore) this variable when you attempt to serialize the object containing it. Example: transient Keyword 1 class MyClass implements Serializable { 2 3 // Skip serialization of the transient field 4 transient Thread thread. 9 String x. changes constantly: Reconstructed object will contain different value anyway For example. In other words.

public final void writeObject(Object obj) throws IOException where obj is the object to be written to the stream 1 import java. 2 public class SerializeBoolean { 3 SerializeBoolean() { 4 Boolean booleanData = new Boolean("true"). 10 oos. 15 } 16 } 17 18 public static void main(String args[]) { 19 SerializeBoolean sb = new SerializeBoolean(). 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.io. 8 ObjectOutputStream oos = new 9 ObjectOutputStream(fos). All Rights Reserved C3: Protected . 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. 12 13 } catch (IOException ie) { 14 ie.close().ser"). 2 public class UnserializeBoolean { 3 UnserializeBoolean() { 4 Boolean booleanData = null. 1 import java.writeObject(booleanData).Handout .printStackTrace().Core Java Serialization: Writing an Object Stream To write an object stream use its writeObject method of the ObjectOutputStream class. 5 try { 6 FileInputStream fis = new 7 FileInputStream("boolean.ser").io.*.*. 11 oos. Page 319 ©Copyright 2007. Cognizant Technology Solutions. 5 try { 6 FileOutputStream fos = new 7 FileOutputStream("boolean.

The flattened object sits in the file system for some time. but it takes a little code manipulation. } System.out.println("Unserialized Boolean from " + "boolean. What happens when you try to read in the flattened object? An exception will be thrown specifically. All Rights Reserved C3: Protected .InvalidClassException.Handout . } Version Control: Problem Scenario Imagine that you create a class. instantiate it. Meanwhile. if you really think about it. } catch (Exception e) { e.ser"). perhaps adding a new field. booleanData = (Boolean) ois.io. System. the java. then the exception will be thrown However.close().out. Page 320 ©Copyright 2007. 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. ois.println("Compare data with true: " + booleanData. 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.equals(new Boolean("true"))).out. Cognizant Technology Solutions. The identifier that is part of all classes is maintained in a field called serialVersionUID. } public static void main(String args[]) { UnserializeBoolean usb = new UnserializeBoolean().Core Java 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 } ObjectInputStream ois = new ObjectInputStream(fis).readObject(). you update the class file. and write it out to an object stream.printStackTrace(). System.println("Boolean data: " + booleanData).

but that’s very rare. 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. 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 object is saved using ObjectOutputStream. you can write and read ALL of the state yourself. If the object does not support Externalizable and does implement Serializable.Handout . These methods supersede customized implementations of writeObject() and readObject() methods. All Rights Reserved C3: Protected . no matter what changes you make to the class file. then the writeExternal() method is called.Core Java If you wish to control versioning. Cognizant Technology Solutions.io. then you simply have to provide the serialVersionUID field manually and ensure that it is always the same. 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 The most common reason to implement writeObject() and readObject() is when you have to save some part of an object’s state manually. When you want to do only a part of the serialization/deserialization yourself. ClassNotFoundException. These methods must explicitly coordinate with the super type to save its state.ObjectInputStream in) throws IOException. you MUST invoke the defaultReadObject() and defaultWriteObject() methods to do the rest. 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.ObjectOutputStream out) throws IOException.io. Page 321 ©Copyright 2007. private void readObject(java. If you choose.

An object of class TestClass1 is assigned to the t1 variable. 9. 0.txt file. Date t4 = new Date().".txt file is reopened as a FileInputStream object.txt").468 JAVA Page 322 ©Copyright 2007. The objects referenced by the t1 through t4 variables are written to outStream using the writeObject() method. ObjectOutputStream outStream = new ObjectOutputStream(outFile). which is then converted to an ObjectInputStream object and assigned to the inStream variable. Code: import java. TestClass1 t1 = new TestClass1(true. Four objects are created and assigned to the t1 through t4 variables. 'A'.Core Java Try It Out Problem Statement: Write a program that illustrates the usage of ObjectInputStream and ObjectOutputStream classes in the process of serialization.io. public class ObjectIOApp { public static void main(String args[]) throws IOException. "java"). and a Date object is assigned to t4. The File object is used to create an object of class FileOutputStream.0E-4 java 0 true 2 j 1. This object is then used to create an object of class ObjectOutputStream. The output of the program is as follows: true 9 A 1. ClassNotFoundException { File file = new File("test. import java.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.*. The stream and file are then closed. Cognizant Technology Solutions. and an object of class TestClass2 is assigned to the t2 variable.util. FileOutputStream outFile = new FileOutputStream(file).234 Java false 7 J 2. which is assigned to the outStream variable.Handout . TestClass2 t2 = new TestClass2(). using the readObject() method. String t3 = "This is a test. A String object is assigned to t3. // continued … Refer File Name: ObjectIOApp.*. The test. Four objects are read from inStream.0001. All Rights Reserved C3: Protected . and they are written to standard output.

If you mark an instance variable transient.Handout . What is object serialization? 2. Why will you ever write a class that was not serializable? 2. because its key instance variables are themselves not serializable. then its subclasses do automatically. Serialization is smart enough to know when two objects in the graph are the same. There are very few reasons. but you might for example. In that case. only one of the objects is saved. What useful purpose does serialization serve? Page 323 ©Copyright 2007. The toString() method is automatically invoked by the println() method to convert objects to string values for printing. the superclass constructor will run. If a superclass doesn’t implement Serializable. What happens if two objects in the object graph are the same object? Does this object get saved twice during serialization? Solution: 1. 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. 2. TestClass1 and TestClass2 are dummy test classes that are used to make the example work. and during deserialization. If a superclass implements Serializable. so there is no useful way for you to make your class serializable. All Rights Reserved C3: Protected . Cognizant Technology Solutions. then when a subclass object is deserialized. Summary A class must implement the Serializable interface before its objects can be serialized. it will not be serialized even though the rest of the object’s state will be. Tips and Tricks: 1. Thu Mar 13 15:37:58 GMT+05:30 2008 Note that you will receive a different date value from this one.Core Java This is a test. any references to that single object are restored. Test Your Understanding 1.

is an excellent language basis for database applications.java. Every database server has corresponding JDBC drivers. 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. What is needed is a way for Java applications to talk to a variety of different data sources. DatabaseMetaData. JDBC Driver JDBC driver is an implementation of JDBC interfaces that is specific to database. easy to understand. The DataSource interface is implemented by a driver vendor. a DataSource object is the preferred means of getting a connection. The Java programming language. ResultSet. JDBC is a part of Java SE (J2SE).sun. CallableStatement and Types The javax. being robust. easy to use. and automatically downloadable on a network. Connection. The JDBC API provides the mechanism for doing this. With a basic implementation.com/products/jdbc/drivers Page 324 ©Copyright 2007. which are DriverManager.Core Java Session 96: JDBC Learning Objectives After completing this session. PreparedStatement. All Rights Reserved C3: Protected . the connection obtained through a DataSource object is identical to a connection obtained through the DriverManager facility.Handout .sql package provides many advanced functionalities. JDBC API The JDBC API is a Java API for accessing virtually any kind of tabular data.sql package. o Example: DataSource For example. You can see the list of available drivers from http://industry. Java SE 6 has JDBC 4. secure. 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. an alternative to the DriverManager facility. Majority of JDBC API is located in java. Cognizant Technology Solutions. ResultSetMetaData.

"myPassword").odbc. 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. b. the following code will load it: Class. Load the JDBC driver that is specific to DB 2. Page 325 ©Copyright 2007.Core Java JDBC Driver In simplest terms.getInt("a"). and so on. "myLogin".next()) { int x = rs. 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.JdbcOdbcDriver"). c FROM Table1"). Execute queries and/or updates 5. ResultSet rs = stmt.Handout . protocol. Get a Connection object 3. All Rights Reserved C3: Protected . Read results 6.forName("sun.getString("b").executeQuery("SELECT a.getFloat("c"). Get a Statement object 4. port. you want to use the JDBC–ODBC Bridge driver. for example. Statement stmt = con. Your driver documentation will give you the class name to use. Read Meta-data (optional step) 7. String s = rs. float f = rs. } Database URL Database URL is used to make a connection to the database and can contain server. If. 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. while (rs.createStatement(). Cognizant Technology Solutions.getConnection( "jdbc:myDriver:wombat".jdbc.

All Rights Reserved C3: Protected .forName will do that for you automatically.out.DriverXYZ"). String user. if the class name is jdbc. If you were to create your own instance.getConnection("jdbc:derby://localhost:1527/sample".sql.Handout . 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. Get a Connection Object DriverManager class is responsible for selecting the database and creating the database connection.sql. you would be creating an unnecessary duplicate. you would load the driver with the following line of code: Class." app "). Cognizant Technology Solutions.println("" + sqle). String password) throws SQLException java. } DriverManager and Connection java. When you have loaded a driver.Core Java For instance. it is available for making a connection with a DBMS.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.forName("jdbc. You do not need to create an instance of a driver and register it with the DriverManager because calling the method Class.DriverManager: getConnection(String url.Statement: ResultSet executeQuery(string sql) int executeUpdate(String sql) Page 326 ©Copyright 2007. “app".DriverXYZ.sql. } catch(SQLException sqle) { System.

getString(0).Core Java Example: Statement statement = connection.ResultSet: boolean next() xxx getXxx(int columnNumber) xxx getXxx(String columnName) void close() The iterator is initialized to a position before the first row.Handout . Reading Results Loop through ResultSet retrieving information: java. // Correct! String value1 = rs. Once you have the ResultSet.next()){ // Wrong this will generate an error String value0 = rs.sql. ACTION COMMAND (UPDATE/DELETE) : int iReturnValue = statement. int value3 = rs.executeUpdate("update manufacture_tbl set name = ‘IBM' where mfr_num = 19985678"). You must call next() once to move it to the first row. you can easily retrieve the data by looping through it while (rs. } When retrieving data from the ResultSet.sql. Cognizant Technology Solutions. All Rights Reserved C3: Protected .createStatement().Types data type. int value2 = rs.executeQuery("select * from customer_tbl").getString(1).getInt(2). use the appropriate getXXX() method: getString() getInt() getDouble() getObject() There is an appropriate getXXX() method of each java. The same Statement object can be used for many unrelated queries Executing Query or Update From the Statement object. Page 327 ©Copyright 2007. the two most used commands are: QUERY (SELECT) : ResultSet rs = statement.getInt(“ADDR_LN1").

Statement.getColumnType(i)).jdbc. java.getPrecision(i)). class ConnectionUsingClassForName { = "oracle.getColumnCount().out.getColumnDisplaySize(i) ). ResultSetMetaData rsMeta = rs.println(“Scale: " + meta. System. Page 328 ©Copyright 2007. i <= iColumnCount .getMetaData().getColumnName(i)). System.out.sql. Cognizant Technology Solutions.out.getMetaData(). System.Handout .println(“Column Name: " + meta. DatabaseMetaData dbmetadata = connection.sql. There are approximately 150 methods in the DatabaseMetaData class.OracleDriver".sql.DriverManager.println(“Column Type" + meta. This gives valuable information about the data that you are retrieving or the database that you are using.println("Precision: " + meta.SQLException. i++){ System. ResultSetMetaData Example ResultSetMetaData meta = rs.ResultSet. System.Connection.getMetaData(). Code: import import import import import public java. java. for (int i =1 . All Rights Reserved C3: Protected .sql. } Try It Out Problem Statement: Write a program that illustrates how to connect to a database by registering the JDBC driver using the Class.sql.driver. Statement stmt = null.getScale(i) ). final String driverClass public void classForName() { Connection con = null.out.forName() method. //Return the column count int iColumnCount = meta.println("Display Size: " + meta. java. you can obtain the metadata about the database or the query.out.Core Java Read ResultSet MetaData and DatabaseMetaData (Optional) Once you have the ResultSet or Connection objects. java.

you should apply this method along with a properties file from which you load the name of the driver. // continued … Refer File Name: ConnectionUsingClassForName. 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. Because a JDBC driver is required to register itself whenever its static initializer is called. by default it is in the auto-commit mode. In real-world applications. 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.Core Java ResultSet rset = null. and DELETE. This complex expression is a tool for dynamically creating an instance of a class when you have some variable representing the class name.newInstance(). this expression has the net effect of registering your driver for you.forName() method.forName(driverClass).print(" Loading JDBC Driver -> " + driverClass + "\n"). Page 329 ©Copyright 2007. and will be committed as soon as its execution is finished. UPDATE. Pay special attention to the space following “INSERT INTO tablename” to separate it in the resulting string from “VALUES”. Class. Solution: When a connection is created using JDBC. try { System.Handout . Cognizant Technology Solutions. the execution of the method executeUpdate() will change the state of the database. 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. Tips and Tricks: Provide some key tips while writing SQL statements and executing it using executeUpdate() methods. Notice that for the SQL statements CREATE. you have to split it into two strings concatenated by a plus sign (+) so that it will compile.out. Whenever the SQL statement will not fit on one line on the page. This means that each individual SQL statement is treated as a transaction by itself.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. INSERT. All Rights Reserved C3: Protected .

Types data type.Handout .sql package. and then everybody has access to the latest version.sql. A programmer can write an application or an update once. Cognizant Technology Solutions. All Rights Reserved C3: Protected . Test Your Understanding 1. the combination of the Java and JDBC technologies offers a better way of distributing information updates to external customers. Installation and version control are greatly simplified. there is an appropriate getXXX() method for each java. Page 330 ©Copyright 2007. State true or false for the following: a) Majority of JDBC API is located in java. c) In the ResultSet class. b) DriverManager class is not responsible for selecting the database and creating the database connection.Core Java Development time for new applications is short. put it on the server. And for businesses selling information services.

xml In Tomcat. they are defined in: <J2EE_HOME>/domains/domain1/config/domain. you will be able to: Define DataSource and Connection Pooling Describe transaction javax.sql.sql. because the properties of the data source can be changed. All Rights Reserved C3: Protected . 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. a data source is called a JDBC resource. Cognizant Technology Solutions. 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. In the Sun Java System Application Server.DataSource Interface and DataSource Object Driver vendor implements the javax. any code accessing that data source does not need to be changed. 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.xml Page 331 ©Copyright 2007.Handout . they are defined in server. DataSource object is the factory for creating database connections.xml: <TOMCAT_HOME>/conf/server.Core Java Session 97: JDBC Learning Objectives After completing this session.DataSource interface.

xa.xaDataSource" failallconnections=" false" idle-timeout-in-seconds="300" is-connectionvalidationrequired="false" is-isolation-level-guaranteed="true" maxpool-size="32" max-wait-time-in-millis="60000" name="PointBasePool" pool-resize-quantity="2" res-type="javax.pointbase. All Rights Reserved C3: Protected .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.1 Admin Console Page 332 ©Copyright 2007. Cognizant Technology Solutions.sql.XADataSource" steadypool-size="8"> <property name="DatabaseName" value="jdbc:pointbase:server://localhost:9092/sun-appservsamples"/> <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.

All Rights Reserved C3: Protected . Cognizant Technology Solutions.1 Admin Console Page 333 ©Copyright 2007.Core Java Editing a sample JDBC Resource Sun Java System Application Server Admin Console Screenshot of Sun Java System Application Server Edition 8.Handout .

specify jdbc/BookDB. a DataSource object is registered to JNDI naming service by the container and then retrieved by a client though a lookup operation. All Rights Reserved C3: Protected . the JNDI name for the resource of a BookDB database could be java:comp/env/jdbc/BookDB. Page 334 ©Copyright 2007.Core Java JNDI Registration of a DataSource Object A driver that is accessed by a DataSource object does not register itself with the DriverManager. for a payroll database. then enter only jdbc/name. the connection obtained through a DataSource object is identical to a connection obtained through the DriverManager facility. Because all resource JNDI names are in the java:comp/env subcontext. For example. For example. Rather. Creating and destroying database connections are expensive operations. a smaller number of connections are shared by a larger number of clients.Handout . With a basic implementation. Cognizant Technology Solutions. Using connection pooling. JNDI Registration of a DataSource (JDBC Resource) Object The JNDI name of a JDBC resource is expected in the java:comp/env/jdbc subcontext. Need of Connection Pooling Database connection is an expensive and limited resource. when you specify the JNDI name of a JDBC resource.

The application code works in the same way. DataSource object in this case. Context envCtx = (Context)initCtx.Handout . the mapping of external resource and JNDI name is provided. In the web.getMessage()). con = ds. each DataSource object is associated with a connection pool. This provides further flexibility.lookup("java:comp/env"). public BookDBAO() throws Exception { try { Context initCtx = new InitialContext(). For Sun Java System App server. The Connection object that the getConnection method returns is a handle to a PooledConnection object rather than being a physical connection.lookup("jdbc/BookDB").getConnection(). DataSource ds = (DataSource) envCtx. Under Sun Java Application Server.java in bookstore1 application: public class BookDBAO { private ArrayList books. is provided. Example: PointBasePool The Sun Java Application Server 8 is distributed with a connection pool named PointBasePool. All Rights Reserved C3: Protected . Then these connections are provided on requirement basis from the pool and finally these connections are returned back to the pool. Connection Pooling and DataSource DataSource objects that implement connection pooling also produce a connection to the particular data source that the DataSource class represents. Cognizant Technology Solutions. private boolean conFree = true. } catch (Exception ex) { throw new Exception("Couldn't open connection to database: " ex. Connection con. which handles connections to the PointBase database server. Retrieval and Usage of a DataSource Object Application perform JNDI lookup operation to retrieve DataSource object. Page 335 ©Copyright 2007. The important advantage of connection pooling mechanism is that it cuts down the overhead of creating and destroying database connections.xml file of the application. information on external resource. a set of database connections are created at firsthand and made available in the pool.Core Java Using connection pooling. DataSource object is then used to retrieve a Connection object. Example: Retrieval of DataSource Object by JNDI BookDBAO.

All Rights Reserved C3: Protected .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.xml of bookstore1 <resource-ref> <res-ref-name>jdbc/BookDB</res-ref-name> <res-type>javax. Cognizant Technology Solutions. JDBC Transaction Methods The JDBC transaction methods are: setAutoCommit() : If set true.Handout .DataSource</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> </resource-ref> JNDI and Resource Mapping in sun-web. the developer can update the database more then once and then commit the entire transaction as a whole. The committing of each statement when it is first executed is very time consuming. every executed statement is committed immediately commit() : o o Relevant only if setAutoCommit(false) Commit operations performed because the opening of a Connection or last commit() or rollback() calls Relevant only if setAutoCommit(false) Cancels all operations performed rollback() : o o Page 336 ©Copyright 2007. Also. if each statement is dependant on the other.Core Java } } } JNDI Resource Information in web. the entire transaction can be rolled back and the user is notified.sql. By setting AutoCommit to false.

commit(). } catch(SQLException sqleRollback) { System. items++) { int itemCode = arrValueToUpdate[items][0]. } try { connection. int iRecordsUpdate = 0.close().prepareStatement("UPDATE STORE_SALES SET QTY = ? WHERE ITEM_CODE = ? "). 350} }."password"). updateQty.getConnection("jdbc:oracle:thin:@machinename:1521:db name".rollback(). connection.println("" + sqleRollback).length .setAutoCommit(false). System. items < arrValueToUpdate."username".setInt(1. PreparedStatement updateQty = connection.out. } finally { try { connection. {124. int qty = arrValueToUpdate[items][1].out. } catch(SQLException sqle) { System.println("" + sqleClose).out. {125. 250}.qty). updateQty. Cognizant Technology Solutions. } connection. } } Page 337 ©Copyright 2007. for ( int items=0 . int [][] arrValueToUpdate = { {123. {126.Handout .itemCode).executeUpdate().out.println("" + sqle). 500} .Core Java Transactions Example Connection connection = null.setInt(2.println(iRecordsUpdate + " record(s) have been updated"). All Rights Reserved C3: Protected . } catch(SQLException sqleClose) { System. iRecordsUpdate += updateQty. try { connection = DriverManager. 10}.

connection. The owner does not want to read any data that has not been committed.PreparedStatement.sql. "username".sql. java.SQLException. java.DriverManager. PreparedStatement updateQty = connection . the transaction isolation level.Handout . Page 338 ©Copyright 2007.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. Code: import import import import java.sql. // continued … Refer File Name: TransactionExampleApp.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. try { connection = DriverManager.setAutoCommit(false). Cognizant Technology Solutions. All Rights Reserved C3: Protected . crset. which determines the transaction isolation level given to the connection that the rowset establishes. Tips and Tricks: Provide some key points on the transaction isolation level namely TRANSACTION_READ_COMMITTED.Connection. Solution: The programmer sets a property namely.getConnection( "jdbc:oracle:thin:@machinename:1521:dbname".setTransactionIsolation(Connection. "password"). java. so the programmer chooses the level TRANSACTION_READ_COMMITTED. public class TransactionExampleApp { public static void main(String[] args) { Connection connection = null.sql.prepareStatement("UPDATE STORE_SALES SET QTY = ? WHERE ITEM_CODE = ? ").TRANSACTION_READ_COMMI TTED).

TRANSACTION_NONE and TRANSACTION_REPEATABLE_READ . and Do not set auto-commit mode to true. Now suppose that A and B both have a transaction isolation level of TRANSACTION_READ_COMMITTED. Connection Pooling o Get the connection with a DataSource object o Always close the connection in a finally block. All Rights Reserved C3: Protected . but it will reflect a value updated by B after B commits the change. Similar to this level. a sensitive result set open in transaction A will not show uncommitted changes that B makes. the developer cannot update the database more than once and then commit the entire transaction as a whole. Distributed Transactions: o o Do not call the methods commit or rollback. so neither A nor B will be able to make a "dirty read. Cognizant Technology Solutions." In this situation. and forbids dirty read. A user can trace a specific data source on a given stream. Summary DataSource o 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.Core Java When you set the transaction isolation level to TRANSACTION_READ_COMMITTED. A sensitive result set open in B will likewise show changes that A makes after A commits them. This level prohibits reading a value that has changed until after it has been committed. the other field values for isolation levels provided in the Connection interface are TRANSACTION_READ_COMMITTED. b) By setting AutoCommit to false. it will not allow a value to be accessed until after it has been committed.Handout . By default. Test Your Understanding 1. Page 339 ©Copyright 2007. 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. the isolation level is set to TRANSACTION_SERIALIZABLE. or multiple data sources can write log messages to the same stream provided that the stream is set for each data source. TRANSACTION_SERIALIZABLE.

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. This is what makes a statement "prepared. the prepared SQL is sent and this step is bypassed.sql. Instead. Depending on the DB engine.PreparedStatement and java.“ The SQL statement contained in a PreparedStatement object may have one or more IN parameters. Page 340 ©Copyright 2007. The more dynamic statement requires this step on every execution. Consequently. an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency. PreparedStatement inherits all the functionality of Statement. Being a subclass of Statement. executeQuery. In addition. the three methods execute.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.sql. Instances of PreparedStatement contain an SQL statement that has already been compiled. their execution can be faster than that of Statement objects.Core Java Session 98: JDBC Learning Objectives After completing this session. The ? is also known as a parameter marker or parameter placeholder. An IN parameter is a parameter whose value is not specified when the SQL statement is created. Because PreparedStatement objects are precompiled. the statement has a question mark (?) as a placeholder for each IN parameter. Also. An application must set a value for each parameter marker in a prepared statement before executing the prepared statement. From this point on. Cognizant Technology Solutions. All Rights Reserved C3: Protected . you will be able to: Identify java. and executeUpdate are modified so that they take no argument.Handout . 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. The Statement forms of these methods (the forms that take an SQL statement parameter) cannot be used with a PreparedStatement object.

int iUpdatedRecords = updateSales.Core Java PreparedStatement Steps The steps of PreparedStatement object are: 1. The binding in of variables is based on position.setInt(2. If AutoCommit is set to true. and loop through the ResultSet object in the same way as in the basic JDBC example: PreparedStatement itemsSold = con. you can just re-use the PreparedStatement object. then once the statement is executed.println( rsItemsSold.setInt(2.order_num. Cognizant Technology Solutions. o.out. From this point forth. 10398001).name.getString(“QUANTITY") + " unit(s)"). which remain set until changed.quantity from order_tbl o."). If the PreparedStatement object is a select statement. You register the drive and create the db connection in the usual manner.executeUpdate(). in left to right order.customer_num = ?.customer_num. while (rsItemsSold. // PreparedStatement's setXXX() methods are used to set // the IN parameters. updateSales.10398002). the changes are committed. create the prepared statement object.customer_num = c. Once all the variables have been bound. 150). Example: PreparedStatement updateSales = con.customer_num and o.getString(“NAME") + "sold "+ rsItemsSold. updateSales.executeQuery(). // starting from 1. All Rights Reserved C3: Protected .next()){ System. updateSales.10398001). c. o. customer_tbl c where o.setInt(1. ResultSet rsItemsSold = itemsSold. then you execute it. itemsSold. updateSales.setInt(1. Bind in your variables. Once you have a db connection. 2.prepareStatement("select o. 75).Handout . then you execute the PreparedStatement. } Page 341 ©Copyright 2007. // “?” are referred to as Parameter Markers // Parameter Markers are referred to by number.prepareStatement(“UPDATE OFFER_TBL SET QUANTITY = ? WHERE ORDER_NUM = ? ").setInt(1.

Stored Procedure Example FUNCTION event_list ( appl_id_in VARCHAR2.prepareCall("{call SHOW_SUPPLIERS}"). Stored procedures are used to encapsulate a set of operations or queries to execute on a database server. Try It Out Problem Statement: Write a program that illustrates the usage of CallableStatement. All Rights Reserved C3: Protected . and INOUT parameters. // register int INOUT parameter cstmt. ResultSet rs = cs.INTEGER ). 333 ). // could use executeUpdate() // get int OUT and INOUT int iOUT = cstmt. CallableStatement cs = con. 666 ).getInt( 2 ). It does not contain the stored procedure itself. Cognizant Technology Solutions. The following first line of code creates a call to the stored procedure SHOW_SUPPLIERS using the connection con .INTEGER ). // set int INOUT parameter cstmt.execute().getInt( 3 ). The part that is enclosed in curly braces is the escape syntax for stored procedures. Types. // register int OUT parameter cstmt.executeQuery().Handout . OUT. int iINOUT = cstmt.setInt( 3.registerOutParameter( 2. Page 342 ©Copyright 2007. CallableStatement Example Here is an example using IN. // set int IN parameter cstmt. status_in VARCHAR2 INOUT) RETURN ref_cur. Types. //You then execute the statement with no return value cstmt.Core Java CallableStatement CallableStatement is the interface used to execute SQL stored procedures. event_type_in VARCHAR2 OUT.registerOutParameter( 3. A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. dow_in VARCHAR2.setInt( 1. A CallableStatement object contains a call to a stored procedure.

java.getConnection("").registerOutParameter(1. This SQL statement is then sent to the DBMS right away. This program is given just for a reference.sql.sql.OTHER). a PreparedStatement is associated as a channel with a connection and a compiled SQL statement.sql.Core Java Code: import import import import import java. ? . ? . java. ? .Handout .prepareCall("{ ? = call SRO21208_PKG.java to obtain soft copy of the program code How It Works: This is an Oracle specific example of a CallableStatement. java. where it is compiled. queryreport.setInt(2. 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. queryreport.QUEUE_REPORT ( ? . Cognizant Technology Solutions.CallableStatement.SQLException. ? . Page 343 ©Copyright 2007. which distinguishes it from its super class Statement. // continued … Refer File Name: OracleCallableStmtApp. All Rights Reserved C3: Protected . Thus. is that unlike Statement. in effect. public class OracleCallableStmtApp { public static void main(String[] args) { try { Connection connection = DriverManager. it gives a SQL statement right when it is created. java.sql.Connection. Solution: The main feature of the PreparedStatement.sql.sql. 10). java. or similar query with different parameters multiple times. ? ) }"). CallableStatement queryreport = connection . Tips and Tricks: Provide the advantages of using PreparedStatement object against Statement.Types. The advantage offered is that if you need to apply the same.DriverManager.ResultSet.

2. All Rights Reserved C3: Protected . Differentiate between PreparedStatement and CallableStatement. 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.Core Java Summary The SQL statement contained in a PreparedStatement object may have one or more IN parameters. A CallableStatement object provides a way to call stored procedures in a standard way for all RDBMSs. Consequently. an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency. A stored procedure is stored in a database. What is a significance of writing a stored procedure? Page 344 ©Copyright 2007.Handout . the call to the stored procedure is what a CallableStatement object contains. a kind of OUT parameter. A result parameter. Cognizant Technology Solutions. Because PreparedStatement objects are precompiled. Test Your Understanding 1. their execution can be faster than that of Statement objects. is the return value for the stored procedure. An application must set a value for each parameter marker in a prepared statement before executing the prepared statement.

Overview of GC Designs The JVM Specification does not in fact specify very much about the GC. 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. Important Facts About GC GC is unpredictable in nature. In that case.Core Java Session 102: Garbage Collection Learning Objectives After completing this session. the GC is simply turned off or left out. It leaves considerable room for variation in implementation. cannot be controlled by the user program.Handout . Research continues in the computer science community for fast and efficient GC algorithms. Java does use a similar "new" operator as in C++ for creating objects but has no "delete" operator. causes serious problems for Real Time (RT) applications of Java. the program must itself make sure that it does not run out of memory. There are no heap commands such malloc() and free() functions in C needed to allocate or de-allocate memory buffers. This takes place automatically without any input from the user program. 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. All Rights Reserved C3: Protected . Cognizant Technology Solutions. 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. The JVM does not actually require a GC and in some special situations. then the Garbage Collector (GC) will release this memory for re-use by new objects. When the free memory drops under a threshold the GC begins to run to eliminate unneeded objects. and in fact. however. Exactly when it runs and for how long. What Does a GC Perform? If a section of memory earlier used by an object is no longer referenced by any variable.

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. All Rights Reserved C3: Protected . 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. Memory Leaks Memory leak refers to the loss of free memory in the heap to unusable data as a program runs. Examples for Memory Leaks Examples of situations that create memory leaks include: Maintaining references to unneeded objects: For example. 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. rather than completing a full clean-up at one go. The generational GC creates at least two sub-heap areas with one for short-lived objects and the other for old objects. Even with the garbage collector. Page 346 ©Copyright 2007. 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. and thus interfere less with the program. These types of algorithms (as discussed in earlier slides) must interrupt the application threads and complete their job before returning control. 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. Cognizant Technology Solutions. memory leaks can still occur in Java. In such cases the references should explicitly be set to null.Handout . There are some algorithms that work in an incremental approach. which is only checked occasionally. then the objects will not be collected and take up memory. 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. This can lead to inefficient memory utilization and eventually to a crash of the program when no free memory remains.

Cognizant Technology Solutions. then you may need to run the program with a value less than 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. which you can use to specify the amount of resources it applies. GarbageDemo. app.Handout . Start at 14 and work backwards until your program is able to execute without running out of memory. Generally. When you run the program on your desktop.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. You set the default to 15.java. The program takes an integer command-line argument. } public GarbageDemo(int n) { max = n. public static void main(String[] args) { int n = 15. Page 347 ©Copyright 2007.run(). it displays the following output: 11 is being collected. Try It Out Problem Statement: Write a program that illustrates the working of Garbage Collector. All Rights Reserved C3: Protected . } // continued … Refer Files: Garbage.length > 0) n = (new Integer(args[0])). 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. However. if (args. int max.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.intValue(). Code: public class GarbageDemo { Garbage g. 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. If your computer has less RAM. a lot of memory might be used up. GarbageDemo app = new GarbageDemo(n).

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.) The earlier output indicates that 12 Garbage objects were being finalized by the Garbage Collector. } Here. Three ways to get rid of the reference: The reference goes out of scope. 9 is being collected. 8 is being collected. indicating that the Garbage Collector has determined that the object has become unreachable. permanently. Hence. 1 is being collected.Handout . look at the run() method: void run() { for(int i=1. This output is displayed by the finalize() method of each Garbage object. the earlier object that was referenced by the g variable is no longer accessible by g or any other variable or object.Core Java 10 is being collected. These objects had become unreachable because they no longer were referenced by the g field variable of the GarbageDemo class.++i) { g = new Garbage(i). (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.i<max. that object becomes subject to Garbage Collection. 7 is being collected. the reference ‘z’ dies at the end of method The reference is assigned another object. Cognizant Technology Solutions. Life z = new Life(). 5 is being collected. } } With each iteration of the for statement. void go() { Life z = new Life(). 12 is being collected. When a new object is assigned to the g variable. All Rights Reserved C3: Protected . 4 is being collected. a new Garbage object is created and assigned to the g variable. 3 is being collected. Page 348 ©Copyright 2007. 6 is being collected. z = new Life(). To get an idea how this happened. 2 is being collected.

You can’t know the GC algorithm for sure. To reach an object. The purpose of GC is to delete objects that can’t be reached. the first object is abandoned when z is ‘reprogrammed’ to a new object. Page 349 ©Copyright 2007. the first object is abandoned when z is ‘deprogrammed’. An object is eligible when no live thread can reach it.Handout . Summary In Java. you must have a live. c) Garbage Collection runs in a high priority thread. garbage collection (GC) provides automated memory management. Here. All Rights Reserved C3: Protected . z = null. you can only suggest it.Core Java Here. The reference is explicitly set to null. Cognizant Technology Solutions. It will never kick in when memory is too low. Only the JVM decides when to run the GC. Test Your Understanding 1. Objects must be considered eligible before they can be garbage collected. reachable reference to that object. Life z = new Life(). making the memory available for new objects. State true or false for the following: a) Garbage Collection is a mechanism for reclaiming memory from objects that are no longer in application. b) An object being no longer in application means that it still can be referenced by any ‘active’ part of the program.

Serial Collector is the default for client-style machines in Java SE 5.Handout . payroll. billing. or simply obscured by network latencies. Parallel Collector Parallel Collector is also known as Throughput Collector. Cognizant Technology Solutions. 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. which do not have low pause time requirement. and so on Parallel Collector can be explicitly requested with XX:+UseParallelGC. 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. All Rights Reserved C3: Protected . This is applied for Java applications. Application Requirement: Different applications have different requirements: Higher throughput is more important for Web application: Pauses during Garbage Collection may be tolerable.Core Java Session 103: Garbage Collection Learning Objectives After completing this session. scientific computing. Page 350 ©Copyright 2007. Pause time: The length of time during which application execution is stopped while garbage collection is being performed is called the pause time. Serial Collector can be explicitly requested with XX:+UseSerialGC. 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.

Core Java Parallel Compact Collector Parallel Compact Collector is used for Java applications.Handout . 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. All Rights Reserved C3: Protected . Parallel Compact Collector can be explicitly requested with XX:+UseParallelOldGC. which run on machines with a lot of physical memory and multiple CPUs and do have low pause time requirement. Cognizant Technology Solutions. Parallel operations of old generation collection reduces pause time. 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.

Islands of objects can be garbage collected. Summary Java applications can run out of memory. but it does not garbage collect the object. Invoking System. Solution: It is not possible to force Garbage Collection. Class Object has a finalize() method. even though they refer to each other. then the object is still eligible for Garbage Collection (at the discretion of gc). It is inherited from the Object class.Core Java Tips and Tricks: Provide some key points on Garbage Collection. Test Your Understanding 1. Request garbage collection with System. but an unreachable object can become reachable again by letting know other objects of its existence from its finalize() method (when called by gc). finalize() method is used to release system resources other than memory. Page 352 ©Copyright 2007. You can uneligibilize an object for GC from within finalize(). Cognizant Technology Solutions. If an exception is thrown in finalize (). 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. finalize() can be called explicitly. Circular references do not prevent objects from being garbage collected. fianlize() may never run.Handout . Therefore the program should not make any decisions based on this assumption. All Rights Reserved C3: Protected . This ‘resurrection’ can be done only once.gc(). (recommended). finalize() method is called only once for an object.gc may start garbage process. The finalize() method is guaranteed to run once and only once before the garbage collector deletes an object. since finalize() is called only once for an object. All objects have a finalize() method. gc keeps track of unreachable objects and garbage-collects them. The garbage collector makes no guarantees.

All Rights Reserved C3: Protected .0 Platform Ad-hoc Annotation-like examples in pre-J2SE 5. 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. 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. general purpose.0 Annotation provides a standard. deployment descriptor.Handout . and more powerful annotation scheme. Annotations are used by tools to produce derived files: Tools: Compiler. and Run-time tools Derived files: New Java code. IDE.0 platform: Transient Serializable interface @deprecated javadoc comments Xdoclet J2SE 5. and class files Ad-hoc Annotation-like Examples in pre-J2SE 5. Cognizant Technology Solutions.Core Java Session 105: Overview of Annotation Learning Objectives After completing this session.

class file during compilation. An annotation with a retention policy of SOURCE is retained only in the source file and is discarded during compilation. it is not available through the JVM during run time. the following annotation (MyAnno) will be available to the JVM during program execution. If no retention policy is specified for an annotation. An annotation with a retention policy of RUNTIME is stored in the . @Retention(RetentionPolicy.lang. An annotation with a retention policy of CLASS is stored in the .class file during compilation and is available through the JVM during run time.lang: @Override @Deprecated @SuppressWarnings Annotation Retention Policy A retention policy determines at what point an annotation is discarded. then the default policy of CLASS is used. retention-policy must be one of the earlier discussed enumeration constants.Handout .annotation. @Retention @Retention is designed to be used only as an annotation to another annotation. The following example uses @Retention to specify the RUNTIME retention policy. } Page 354 ©Copyright 2007. Its general form is as follows: @Retention(retention-policy) Here. and RUNTIME. Java defines three such policies of SOURCE. Cognizant Technology Solutions.annotation: @Retention @Documented @Target @Inherited The following three are included in java. All Rights Reserved C3: Protected . However. The earlier policies are encapsulated within the java.lang. Thus. The following four are imported from java.RetentionPolicy enumeration. int val(). RUNTIME retention offers the greatest annotation persistence.RUNTIME) @interface MyAnno { String str(). CLASS.Core Java Built-in Annotations Java defines seven built-in annotations.

This argument specifies the types of declarations to which the annotation can be applied.Core Java @Documented The @Documented annotation is a marker interface. It is designed to be used only as an annotation to an annotation declaration. Cognizant Technology Solutions. It is designed to be used only as an annotation to another annotation. All Rights Reserved C3: Protected . to specify that an annotation applies only to fields and local variables. or enumeration You can specify one or more of the values (as shown in the earlier slide) in a @Target annotation. The following table shows the constants and the type of declaration to which they correspond: Target Constant ANNOTATION_TYPE CONSTRUCTOR FIELD LOCAL_VARIABLE METHOD PACKAGE PARAMETER TYPE Annotation Can Be Applied To Another annotation Constructor Field Local variable Method Package Parameter Class. To specify multiple values.Handout .ElementType. It affects only annotations that will be applied on class declarations. interface.LOCAL_VARIABLE } ) @Inherited @Inherited is a marker annotation that can be applied only on another annotation declaration. which must be a constant from the ElementType enumeration. you must specify them within a braces-delimited list.FIELD. @Target takes one argument. which tells a tool that an annotation is to be documented. @Inherited causes the annotation for a super class to be inherited by a subclass. @Target The @Target annotation specifies the types of declarations to which an annotation can be applied. Page 355 ©Copyright 2007. For example. you can use this @Target annotation: @Target( { ElementType.

0 adds a powerful new facility called metadata. However.annotation package.lang. and not simply overloaded. the term program annotation facility is also applied. which are defined by Object. The Annotation interface is declared within the java. This information. An annotation leaves the semantics of a program unchanged. this information can be applied by various tools. then a compile-time error will result. in string form.0 called ‘metadata’ is same as the ‘annotation’ feature? Solution: Java 2. and is more descriptive. which returns a Class object that represents the invoking annotation. Tips and Tricks: Does the new feature in Java 2. which enables you to embed supplemental information into a source file. It is used to ensure that a super class method is actually overridden. v5. This annotation can be applied to any type of declaration. If it does not. It also specifies annotationType(). Summary All annotation types automatically extend the Annotation interface. v5. during both development and deployment. Page 356 ©Copyright 2007. Thus Annotation is a super-interface of all annotations. @Deprecated @Deprecated is a marker annotation. equals(). @SuppressWarnings @SuppressWarnings specifies that one or more warnings that might be issued by the compiler are to be suppressed. A method annotated with @Override must override a method from a super class. an annotation might be processed by a source-code generator. and toString(). Although Sun refers to this feature as metadata. called an annotation. For example. Cognizant Technology Solutions.Handout . does not change the actions of a program. All Rights Reserved C3: Protected . It overrides hashCode(). The warnings to suppress are specified by name.Core Java @Override @Override is a marker annotation that can be applied only on methods. It indicates that a declaration is obsolete and has been replaced by a new form.

Cognizant Technology Solutions. e) RUNTIME retention offers the least annotation persistence.Handout . d) The target constant ANNOTATION_TYPE is available in the @Target built-in annotation. All Rights Reserved C3: Protected . 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. Page 357 ©Copyright 2007. c) @Documented is one of the built-in annotations defined in java.Core Java Test Your Understanding 1.lang package.annotation package.

Cognizant Technology Solutions.Handout . It can be used anywhere in the statement whenever the other modifiers such as public. 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. or final are used. methods.Core Java Session 106: Overview of Annotation Learning Objectives After completing this session. String engineer() default "[unassigned]". annotations precede other modifiers. annotations. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. } How To “Use” Annotation Once an annotation type is defined. An annotation is a special kind of modifier. 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. you can use it to annotate declarations like classes. parameters. String date() default "[unimplemented]". */ public @interface RequestForEnhancement { int id(). static. String synopsis(). and enum constant declarations. By convention. Class. fields. enums. Page 358 ©Copyright 2007. All Rights Reserved C3: Protected . String.

@interface MyAnno { String str(). The best way to determine whether a marker annotation exists is to use the method isAnnotationPresent(). } Here is an example of MyAnno being applied to a method. int val(). This interface is available in Class. which is defined by the AnnotatedElement interface. @Retention(RetentionPolicy. and Package. // Annotate a method. @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.RUNTIME) @interface MyMarker { } class Marker { // Annotate a method using a marker. Constructor.*. // A marker annotation. 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. determining the existence of the marker annotation is sufficient.Handout . Because a marker annotation contains no members.annotation.Core Java Example: Usage of Annotation Here is the declaration for an annotation called MyAnno: // A simple annotation type. Definition Page 359 ©Copyright 2007. Cognizant Technology Solutions. Method. @MyAnno (str = “Annotation Example”. // Notice that no parentheses ‘( )’ is needed.lang. Field. Example: import java. All Rights Reserved C3: Protected .

synopsis = "Enable time-travel". All Rights Reserved C3: Protected .FIELD) @Retention(RetentionPolicy. default "[unimplemented]".. } Example: Definition and Usage of a User-defined Annotation Definition of ‘Accessor’ annotation (user-defined): @Target(ElementType. String date(). @Copyright("2008 Cognizant Technology Solutions") public class SomeClass { . } Usage Example of the Accessor annotation: @Accessor(variableName = "name") public String myVariable. */ public @interface Copyright { String value().. } Usage: @RequestForEnhancement( id = 2868724.Handout .. Peabody".Core Java /** * Associates a copyright notice with the annotated API element. Cognizant Technology Solutions. } Usage: Can omit the element name and equals sign (=). Page 360 ©Copyright 2007.. String synopsis(). String variableType() default "String". engineer = "Mr. date = "4/1/3007" ) public static void travelThroughTime(Date destination) { . String engineer() default "[unassigned]".CLASS) public @interface Accessor { String variableName(). } Normal Annotation Definition: public @interface RequestForEnhancement { int id().

Cognizant Technology Solutions. Method. Page 361 ©Copyright 2007.Core Java Note: The preceding annotation (Accessor) has a member with default value. This interface supports reflection for annotations and is implemented by the classes Method.reflect package. From a Class. Constructor. these methods are available to any object to which annotations can be applied. AnnotatedElement defines the methods as shown in the following slide. There are a number of a ways to apply reflection. Field.reflect package. which is defined in java. The default value can be given for an annotation member if no value is specified when the annotation is applied. you can obtain the values associated with the members of the annotation. annoType is a Class object that represents the annotation in which you are interested.Handout . or Package object. Returns true if an annotation specified by annoType is associated with the invoking object. and Package. Returns an array containing all noninherited annotations associated with the invoking object. If you want to obtain the annotations associated with a specific item declared within a class. 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. All Rights Reserved C3: Protected . then you must first obtain an object that represents that item. The reflection API is contained in the java. Methods Defined by AnnotatedElement Method <T extends Annotation> T getAnnotation(Class<T> annoType) Annotation[ ] getAnnotations() Annotation[ ] getDeclaredAnnotations() boolean isAnnotationPresent Class<? extends Annotation> annoType) Description Returns the annotation of type annoType associated with the invoking object. The AnnotatedElement Interface The methods such as getAnnotation() and getAnnotations() are defined by the AnnotatedElement interface. Reflection Reflection is a feature that enables information about a class to be obtained at run time. Field. Returns an array containing all annotations associated with the invoking object. Class. Constructor.lang. It returns false otherwise.lang. Using the reference. Therefore. It returns a reference to the annotation. The first step for applying a reflection is to obtain a Class object that represents the class whose annotation you want to obtain.

class).lang. Code: import java.first().getAnnotation(Author. Cognizant Technology Solutions. String last = author.last().Core Java Usage of Reflection in Annotations Marker annotation: boolean isBeta = MyClass. Because a marker interface contains no members.class).*.RUNTIME) @interface MyMarker { } class Marker { // Annotate a method using a marker. All Rights Reserved C3: Protected . Try It Out Problem Statement: Write a program that applies a Marker annotation. The following output confirms that @MyMarker is present: Page 362 ©Copyright 2007.isAnnotationPresent(BetaVersion. simply determining its existence is sufficient. Single value annotation: String copyright = MyClass. String first = author. Normal annotation: Name author = MyClass.java to obtain soft copy of the program code How It Works: The preceding example applies a marker annotation.getAnnotation(Copyright.reflect.annotation.Handout .class.class.value().value(). It implements isAnnotationPresent() to determine if the marker is present. // Notice that no ( ) is needed. import java. // continued … Refer File Name: Marker.class. @MyMarker public static void myMeth() { Marker ob = new Marker().lang.*.class). // A marker annotation @Retention(RetentionPolicy.

notice that you do not need to follow @MyMarker with parentheses when it is applied. they must return one of the following: A simple type. Furthermore.0 adds a powerful new facility called metadata. All Rights Reserved C3: Protected . Cognizant Technology Solutions. Test Your Understanding 1. In the program. A single-member annotation is another special kind of annotation that contains only one member. Java defines seven built-in annotations. they cannot specify a throws clause. State true or false for the following: a) In the single-member or single value annotation. @Override. Tips and Tricks: List out some of the restrictions that are applied to annotation declarations. they cannot take parameters. Thus MyMarker is applied simply by applying its name like this: @MyMarker It is not wrong to supply an empty set of parentheses. b) A marker annotation is a special kind of annotation that contains no members. @Target. but they are not needed. This information called an annotation. @Deprecated and @SuppressWarnings. which enables you to embed supplemental information into a source file. v5. You can give annotation members default values that will be used if no value is specified when the annotation is applied.Handout . A default value is specified by adding a default clause to a member’s declaration. Summary Java 2. no annotation can inherit another. @Documented. 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. Solution: There are a number of restrictions that apply to annotation declarations. Metadata is created through a mechanism based on the interface. Page 363 ©Copyright 2007. Second. They are: @Retention. the name of the member must be element. In other words. First. @Inherited. all methods declared by an annotation must be without parameters. Finally. does not change the actions of a program.Core Java MyMarker is present. A marker annotation is a special kind of annotation that contains no members and its sole purpose is to mark a declaration.

Core Java Session 108: Updates in JDK 1.java.6 are: Scripting Web Services Database (JDBC 4. you will be able to: Describe the key features of Java SE (Standard Edition) 6 (JDK 1. You can now mix in JavaScript technology with your Java technology source code. Compatibility. Cognizant Technology Solutions. It provides reuse of code modules in other programming languages. All Rights Reserved C3: Protected . It produces an environment in which developers and end users can collaborate to create more useful and dynamic applications. 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.0.6) The Java SE 6 (JDK 1. and Stability Motivation for Scripting Support Scripting support provides developers an opportunity to leverage the advantages of different languages in the same application.6) Top 10 Features The top 10 features of JDK 1.Handout . It extends scripting languages applying the powerful Java technology libraries.6 Learning Objectives After completing this session. Also useful when you have teams with a variety of skill sets. Java DB) More Desktop APIs Monitoring and Management Compiler Access Pluggable Annotations Desktop Deployment Security Quality. useful for prototyping.net Page 364 ©Copyright 2007.

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.getEngineByName("js").Handout .eval("alert(\"Hello World!\")").0 Support Developers will get the updated JDBC 4. // evaluate a script engine. Web Services Support on Java SE 6 Platform JAX-WS Data binding using JAXB 2. 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.0.Core Java Scripting: Developer Example // create a ScriptEngineManager ScriptEngineManager m = new ScriptEngineManager(). Page 365 ©Copyright 2007. For the client side: Service class for creating proxy For the server side: Endpoint class for publication Database: JDBC 4.2 WS-I Basic Profile 1.WS Web services stack. Cognizant Technology Solutions. All Rights Reserved C3: Protected .0 Updates to the JAXP. 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. which includes StaX Standards supported are: SOAP 1. // get an instance of JavaScript script engine ScriptEngine engine = m. which focuses on ease of use. and that being all you need.

// Add the tray icon to the System tray SystemTray. Page 366 ©Copyright 2007.add(trayIcon). "Tray Demo". popup menus. and floating tip functionality to the system tray.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.getSystemTray().Handout . Cognizant Technology Solutions. All Rights Reserved C3: Protected . // Add event listener trayIcon.addActionListener(actionListener). Tray Icon: Usage // Construct a TrayIcon TrayIcon trayIcon = new TrayIcon(image. popupMenu).

Handout .gif Painting: You can change the image shown after the splash screen is loaded. SplashScreen splash = SplashScreen.createGraphics().getSplashScreen(). or limit the modality blocking of a dialog box. and animation supported Closed automatically when first top-level window displays Splash Screen: Usage Display from command line: java -splash:image. Desktop class has an enumeration of actions that may be supported for a file or URI like BROWSE. 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. EDIT. Page 367 ©Copyright 2007.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. and PRINT. Cognizant Technology Solutions. editing. This new model allows windows and dialog boxes to be truly parentless. MAIL. but before the application starts.gif TheApp Display from MANIFEST. based on the modality type that the developer chooses. File processing: Opening.update().5 when modal dialog box is on the front.MF (in a jar file): Splashscreen-Image: image. All Rights Reserved C3: Protected . // your painting code here splash. 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. PNG (Portable Network Graphics). Splash screen allows displaying a splash screen for the application instantly before the Java runtime software starts: GIF (Graphic Interchange Format). translucency. Graphics2D g = splash. and a new facility for quick splash screens to quiet impatient users. This new model solves the problem of interacting with JavaHelp in J2SE 1. and JPEG (Joint Photographic Experts Group) images supported Transparency. JTable sorting and filtering. OPEN.

print(). All Rights Reserved C3: Protected . Cognizant Technology Solutions.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.Handout . Text printing reformats for printed page. It optionally displays print dialog and progress box. It supports optional header or footer.JTextComponent.text. It will not split lines in half! Page 368 ©Copyright 2007.swing.

5 software implementing stand-alone library This has more capabilities for relative positioning of components. It supports PropertyChangeListener. This works with horizontal and vertical layout separately.Handout .sun. It supports partial results. It makes use of concurrency package.swing. Cognizant Technology Solutions. This is really aimed at people who create tools for Java development and for frameworks: Page 369 ©Copyright 2007. 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.com/docs/books/tutorial/uiswing/concurrency/ javax. All Rights Reserved C3: Protected .Core Java SwingWorker SwingWorker makes it easy to offload work to separate threads.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. It makes it more generic. More information: http://java.

Handout . roll up your sleeves and give it a try. It seamlessly integrates your custom annotations. but for those of you deafened by your screaming inner geek. 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. The annotation processors act as plug-ins to the compiler.0 Windows look and feel improvements SwingSet on Vista with 5. Cognizant Technology Solutions. 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. hence "pluggable annotation processing”. Processing API standardizes annotation processing as well. All Rights Reserved C3: Protected .0 is shown in the following screenshot: Page 370 ©Copyright 2007. 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 o Updated Swing Look and Feel Windows/Unix 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.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.

Handout . 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. All Rights Reserved C3: Protected . Cognizant Technology Solutions.Core Java Sample screen shot on Vista with Java 2.

Page 372 ©Copyright 2007.Core Java Sample screen shot on Vista with Java 2. All Rights Reserved C3: Protected .Handout . Java Generic Security Services (Java GSS) and Kerberos services for authentication. such as native Public Key Infrastructure (PKI) and cryptographic services on Microsoft Windows for secure authentication and communication. Cognizant Technology Solutions. and access to LDAP servers for authenticating users. 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.

000 test cases and several million lines of code testing conformance.Core Java Quality. All Rights Reserved C3: Protected . and Compatibility Sun has around 80. Cognizant Technology Solutions. several quality and regression issues were fixed. So even before beta release.Handout . Performance Improvement Client Benchmark: SwingMark Server Benchmark: SPECjbb2000 Page 373 ©Copyright 2007. People have been downloading (and testing) snapshots of Java SE 6 (Mustang) for the last 15 months and filing bugs. Performance is claimed to be better than J2SE 5. Stability.

And.1 and v6. Multi-platform use due to Java portability. Scripting languages framework extends support for Ruby. Cognizant Technology Solutions. incorporating the newer XML-based web services functionality. o The NetBeans IDE fully supports Java SE v5.6) are: o o o o o o o Scripting Web Services Database (JDBC 4. New 'Dynamic Attach' diagnostics simplify troubleshooting.0. (ii) the new desktop integration features.Handout . v5. Java DB) More Desktop APIs Monitoring and Management Compiler Access Pluggable Annotations Page 374 ©Copyright 2007. Building Applications on Java SE 6 The JDBC 4. With Java SE 6. All Rights Reserved C3: Protected . Python. it is easy to migrate an application using Java DB to other open standard databases.5. The JSR 223 specification is concerned with how to write and package Java classes that will be accessible from different scripting engines. transactional SQL database that protects against data corruption or systems crashes without also requiring a database administrator.0 Summary The key features of Java SE 6 (Mustang) (JDK 1. and (iii) the new Dialog modality options.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. 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. and other languages. JDK 6 uses: (i) the host desktop's font smoothing settings to ensure consistent text rendering. The Java classes may be part of a Servlet application or may be in a standard Java VM. because Java DB is fully standards-compliant and 100% Java.5. applications can use JAX-WS to build web applications and web services.Core Java Running Applications on Java SE 6 Applications run faster on the desktop and servers. Expanded Solaris DTrace support provides additional value on Solaris. 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.

applications can use JAX-WS to build web applications and web services.Handout . All Rights Reserved C3: Protected . and Stability Test Your Understanding 1. c) A JavaScript engine named as Mozilla Rhino engine is included in the Sun’s implementation of Java SE 6. Cognizant Technology Solutions. Compatibility. incorporating the newer XML-based web services functionality. b) With Java SE 6. Page 375 ©Copyright 2007.0 is available with Java SE v5 (Tiger).Core Java o o o Desktop Deployment Security Quality. State true or false for the following: a) JDBC 4.

Handout . Cognizant Technology Solutions.Core Java Glossary ANT API ASCII AWT BLOB CLOB CMS DB EJB GC GIF GSSAPI GUI HTML I/O IDE J2SE JAAS JAR Java SE JAX JAXB JAXP JAX-WS JDBC JDK JMX JPEG JRE JSP JSR JVM LCD LDAP MTOM Another Neat Tool Application Programming Interface American Standard Code for Information Interchange Abstract Windows Toolkit Binary Large OBject Character Large OBject Concurrent Mark Sweep DataBase Enterpise Java Bean Garbage Collection Graphic Interchage Format Generic Security Services Application Programming Interface Graphical User Interface HyperText Markup Language Input/Output Integrated Development Environment Java 2 Standard Edition Java Authentication and Authorization Service Java Archive Java Standard Edition Java API for XML Java Architecture for XML Binding Java API for XML Processing Java API for XML Web Services Java DataBase Connectivity Java Development Kit Java Management eXtensions Joint Photographic Experts Group Java Runtime Environment Java Server Pages Java Specification Request Java Virtual Machine Liquid Crystal Display Lightweight Directory Access Protocol Message Transmission Optimization Mechanism Page 376 ©Copyright 2007. All Rights Reserved C3: Protected .

Core Java PHP PKI PNG REST SDE SOAP SQL URL WS XML XMLDSig XOP XSLT PHP: Hypertext Preprocessor (HTML-embedded scripting language) Public Key Infrastructure Portable Network Graphics Representational State Transfer Standard Development Environment Simple Object Access Protocol Structured Query Language Uniform Resource Locator Web Service eXtensible Markup Language XML Digital Signature XML-binary Optimized Packaging eXtensible Stylesheet Language Transformation Page 377 ©Copyright 2007.Handout . Cognizant Technology Solutions. All Rights Reserved C3: Protected .

0 (Tiger) New Features – Herbert Schildt Essentials of Java Programming – C.com http://www.Core Java References Websites http://java.stanford.html Books Head First Java – 2nd edition – Kathy Sierra & Bert Bates Java 2.edu/class/cs193j/slidesSummer2003/ http://www.se/~lindsey/JavaCourse/Book/courseMap.org/wiki/ExternalClassProblemInJUnit http://www.kth. All Rights Reserved C3: Protected .javapassion. v5.jspwiki.Muthu Sun Certified Programmer for Java 5 .Kathy Sierra & Bert Bates Page 378 ©Copyright 2007.particle.com http://www.Exam Study Guide .sun. Cognizant Technology Solutions.Handout .

All Rights Reserved C3: Protected .Core Java STUDENT NOTES: Page 379 ©Copyright 2007. Cognizant Technology Solutions.Handout .

Sign up to vote on this title
UsefulNot useful