Core Java Handout v1.0
Core Java Handout v1.0
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
Page 2
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 3
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 4
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 5
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 6
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 7
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Session 26: Wrapper Classes, Selection Statements and Iteration Blocks .........................116
Learning Objectives ..................................................................................................................116
The Wrapper Classes ...............................................................................................................116
Why Should You Use Wrapper Classes? .................................................................................117
Converting Primitive Types to Objects (Wrapper) and the Reverse ........................................117
Wrappers are Immutable ..........................................................................................................118
Try It Out ...................................................................................................................................118
Tips and Tricks: ........................................................................................................................119
Summary ..................................................................................................................................119
Test Your Understanding..........................................................................................................119
Session 27: Wrapper Classes, Selection Statements and Iteration Blocks .........................120
Learning Objectives ..................................................................................................................120
Primitive Types: Wrapper Classes ...........................................................................................120
Converting Strings to Primitive Types ......................................................................................120
Converting Primitive Types to Strings ......................................................................................121
Converting Primitive Types to Strings (Example) .....................................................................121
Autoboxing ................................................................................................................................122
Without Autoboxing (Java versions before 5.0) ........................................................................122
With Autoboxing (Java versions 5.0 or greater) .......................................................................122
Autoboxing Illustrations ............................................................................................................122
Method Arguments ...................................................................................................................123
Return Values ...........................................................................................................................123
Boolean Expressions ................................................................................................................123
Autoboxing With Switch Statement ..........................................................................................123
Operations on Numbers ...........................................................................................................123
Assignments .............................................................................................................................124
Try It Out ...................................................................................................................................124
Tips and Tricks: ........................................................................................................................125
Summary ..................................................................................................................................126
Test Your Understanding..........................................................................................................126
Page 8
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Session 30: Wrapper Classes, Selection Statements and Iteration Blocks .........................127
Learning Objectives ..................................................................................................................127
Control Structures .....................................................................................................................127
Decision Control Structures ......................................................................................................127
if-statement ...............................................................................................................................127
if-statement Flowchart ..............................................................................................................128
Examples of if-statement ..........................................................................................................128
Coding Guidelines ....................................................................................................................128
if-else Statement .......................................................................................................................129
if-else Flowchart........................................................................................................................129
Examples of if-else Statement ..................................................................................................129
Coding Guidelines ....................................................................................................................130
if-else-else if Statement ............................................................................................................130
if-else-else if Flowchart .............................................................................................................130
Example of if-else-else if Statement .........................................................................................131
Common Errors ........................................................................................................................131
Sample Program .......................................................................................................................132
switch Statement ......................................................................................................................132
Flowchart of switch Statement..................................................................................................133
Coding Guidelines ....................................................................................................................134
Try It Out ...................................................................................................................................134
Tips and Tricks: ........................................................................................................................135
Summary ..................................................................................................................................135
Test Your Understanding..........................................................................................................135
Session 31: Wrapper Classes, Selection Statements and Iteration Blocks .........................137
Learning Objectives ..................................................................................................................137
Repetition Control Structures ...................................................................................................137
while-loop..................................................................................................................................137
Examples of while-loop .............................................................................................................137
do-while-loop ............................................................................................................................138
Examples of do-while-loop .......................................................................................................138
Coding Guidelines ....................................................................................................................139
for-loop......................................................................................................................................139
Example of for-loop ..................................................................................................................139
Branching Statements ..............................................................................................................140
Unlabelled Break Statement .....................................................................................................140
Example of Unlabelled Break Statement ..................................................................................140
Labeled Break Statement .........................................................................................................140
Page 9
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 10
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 11
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 12
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 13
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 14
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 15
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 16
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 17
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 18
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Threads.....................................................................................................................................263
Multi-Threading in Java Platform ..............................................................................................263
Thread Priorities .......................................................................................................................263
Try It Out ...................................................................................................................................264
Tips and Tricks : .......................................................................................................................265
Summary ..................................................................................................................................265
Test Your Understanding..........................................................................................................266
Page 19
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 20
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 21
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 22
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 23
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 24
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 25
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
@SuppressWarnings................................................................................................................356
Tips and Tricks: ........................................................................................................................356
Summary ..................................................................................................................................356
Test Your Understanding..........................................................................................................357
Page 26
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Glossary ......................................................................................................................................376
References ..................................................................................................................................378
Websites ...................................................................................................................................378
Books ........................................................................................................................................378
Page 27
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Introduction
Target Audience
This module is designed for beginners of Java who are expected to know the basic
concepts of Object Oriented Programming.
Module Objectives
After completing this module handout, you will be able to:
Describe the characteristics of Java language
Define Java platform
Explain the concepts of packages, classes, objects, main method and
System.out.println methods in Java language
Create Java application programs manually
Run Java application programs manually
Describe the features of Standard Development Environment (SDE)
Create a simple JAVA program in SDE
Execute a simple JAVA program in SDE
Write Java programs using keywords, variable declaration, operators, data types,
arrays and Enum
Write Java programs using Control Flow statements, wrapper classes and autoboxing
Write Java programs using access specifiers, constructors, and methods
Write Java programs using the concepts of inheritance, interfaces, and abstract
classes
Write Java programs implementing exceptions handling
Write Java programs using Strings, StringBuffer, StringBuilder, and its
functions
Write Java programs using Collections and Util package
Write Java programs based on threading concepts
Write Java programs based on I/O operations
Write database application Java programs using JDBC
Explain Garbage Collection concepts
Implement Annotations in Java programs
List the new features of JDK 1.6
Pre-requisite
The prerequisite of Core Java is knowledge in concepts of Object Oriented Programming.
Page 28
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Describe OOP as a programming methodology
Explain classes and objects
OOP defines “things” (objects), which can either do something or have something done to them.
OOP creates a “type” (class) for these objects so that you do not have to redo all the work in
defining the properties and behavior of an object.
Examples of class:
Classroom
Car
Person
Procedural Languages:
C or Pascal and so on
Verb-oriented
No formal noun-verb structure (not enforced by language or compiler)
OOP languages: Operations (verbs) are performed by or on “Actors” (objects), which have names
and store data (nouns)
Objects
An object is a unique programming entity that has attributes to describe it (like adjectives in
grammar) and methods to retrieve or set attribute values (like verbs in grammar).
Page 29
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Class
Exists once:
The class is the template for the object
Every object must belong to a class: The creation (construction) of an object is called instantiation.
The created object is often called an instance (or an instance of class X)
Example:
Person is a class
EdmundHillary is an instance of class Person
Try It Out
Problem Statement:
What is the difference between a class and an object?
Answer:
A class is not an object. But it is used to construct objects.
A class is a blueprint for an object. It tells the virtual machine how to make an object of that
particular type. Each object made from the class can have its own values for the instance variables
of that class.
Class Book {
String id;
String title;
String author;
void getChaptersList() {
System.out.println(“Getting the chapters list”);
}
Page 30
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Refer File Name: Book.java to obtain soft copy of the program code
How It Works:
In the example provided, you have used the Book class to make different books, and each book
has its own id, title, and author.
Solution: The preceding file will result in compilation error since object is not created for the
DiscDeck class. This error will be fixed by adding DiskDeck dd = new DiscDeck(); statement in the
main method.
Summary
Object-oriented programming lets you to extend a program without having to touch the
working code that is tested earlier.
A class describes how to make an object of that class type. A class is like a blueprint.
An object knows things and does things.
The things an object knows about itself are called instance variables. They represent
the state of an object.
The things an object does are called methods. They represent the behavior of an
object.
Page 31
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 32
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Describe abstraction, encapsulation, and inheritance
Abstraction
One of the chief advantages of object oriented programming is the idea that programmers can
essentially focus on the “big picture” and ignore specific details regarding the inner-workings of an
object. This concept is called abstraction.
Encapsulation
Abstraction in OOP is closely related to a concept called encapsulation.
The Object Orientation has two major promises/benefits. They are: flexibility and
maintainability.
You have to write your classes and code in a way that supports flexibility and
maintainability.
The ability to make changes in your implementation code without breaking the code of
others who use your code is a key benefit of encapsulation.
If you want maintainability, flexibility and extensibility your design must include
encapsulation.
The following are some of the ways to include encapsulation:
o Keep instance variables protected (with an access modifier, often private).
o Make public accessor methods, and force calling code to use those methods
rather than directly accessing the instance variable.
o For the methods, use the JavaBeans naming convention of
set<someProperty> and get<someProperty>
Encapsulation is the mechanism that binds together the code and the data it
manipulates, and keeps both safe from outside interference and misuse.
Page 33
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Encapsulation: Example
Bank machine
Hidden data
Account balance
Personal information
Interface
Deposit, Withdraw, Transfer
Display account information
Class Hierarchy
Classes are arranged in a tree hierarchy:
A class’ “superclass” is the class preceding it in the hierarchy
Classes following it are “subclasses”
Classes have all the properties of their superclasses:
General: Towards the root (top)
More specific: Towards the leaves (down)
NB: In Computer Science trees grow upside down!
...
Animal ...
Bird
...
Duck ...
Inheritance
One of the main tenets of OOP is inheritance.
The process by which a class inherits the properties of its superclasses is called inheritance:
Methods
Instance variables
A child class inherits its properties and attributes from its parents.
Inheritance is the process by which one object acquires the properties of another object. By use of
inheritance, an object needs only to define all of its characteristics that make it unique within its
class; it can inherit its general attributes from its parent.
The inheriting class contains all the attributes and behaviors of its parent class. Moreover the
inheriting class can define its own attributes and behaviors.
Page 34
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The inheriting class can override the definition of existing methods by providing its own
implementation.
The code of the inheriting class consists only the changes and additions to the base class.
Need of inheritance
Inheritance is required for the following reasons:
Modular coding, which means less code and easier to get an idea about the code
Code reuse:
Do not break what is already working
Easier updates
Inheritance: Example
BankAccount
int acctNum SavingsAccount
Client acctHolder
double balance double interestRate
double accruedInterest
bankAccount(Client Time lastBalanceChange
info)
void deposit(double
amt) savingsAccount(...)
boolean withdraw(double void
amt) updateIntRate(double
void printStatement() rate)
void deposit(double amt)
boolean withdraw(double
CurrentAccount amt)
double minBalance
currentAccount(…)
boolean withdraw(double
amt)
double calcServiceFee()
Try It Out
Problem Statement:
Design a class inheritance class diagram (tree structure) for the following:
Shirt Clothing
Page 35
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Answer:
Inheritance Class Diagram
Clothing
Shirt Trouser
Refer File Name: Clothing.java, Shirt.java, Trouser.java to obtain soft copy of the program
code
How It Works:
In the given example, Clothing is the superclass and its subclasses are Shirt and Trouser that is a
Shirt extends Clothing and also a Trouser extends Clothing.
Solution: With regard to Java API, there is no hard limit for the limits on the level of subclassing.
Using Java, you cannot extend any class as such. The factors like access control and access
modifier determine whether a class can be subclassed.
Summary
A class can inherit instance variables and methods from a more abstract superclass.
Page 36
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Describe polymorphism
Explain the relationship between objects
Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be
used for a general class of actions that is one interface with multiple methods.
Idea of polymorphism:
See internet definition: On Google type “definition polymorphism” and see the results
Moreover, refer the following url:
http://www.wordiq.com/definition/Polymorphism_%28computer_science%29
Generally, polymorphism allows you to mix methods and objects of different types in a consistent
way.
Method Overloading
This is called ad hoc polymorphism, or method overloading. In this case, different methods within
the same class or in a common hierarchy share the same name but have different method
signatures (name + parameters)
public static float max(float a, float b)
public static float max(float a, float b, float c)
public static int max(int a, int b)
When a method is called, the call signature is matched to the correct method version.
Note: This is done during program compilation
Subclassing Polymorphism
Subclassing polymorphism is sometimes called “true polymorphism”.
It consists basically of two ideas:
Method overriding:
o A method defined in a superclass is redefined in a subclass with an identical
method signature.
o As the signatures are identical, rather than overloading the method, it is instead
overriding the method:
o For subclass objects, the definition in the subclass replaces the version in the
superclass.
Dynamic (or late) binding:
o The code executed for a method call is associated with the call during run-time.
o The actual method executed is determined by the type of the object and not the
type of the reference.
Page 37
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Example of a class
move()
Page 38
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Aggregation:
Aggregation is a special form of association. The relation may be referred alternatively
as “contains”, “is composed of”, or “is part of”.
Example: A car contains wheels. Wheels can exist independently from the car and
are not necessarily destroyed when the car is wrecked.
Composition:
Composition is the relation in which the objects cannot exist independently from the
whole.
Example: The car registration cannot exist without a car. So the relationship between
car and car registration number is composition.
Solution: Yes. This is a great feature of Object Oriented approach, and sometimes it saves you
from having to rewrite the class from scratch, or track down the programmer who is hiding the
source code.
Summary
Object-oriented programming lets you to extend a program without having to touch the
working code that is tested earlier.
All Java code is defined in a class.
A class describes how to make an object of that class type. A class is like a blueprint.
An object can take care of itself, you do not have to know or care how the object does
it.
An object knows things and does things.
The things an object knows about itself are called instance variables. They represent
the state of an object.
The things an object does are called methods. They represent the behavior of an
object.
When you create a class, you may also want to create a separate test class, which
you will use to create objects of your new class type.
A class can inherit instance variables and methods from a more abstract superclass.
At run-time, a Java program is nothing more than objects ‘talking’ to other objects.
Page 39
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Explain the history of Java
Describe the features or characteristics of Java
Explain applets
Describe Java Virtual Machine (JVM) and bytecode
Explain Java Runtime Environment (JRE) and Java Development Kit (JDK)
History of Java
The original name of Java was Oak, and it was developed as a part of the Green project at Sun
Microsystems.
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridon at Sun Microsystems in 1991.
The World Wide Web (WWW), by nature, had requirements such as reliability, security, and
architecture independence, which were fully compatible with the design patterns of Java.
Java Technology
Java is a programming language.
Java is a development environment that provides tools such as compiler, interpreter,
documentation generator, and so on.
Java is an application environment to run standalone programs that run on any
machine where the Java Runtime Environment (JRE) is installed.
Java is a deployment environment that supplies Java2 Software Development Kit
(J2SDK) with complete set of Application Programming Interface (APIs) as packages.
Java provides an easy-to-use language by avoiding pitfalls of other languages, such
as pointer arithmetic and memory management, which affect the robustness of the
code.
Page 40
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Applets
An applet is a program written in the Java programming language that can be included
in a HTML page, much in the same way an image is included in a page.
An applet is designed to be transmitted over the Internet and is executed by a Java
compatible Web browser.
An applet can react to user input dynamically.
Because applets are executed in the client machine, Java enforces a lot of restriction
on applets.
Page 41
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Solution: A Java program is a pile of classes (or at least one class). In a Java application, one of
the classes must have a main method, used to start-up the program. So as a programmer, you
write one or more classes, which you deliver. If the end-user does not have a JVM, then you will
also need to include that with the classes of your application, so that they can run your program.
There are a number of installer programs that lets you to bundle your classes with a variety of
JVMs (say, for different platforms), and put it all on a CD-ROM. Then the end-user can install the
correct version of JVM (assuming they do not already have it on their machine.).
Summary
Keeping the following objectives in mind, Java language has been developed:
o Security
o Reliability
Completely platform independent and functions seamlessly regardless of the type of
CPU
Java is a development environment, which provides tools like compiler, interpreter,
documentation generator, and so on.
Secure, object oriented, robust, portable, platform independent, multithreaded are
some of the salient features of Java.
An applet is a program, which is downloaded in the client machine and executed by
the JVM of the client machine.
Bytecode is a highly optimized set of instructions designed to be executed by the JVM.
The JRE provides the libraries, JVM, Java Interpreter, and other components
necessary for you to run applets and applications written in Java.
Page 42
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define a class
Create objects
Identify packages, import statement, and Object class
Explain object messaging
Defining a Class
A class is a basic building block of an object oriented language.
A class is a template that describes the data and the methods that manipulate the data.
Examples of class:
Classroom
Car
Person
The following Java program defines a class Person with data member name:
Class Person
private String name;
Page 43
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
o These variables are also referred to as static fields because they are declared with
the keyword static.
o Data members of the class are normally declared as instance variables using the
keyword private.
Creating Objects
An object is created from a class.
The following statement creates an object:
Person EdmundHillary = new Person();
Packages
Every class in the Java library belong to a package.
In the Java API, classes are grouped into packages.
A class has a full name, which is a combination of the package name and the class
name. For example, the class ArrayList is actually java.util.ArrayList.
To use a class in a package other than java.lang, you must tell Java the full name of
the class.
Packages are important for three main reasons:
o Firstly, they help in the overall organization of a project or library.
o Secondly, packages give you a name-scoping, to help to prevent collisions if many
programmers in a company decide to make a class with the same name.
o Thirdly, packages provide a level of security, because you can restrict the code,
which you write so that only other classes in the same package can access it.
To put a class in a package, put a package statement at the top of the source code
file, before any import statement like package com.mypack;.
To be in a package, a class must be in a directory structure that exactly matches the
package structure. For a class, com.mypack.Book, the Book class must be in a
directory named mypack, which is in a directory named com.
Organizing your classes into packages prevents naming collisions with other classes,
if you preponed your reverse domain name on to the front of a class name.
Import Statement
A typical set of import statements might look like the following:
import java.io.*;
import java.util.ArrayList;
Page 44
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
import java.util.Date;
import java.util.Properties;
The import statements must come right after the package statement, before the class statement.
Purpose of import statement:
Because of the rigid source code naming convention, the Java compiler can easily find
the corresponding source or class files just from the fully qualified name of a package
and class. This can be illustrated with the following example:
java.util.ArrayList myList = new java.util.ArrayList(50);
The alternative to this long-winded style of coding (as shown earlier), is to use import
statements like the following:
import java.util.ArrayList;
…
ArrayList myList = new ArrayList(50);
To derive a class from an external superclass, you must first import the superclass using the
import statement.
Object Class
Every class in Java extends class Object that is the Object class is the mother of all classes. It is
the superclass of everything.
Any class that does not explicitly extend another class, implicitly extends Object class.
Object Messaging
Objects cooperate and communicate with other objects in a program by passing
messages to one another (setting a value, returning a value, or sending an email).
When an object invokes a method on itself or on the method of another object, it is
said to pass a message to the object that contains the target method.
The message contains the name of the method and any data that the method
requires.
Example: person.setName(“EdmundHillary”);
Data that are passed to a method are known as arguments. The required arguments
for a method are defined by a parameter list of the method.
After performing the operation, the body of the method uses the return statement to
return the value to the calling object.
this keyword:
o Used to represent the object that invokes the method:
o Used within the member methods of the class those are not static
Page 45
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
this keyword
this keyword refers to the object that is currently executing.
this keyword also allows one constructor to explicitly invoke another constructor in
the same class.
It is useful for a method to refer to instance variables relative to this keyword when a
local variable hides the data member with the same name, like the following code:
Class Person {
String name;
Person(String name) {
this.name = name;
}
…….
}
Try It Out
Problem Statement:
Illustrate the importance of the objects with relevant to entries in the address book.
Code:
class AddressBook {
String id;
int telephoneNumber;
public void getName() { }
public String setName(String aName) { }
public String changeName(String aName) { }
}
Refer File Name: AddressBook.java to obtain soft copy of the program code
How It Works:
One analogy for objects is a packet of unused visiting cards in the address book.
Each card has the same blank fields (the instance variables).
When you fill out a card, you are creating an instance (object), and the entries you
make on that card represent its state.
The methods of the class are the things you do to a particular card.
getName() , changeName(String aName) , and setName(String aName) could all be
the methods for the class AddressBook.
So, each card can do the same things (getName() , setName(String aName) ,and so
on), but each card knows things unique to that particular card.
Page 46
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Solution: Yes, it would be a big pain to deliver a huge bunch of individual files to your end-users,
but you will not have to. You can put all of your application files into a Java Archive or a .jar file that
is based on the pkzip format. In the jar file, you can include a simple text file formatted as
something called a manifest, that defines which class in that jar holds the main() method that
should run.
Summary
Object-oriented programming lets you to extend a program without having to touch the
working code that is tested earlier.
A class describes how to make an object of that class type. A class is like a blueprint.
An object knows things and does things.
The things an object knows about itself are called instance variables. They represent
the state of an object.
The things an object does are called methods. They represent the behaviour of an
object.
Page 47
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to explain the following:
The main() method and SOP (System.out.println method)
Code structure in Java
Page 48
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Example
/**
*
* Sample program to print This is my first Java program
*
*/
class MyFirstProgram { // Declare class MyFirstProgram
void displayMessage() {
System.out.println(“This is my first Java program”);
}
After successfully compiling the earlier source file, the compiler generates MyFirstProgram.class
file, which is made up of bytecodes. The compiled bytecode is platform independent.
Run: To run the earlier Java program in a MS-DOS prompt, give the following command:
java MyFirstProgram
The JVM translates the bytecode into something that the underlying platform understands, and
runs your program.
The following output will be displayed in the command prompt after running the earlier command:
This is my first Java program
Try It Out
Problem Statement:
Illustrate the basic structure of a Java application program.
Code:
/**
* A Simple application.
*/
Page 49
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Refer File Name: SimpleApp1.java to obtain soft copy of the program code
How It Works:
/**
* A Simple application.*/ : A comment describing the program
public class SimpleApp1 { : Begin with the class specification
public static void main(String args[]) { : Required method for
application programs
// A method to output to the console. : Comment using two slashes
System.out.println("Simple program"); : Print to console
}: Curly braces span the code for a class. They also bracket the code of a method.
Solution: No, a Java program might use dozens of classes (even hundreds), but you might have
only one with a main() method, the one that starts the running of the program. You might write test
classes, though, that have main methods for testing your other classes.
Summary
The method signature for the main method in a Java application is as follows:
public static void main(String[] args)
Briefly explain the reason that the main method in a Java application is declared
public.
The keyword public indicates that the method can be called by any object.
Explain the reason that the main method in a Java application must be declared static.
The keyword static indicates that the method is a class method which can be called
without the requirement to instantiate an object of the class. This is used by the Java
interpreter to launch the program by invoking the main method of the class identified in
the command to start the program.
Describe the purpose of the keyword void when used as the return type for the main
method.
The void keyword when used as the return type for any Java methods indicates that
the method does not return anything.
Page 50
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 51
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Describe the Standard Development Environment (SDE)
Identify the various kinds of projects in SDE
Page 52
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Hibernate support
Database tools
Others:
o Testing tool and Profiling tool
o Reporting tool
o SHRIMP 2.0 support
o JBoss seam support
o MyLyn support
o Portlet support
o Cheatsheet Support (ongoing updates)
CTS Project:
Designed for the Application Development Projects of CTS
You can build Java, Web, andJ2EE projects
System Requirements:
Hardware:
Intel Pentium III 800 MHz or higher recommended
1 GB RAM minimum and 2GB RAM works well
Disk space requirements: 1.5GB minimum for installing SDE 4.0, Apache Tomcat
6.x, and MySQL 5.x
Software: Windows XP and Linux
Tools
Purpose Plugins
J2EE Development Tools Lomboz STRUTS, Spring IDE, AspectJ Dev Tools
Page 53
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Solution: If Eclipse does not startup by clicking on short cut on desktop, then you do not have
JDK 1.5 configured in your path. Please check the version of java by running java –version
command. The JRE version needs to be 1.5.0.
If the JDK version is lesser than 1.5, then please update the path settings to have
%JAVA_HOME%\bin in the path before all other entries or run eclipse using eclipse.exe -vm
%JAVA_HOME%\bin\javaw.exe command.
Summary
SDE 4.x was built on top of Eclipse 3.3.0
SDE is easy to install
The following applications can be built using SDE:
o Simple Java Application
o Java Applets
o Dynamic web applications using different frameworks such as Struts (1.1-2.0) and
Spring MVC
o J2EE Applications (Web applications + EJB and Web Services).
Page 54
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Create Java classes and packages
Page 55
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
2. Name the Java project and specify the directory, where the project files should be stored.
3. Click Finish.
4. The project is configured with default options.
Page 56
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 57
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
After all the settings have been made, click Finish to create the class.
Page 58
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 59
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Tools
SDE (Standard Development Environment)
Solution:
All compilation errors in your Java code are shown in the Problems view.
Double-clicking the entry in the problems list will navigate to the line in the source
editor, when the error was detected.
Fix the errors highlighted by SDE and go on saving the work.
Page 60
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
When a new Java project is created in SDE, the following can be performed:
Create new packages
Create new Java classes
Build the Java classes
Run the Java programs
Page 61
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Identify Java keywords, Java literals, and primitive data types
Java Keywords
Keywords are predefined identifiers reserved by Java for a specific purpose.
You cannot use keywords as names for your variables, classes, methods, and so on.
Java Literals
Literals are tokens that do not change. They are constant in value.
Page 62
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Hexadecimal:
Precede by 0x or 0X
Example: 0xC
Octal:
Precede by zero
Example: 014
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
Page 63
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 64
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Examples are:
3.14 //A simple floating-point value (a double)
6.02E23 //A large floating-point value
2.718F //A simple float size value
123.4E+306D //A large double value with redundant D
Floating-point data types have the following ranges:
Try It Out
Problem Statement:
Write a program that contains the literal values for the following statements:
1. Declare an int named size and assign it the value 32
2. Declare a char named initial and assign it the value ‘j’.
3. Declare double named d and assign it the value 456.709
4. Declare a boolean named isAvailable(no assignment)
5. Assign the value true to the isAvailable that is declared earlier
6. Declare an int named y, and assign it the value that is the sum of whatever x and 456.
Page 65
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Code:
class LiteralValues {
Refer File Name: LiteralValues.java to obtain soft copy of the program code
How It Works:
You can assign a value to a variable in one of the following several ways including:
Type a literal value after the equals sign (x = 12, isGood = true, and so on)
Assign the value of one variable to another (x = y)
Use an expression combining the two (x = y + 43)
For the given problem statement, the literal values are shown in bold italics:
int size = 32;
char initial = ‘j’;
double d = 456.709;
boolean isAvailable;
isAvailable = true;
int y = x + 456;
Solution:
An identifier must begin with a letter, dollar sign($), or underscore (_). Subsequent
characters may be letters, $, _ (underscore), or digits.
An identifier cannot have a name of a Java keyword. Embedded keywords are
accepted. true, false, and null are literals (not keywords), but they cannot be used as
identifiers as well.
const and goto are reserved words, but not used.
All numeric data types are signed. char is the only unsigned integral type.
A number is by default an int literal. A decimal number is by default a double literal.
1E-5d is a valid double literal and E2d is not (since it starts with a letter, compiler
thinks that it’s an identifier).
Page 66
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
Integer literals can be decimal, octal (e.g. 013), or hexadecimal (e.g. 0x3d).
Literals for longs end in L or l (lowercase of the alphabet L).
Float literals end in F or f, double literals end in a digit D or d.
The boolean literals are true and false.
Literals for chars are single character inside single quotes: ‘d’.
Page 67
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define variables
Declare variables
Initialize variables
Convert data types
Cast data types
Variables
A variable is an item of data used to store the state of objects.
A variable has a:
data type: The data type indicates the type of value that the variable can hold.
name: The variable name must follow rules for identifiers.
Primitive Variables:
Variables with primitive data types such as int or long.
Stores data in the actual memory location of where the variable is present
Reference Variables:
Variables that store the address in the memory location
Points to another memory location where the actual data is present
When you declare a variable of a certain class, you are actually declaring a reference
variable to the object with that certain class
Page 68
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Type Casting
Type Casting is the mapping type of an object to another.
Implicit Casting
Suppose you want to store a value of int data type to a variable of data type double.
int numInt = 10;
double numDouble = numInt; //implicit cast
In this example, as the data type (double) of the destination variable holds a larger value than the
data type (int) of the value, the data is implicitly casted to the data type double of the destination
variable.
Page 69
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Explicit Casting
When you convert a data that has a large type to a smaller type, you must use an explicit cast.
Explicit casts take the following form:
(Type)value where, Type is the name of the type you are converting to value. It is an
expression that results in the value of the source type.
Casting Objects
Instances of classes also can be cast into instances of other classes, with one restriction. The
source and destination classes must be related by inheritance. One class must be a subclass of
the other.
Casting objects is analogous to converting a primitive value to a larger type. Some objects might
not need to be cast explicitly.
Cast, (classname)object where, classname is the name of the destination class and object is a
reference to the source object.
Page 70
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
emp = vp;
Try It Out
Problem Statement:
Write a program that illustrates the implementation of the automatic initialization of member
variables.
Code:
class Initialization {
boolean bo;
byte by;
char c;
short s;
int i;
long l;
float f;
double d;
Object o;
Refer File Name: Initialization.java to obtain soft copy of the program code
How It Works:
The Initialization program illustrates the use of the automatic initialization of member variables. It
displays the following output:
boolean: false
byte: 0
char:
short: 0
int: 0
long: 0
float: 0.0
double: 0.0
Object: null
Page 71
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Can have the same name as a member variable and resolution is based on scope
Note: Here is the figure of allowable primitive conversion
byte -> short -> int -> long -> float -> double
char
Summary
Automatic conversion from narrow to wider type. For e.g., whenever division is
performed between a floating type and an integer type, the integer type is
automatically converted (sometimes called promoted) to a floating type and floating
arithmetic is performed.
Arithmetic with boolean is not allowed.
Variables can be initialized when declared
All Java variables can be initialized when they are declared.
Member (or instance) variables are automatically initialized
If the programmer doesn't initialize the variables declared inside the class but outside
of a method (often referred to as member variables as opposed to local variables),
they are automatically initialized to a default value.
The default value for a boolean member variable is false.
Local variables are not automatically initialized
Unlike instance (or member) variables, if you fail to initialize a local variable, the
variable is not automatically initialized.
Must initialize or assign value to all local variables
Page 72
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Thus, the programmer is responsible for either initializing all local variables, or
assigning a value to them before attempting to access their value with code later in the
program.
Cannot access value from uninitialized local variable
If you attempt to access and use the value from an uninitialized local variable before
you assign a value to it, you will get a compiler error.
Page 73
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Write Java programs by declaring and initializing variables
Page 74
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
What will happen if you try to compile the code given in the next slide?
Code:
class Digit {
public void add() {
int k;
int s = k + 3;
}
}
Refer File Name: Digit.java to obtain soft copy of the program code
How It Works:
The preceding code will not compile. You can declare k without a value, but as soon as you try to
use it, the compiler freaks out.
Solution:
The three types of conversion are namely assignment conversion, method call
conversion, and arithmetic promotion.
boolean may not be converted to or from any type that is not boolean.
byte and short, cannot be converted to char and char cannot be converted to byte and
short.
Arithmetic promotion:
Unary operators:
If the operand is byte, short or char {
convert it to int;
}
else {
do nothing; no conversion needed;
}
Binary operators:
If the operand is double {
all double; convert the other operand to double;
}
else if one operand is float {
Page 75
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
Local variables (method variables) live on the stack.
Objects and their instance variables live on the heap.
Scope of a variable refers to the lifetime of variable.
There are four basic scopes:
Static variables live basically as long as their class lives.
Instance variables live as long as their object lives.
Local variables live as long as their method is on the stack; however, if their method
invokes another method, they are temporarily unavailable.
Block variables (e.g., in a for or an if) live until the block completes.
Page 76
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Identify the different types of operators in Java
Operators
Different types of operators are:
arithmetic operators
relational operators
logical operators
conditional operators
binary operator
These operators follow a certain kind of precedence so that the compiler will know which operator
to evaluate first, in case multiple operators are used in one statement.
Arithmetic Operators
Arithmetic Operators: Sample Program
1 public class ArithmeticDemo {
2 public static void main(String[] args){
3 //a few numbers
4 int i = 37;
5 int j = 42;
6 double x = 27.475;
7 double y = 7.22;
8 System.out.println("Variable values...");
9 System.out.println(" i = " + i);
10 System.out.println(" j = " + j);
11 System.out.println(" x = " + x);
12 System.out.println(" y = " + y);
13 System.out.println("Adding...");
14 System.out.println(" i + j = " + (i + j));
15 System.out.println(" x + y = " + (x + y));
16 //subtracting numbers
17 System.out.println("Subtracting...");
18 System.out.println(" i - j = " + (i – j));
19 System.out.println(" x - y = " + (x – y));
20
21 //multiplying numbers
Page 77
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
22 System.out.println("Multiplying...");
23 System.out.println(" i * j = " + (i * j));
24 System.out.println(" x * y = " + (x * y));
25
26 //dividing numbers
27 System.out.println("Dividing...");
28 System.out.println(" i / j = " + (i / j));
29 System.out.println(" x / y = " + (x / y));
30 //computing the remainder resulting from dividing
31 // numbers
32 System.out.println("Computing the remainder...");
33 System.out.println(" i % j = " + (i % j));
34 System.out.println(" x % y = " + (x % y));
35
36 //mixing types
37 System.out.println("Mixing types...");
38 System.out.println(" j + y = " + (j + y));
39 System.out.println(" i * x = " + (i * x));
40 }
Multiplying...
i * j = 1554
x * y = 198.37
Arithmetic Operators
Note: When an integer and a floating-point number are used as operands to a single arithmetic
operation, the result is a floating point. The integer is implicitly converted to a floating-point number
before the operation takes place.
Page 78
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Increment and decrement operators increase and decrease a value stored in a number variable by
1.
For example
the expression, count=count + 1; //increment the value of count by 1 is equivalent to count++;.
Operator Use Description
The increment and decrement operators can be placed before or after an operand.
When used before an operand, it causes the variable to be incremented or decremented by 1, and
then the new value is used in the expression in which it appears.
For example:
int i = 10;
int j = 3;
int k = 0;
k = ++j + i; //will result to k = 4+10 = 14
When the increment and decrement operators are placed after the operand, the old value of the
variable will be used in the expression where it appears.
For example:
int i = 10;
int j = 3;
int k = 0;
k = j++ + i; //will result to k = 3+10 = 13
Relational Operators
Relational operators compare two values and determine the relationship between those values.
The output of evaluation is the boolean value of true or false.
Page 79
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 80
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
35 //not equal to
36 System.out.println("Not equal to...");
37 System.out.println(" i != j = " + (i!=j));//true
38 System.out.println(" k != j = " + (k!=j));//false
39 }
40 }
Logical Operators
Logical operators have one or two boolean operands that yield a boolean result.
Page 81
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The basic expression for a logical operation is, x1 op x2 where, x1, x2 can be boolean
expressions, variables or constants. op is either &&, &, ||, | or ^ operator.
The truth tables that will be shown next, summarize the result of each operation for all possible
combinations of x1 and x2.
x1 x2 Result
The basic difference between && and & operators is that && supports short-circuit evaluations (or
partial evaluations), while & does not.
Page 82
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
15 System.out.println(test);
16 }
17 }
Note, that the j++ on the line containing the && operator is not evaluated because the first
expression (i>10) is already equal to false
The basic difference between || and I operators is that || supports short-circuit evaluations (or
partial evaluations), while | does not.
Page 83
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
11 //demonstrate |
12 test = (i < 10) | (j++ > 9);
13 System.out.println(i);
14 System.out.println(j);
15 System.out.println(test);
16 }
17 }
Note, that the j++ on the line containing the || operator is not evaluated because the first
expression (i<10) is already equal to true
The result of an exclusive OR operation is TRUE, if and only if one operand is true and the other is
false.
Note that both operands must always be evaluated in order to calculate the result of an exclusive
OR.
1 public class TestXOR {
2 public static void main( String[] args ){
3 boolean val1 = true;
4 boolean val2 = true;
5 System.out.println(val1 ^ val2);
6 val1 = false; val2 = true;
7 System.out.println(val1 ^ val2);
8 val1 = false; val2 = false;
9 System.out.println(val1 ^ val2);
10 val1 = true; val2 = false;
Page 84
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
11 System.out.println(val1 ^ val2);
12 }
13 }
Page 85
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Result:
If exp1 is true, then exp2 is the value returned
If it is false, then exp3 is returned
1 public class ConditionalOperator {
2 public static void main( String[] args ){
3 String status = "";
4 int grade = 80;
5 //get status of the student
6 status = (grade >= 60)?"Passed":"Fail";
7 //print status
8 System.out.println( status );
9 }
10 }
Page 86
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The instanceof operator returns false if none of the preceding conditions are met or if
the left operand is null.
Operator Precedence
In a complicated expression, 6%2*5+4/2+88-10 you can rewrite the expression and place some
parenthesis based on operator precedence, like ((6%2)*5)+(4/2)+88-10;.
Try It Out
Problem Statement:
Write a program that illustrates the use of the instanceof operator.
Code:
import java.util.*;
class Instance {
public static void main(String args[]) {
String s = "abcd";
Vector v = new Vector();
v.add(s);
Object o = v.elementAt(0);
System.out.println(s instanceof String);
System.out.println(s instanceof Object);
Page 87
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Refer File Name: Instance.java to obtain soft copy of the program code
How It Works:
When you run the program, it produces the following results:
true
true
true
true
false
The first two output lines reflect the fact that s is a String and therefore an Object
(because String is a subclass of Object)
The third output line displays a value of true even though o is declared to be of type
Object because the object assigned to o is the String object that was added to Vector
v
The fourth and fifth output lines result from the fact that a String object is an Object
object but not a Vector object.
Page 88
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
The different types of operators are:
o Arithmetic operators
o Increment and decrement operators
o Relational operators
o Conditional operators
o Logical operators
To avoid confusion in evaluating mathematical operations, keep your expressions
simple and use parentheses.
Page 89
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define JUnit Framework
Identify the importance of JUnit Framework
Describe JUnit mechanics
List the Fixtures
Identify Test Suites
List Test Runners
Identify JUnit classes
Identify the best practice guidelines
Identify the design patterns for testing
List Extensions
Importance of Test
Automated tests prove feature
Tests retain their value over time and allow others to prove that the software still works
(as tested)).
Write test cases first and then code it.
Code quality is improved since the code is tested against the test cases at various
stages.
Unit Testing
Unit testing is a procedure used to validate that individual units of source code are
working properly.
A unit is the smallest testable part of an application. In procedural programming a unit
may be an individual program, function, procedure, Web page, menu, and so on while
in object-oriented programming, the smallest unit is always a class, which may be a
base or super class, abstract class or derived or child class.
JUnit
JUnit is a regression testing framework.
JUnit is used by developers to implement unit tests in Java (de-facto standard)
Page 90
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Importance of JUnit
Without JUnit, you will have to use println() to print out some result:
No explicit concept of test passing or failure
No mechanism to collect results in a structured fashion
No replicability
JUnit addresses all these issues
Test Methods
Test methods has name pattern testXxx().
Xxx reflects the method of the target class.
Test methods must have no arguments.
Test methods are type of void.
Page 91
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
// Test code
public void testSomething() {
System.out.println("About to call assertTrue() method...");
assertTrue(4 == (2 * 2));
}
// Create fixtures
protected void setUp(){ /* run before */}
protected void tearDown(){ /* after */ }
Page 92
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Assert Statements
JUnit assertions are methods starting with the keyword assert.
An assert statement determines the success or failure of a test.
An assert is simply a comparison between an expected result and the actual value.
Two variants are:
o assertXxx(...)
o assertXxx(String message, ...)
The message is displayed when assertXxx() fails.
assertTrue() statement asserts that the given condition is true:
o assertTrue(boolean condition)
o assertTrue(String message, boolean condition)
assertFalse() statement asserts that the given condition is false
o assertFalse(boolean condition)
o assertFalse(String message, boolean condition)
assertEquals() statement asserts that the expected result is equal to the actual
behavior
o assertEquals(expected, actual)
o assertEquals(String message, expected, actual)
assertSame() statement asserts that the expected result is same as the actual
behavior
o assertSame(Object expected, Object actual)
o assertSame(String message, Object expected, Object actual)
Page 93
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Fixtures
setUp() and tearDown()methods are used to initialize and release common test data.
The setUp() method is run before every test invocation and the tearDown() method is
run after every test method.
Example: setUp
public class MathTest extends TestCase {
protected double fValue1, fValue2;
Test Suites
Test Suites are used to collect all the test cases
Test Suites can contain testCases and testSuites:
TestSuite(java.lang.Class theClass, <java.lang.String name>)
addTest(Test test) or addTestSuite(java.lang.Class testClass)
Test Suites can have hierarchy
Page 94
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
TestRunners
Highlights of the Test Runner in text mode:
Lightweight, quick quiet
Run from command line
Example:
java StringTest
.......
Time: 0.05
Tests run: 7, Failures: 0, Errors: 0
TestRunners: Swing
Run with java junit.swingui.TestRunner:
Page 95
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 96
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 97
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
try {
s1.toString();
fail("Should see null pointer");
} catch(NullPointerException ex) {
assertTrue(true);
}
}
Page 98
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
JUnit Extensions
The extensions of JUnit are:
JUnitReport
Cactus
JWebUnit
XMLUnit
MockObjects
StrutsTestCase
JUnitReport
JUnitReport is an Apache Ant extension task.
This uses XML and XSLT to generate HTML.
Page 99
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
JWebUnit
JWebUnit is a framework that facilitates creation of acceptance tests for Web applications.
XMLUnit
XMLUnit provides a XMLTestCase class, which enables assertions to be made about the content
and structure of XML:
Differences between two pieces of XML
Validity of a piece of XML
Outcome of transforming a piece of XML using XSLT
Evaluation of an XPath expression on a piece of XML
Page 100
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Mock Objects
The goal of generic unit testing framework is to facilitate developing unit tests in the
mock object style.
Mock object: "double agent" used to test the behavior of other objects
Dummy object, which mimics the external behavior of a true implementation
Observes how other objects interact with its methods and compares actual behavior
with preset expectations
StrutsTestCase
StrutsTestCase extends the JUnit TestCase class that provides facilities for testing code based on
the Struts framework.
Try It Out
Problem Statement:
Write a JUnit test file for a Java source and run it using JUnit tool in SDE.
Code:
package com.testing;
import junit.framework.TestCase;
Refer Files: Hello.java, HelloTest.java to obtain soft copy of the program code
Page 101
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
How It Works:
To test a file using JUnit tool in SDE, create a new JUnit test case by clicking NEW >
JUnit Test Case.
There you can also give the name of the class you are intending to test. Like in this
case, Hello is the class, which is to be, tested using JUnit. The class only contains
getters and setters for the string ‘str’.
1. Click Next to go the next page where you can specify, which all methods you need to test
in the Hello class.
Page 102
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 103
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
You can also see the expected and the actual result by clicking the ‘Compare actual with the
expected result’ button.
In this case, the expected result was ‘Hello world” but the actual result was ‘Hello world!”.
Page 104
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Solution:
Does your class work fine if you run the test cases using the TextRunner?
If yes, then the following explanation is probably correct:
The graphical test runners apply a different class loader than the text version. This
class loader uses a special list, junit/runner/excluded.properties to define, which
classes are never reloaded, and it typically contains classes such as sun.* , javax.* ,
com.sun.* , and so on.
The class loader does not load files from a jar-file, and as most of the external libraries
are distributed as such, you need to either unpack your external jar, or tell the JUnit
class loader, which classes should never be reloaded.
The latter is probably more sensible, so you will not have unpacked jars cluttering your
directory structure.
You need to unpack the junit.jar file, and edit the excluded.properties file to add
packages like org.apache.* and org.xml.*.
Then repack the junit.jar file and apply that.
Here is an example of excluded.properties file:
#
# The list of excluded package paths for the TestCaseClassLoader
#
excluded.0=sun.*
excluded.1=com.sun.*
excluded.2=org.omg.*
excluded.3=javax.*
excluded.4=sunw.*
excluded.5=java.*
excluded.6=junit.*
excluded.7=oracle.*
excluded.8=org.apache.*
Summary
Testing Idioms:
Keep the following things in mind when writing JUnit tests:
o The software does well those things that the tests check.
o Test a little, code a little, test a little, code a little...
o Make sure all tests always run at 100%.
o Run all the tests in the system at least once per day (or night).
o Write tests for the areas of code with the highest probability of breakage.
o Write tests that have the highest possible return on your testing investment.
o If you find yourself debugging using System.out.println(), write a test to
automatically check the result instead.
Page 105
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 106
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define an array
Declare an array
Instantiatiate an array
Access array element
Identify array length, array of multiple dimension, and Enum
Introduction to Arrays
Suppose you have here three variables of type int with different identifiers for each variable.
int number1;
int number2;
int number3;
number1 = 1;
number2 = 2;
number3 = 3;
As you can see, it seems like a tedious task in order to just initialize and use the variables
especially if they are used for the same purpose.
In Java and other programming languages, there is one capability wherein you can apply one
variable to store a list of data and manipulate them more efficiently. This type of variable is called
an array.
An array stores multiple data items of the same data type, in a contiguous block of memory,
divided into a number of slots.
Declaring Arrays
To declare an array, write the data type, followed by a set of square brackets[], followed by the
identifier name.
For example,
int []ages;
or
int ages[];
Page 107
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Array Instantiation
After declaring, you must create the array and specify its length with a constructor statement.
Definitions:
Instantiation: In Java, this means creation
Constructor:
In order to instantiate an object, you need to use a constructor for this. A constructor is a method
that is called to create a certain object.
You will cover more about instantiating objects and constructors later.
To instantiate (or create) an array, write the new keyword, followed by the square brackets
containing the number of elements you want the array to have.
For example,
//declaration
int ages[];
//instantiate object
ages = new int[100];
or, can also be written as,
//declare and instantiate object
int ages[] = new int[100];
Sample diagram illustrating array instantiation
Page 108
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Sample Program
1 //creates an array of boolean variables with identifier
2 //results. This array contains 4 elements that are
3 //initialized to values {true, false, true, false}
4
5 boolean results[] = { true, false, true, false };
6
7 //creates an array of 4 double variables initialized
8 //to the values {100, 90, 80, 75};
9
10 double []grades = {100, 90, 80, 75};
11
12 //creates an array of Strings with identifier days and
13 //initialized. This array contains 7 elements
14
15 String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”};
Begins with zero and progress sequentially by whole numbers to the end of the array
For example, in the given array you have declared a while ago (see slide 10), you have:
//assigns 10 to the first element in the array
ages[0] = 10;
Note: Once an array is declared and constructed, the stored value of each member of the array
will be initialized to zero for number data.
For reference data types such as Strings, they are not initialized to blanks or an empty string “”.
Therefore, you must populate the String arrays explicitly.
Page 109
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The following is a sample code on how to print all the elements in the array. This uses a for loop,
so your code is shorter.
1 public class ArraySample{
2 public static void main( String[] args ){
3 int[] ages = new int[100];
4 for( int i=0; i<100; i++ ){
5 System.out.print( ages[i] );
6 }
7 }
8 }
Coding Guidelines
It is usually better to initialize or instantiate the array right away after you declare it. For example,
the declaration,
int []arr = new int[100];
is preferred over,
int []arr;
arr = new int[100];
The elements of an n-element array have indexes from zero to n-1. Note that there is no array
element arr[n]! This will result in an array-index-out-of-bounds exception.
Array Length
In order to get the number of elements in an array, you can use the length field of an
array.
The length field of an array returns the size of the array. It can be applied by writing,
arrayName.length
1 public class ArraySample {
2 public static void main( String[] args ){
3 int[] ages = new int[100];
4
5 for( int i=0; i<ages.length; i++ ){
6 System.out.print( ages[i] );
7 }
8 }
9 }
Coding Guidelines
When creating for loops to process the elements of an array, use the length field of the
array object in the condition statement of the for loop. This will allow the loop to adjust
automatically for different-sized arrays.
Page 110
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Declare the sizes of arrays in a Java program using named constants to make them
easy to change. For example,
final int ARRAY_SIZE = 1000; //declare a constant
. . .
int[] ages = new int[ARRAY_SIZE];
Multidimensional Arrays
Multidimensional arrays are implemented as arrays of arrays.
Multidimensional arrays are declared by appending the appropriate number of bracket
pairs after the array name.
For example:
// integer array 512 x 128 elements
int[][] twoD = new int[512][128];
// character array 8 x 16 x 24
char[][][] threeD = new char[8][16][24];
To access an element in a multidimensional array is just the same as accessing the elements in an
one dimensional array.
For example, to access the first element in the first row of the array dogs, you write,
System.out.print( dogs[0][0] );
This will print the String "terry" on the screen.
Enum
An enum type is a type whose fields consist of a fixed set of constants.
Common examples include compass directions (values of NORTH, SOUTH, EAST,
and WEST) and the days of the week.
As they are constants, the names of the fields of an enum type are in uppercase
letters.
enum Keyword
In the Java programming language, you define an enum type by using the enum
keyword.
Page 111
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
enum Type
You should use enum types any time you need to represent a fixed set of constants,
which includes natural enum types such as the planets in your solar system and data
sets where you know all possible values at compile time
For example, the choices on a menu, command line flags, and so on
Java programming language enum types are much more powerful than their
counterparts in other languages.
The enum declaration defines a class (called an enum type).
The enum class body can include methods and other fields.
The compiler automatically adds some special methods when it creates an enum.
For example, they have a static values method that returns an array containing all of
the values of the enum in the order they are declared. This method is commonly used
in combination with the for-each construct to iterate over the values of an enum type.
Detailed Example
Here is some code that shows you how to apply the Day enum defined earlier:
public class EnumTest {
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
Page 112
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}
Output
The output is:
Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.
Try It Out
Problem Statement:
Consider the following :
Bird myBird = new Bird();
myBird.name = “Parrot”;
Page 113
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
From the preceding code, you have created a Bird object and used the dot operator on the
reference variable myBird to access the name variable. You can further use the myBird reference
to get the bird to sing() or fly()as given below:
cuckoo.sing();
cuckoo.fly();
What happens if the Bird is in a Bird array? You can access the instance variables of Bird and
methods using the dot operator, but on what?
Code:
class Bird {
String name;
public void sing() { };
public static void main(String[] args) {
Bird[] myBirds = new Bird[3];
myBirds[0] = new Bird();
myBirds[0].name = “Parrot”;
myBirds[0].sing();
}
}
Refer File Name: Bird.java to obtain soft copy of the program code
How It Works:
When the Bird is in an array, you do not have an actual variable name (like “myBird”).
Instead, you apply array notation and the dot operator on an object at a particular
index (position) in the array.
For example myBirds[0].name = “Parrot”;
Solution: A method can declare only one return value, but, if you want to return, say, three int
values, then the declared return type can be an int array. Stuff those ints into the array, and pass it
on back.
Summary
Arrays can hold primitives or objects, but the array itself is always an object.
When you declare a array, the square brackets can be placed left side or right side of
its name.
You must include the size of an array when you construct it (using new) unless you
are creating an anonymous array.
Page 114
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
You’ll get a NullPointerException if you try to use an array element in an object array,
if that element does not refer to a real object.
Arrays are indexed beginning with zero.
An ArrayIndexOutOfBoundsException occurs if you use a bad index value.
The last index you can access is always one less than the length of the array.
Multidimensional arrays are just arrays of arrays.
The dimensions in a multidimensional array can have different lengths.
Page 115
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Implement wrapper classes
Definition: Object representations of simple variables that are not object variables
The designers decided instead that for each primitive type there would be a
corresponding wrapper class.
An instance of a wrapper contains, or wraps, a primitive value of the corresponding
type.
The wrappers are normal classes in the java.lang package that extend the Object
superclass like all Java classes.
Other than for the primitive type int, the wrappers come with the same name as the
corresponding primitive type except that the first letter is capitalized:
o Integer is a wrapper class of the primitive int
o Character is a wrapper class of the primitive char
o Double is a wrapper class of the primitive double
Wrapping a value:
Give the primitive to the wrapper constructor as shown in the following example:
Example:
int i = 123;
Integer iWrap = new Integer(i);
UnWrapping a value:
Each wrapper class has its own method for unwrapping a value.
For example, Boolean class has the method booleanValue(),
Character class has the method charValue() , and so on
Example: int unWrapped = iWrap.intValue();
Page 116
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Here a Double wrapper object is created by passing the double value in the Double constructor
argument.
In turn, each wrapper provides a method to return the primitive value like:
double r = aDouble.doubleValue();
The following statement creates an instance of the Integer class with the integer value 7801.
Integer dataCount = new Integer(7801);
The following statement converts an Integer object to its primitive data type int. The result is an int
with value 7801.
int newCount = dataCount.intValue();
A common translation you need in programs is converting a String to a numeric type, such as an
int (Object->primitive).
String pennsylvania = "65000";
int penn = Integer.parseInt(pennsylvania);
Page 117
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Once you create a wrapper object, there is no way to change the value of that object.
There is no setter method for a wrapper object.
You can, of course, refer iWrap to a different wrapper object, but then you will have two objects.
Try It Out
Problem Statement:
Write a program that illustrates the use of Boolean Wrapper class.
Code:
class BooleanWrapper {
public static void main(String args[]) {
boolean booleanVar = 1 > 2;
Boolean booleanObj = new Boolean("True");
/*
* primitive to object; can also use valueOf method
*/
Boolean booleanObj2 = new Boolean(booleanVar);
System.out.println("booleanVar = " + booleanVar);
System.out.println("booleanObj = " + booleanObj);
System.out.println("booleanObj2 = " + booleanObj2);
System.out.println("compare 2 wrapper objects: "
+ booleanObj.equals(booleanObj2));
/* object to primitive */
booleanVar = booleanObj.booleanValue();
System.out.println("booleanVar = " + booleanVar);
}
}
Refer File Name: BooleanWrapper.java to obtain soft copy of the program code
Page 118
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
How It Works:
When you run the program, it produces the following results:
booleanVar = false
booleanObj = true
booleanObj2 = false
compare 2 wrapper objects: false
booleanVar = true
Solution:
Integer.parseInt() is used to get the int value of a String
Integer.parseInt() works only on Strings that represent the ASCII values for digits
(0,1,2,3,4,5,6,7,8,9). If you try to parse something like “two” or “real”, then the code will
throw an exception.
Summary
The wrapper classes correlate to the primitive types.
Wrappers have two main functions:
o To wrap primitives so that they can be handled like objects.
o To provide utility methods for primitives (usually conversions)
The three most important methods available in the wrapper classes are:
o xxxValue() takes no argument, returns a primitive
o parseXxx() takes a String, returns a primitive, and throws
NumberFormatException
o valueOf() takes a String, returns a wrapped object, throws
NumberFormatException
Wrapper constructors can take a String or a primitive, except for Character, which can
only take a char.
Page 119
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Identify Wrapper classes for the primitive data types
Describe Auto boxing
Explain unboxing
Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void
You occasionally want to pass values to an applet. The applet hypertext tag includes the param
sub-tag for this like the following:
<applet ...>
<param name = "string_name" value = "string_value" >
</applet>
Page 120
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
for passing strings to the applet program. The parameter has a name and corresponding value.
For example, you could pass two strings with numbers like the following:
<applet code="myApplet" codebase="Java" width=100 height=50>
<param name="fpNumber" value="12.45">
<param name="intNumber" value="10">
</applet>
In the applet code, usually in the init() method, you then use the getParameter(String) method from
the applet class to obtain a given parameter, as in the following code:
String fpStr = getParameter ("fpNumber");
String intStr = getParameter ("intNumber");
You now have the parameter values in string form and need to convert them to numbers. The
wrapper classes provide tools for this in the form of static methods.
Page 121
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
In the following code, you convert numerical values to strings using the "+" operator:
String aStr = "d = " + d;
String bStr = "i = " + i;
Now dStr and iStr objects hold string representations of 5.0 and 1, while aStr holds "d = 5.0" and
bStr holds "i = 1“.
Autoboxing
The autoboxing feature added to Java 5.0 does the conversion (wrapping) from
primitive to wrapper object.
This "wrapping" is called "autoboxing" in the sense that the primitive value is
automatically "boxed up" into the wrapper object.
Autoboxing is available for all the primitive or wrapper types.
Autoboxing Illustrations
The general rule is that boxing and unboxing work wherever you can normally use a primitive or a
wrapped object.
Page 122
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Method Arguments
If a method takes a wrapper type, then you can pass a reference to a wrapper or a
primitive of the matching type.
If a method takes a primitive, then you can pass in either a compatible primitive or a
reference to a wrapper of that primitive type.
Example: void takeNumber(Integer i) { }
Return Values
If a method declares a primitive return type, then you can return either a compatible
primitive or a reference to the wrapper of that primitive type.
If a method declares a wrapper return type, then you can return either a reference to
the wrapper type or a primitive of the matching type.
Example:
int giveNumber() {
return x;
}
In the preceding example, x can be either a reference to Integer wrapper or int
primitive type.
Boolean Expressions
Any place a boolean value is expected, you can use either an expression that evaluates to a
boolean (4 > 2), or a primitive boolean, or a reference to a Boolean wrapper.
Example:
boolean one = true; // nothing new here
Boolean two = true; // autoboxing of primitive 'true' to
Boolean type
if (one && two) // auto unboxing do_something ();
Before Java 5.0, the if, while, and do-while statements are all expected as boolean expressions.
Through the use of unboxing, those flow control statements now also accept expressions that
evaluate to Boolean types.
With the addition of autoboxing in Java 5.0, switch now also accepts Byte, Short, Integer, and
Character types.
Operations on Numbers
This is probably the strangest one. You can now use a wrapper type as an operand in operations
where the primitive type is expected.
Page 123
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
That means you can apply, say, the increment operator against a reference to an Integer object!
Examples:
Integer i = new Integer(56);
i++;
Integer j = new Integer(4);
Integer k = j + 3;
Assignments
You can assign either a wrapper or primitive to a variable declared as a matching wrapper or
primitive.
For example, a primitive int can be assigned to an Integer reference variable and a reference to an
Integer object can be assigned to a variable declared as an int primitive.
Example: Double d = x;
In the preceding example, x can be either a reference to Double wrapper or double primitive type.
Try It Out
Problem Statement:
Write a program that illustrates the use of Wrapper classes for the primitive types namely int, char,
long, float, double, and boolean.
Code:
public class WrappedClassApp {
public static void main(String args[]) {
Boolean b1 = new Boolean("TRUE");
Boolean b2 = new Boolean("FALSE");
System.out.println(b1.toString() + " or " + b2.toString());
for (int j = 0; j < 16; ++j)
System.out.print(Character.forDigit(j, 16));
System.out.println();
Integer i = new Integer(Integer.parseInt("ef", 16));
Long l = new Long(Long.parseLong("abcd", 16));
long m = l.longValue() * i.longValue();
System.out.println(Long.toString(m, 8));
System.out.println(Float.MIN_VALUE);
System.out.println(Double.MAX_VALUE);
}
}
Refer File Name: WrappedClassApp.java to obtain soft copy of the program code
Page 124
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
How It Works:
The program examines some of the more useful methods provided by the wrapped
classes.
It creates two objects of class Boolean from string arguments passed to their
constructors.
It assigns these objects to b1 and b2 and then converts them back to String objects
when it displays them.
They are displayed in lowercase, as boolean values are traditionally represented.
The program then executes a for loop that prints out the character corresponding to
each of the hexadecimal digits.
The static forDigit() method of the Character class is used to generate the character
values of digits in a number system of a different radix.
The static parseInt() and parseLong() methods are used to parse strings according to
different radices.
In the example, they are used to convert strings representing hexadecimal numbers
into Integer and Long values.
These values are then multiplied together and converted to a string that represents the
resulting value in base 8.
This is accomplished using an overloaded version of the toString() method.
The sample program concludes by displaying the minimum float value and the
maximum double value, using the predefined class constants of the Float and Double
classes.
The output of the program is as follows:
true or false
0123456789abcdef
50062143
1.4E-45
1.7976931348623157E308
Java 5 (JDK 1.5 and further) includes autoboxing and auto-unboxing. A developer might be
tempted to apply objects such Integer or Double exclusively, abandoning primitives altogether.
Page 125
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Solution:
In this example, objects of type Double hold values that are used to calculate the
hypotenuse of a right triangle.
Although this code is technically correct, and in fact, work properly, it is a very bad use
of autoboxing or unboxing.
It is far less efficient than the equivalent code written applying the primitive double.
The reason is that each autobox and auto-unbox adds overhead that is not present if
the primitive type is used.
In general, you should restrict your use of the type wrappers to only those cases in
which the object representation of a primitive type is required.
Summary
As of Java 5, autoboxing / unboxing allow you to convert primitives to wrappers or to
convert wrappers to primitives automatically.
Using the == with wrappers is tricky; wrappers with the same small values (typically
lower than 127), will be ==, larger values will not be ==.
Page 126
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Use decision control structures (if, if-else, switch), which allows selection of specific
sections of code to be executed.
Control Structures
Control structures allows you to change the ordering of how the statements in your programs are
executed
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.
Page 127
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
if-statement Flowchart
The following figure shows the flowchart of an if statement:
Examples of if-statement
Example 1:
int grade = 68;
if( grade > 60 )
System.out.println("Congratulations!");
Example 2:
int grade = 68;
if( grade > 60 ) {
System.out.println("Congratulations!");
System.out.println("You passed!");
}
Coding Guidelines
The boolean_expression part of a statement should evaluate to a boolean value,
which means that the execution of the condition should either result to a value of true
or a false.
Indent the statements inside the if-block.
For example,
if( boolean_expression ) {
//statement1;
//statement2;
}
Page 128
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
if-else Statement
if-else statement is used when you want to execute a certain statement if a condition is
true, and a different statement if the condition is false.
if-else statement has the form:
if( boolean_expression ) {
statement1;
statement2;
. . .
}
else {
statement3;
statement4;
. . .
}
if-else Flowchart
The following figure shows the flowchart of an if-else statement:
Example 2:
int grade = 68;
if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println(“You passed!");
}
Page 129
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
else{
System.out.println("Sorry you failed");
}
Coding Guidelines
To avoid confusion, always place the statement or statements of an if or if-else block
inside brackets {}.
You can have nested if-else blocks. This means that you can have other if-else blocks
inside another if-else block.
For example,
if( boolean_expression ){
if( boolean_expression ){
//some statements here
}
}
else{
//some statements here
}
if-else-else if Statement
The statement in the else-clause of an if-else block can be another if-else structure.
This cascading of structures allows you to make more complex selections.
The statement has the form:
if( boolean_expression1 )
statement1;
else if( boolean_expression2 )
statement2;
else
statement3;
if-else-else if Flowchart
The following figure shows the flowchart of an if-else-else if statement:
Page 130
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Common Errors
The condition inside the if-statement does not evaluate to a boolean value,
for example,
//WRONG
int number = 0;
if( number ) {
//some statements here
}
Page 131
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
For example,
//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}
Sample Program
1 public class Grade {
public static void main( String[] args )
{
4 double grade = 92.0;
5 if( grade >= 90 ){
6 System.out.println( "Excellent!" );
7 }
8 else if( (grade < 90) && (grade >= 80)){
9 System.out.println("Good job!" );
10 }
11 else if( (grade < 80) && (grade >= 60)){
12 System.out.println("Study harder!" );
13 }
14 else{
15 System.out.println("Sorry, you failed.");
16 }
17 }
18 }
switch Statement
switch allows branching on multiple outcomes
switch statement has the form:
switch( switch_expression ){
case case_selector1:
statement1;//
statement2;//block 1
break;
case case_selector2:
Page 132
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
statement1;//
statement2;//block 2
break;
:
default:
statement1;//
statement2;//block n
}
where:
switch_expression is an integer or character expression
case_selector1, case_selector2 and so on, are unique integer or character constants
Page 133
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
15 default:
16 System.out.println("Sorry, you failed.");
17 }
18 }
19 }
Coding Guidelines
Deciding whether to use an if statement or a switch statement, is a judgment call. You can decide
which to use, based on readability and other factors.
An if statement can be used to make decisions based on ranges of values or conditions, whereas
a switch statement can make decisions based only on a single integer or character value. Also, the
value provided to each case statement must be unique.
Try It Out
Problem Statement:
Write a program that illustrates the use of switch with break statements.
Code:
class SwitchWithBreak {
public static void main(String[] args) {
int n = 3;
switch (n) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
// continued …
Refer File Name: SwitchWithBreak.java to obtain soft copy of the program code
How It Works:
SwitchWithBreak program shows how the break statement is used to ensure that only
a single case of a switch statement is executed.
This program displays the following single line of output:
3
Page 134
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Solution:
if (false) { x = 3}; // will compile, to provide the ability to conditionally compile the code.
The if statement takes boolean arguments. Parenthesis is required. else part is
optional.
The compiler checks each case value against the range of the data type of switch
expression.
The following code will not compile.
byte b;
switch (b) {
case 200: // 200 not in the range of byte
default:
}
You need to place a break statement in each case block to prevent the execution to
fall through other case blocks. But this is not a part of switch statement and not
enforced by the compiler.
Default case can be placed anywhere. It will be executed only if none of the case
values match.
Empty switch construct is a valid construct. But any statement within the switch block
should come under a case label or the default case label.
Summary
The only legal expression in an if statement is a boolean expression; in other words an
expression that resolves to a boolean or a Boolean variable.
Watch out for boolean assignments (=) that can be mistaken for boolean equality (==)
tests.
Curly braces are optional for if blocks that have only one conditional statement. But
watch out for misleading indentations.
switch statements can evaluate only to enums or the byte, short, int, and char data
types.
The case constant must be a literal or final variable, or a constant expression,
including an enum. You cannot have a case that includes a non-final variable, or a
range of values.
The default keyword can be located anywhere in the switch block.
Page 135
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
2. Which one of the following is not correct in the case of ‘switch’ statement?
a) The expression involved in a switch statement may be an arithmetic expression.
b) The body of a case may be empty.
c) The body of a case should have the break statement.
d) The default part is optional.
Page 136
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Use repetition control structures (while, do-while, for), which allow executing specific
sections of code a number of times
Use branching statements (break, continue, return), which allows redirection of
program flow
while-loop
while loop is a statement or block of statements that is repeated as long as some condition is
satisfied.
The statements inside the while loop are executed as long as the boolean_expression evaluates to
true.
Examples of while-loop
Example 1:
int x = 0;
while (x<10) {
System.out.println(x);
x++;
}
Page 137
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Example 2:
//infinite loop
while(true)
System.out.println(“hello”);
Example 3:
//no loops
// statement is not even executed
while (false)
System.out.println(“hello”);
do-while-loop
do-while loop:
Similar to the while-loop
Statements inside a do-while loop are executed several times as long as the condition
is satisfied
The main difference between a while and do-while loop is that the statements inside a
do-while loop are executed at least once
do-while loop has the following form:
do{
statement1;
statement2;
. . .
}while( boolean_expression );
Examples of do-while-loop
Example 1:
int x = 0;
do {
System.out.println(x);
x++;
} while (x<10);
Example 2:
//infinite loop
do {
System.out.println(“hello”);
] while(true);
Page 138
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Example 3:
//one loop
// statement is not executed only once
do {
System.out.println(“hello”);
} while (false);
Coding Guidelines
Common programming mistakes when using the do-while loop is forgetting to write the semi-colon
after the while expression.
do{
...
}while(boolean_expression)//WRONG->forgot semicolon;
Just like in while loops, make sure that your do-while loops will terminate at some point.
for-loop
for loop allows execution of the same code a number of times.
for loop has the following form:
for(InitializationExpression;LoopCondition;StepExpression)
{
statement1;
statement2;
. . .
}
Where:
InitializationExpression initializes the loop variable.
LoopCondition compares the loop variable to some limit value.
StepExpression updates the loop variable.
Example of for-loop
int i;
for( i = 0; i < 10; i++ ){
System.out.println(i);
}
Page 139
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Branching Statements
Branching statements allows you to redirect the flow of program execution.
Page 140
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
searchLabel:
for( int i=0; i<numbers.length; i++ ){
for( int j=0; j<numbers[i].length; j++ ){
if( searchNum == numbers[i][j] ){
foundNum = true;
break searchLabel;
}
}
}
Page 141
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Return Statement
Return statement:
Applied to exit from the current method
Flow of control returns to the statement that follows the original method call
To return a value:
Simply put the value (or an expression that calculates the value) after the return keyword. For
example:
return ++count;
or
return "Hello";
The data type of the value returned by return must match the type of the declared return value of
the method. When a method is declared void, use the form of return that does not return a value.
For example:
return;
Try It Out
Problem Statement:
Write a program that illustrates the use of for loop.
Code:
class ForLoop {
public static void main(String[] args) {
int i, j;
for (i = 0, j = 0; i + j < 20; ++i, j += i) {
System.out.println(i + j);
}
}
}
Refer File Name: ForLoop.java to obtain soft copy of the program code
How It Works:
A little-known fact about the for statement is that commas can be used to separate
multiple statements in the initialization and iteration part of the statement.
The only catch is, if you apply a comma separator in the initialization block, then you
cannot declare variables within the initialization block.
Page 142
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
The types of Repetition Control Structures are:
while
do-while
for
The types of Branching Statements are:
break
continue
return
Page 143
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 144
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Identify constructors and the different types of method declaration
Constructors
Java provides a special construct named constructor exclusively for creating an object
of a class and initializing its instance variables.
Constructors should have the same name as the name of the class.
It is generally declared as public.
It may have optional list of arguments.
It does not have any return type and not even void.
You cannot invoke a constructor on an existing object.
You can use a constructor only in combination with the new operator.
Page 145
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Applying Constructors
To apply these constructors, you have the following code:
public static void main( String[] args ){
//create three objects for Student record
StudentRecord annaRecord=new StudentRecord("Anna");
StudentRecord beahRecord=new StudentRecord("Beah",
"Philippines");
StudentRecord crisRecord=new
StudentRecord(80,90,100);
//some code here
}
Page 146
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
“this” Reference
The this reference:
Refers to current object instance itself
Used to access the instance variables shadowed by the parameters
To use the this reference, you type, this.<nameOfTheInstanceVariable>
You can only use the this reference for instance variables and not for static or class
variables
The this reference is assumed when you call a method from the same object.
public class MyClass {
void aMethod() {
// same thing as this.anotherMethod()
anotherMethod();
}
void anotherMethod() {
// method definition here...
}
}
Page 147
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Declaring Methods
To declare methods you write,
<modifier> <returnType>
<name>(<parameter>*) {
<statement>*
}
Where:
<modifier> can carry a number of different modifiers
<returnType> can be any data type (including void)
<name> can be any valid identifier
<parameter> can be one or more parameters passed as argument to the method.
Each <parameter> is associated with a parameter type (primitive or object) and a
parameter name.
Page 148
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 149
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
return defaultNum;
}
Static Methods
Example:
public class StudentRecord {
private static int studentCount;
public static int getStudentCount(){
return studentCount;
}
}
where,
public means that the method can be called from objects outside the class.
static means that the method is static and should be called by typing,
[ClassName].[methodName. For example, in this case, you call the method
StudentRecord.getStudentCount()
int is the return type of the method. This means that the method should return a value
of type int.
getStudentCount is the name of the method.
() means that your method does not have any parameters.
Coding Guidelines
Method names should start with a small letter
Method names should be verbs
Always provide documentation before the declaration of the method
Page 150
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
/**
* Changes the name of the student (Mutator method)
*/
public void setName( String temp ){
name = temp;
}
/**
* Computes the average of the english, math and science
* grades (Accessor method)
*/
public double getAverage(){
double result = 0;
result = ( mathGrade+englishGrade+scienceGrade )/3;
return result;
}
/**
* returns the number of instances of StudentRecords
* (Accessor method)
*/
public static int getStudentCount(){
return studentCount;
}
Page 151
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
beahRecord.setName("Beah");
crisRecord.setName("Cris");
System.out.println("Count="+StudentRecord.getStudentCount());
}
}
Program Output
Anna
Student Count = 0
Try It Out
Problem Statement:
Write a program that illustrate the use of ‘this’ statement in constructor overloading.
Code:
public class Box {
double x, y, width, height;
// continued …
Refer File Name: Box.java to obtain soft copy of the program code
How It Works:
The first Box() constructor takes the arguments x, y, width, and height and assigns
them to the appropriate field variables.
Page 152
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The second Box() constructor takes just the coordinates of the box as arguments and
invokes the first constructor, passing 10 as the default value for the height and width of
the box.
The third constructor has no arguments and invokes the second constructor with the
default value of 1 for the x and y coordinates of the box.
The this(x,y,10,10) and this(1,1) used in the second and third constructors is a special
notation provided by Java to enable you to invoke a constructor of the same class
from another constructor of that class.
It is referred to as a constructor call statement. In order to use a constructor call
statement, there must be a constructor whose argument list matches those supplied
with this() .
Note: If this() appears in a constructor, then it must appear as the first statement in the
constructor.
Solution:
Java lets you to declare a method with the same name as your class, which does not
make it a constructor, though.
The thing that separates a method from a constructor is the return type.
Methods must have a return type, but constructors cannot have a return type and not
even void.
No, constructors are not inherited.
A method that is not static in a class can always call a static method in the class or
access a static variable of the class.
Summary
A constructor is always invoked when a new object is created.
Every class, even an abstract class, has at least one constructor.
Interfaces do not have constructors.
Constructors must have the same name as the class.
Constructors can use any access modifier (even private!)
The default constructor is a no-arg constructor with a no-arg call to super().
The first statement of every constructor must be a call to either this() (an overloaded
constructor) or super().
Calls to this() and super() cannot be in the same constructor, you can have one or the
other, but never both.
Page 153
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 154
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Explain method overloading
Method Overloading
Method overloading:
Allows a method with the same name but different parameters, to have different
implementations and return values of different types
Can be applied when the same operation has different implementations
Always remember that overloaded methods have the following properties:
The same method name
Different parameters or different number of parameters
Return types can be different or same
Page 155
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
//overloaded methods
annaRecord.print( annaRecord.getName() );
annaRecord.print( annaRecord.getEnglishGrade(),
annaRecord.getMathGrade(),
annaRecord.getScienceGrade());
}
Program Output
You will have the output for the first call to print:
Name:Anna
Address:Philippines
Age:15
You will have the output for the second call to print:
Name:Anna
Math Grade:80.0
English Grade:95.5
Science Grade:100.0
Try It Out
Problem Statement:
Write a program that illustrates invoking overloaded methods.
Code:
class TestAdder {
public int addThem(int x, int y) {
System.out.println("Inside addThem(int x, int y) method...");
return x + y;
}
// Overload the addThem method to add doubles instead of ints
public double addThem(double x, double y) {
System.out.println("Inside addThem(double x, double y)
method...");
return x + y;
}
}
Page 156
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
int c = 3;
int result = a.addThem(b, c); // which addThem is invoked?
double doubleResult = a.addThem(22.5, 9.3); // which addThem?
}
}
Refer File Name: TestAdder.java to obtain soft copy of the program code
How It Works:
In the TestAdder program, the first call to a.addThem(b,c) passes two ints to the
method.
So, for the above call, the first version of addThem() – the overloaded method that
contains two int arguments – is done.
The second call to a.addThem(22.5, 9.3) passes two doubles to the method.
So, for the above call, the second version of addThem() – the overloaded method that
contains two double arguments – is done.
Signature has to be different. Just a difference Signature has to be the same. (including the return
in return type is not enough. type)
Just the name is reused. Methods are Related directly to sub-classing. Overrides the
independent methods. Resolved at compile- parent class method. Resolved at run-time based on
time based on method signature. type of the object.
Methods can be static or non-static. If two static methods do not participate in overriding, since
methods have the same signature, declaring they are resolved at compile time based on the type
one as static and another as non-static does of reference variable. A static method in a sub-class
not provide a valid overload. It’s a compile cannot use super. A static method cannot be
time error. overridden to be non-static and vice-versa.
There is no limit on number of overloaded Each parent class method may be overridden at
methods a class can have. most once in any sub-class.
Page 157
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
Methods can be overridden or overloaded; constructors can be overloaded but not
overridden.
Overloading means reusing a method name, but with different arguments.
Overloaded methods:
o Must have different argument lists
o May have different return types, if argument lists are also different
o May have different access modifiers
o May throw different exceptions
Methods from a superclass can be overloaded in a subclass.
Reference type determines which overloaded method will be used at compile time.
Page 158
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Apply access modifiers
Access Modifiers
You can define the scope of a variable or method or class by using the access modifiers.
There are four different types of access modifiers in Java:
public (Least restrictive)
protected
default
private (Most restrictive)
The first three access modifiers are explicitly written in the code to indicate the access type, for the
third one, which is default, no keyword is used.
public Accessibility
Public access:
Specifies that class members (variables or methods) are accessible to anyone, both
inside and outside the class and outside of the package
Any object that interacts with the class can have access to the public members of the
class
Keyword: public
Page 159
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
protected Accessibility
Protected access:
Specifies that the class members are accessible only to methods in that class and the
subclasses of the class
The subclass can be in different packages
Keyword: protected
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
private Accessibility
Private accessibility: Specifies that the class members are only accessible by the class in which
they are defined
Keyword: private
Page 160
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Coding Guidelines
The instance variables of a class should normally be declared private, and the class will just
provide accessor (getter) and mutator (setter) methods to these variables.
Try It Out
Problem Statement:
Write a program that illustrates about access modifiers.
Code:
package learn;
public class OtherClass {
void testIt() { // No modifier means method has default access
System.out.println(“OtherClass”);
}
}
------------------------------------------------------------------------
In another source code, you have the following:
package somethingElse;
import learn.OtherClass;
Page 161
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
class AccessClass {
static public void main(String[] args) {
OtherClass o = new OtherClass();
o.testIt();
}
}
Refer Files : OtherClass.java, AccessClass.java to obtain soft copy of the program code
How It Works:
In the OtherClass program, the testIt() method has default (think: package-level)
access.
Notice also that class OtherClass is in a different package from the AccessClass.
Now the question is, will AccessClass be able to apply the method testIt() ? Will it
cause a compiler error?
No method matching testIt()is found in class learn.OtherClass. o.testIt();.
From the preceding results, you can see that AccessClass cannot use the OtherClass
method testIt() because testIt() has default access, and AccessClass is not in the
same package as OtherClass. So AccessClass cannot see it, and hence the compiler
complains.
Page 162
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
The different access modifiers in Java are default, public, private, and protected.
Page 163
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define Inheritance
Explain the need of Inheritance
Identify how to derive a subclass
Define Object class
Explain constructor calling chain
Identify “super” keyword
Override methods
Hide methods and fields
Apply type casting
Write final class and final methods
Inheritance
Inheritance is the concept of a child class (sub class) automatically inheriting the
variables and methods defined in its parent class (super class).
The primary features of object-oriented programming are encapsulation and
polymorphism.
Importance of Inheritance
The benefit of inheritance in OOP is reusability. Once a behavior (method) is defined
in a super class, that behavior is automatically inherited by all subclasses
Thus, you write a method only once and it can be used by all subclasses:
Once a set of properties (fields) are defined in a super class, the same set of
properties are inherited by all subclasses. A class and its children share common set
of properties
A subclass only needs to implement the differences between itself and the parent.
Deriving a Subclass
To derive a child class, you use the extends keyword.
Suppose you have a parent class called Person.
public class Person {
protected String name;
protected String address;
/**
* Default constructor
*/
Page 164
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
public Person(){
System.out.println(“Inside Person:Constructor”);
name = ""; address = "";
}
. . . .
}
extends Keyword
Now, you want to create another class named Student.
Since a student is also a person, you decide to just extend the class Person, so that
you can inherit all the properties and methods of the existing class Person.
To do this, you write,
public class Student extends Person {
public Student(){
System.out.println(“Inside Student:Constructor”);
}
. . . .
}
Page 165
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Object Class
Object class is mother of all classes.
In Java language, all classes are subclassed (extended) from the Object super class.
Object class is the only class that does not have a parent class
Object class defines and implements behavior common to all classes including the ones that you
write.
Class Hierarchy
A sample class hierarchy is shown in the following figure:
Page 166
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 167
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
For example:
public Student() {
super.name = “somename”;
super.address = “some address”;
}
Overriding Methods
If a derived class needs to have a different implementation of a certain instance
method from that of the super class, then override that instance method in the sub
class:
Note that the scheme of overriding applies only to instance methods.
For static methods, it is called hiding methods.
The overriding method has the same name, number and type of parameters, and
return type as the method it overrides.
The overriding method can also return a subtype of the type returned by the
overridden method This is called a covariant return type.
To override the getName() method of the superclass Person in the subclass Student, reimplement
the method with the same signature.
public class Student extends Person{
:
public String getName(){
System.out.println("Student: getName");
return name;
}
:
}
Now, when you invoke the getName() method of an object of the subclass Student, the getName()
method of the Student class would be called, and the output would be:
Student: getName
Page 168
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Result:
myMethod(test4) in Student class is called
myMethod(test5) in InternationalStudent class is called.
Hiding Methods
If a subclass defines a class method (static method) with the same signature as a class method in
the super class, then the method in the subclass “hides” the one in the super class.
Page 169
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Hiding Fields
Within a sub class, a field that has the same name as a field in the super class, hides
the super class' field, even if their types are different.
Within the subclass, the field in the super class cannot be referenced by its simple
name, instead, the field must be accessed through super keyword.
Generally speaking, hiding fields is not a recommended programming practice as it
makes code difficult to read.
Try It Out
Problem Statement:
Write a program that illustrate the use of ‘this’ and ‘super’.
Page 170
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Code:
class ThisSuper extends SuperClass {
String s = "this";
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
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.
Page 172
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 173
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define abstract method and an abstract class
Define an interface
Explain the importance of interface
Identify interface as a type
Differentiate between interface and class
Implement an interface
Implementing multiple interfaces
Identify inheritance among interfaces
Describe interface and polymorphism
Rewrite an interface
Abstract Methods
Methods that do not have implementation (body) are called abstract methods
To create an abstract method, just write the method declaration without the body and use the
keyword abstract
No { } Please make this point that there are no parentheses will be available.
For example,
// Note that there is no body
public abstract void someMethod();
Abstract Class
An abstract class is a class that contains one or more abstract methods.
An abstract class cannot be instantiated.
You will get a compile error on the following code
MyAbstractClass a1 = new MyAbstractClass();
Another class (Concrete class) has to provide implementation of abstract methods:
Concrete class has to implement all abstract methods of the abstract class in order to
be used for instantiation
Concrete class uses extends keyword
Page 174
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
For example,
public class Human extends LivingThing {
public void walk(){
System.out.println("Human walks...");
}
}
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);
}
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
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.
Page 177
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
For example:
PersonInterface pi = new PersonInterface(); //ERROR!
An interface can only be implemented by classes or extended by other interfaces.
Defining Interface
To define an interface, you write:
As an example, create an interface that defines relationships between two objects according to the
“natural order” of the objects.
public interface Relation {
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}
Implementing Interfaces
To create a concrete class that implements an interface, use the implements keyword.
/**
* Line class implements Relation interface
*/
public class Line implements Relation {
private double x1;
private double x2;
private double y1;
private double y2;
public Line(double x1, double x2, double y1, double y2){
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
public double getLength(){
double length = Math.sqrt((x2-x1)*(x2-x1) +
(y2-y1)* (y2-y1));
return length;
Page 178
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Implementing Class
Implementing class can have its own methods.
Implementing class extend a single super class or abstract class.
Page 179
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 180
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
If you make this change, then all classes that implement the old DoIt interface will break because
they do not implement all methods of the interface anymore.
Now users of your code can choose to continue to apply the old interface or to upgrade to the new
interface
Try It Out
Problem Statement:
Write a program that illustrates an inheritance tree with two abstract classes and one concrete
(that is not abstract) class.
Code:
public abstract class Vehicle {
private String type;
public abstract void goUpHill();
public String getType() {
return type;
}
}
Page 181
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Refer File Name: Vehicle.java, Car.java, Mini.java to obtain soft copy of the program code
How It Works:
The class Mini have three methods.
It inherits both the getType() and doCarThings() methods, because they are public and
concrete (nonabstract).
goUpHill() is abstract in the super class Vehicle, and is never implemented in the Car
class (so it remains abstract).
It means the class Mini as the first concrete class below Vehicle must implement the
goUpHill() method.
In other words, class Mini cannot pass the buck (of abstract method implementation)
to the next class down the inheritance tree, but class Car can, because Car like
Vehicle, is abstract.
Summary
Interfaces can be implemented by any class, from any inheritance tree.
An interface is like a 100-percent abstract class, and is implicitly abstract whether you
type the abstract modifier in the declaration or not.
An interface can have only abstract methods, no concrete methods allowed.
Interface methods are by default public and abstract – explicit declaration of these
modifiers is optional.
Interfaces can have constants, which are always implicitly public, static and final.
A class implementing an interface can itself be abstract.
An abstract implementing class does not have to implement the interface methods (but
the first concrete subclass must implement all of the interface’s methods).
Page 182
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
A class can extend only one class (no multiple inheritance), but it can implement many
interfaces.
Interfaces can extend one or more interfaces.
Interfaces cannot extend a class, or implement a class or interface.
Page 183
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define IS-A and HAS-A relationship
When two classes are related, but not through inheritance, (for example, one class has a reference
to another class) then you say that the two classes are joined by HAS-A relationship. Examples for
HAS-A relationship:
Bathroom HAS-A Tub
Tub HAS-A Bubble
Do not apply inheritance if the subclass and super class do not pass the IS-A test. Always ask
yourself if the subclass IS-A more specific type of the super class.
Example: Tea IS-A beverage makes sense. Beverage IS-A tea does not make sense.
The IS-A relationship implies that if X IS-A Y, then X can do anything a Y can do (and possibly
more).
Examples:
If class B extends class A, then class B IS-A class A.
If class C extends class B, then class C passes the IS-A test for both B and A.
Triangle IS-A Shape makes sense, so you can have Triangle extends Shape. But the
reverse, Shape IS-A Triangle does not make sense, so Shape should not extend
Triangle.
Page 184
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that illustrates the HAS-A relationship between Horse and Halter.
Code:
public class Animal { }
Refer Files: Animal.java, Halter.java, Horse.java to obtain soft copy of the program code
How It Works:
A Horse IS-A Animal. A Horse HAS-A Halter.
The following point summarizes the HAS-A relationship between Horse and Halter.
Horse class has a Halter, because Horse declares an instance variable of type Halter.
When code invokes tie() on a Horse instance, the Horse invokes tie() on the Halter
instance variable of the Horse object.
Solution:
Make a class that does not extend anything (other than Object) when your new class
does not pass the IS-A test for any other type.
Make a subclass (in other words, extend a class) only when you need to make a more
specific version of a class and need to override or add new behaviors.
Use an abstract class when you want to define a template for a group of subclasses,
and you have at least some implementation code that all subclasses could use. Make
the class abstract when you want to guarantee that nobody can make objects of that
type.
Page 185
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Use an interface when you want to define a role that other classes can play,
regardless of where those classes are in the inheritance tree.
Summary
IS-A refers to inheritance.
IS-A is expressed with the keyword extends.
IS-A, “inherits from” and “is a subtype of” are all equivalent expressions.
HAS-A means an instance of one class “has a” reference to an instance of another
class or another instance of the same class.
Page 186
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define a “Type”?
Cast Primitive Types
Describe Implicit Type Casting
Explain Explicit Type Casting
Cast Objects
What is a “Type”?
When an object instance is created from a class, you say the object instance is “type” of the class
and its super classes.
Significance of Type
An object instance of a particular type can be used in any place where an instance of the type and
its super type is called for.
Example:
student1 object instance is a “type” of TuftsStudent, Student, and Person
student1 object can be used in any place where object instance of the type of
TuftsStudent, Student, or Person is called for
This enables polymorphism.
There is one primitive data type that you cannot do casting though, and that is the boolean data
type
Types of Casting:
Implicit Casting
Explicit Casting
Page 187
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Implicit Casting
Suppose you want to store a value of int data type to a variable of data type double.
int numInt = 10;
double numDouble = numInt; //implicit cast
In this example, as the data type (double) of the destination variable holds a larger value than the
data type (int) of the value, the data is implicitly casted to the data type double of the destination
variable.
Explicit Casting
When you convert a data that has a large type to a smaller type, you must use an explicit cast.
Explicit casts take the following form:
(Type)value
where, Type is the name of the type you are converting to and value is an expression that results
in the value of the source type.
Casting Objects
Instances of classes also can be cast into instances of other classes, with one restriction. The
source and destination classes must be related by inheritance. One class must be a subclass of
the other.
Casting objects is analogous to converting a primitive value to a larger type, some objects might
not need to be cast explicitly.
Page 188
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Cast (classname)object where, classname is the name of the destination class and object is a
reference to the source object
Example:
Assume Student class as a child class of Person class
Assume CollegeStudent class as a child class of Student class
CollegeStudent collegeStudent = new CollegeStudent();
Student student = collegeStudent; // Implicit type casting
Person person = collegeStudent; // Implicit type casting
Object object = collegeStudent; // Implicit type casting
collegeStudent
CollegeStudent
student Object instance
person
Page 189
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
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
Assume Teacher class is also a child class of Person class
Person person1 = new Student();
Person person2 = new Teacher();
Student student1 = (Student) person1; // Explicit type casting
// No compile error, but runtime type mismatch exception
Student student2 = (Student) person2;
Example:
Person person1 = new Student();
Person person2 = new Teacher();
Try It Out
Problem Statement:
Write a program that illustrates the use of Casting Object References.
Page 190
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Code:
import java.util.*;
class CastObjRef {
public static void main(String args[]) {
String s1 = "abc";
String s2 = "def";
Vector v = new Vector();
v.add(s1);
s2 = (String) v.elementAt(0);
System.out.println(s2);
}
}
Refer File Name: CastObjRef.java to obtain soft copy of the program code
How It Works:
When you run the program, it produces the following result:
abc
Without the (String) cast operator, the result returned by v.elementAt(0) is an object of
the Object class.
The compiler recognizes this inconsistency and generates an error message.
When the (String) cast operator is used, the compiler recognizes that you are casting
the reference to an Object object into a String object and proceeds with the
compilation.
Solution:
Casting of Primitives:
Explicit type casting is required for the narrow conversion of primitive data types.
Can cast any type that is not boolean type to another type that is not boolean
Cannot cast a boolean or to a boolean type
Cast operator, instanceof operator and the == operator behave in the same way in allowing
references to be the operands of them. You cannot cast or apply instanceof or compare unrelated
references, sibling references or any incompatible references.
Page 191
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Compile-time rules: When old and new types are classes, one class must be the subclass of the
other.
When old and new types are arrays, both must contain reference types and it must be legal to cast
between those types (primitive arrays cannot be cast, conversion possible only between same
type of primitive arrays).
You can always cast between an interface and an object that is not final.
Run-time rules:
If new type is a class, then the class of the expression being converted must be new
type or extend new type.
If new type is an interface, then the class of the expression being converted must
implement the interface.
Summary
Reference Variable Casting: There are two types of reference variable casting:
downcasting and upcasting.
o Downcasting: If you have a reference variable that refers to a subtype object, you
can assign it to a reference variable of the subtype. You must make an explicit
cast to do this, and the result is that you can access the subtype’s members with
this new reference variable.
o Upcasting: You can assign a reference variable to a supertype reference variable
explicitly or implicitly. This is an inherently safe operation because the assignment
restricts the access capabilities of the new variable.
Page 192
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Identify inner classes, static nested classes, and, anonymous classes
Inner Class
Inner class is a class declared within another class
Accessing the members of the inner class:
Need to instantiate an object instance of an inner class first
Example:
innerObj.innerMember = 5;
//innerObj is an instance of the inner class
//innerMember is a member of the inner class
Page 193
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
class Test {
public static void main(String[] args) {
OuterClass.InnerClass inner = new OuterClass.InnerClass();
inner.sayIt();
}
}
Page 194
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Anonymous Classes
It is common in Java programming to encounter situations where you need to create
an object but do not need to bother giving it an explicit name.
With the inner classes you can take this to another level by creating and instantiating a
class without bothering to give it a name. This is called as an anonymous class.
This anonymity eliminates a lot unnecessary named objects and makes the code more
readable.
);
add(fBt);
}
} // class AnOuterClass
Now the compiler will create a class file name AnOuterClass$1.class where a number, in this case
"1", is used to identify the class files for anonymous inner classes.
Try It Out
Problem Statement:
Write a program that illustrates the use of an instance of an inner class and an outer class.
Page 195
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Code:
class Outer {
String s = "Outer";
class Inner {
String s = "Inner";
Inner() {
System.out.println(this.s);
System.out.println(Outer.this.s);
}
}
}
Refer File Name: Outer.java to obtain soft copy of the program code
How It Works:
The program displays the line Inner followed by the line Outer.
In the Inner() constructor, this.s, yields the value of the s variable corresponding to the
Inner class and Outer.this.s refers to the s variable of the Outer class.
To refer to the instance of an outer class preponed the outer class name and a period
to this.
Page 196
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Direct Defines
Declaration Accessibility Outer access to static or non-
Entity
context Modifiers instance enclosing static
context members
All members
In block with in enclosing
Local class Only non-
non-static None Yes context +
(non-static) static
context local final
variables
Static
members in
Local class In block with enclosing Only non-
None No
(static) static context context + static
local final
variables
All members
Non static As non-static Only non-
All Yes in enclosing
inner class class member static
context
All members
Anonymous In block with in enclosing
Only non-
class (non- non-static None Yes context +
static
static) context local final
variables
Static
members in
Anonymous In block with enclosing Only non-
None No
class (static) static context context + static
local final
variables
static
Package level As package public or variables and
No N/A
interface member default non-static
prototypes
static
Top level Static
variables and
nested As static class members in
All No non-static
interface member enclosing
method
(static) context
prototypes
Summary
Inner Classes:
A “regular” inner class is declared inside the curly braces of another class, but outside
any method or other code block.
To instantiate an inner class, you must have a reference to an instance of the outer
class.
Page 197
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 198
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to describe the process of debugging Web
applications using the following views in SDE:
Breakpoint view
Console view
Debug view
Display view
Expressions view
Registers view
Breakpoint View
Breakpoints are indicators to the debugger that it should stop execution at specific
places in the code, and let you step through it.
A breakpoint causes the execution of a thread to suspend at the location where the
breakpoint is set.
Breakpoints view lists all the breakpoints you have set in the workbench projects.
In this view, you can double-click a breakpoint to display its location in the editor.
You can also enable or disable breakpoints, delete them, or add new ones.
Breakpoints can be set to trigger always or when a certain condition has been met.
The Breakpoints view lists Java exception breakpoints, which suspend execution at
the point where the exception is thrown. You can add or remove exceptions.
To add a breakpoint in the code, do the following:
Open the file in the Java editor
Place your cursor in the grey bar (along the left edge of the editor area) on the line
Double-click to set a breakpoint and a marker will be shown at the line
Console View
This view shows the output of the execution of your program and allows you to enter input for the
program.
You can choose the different colors for these kinds of text on the preferences pages. (Window >
Preferences > Run/Debug > Console).
Page 199
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Debug View
This view allows you to manage the debugging or running of a program in the
workbench.
It displays the stack frame for the suspended threads for each target you are
debugging.
Each thread in your program appears as a node in the tree.
It displays the process for each target you are running.
If the thread is suspended, then its stack frames are shown as child elements.
Display View
This view displays the result of evaluating an expression in the context of the current
stack frame.
You can evaluate and display a selection either from the editor or directly from the
Display view.
Expressions View
Data can be inspected in the Expressions view.
You can inspect data from a scrapbook page, a stack frame of a suspended thread,
and other places.
The Expressions view opens automatically when the Inspect command is activated.
Registers View
You can view the contents of a register from the Registers view.
To view the contents of a register in the Register view:
In the Debug view, select the thread for which you want to view the registers.
In the Registers view, expand the register group that you want to view.
If necessary, use the scroll bars or PageUp and PageDown keys to scroll the Register
view until the register is visible.
Nodes in the Registers view are visible if they are at the top level of the tree structure,
or if the nodes at a level higher have been expanded.
For all nodes that are visible in this view, you can jump to a specific node by typing the
first letter of the node.
The view will jump to the next node that begins with that letter.
Page 200
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Solution:
When a thread is suspended, the step controls can be used to step through the
execution of the program line-by-line.
Step Over: The currently selected line is executed and suspends on the next
executable line. Click on Run > Step Over in the tool bar or press F6 key to perform
this operation.
Step Into: The next expression on the currently selected line to be executed is
invoked, and execution suspends at the next executable line in the method that is
invoked. Click on Run > Step Into in the tool bar or press F5 key.
Step Return: Execution resumes until the next return statement in the current method
is executed, and execution suspends on the next executable line. Click on Run > Step
Return in the tool bar or press F7 key.
Summary
Breakpoints view lists all the breakpoints you have set in the workbench projects.
Console view shows the output of the execution of your program and allows you to
enter input for the program.
Debug view allows you to manage the debugging or running of a program in the
workbench.
Display view displays the result of evaluating an expression in the context of the
current stack frame.
Data can be inspected in the Expressions view.
Registers view displays the contents of a register.
Page 201
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define an exception
Identify what happens when an exception occurs
List the benefits of Exception Handling framework
Catch exceptions with try-catch and finally
Exception
Exceptional event
Error that occurs during run-time
Cause normal program flow to be disrupted
Examples are:
Divide by zero errors
Accessing the elements of an array beyond its range
Invalid input
Hard disk crash
Opening a file that does not exist
Heap memory exhausted
Exception Example
1 class DivByZero {
2 public static void main(String args[]) {
3 System.out.println(3/0);
4 System.out.println(“Pls. print me.”);
5 }
6 }
Page 202
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
When an appropriate handler is found, the run-time system passes the exception to
the handler:
An exception handler is considered appropriate if the type of the exception object
thrown matches the type that can be handled by the handler.
The exception handler chosen is said to catch the exception.
If the run-time system exhaustively searches all the methods on the call stack without
finding an appropriate exception handler, then the run-time system (and,
consequently, the program) terminates and uses the default exception handler.
Page 203
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Consider the pseudo code method here that reads an entire file into memory:
readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
Page 204
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 205
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Exception class:
Conditions that user programs can reasonably deal with
Usually the result of some flaws in the user program code
Examples:
o Division by zero error
o Array out-of-bounds error
Error class:
Used by the Java run-time system to handle errors occurring in the run-time
environment
Generally beyond the control of user programs
Examples:
o Out of memory errors
o Hard disk crash
Page 206
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 207
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 208
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 209
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
18 System.out.println("try-block entered.");
19 }
20 }
21 //continued
22 public static void main(String args[]){
23 for (int i=1; i<=4; i++) {
24 try {
25 FinallyDemo.myMethod(i);
26 } catch (Exception e){
27 System.out.print("Exception caught: ");
28 System.out.println(e.getMessage());
29 }
30 System.out.println();
31 }
32 }
33 }
Try It Out
Problem Statement:
Write a program that illustrates the importance of handling classes in the Exception Hierarchy.
Code:
import java.io.*;
Refer File Name: ExceptionHierarchyApp.java to obtain soft copy of the program code
Page 210
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
How It Works:
When you run the program, it produces the following result:
File not found myfile.txt (The system cannot find the file specified)
java.io.FileNotFoundException: myfile.txt (The system cannot find the
file specified)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(Unknown Source)
at java.io.RandomAccessFile.<init>(Unknown Source)
at ExceptionHierarchyApp.main(ExceptionHierarchyApp.java:6)
This program attempts to open a file and read some data from it.
Opening and reading files can generate many exceptions, most of which are some
type of IOException.
Imagine that in this program you are interested in knowing only whether the exact
exception is a FileNotFoundException.
FileNotFoundException is a subclass of IOException.
You can handle it in the catch clause that catches all subtypes of IOException, but
then you will have to test the exception to determine whether it was a
FileNotFoundException.
Instead, you have coded a special exception handler for the FileNotFoundException
and a separate exception handler for all other IOException subtypes.
If this code generates a FileNotFoundException, then it will be handled by the catch
clause related to FileNotFoundException.
If it generates another IOException perhaps EOFException, which is a subclass of
IOException, then it will be handled by the catch clause related to IOException.
If some other exception is generated, such as a run time exception of some type, then
neither catch clause will be executed nor the exception will be propagated down the
call stack.
Notice that the catch clause for the FileNotFoundException has been placed before
the handler for the IOException. This is really important.
If you do it in the opposite way, then the program will not compile.
The handlers for the most specific exceptions must always be placed before those for
more general exceptions.
The following program will not compile:
try {
// do risky IO things
} catch (IOException ioe) {
// handle general IOExceptions
} catch (IOException ioe) {
// handle general IOExceptions
}
You will get a compiler error message like this:
Unreachable catch block for FileNotFoundException. It is already handled by the catch
block for IOException.
Page 211
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Solution:
You cannot have a catch or finally without a try.
void go() {
Foo f = new Foo();
f.foof();
catch(FooException fe) { }
}
You cannot put code between the try and the catch.
try {
x.doStuff();
}
int y = 50;
} catch(FooException fe) { }
A try with only a finally (no catch) must still declare the exception.
void go() throws FooException {
try {
x.doStuff();
} finally { }
}
Summary
Exceptions come in two flavours: checked and unchecked.
Checked exceptions include all subtypes of Exception, excluding classes that extend
RuntimeException.
Checked exceptions are subject to the handle or declare rule; any method that might
throw a checked exception must either declare the exception using throws, or handle
the exception with an appropriate try/catch.
Subtypes of Error or RuntimeException are unchecked.
If you use an optional finally block, it will always be invoked, regardless of whether an
exception in the corresponding try is thrown or not, and regardless of whether a
thrown exception is caught or not.
Page 212
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The only exception to the finally-will-always-be-called true is that a finally will not be
invoked if the JVM shuts down. That could happen if code from the try or catch blocks
calls System.exit().
Just because finally is invoked does not mean it will complete. Code in the finally block
could itself raise an exception or issue a System.exit().
Page 213
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Throw Exceptions
Apply Throw and Throws clauses
Propagate exceptions
Example:
throw new ArithmeticException(“testing...”);
Page 214
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Suppose also that method1 is the only method interested in the errors that might occur within
readFile.
method1 {
call method2;
}
method2 {
call method3;
}
method3 {
call readFile;
}
Page 215
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 216
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that looks for code that invokes a method declaring an exception, where the
calling method does not handle or declare the checked exception.
Code:
import java.io.IOException;
void doMore() {
throw new IOException();
}
}
Refer File Name: ExceptionThrowApp.java to obtain soft copy of the program code
How It Works:
First, the doMore() method throws a checked exception, but does not declare it.
But suppose you fix the doMore() method like the following:
void doMore() throws IOException { … }
The doStuff() method is still in trouble, because it, too, must declare the IOException,
unless it handles it by providing a try or catch, with a catch clause that can take an
IOException.
Solution:
If you throw an exception in your code, then you must declare it using the throws
keyword in your method declaration.
If you call a method that throws an exception (in other words, a method that declares it
throws an exception), then you must acknowledge that you are aware of the exception
possibility. One way to satisfy the compiler is to wrap the call in a try or catch.
Page 217
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
Uncaught exceptions propagate back through the call stack, starting from the method
where the exception is thrown and ending with either the first method that has a
corresponding catch for that exception type or a JVM shutdown.
Subtypes of Error or RuntimeException are unchecked, so the compiler does not
enforce the handle or declare rule. You are free to handle them, or to declare them,
but the compiler does not care one way or the other.
Page 218
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Identify Checked and Unchecked exception
Create your own exception
Describe Run time exception
Page 219
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
8 System.out.println("Accept string.");
9 } catch (HateStringExp e) {
10 System.out.println("Hate string!”);
11 }
12 }
13 }
Try It Out
Problem Statement:
Write a program that illustrates the creation and usage of your own exceptions.
Code:
import java.io.*;
Refer File Name: ExceptionTest.java to obtain soft copy of the program code
How It Works:
The ExceptionTest program reads a character entered by the user.
It then throws and catches a VowelException, BlankException, or ExitException based
on the input of the user.
Page 220
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 221
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The finally clause is always executed, no matter what happens during the execution of
a try statement.
Go ahead and type x to exit the ExceptionTest program. The program displays the
output as shown below:
o Enter a character: x
o An exit exception occurred.
o This is the finally clause.
The program then returns you to the command prompt.
The output acknowledges the fact that the Exit Exception was thrown by
processUserInput() and caught by main().
Solution:
Most run time exceptions come from a problem in your code logic, rather than
conditions that fails at run time in ways that you cannot predict or prevent. You cannot
guarantee that the file is there. You cannot guarantee the server is up. But you can
make sure your code does not index off the end of an array (that is what the .length
attribute is for).
You want run time exceptions to happen at development and testing time. You do not
want to code in a try or catch.
A try or catch is for handling exceptional situations and not flaws in your code. Use
your catch blocks to try to recover from situations that you cannot guarantee will
succeed. Or at the very least, print out a message to the use and a stack trace, so that
somebody can figure out what had happened.
Summary
You can create your own exceptions, normally by extending Exception or one of its
subtypes. Your exception will then be considered a checked exception, and the
compiler will enforce the handle or declare rule for that exception.
All catch blocks must be ordered from most specific to most general. If you have a
catch clause for both IOException and Exception, you must put the catch for
IOException and Exception, you must put the catch for IOException first in your code.
The compiler will stop you from defining catch clauses that can never be reached.
Some exceptions are created by programmers, some by the JVM.
Page 222
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Identify the String class and its methods
Page 223
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that illustrates the usage of String constructors.
Code:
class StringConstructors {
public static void main(String args[]) {
String s1 = new String(); // empty string
char chars[] = { 'h', 'e', 'l', 'l', 'o' };
String s2 = new String(chars); // s2="hello";
byte bytes[] = { 'w', 'o', 'r', 'l', 'd' };
Page 224
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Refer File Name: StringConstructors.java to obtain soft copy of the program code
How It Works:
When you run the program, it produces the following results:
hello
world
ell
hello
hello
Solution:
Strings are immutable.
They can be created from a literal, a byte array, a char array, or a string buffer.
A String created by a new operator is always a different new object, even if it is
created from a literal.
All string operations (concat, trim, replace, substring, and so on) construct and return
new strings.
toUpperCase and toLowerCase will return the same string if no case conversion was
needed.
Passing null to indexOf or lastIndexOf will throw NullPointerrException, passing empty
string returns zero, and passing a string that is not in the target string returns -1.
trim method removes all leading and trailing white-space from a String and returns a
new String. White spaces means, all characters with values less than or equal to the
space character – ‘\u0020’.
String class is final.
= and += operators are overloaded for Strings.
reverse, append, and insert are not String methods.
Page 225
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
String objects are immutable, and String reference variables are not.
If you create a new String without assigning it, it will be lost to your program.
If you redirect a String reference to a new String, the old String can be lost.
String methods use zero-based indexes, except for the second argument of
substring().
The String class is final – its methods can’t be overridden.
Page 226
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Write Java programs using String class
Page 227
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
35 substring*/
36 System.out.println("A substring of name: " +
37 name.substring(0, 2));
38 //continued...
39 System.out.println("Trim \" a b c d e f \": \"" +
40 " a b c d e f ".trim() + "\"");
41 System.out.println("String representation of boolean
42 expression 10>10: " + String.valueOf(10>10));
43 /* toString method is implicitly called in the println
44 method*/
45 System.out.println("String representation of boolean
46 expression 10<10: " + (10<10));
47 /* Note there's no change in the String object name
48 even after applying all these methods. */
49 System.out.println("name: " + name);
50 }
51 }
Try It Out
Problem Statement:
Write a program that illustrates the usage of various methods available in the String class.
Code:
public class StringApp {
public static void main(String args[]) {
String s = " Java 2 Certification ";
System.out.println(s);
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println("[" + s + "]");
s = s.trim();
System.out.println("[" + s + "]");
s = s.replace('J', 'X');
s = s.replace('C', 'Y');
s = s.replace('2', 'Z');
System.out.println(s);
// continued …
Refer File Name: StringApp.java to obtain soft copy of the program code
Page 228
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
How It Works:
This program performs several manipulations of a string s, which is initially set to "
Java 2 Certification ".
It prints the original string and then prints uppercase and lowercase versions of it,
illustrating the use of the toUpperCase() and toLowerCase() methods.
It prints the string enclosed between two braces to show that it contains leading and
trailing spaces.
It then trims away these spaces using the trim() method and reprints the string to show
that these spaces were removed.
The program uses the replace() method to replace 'J‘ , 'C‘ , and '2' with 'X', 'Y', and 'Z',
and prints out the string to show the changes.
The replace() method is case sensitive.
It uses the indexOf() method to get the indices of 'X', 'Y', and 'Z' within s.
It uses the toCharArray() to convert the string to a char array.
It then uses the indices to put 'J', 'C', and '2' back in their proper locations within the
character array.
The String() constructor is used to construct a new string from the character array.
The new string is assigned to s and is printed.
The output of the program is as follows:
Java 2 Certification
JAVA 2 CERTIFICATION
java 2 certification
[ Java 2 Certification ]
[Java 2 Certification]
Xava Z Yertification
Java 2 Certification
Solution:
String concatenation process will add a string with the value of “null”, if an object
reference is null and that object is appearing in a concatenation expression by itself.
But if you try to access its members or methods, then a NullPointerException is
thrown.
The same is true for arrays. Array name is replaced with null, but trying to index it
when the null of it throws a NullPointerException.
Summary
String methods to remember are charAt(), concat(), equalsIgnoreCase(), length(),
replace(), substring(), toLowerCase(), toString(), toUpperCase(), and trim().
Strings have a method: length(); arrays have an attribute named length.
When the JVM finds a String literal, it is added to the String literal pool.
Remember that chained methods are evaluated from left to right.
Page 229
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 230
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Identify equals() method and hashCode() method
Try It Out
Problem Statement:
Write a program that illustrates the usage of equals() and hashCode() methods.
Code:
class HashHash {
public int x;
Page 231
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
if (h.x == this.x) {
return true;
} else {
return false;
}
}
Refer File Name: HashHash.java to obtain soft copy of the program code
How It Works:
This program has overridden both the equals() and hashCode() methods.
Notice that in order for an object to be located, the search object and the object in the
collection must have both identical hashcode values and return true for the equals()
method.
So there is just no way out of overriding both methods to be absolutely certain that
your objects can be applied in Collections that implement hashing.
Solution:
HashSets use hashcodes to store the elements in a way that makes it much faster to
access. If you try to find an object in an ArrayList by giving the ArrayList a copy of the
object (as opposed to an index value), then the ArrayList has to start searching from
the beginning, looking at each element in the list to see if it matches. But a HashSet
can find an object more quickly, because it uses the hashcode as a kind of label on
the “bucket” where it stored the element.
Hashcodes can be the same without necessarily guaranteeing that the objects are
equal, because the “hashing algorithm” applied in the hashCode() method might
happen to return the same value for multiple Objects. This means that multiple objects
would all land in the same bucket in the HashSet.
Hashcode values are sometimes used to narrow down the search, but to find the one
exact match, the HashSet still has to take all the objects in that one bucket (the bucket
for all objects with the same hashcode) and then call equals() on them to see if the
object it is looking for is in that bucket.
Page 232
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
equals(), hashCode(), and toString() are public.
When overridding equals(), use the instanceof operator to be sure you are evaluating
an appropriate class.
Highlights of the equals() contract:
o Reflexive: x.equals(x) is true.
o Symmetric: if x.equals(y) is true, then y.equals(x) must be true.
o Transitive: if x.equals(y) is true, and y.equals(z) is true, then z.equals(x) is true.
o Consistent: Multiple calls to x.equals(y) will return the same result.
o Null: If x.equals(y) is true, then x.hashCode() == y.hashCode() is true.
o If you override equals(), override hashCode().
Highlights of the hashCode() contract:
o Consistent: multiple calls to x.hashCode() return the same integer.
o If x.equals(y) is true, x.hashCode() == y.hashCode() is true.
o If x.equals(y) is false, then x.hashcode() == y.hashCode() can be either true or
false, but false will tend to create better efficiency.
o transient variables are not appropriate for equals() and hashCode().
Page 233
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define StringBuffer and StringBuilder
Page 234
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
5 /* initial capacity is 16 */
6 System.out.println("capacity of sb: "+sb.capacity());
7 System.out.println("append \'O\' to sb: " +
8 sb.append('O'));
9 System.out.println("sb = " + sb);
10 System.out.println("3rd character of sb: " +
11 sb.charAt(2));
12
13 char charArr[] = "Hi XX".toCharArray();
14 /* Need to add 1 to the endSrc index of getChars */
15 sb.getChars(0, 2, charArr, 3);
16 System.out.print("getChars method: ");
17 System.out.println(charArr);
18 System.out.println("Insert \'jo\' at the 3rd cell: "
19 + sb.insert(2, "jo"));
20 System.out.println("Delete \'jo\' at the 3rd cell: "
21 + sb.delete(2,4));
22 System.out.println("length of sb: " + sb.length());
23
24 System.out.println("replace: " +
25 sb.replace(3, 9, " Ong"));
26 /* Need to add 1 to the endIndex parameter of
27 substring*/
28 System.out.println("substring (1st two characters): "
29 + sb.substring(0, 3));
30 System.out.println("implicit toString(): " + sb);
31 }
32 }
Page 235
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The String class defines a new constructor that enables you to construct a String from
a StringBuilder as shown in the following code:
String(StringBuilder strBuildObj)
Try It Out
Problem Statement:
Write a program that illustrates the manipulation of the StringBuffer objects using the append() ,
insert() , and setCharAt() methods.
Code:
public class StringBufferApp {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer(" is ");
sb.append("Hot");
sb.append('!');
sb.insert(0, "Java");
sb.append('\n');
sb.append("This is ");
sb.append(true);
sb.setCharAt(21, 'T');
sb.append('\n');
sb.append("Java is #");
sb.append(1);
String s = sb.toString();
System.out.println(s);
}
}
Refer File Name: StringBufferApp.java to obtain soft copy of the program code
How It Works:
The program creates a StringBuffer object using the string " is ". It appends the string
"Hot" using the append() method and the character '!' using an overloaded version of
the same method.
The insert() method is used to insert the string "Java" at the beginning of the string
buffer.
Three append methods are used respectively to tack on the following:
o A new line character (\n), the string "This is ", and the boolean value true.
The append() method is overloaded to support the appending of the primitive data
types as well as arbitrary Java objects.
The setCharAt() method is used to replace the letter 't' at index 21 with the letter 'T‘ .
The charAt() and setCharAt() methods allow StringBuffer objects to be treated as
arrays of characters.
Finally, another newline character is appended to sb, followed by the string "Java is #"
and the int value 1.
Page 236
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The StringBuffer object is then converted to a string and displayed to the console
window.
The output of the program is as follows:
Java is Hot!
This is True
Java is #1
Solution:
String Buffers are mutable strings.
StringBuffer is a final class.
They can be created empty, from a string or with a capacity. An empty StringBuffer is
created with 16-character capacity. A StringBuffer created from a String has the
capacity of the length of String + 16. StringBuffer created with the specified capacity
has the exact capacity specified. As they can grow dynamically in size without bounds,
capacity does not have much effect.
append, insert, setCharAt, and reverse are used to manipulate the string buffer.
setLength changes the length. If the current content is larger than specified length,
then it is truncated. If it is smaller than the specified length, then nulls are padded. This
method does not affect the capacity.
equals on StringBuffer does a shallow comparison (same like ==) and will return true
only if the objects are same. Do not use it to test content equality.
trim is not a StringBuffer method.
There is no relationship between String and StringBuffer. Both extend Object class.
String context means, ‘+’ operator appearing with one String operand. String
concatenation cannot be applied to StringBuffer.
A new StringBuffer is created.
All operands are appended by calling toString method, if needed.
Finally a string is returned by calling toString on the StringBuffer.
Summary
The StringBuffer’s API is the same as the new StringBuilder’s API, except that
StringBuilder’s methods are not synchronized for thread safety.
StringBuilder methods should run faster than StringBuffer methods.
All of the following apply to both StringBuffer and StringBuilder:
They are mutable – they can change without creating a new object.
StringBuffer methods act on the invoking object, and objects can change without an
explicit assignment in the statement.
StringBuffer equals() is not overridden; it doesn’t compare values.
StringBuffer methods to remember: append(), delete(), insert(), reverse(), and
toString().
Page 237
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 238
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
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.
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
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.
“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.
// Bulk operations
boolean containsAll(Collection<?> c);
Page 241
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
// Array operations
Object[] toArray();
<T> T[] toArray(T[] a);
}
boolean b1 = c1.isEmpty();
boolean b2 = c1.add(new Integer(1))
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.
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.*;
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.
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 Collection: Represents the data structure in which objects are stored
o Collection: java.util interface from which Set and List extend
o Collections: A class that holds static collection utility methods
Four basic sub-flavors of collections: Sorted, Unsorted, Ordered, Unordered
o Ordered: Iterating through a collection in a specific, non-random order.
o Sorted: Iterating through a collection in a sorted order.
Sorting can be alphabetic, numeric, or programmer-defined.
Page 245
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Set Interface and Implementations
List Interface and Implementations
Map Interface and Implementations
Queue Interface and Implementations
Define Abstract Classes
Explain Routine Data Manipulation
Describe Searching
Define Composition
“Set” Interface
The Set interface is a collection that cannot contain duplicate elements.
The Set interface models the mathematical set abstraction and is used to represent sets:
Cards comprising a poker hand
Courses making up the schedule of a student
The processes running on a machine
The Set interface contains only methods inherited from Collection and adds the restriction to
prohibit the duplicate elements.
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional
Page 246
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
// Array Operations
Object[] toArray();
<T> T[] toArray(T[] a);
}
“SortedSet” Interface
Sorted Set interface is a set that maintains its elements in ascending order. Several additional
operations are provided to take advantage of the ordering.
Sorted sets are used for naturally ordered sets, such as word lists and membership roll.
HashSet
HashSet is much faster than TreeSet (constant-time versus log-time for most
operations) but offers no ordering guarantees.
HashSet is the mostly commonly used implementation.
Page 247
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
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.
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");
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.
ts2.add(2);
ts2.add(1);
ts2.add(3);
ts2.add(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).
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);
}
“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
// 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();
“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.
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.
Abstract Classes
Abstract classes include the following abstract implementations:
AbstractCollection
AbstractSet
AbstractList
AbstractSequentialList
AbstractMap
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);
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.*;
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.
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
Handout - Core Java
Interfaces
Data structures
used to
implement Set SortedSet List Map SortedMap
HashTable HashSet This field is This field is HashMap (Nulls This field is blank.
(Nulls blank. blank. OK)
OK) HashTable (No
Nulls)
Resizable Array This field This field is ArrayList This field is This field is blank.
is blank. blank. (Nulls OK) blank.
Vector (Nulls
OK)
Balanced Tree This field TreeSet This field is This field is TreeMap
is blank. blank. blank.
Linked List This field This field is LinkedList This field is This field is blank.
is blank. blank. (Nulls OK) blank.
Summary
The four basic flavors of collections include Lists, Sets, Maps, Queues:
Lists of things Ordered, duplicates allowed, with an index.
Sets of things May or may not be ordered and/or sorted;
duplicates not allowed.
Maps of things with keys May or may not be ordered and/or sorted;
Duplicate keys are not allowed.
Queues of things to process Ordered by FIFO or by priority.
Page 255
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Describe the two schemes of Traversing Collections
Define Iterator interface and Iterable Interface
Apply Iterator
Iterator Interface
public interface Iterator {
boolean hasNext();
Object next();
void remove(); //optional
}
hasNext() method returns true if the iteration has more elements.
next() method returns the next element in the iteration.
remove() is the only safe way to modify a collection during iteration. The behavior is
unspecified if the underlying collection is modified in any other way while the iteration
is in progress.
Page 256
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that illustrates the usage of List and an Iterator.
Code:
import java.util.*;
class Dog {
public String name;
Dog(String n) {
name = n;
}
}
class IteratorTest {
public static void main(String[] args) {
List<Dog> d = new ArrayList<Dog>();
Dog dog = new Dog("aiko");
d.add(dog);
d.add(new Dog("clover"));
d.add(new Dog("magnolia"));
Iterator<Dog> itr = d.iterator(); // make an iterator
while (itr.hasNext()) {
Dog d2 = itr.next(); // cast not required
System.out.println(d2.name);
}
Page 257
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Refer File Name: IteratorTest.java to obtain soft copy of the program code
How It Works:
When you run IteratorTest, it displays the following results:
aiko
clover
magnolia
size 3
get1 clover
aiko 0
oa aiko
oa clover
Firstly, you have used generics syntax to create the Iterator (an Iterator of type Dog).
Because of this, when you have used the next() method, you did not have to cast the
object returned by next() to a Dog.
You could have declared the Iterator like this (on using JDK1.4 or lesser version):
Iterator itr = d.iterator; // make an Iterator
But then you would have had to cast the following returned value:
Dog d2 = (Dog)itr.next();
The rest of the code demonstrates using the size() , get() , indexOf() , and toArray()
methods.
Note: Invoking hasNext() does not move the iterator to the next element of the
collection.
Page 258
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
Iterable is a generic interface that was added by Java 2, v5.0.
Iterable contains only one method as shown below:
Iterator<T> iterator()
The earlier method returns an Iterator to the elements contained in the invoking object.
Because the iterator() method of Iterable returns an Iterator, often a class that
implements Iterable will also implement Iterator.
Iterator is a generic class in Java 2, v5.0, when the entire Collections Framework was
retrofitted for generics.
Earlier versions of Iterator were not generic.
Page 259
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Identify java.util.Date and java.util.Properties classes
Page 260
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that illustrates the usage of java.util.Date class along with
java.util.GregorianCalendar and java.util.TimeZone classes in order to access date and time
information.
Code:
import java.util.*;
Refer File Name: DateApp.java to obtain soft copy of the program code
How It Works:
The program creates a Date object and a GregorianCalendar object using the default
Date() and GregorianCalendar() constructors.
The Date object is assigned to the today variable, and the GregorianCalendar object is
assigned to the cal variable.
The cal variable is updated with the current date by invoking its setTime() method with
the Date object stored in today.
The displayDateInfo() method is then invoked to display date and time information
about the cal variable.
The clear() method of the Calendar class is invoked to reset the date of the
GregorianCalendar object stored in cal.
The set() method is used to set its date to New Year's 2000. There are several
versions of the set() method, each of which takes a different set of parameters.
Page 261
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The version used in DateApp takes the year, month, and date as parameters.
Note that the month value ranges from zero to 12, where the year and date values
begin at one.
The displayDateInfo() method is invoked again to display information about the new
calendar date.
The displayDateInfo() method creates the days, months, and am_pm arrays to define
string values corresponding to the days of the week, months of the year, and a.m./p.m.
It then prints a line corresponding to date and time values.
These values are retrieved using the get() method of the Calendar class and the
Calendar constants corresponding to date and time values.
The getTimeZone() method of Calendar is invoked to retrieve the local TimeZone
object.
The getID() method of the TimeZone class is used to retrieve the local time zone ID
string.
Summary
The classes you need to understand are java.util.Date, java.util.Calendar,
java.text.DateFormat, java.text.NumberFormat, and java.util.Locale.
Most of the Date class’s methods have been deprecated.
A Date is stored as a long, the number of milliseconds since January 1, 1970.
Date objects are go-betweens the Calendar and Locale classes.
The Calendar provides a powerful set of methods to manipulate dates, performing
tasks such as getting days of the week, or adding some number of months or years to
a date.
The DateFormat.format() method is used to create Strings containing properly
formatted dates.
The Locale class is used in conjunction with DateFormat and NumberFormat.
Page 262
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define a thread
Identify the thread priorities
Threads
Threads are required to handle concurrent processes.
Definition of threads: Single sequential flow of control within a program
For simplicity, think of threads as processes executed by a program
Example:
o Operating System
o HotJava Web browser
The following diagram shows sequential program and multi-threaded program:
Thread Priorities
Priorities determine, which thread receives CPU control and gets to be executed first.
Definition: Integer value ranging from one to 10
Higher the thread priority larger is the chance of being executed first
Example:
Two threads are ready to run
First thread: priority of 5, already running
Second thread = priority of 10, comes in while first thread is running
Context switch: Occurs when a thread snatches the control of CPU from another
Page 263
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that illustrates the construction of threads and starting the threads.
Code:
class ThreadPriorityApp {
public static void main(String args[]) {
MyThread t1 = new MyThread("t1");
MyThread t2 = new MyThread("t2");
t1.start();
t2.start();
}
}
Refer File Name: ThreadPriorityApp.java to obtain soft copy of the program code
Page 264
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
How It Works:
When you run the program, the output sequence will vary from computer to computer. Also, the
output differs between each and every run.
Solution: Thread priorities might help you to influence the scheduler, but they still do not offer any
guarantee. Thread priorities are numerical values that tell the scheduler (if it cares) how important
a thread is to you. In general, the scheduler will kick a lower priority out of the running state if a
higher priority thread suddenly becomes runnable. Still, there is no guarantee. It is recommended
that you use priorities only if you want to influence performance, but never, ever rely on them for
program correctness.
Summary
Once a thread is started, it will always enter the runnable state.
The setPriority() method is use don Thread objects to give threads a priority of
between 1 (low) and 10 (high), although priorities are not guaranteed, and not all
JVMs recognize 10 distinct priority levels.
If not explicitly set, a thread’s priority will have the same priority as the priority of the
thread that created it.
Page 265
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The yield() method may cause a running thread to back out if there are runnable
threads of the same priority.
The closest thing to a guarantee is that at any given time, when a thread is running it
will usually not have a lower priority than any thread in the runnable state. If a low-
priority thread is running when a high priority thread enters runnable, the JVM will
usually preempt the running low-priority thread and put the high-priority thread in.
Page 266
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Identify Thread class and Runnable interface
Create Thread classes using the earlier concepts
Define Thread Group
Page 267
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 268
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 269
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
You can replace the class ExtendThreadClassTest2 and its main() method given earlier with the
following code:
14 class ExtendThreadClassTest3 {
15 public static void main(String args[]) {
16 new PrintNameThread("A");
17 new PrintNameThread("B");
18 }
19 }
Runnable Interface
The Runnable interface should be implemented by any class whose instances are
intended to be executed as a thread.
The class must define run() method of no arguments. The run() method is like main()
for the new thread.
The Runnable interface provides the means for a class to be active while not
subclassing Thread. A class that implements Runnable can run without subclassing
Thread by instantiating a Thread instance and passing itself in as the target.
String name;
PrintNameRunnable(String name) {
this.name = name;
}
Page 270
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
}
}
public class RunnableThreadTest1 {
Thread thread;
PrintNameRunnable(String name) {
thread = new Thread(this, name);
thread.start();
}
new PrintNameRunnable("B");
new PrintNameRunnable("C");
}
}
Page 271
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
ThreadGroup Class
A thread group represents a set of threads.
In addition, a thread group can also include other thread groups. The thread groups
form a tree in which every thread group except the initial thread group has a parent.
A thread is allowed to access information about its own thread group, but not to
access information about the parent thread group of the thread group or any other
thread groups.
Example: ThreadGroup
1 // Start three threads
2 new SimpleThread("Jamaica").start();
3 new SimpleThread("Fiji").start();
4 new SimpleThread("Bora Bora").start();
5
6 ThreadGroup group
7 = Thread.currentThread().getThreadGroup();
8
9 Thread[] tarray = new Thread[10];
10 int actualSize = group.enumerate(tarray);
11 for (int i=0; i<actualSize;i++){
12 System.out.println("Thread " +
13 tarray[i].getName() + " in thread group "
14 + group.getName());
15 }
Page 272
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that illustrates the usage of Runnable interface in the creation of threads.
Code:
class ThreadUsingRunnableApp {
public static void main(String args[]) {
Thread thread1 = new Thread(new MyClass("thread1: "));
Refer File Name: ThreadUsingRunnableApp.java to obtain soft copy of the program code
Refer File Name: ThreadUsingRunnableApp_output_on_two_executions.txt for the console
output on two different occasions
How It Works:
The advantage of using the Runnable interface is that your class does not need to
extend the Thread class. Instead, your class can extend some other required class, if
desired.
This is a very helpful feature when you create multithreaded applets.
The only disadvantage to this approach is that you have to do a little more work to
create and execute your threads.
Solution:
Yes, that is another way of making your own thread. Remember that there are two
things to be noticed, which are the Thread and the job of the thread. From an OO
view, those two are very separate activities, and belong to separate classes.
The only time you want to subclass or extend the Thread class is if you are making a
new and more specific type of Thread. In other words, if you think of the Thread as the
worker, then do not extend the Thread class unless you need more specific worker
behaviors.
Page 273
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
But if all you need is a new job to be run by a Thread or worker, then implement
Runnable in a separate class that is specific to job and not specific to worker.
This is a design issue and not a performance or language issue. It is perfectly legal to
subclass Thread and override then run() method, but it is rarely a good idea.
Summary
Threads can be created by extending Thread and overriding the public void run()
method.
Thread objects can also be created by calling the Thread constructor that takes a
Runnable argument. The Runnable object is said to be the target of the thread.
You can call start() on a Thread object only once. If start() is called more than once on
a Thread object, it will throw a RuntimeException.
It is legal to create many Thread objects using the same Runnable object as the
target.
When a Thread object is created, it does not become a thread of execution until its
start() method is invoked. When a Thread object exists but hasn’t been started, it is in
the new state and is not considered alive.
Page 274
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Describe Thread Synchronization
Explain lifecycle of threads
Identify wait() method and notify() method of the Object class
An Unsynchronized Example
1 class TwoStrings {
2 static void print(String str1, String str2) {
3 System.out.print(str1);
4 try {
5 Thread.sleep(500);
6 } catch (InterruptedException ie) {
7 }
8 System.out.println(str2);
9 }
10 }
11
12 class PrintStringsThread implements Runnable {
13 Thread thread;
14 String str1, str2;
15 PrintStringsThread(String str1, String str2) {
16 this.str1 = str1;
17 this.str2 = str2;
18 thread = new Thread(this);
19 thread.start();
20 }
21 public void run() {
22 TwoStrings.print(str1, str2);
23 }
24 }
Page 275
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
25
26 class TestThread {
27 public static void main(String args[]) {
28 new PrintStringsThread("Hello ", "there.");
29 new PrintStringsThread("How are ", "you?");
30 new PrintStringsThread("Thank you ",
31 "very much!");
32 }
33 }
Sample output:
Hello How are Thank you there.
you?
very much!
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
Page 276
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
20 thread.start();
21 }
22 public void run() {
23 TwoStrings.print(str1, str2);
24 }
25 }
26
27 class TestThread {
28 public static void main(String args[]) {
29 new PrintStringsThread("Hello ", "there.");
30 new PrintStringsThread("How are ", "you?");
31 new PrintStringsThread("Thank you ",
32 "very much!");
33 }
34 }
Page 277
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 278
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
notify() Method
notify() method wakes up a single thread that is waiting on the monitor of this object:
If any threads are waiting on this object, then one of them is chosen to be awakened.
The choice is arbitrary and occurs at the discretion of the implementation.
notify() method can only be used within synchronized code.
The awakened thread will not be able to proceed until the current thread relinquishes
the lock on this object.
Try It Out
Problem Statement:
Write a program that illustrates the usage of synchronized statement in thread synchronization.
Code:
class ThreadSynchronizedStmtApp extends Thread {
static String message[] = { "Java", "is", "hot,", "aromatic,",
"and",
"invigorating." };
Refer File Name: ThreadSynchronizedStmtApp.java to obtain soft copy of the program code
Refer File Name : ThreadSynchronizedStmtApp_output_on_two_executions.txt for the
console output on two different occasions
Page 279
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
How It Works:
The synchronized statement is similar to a synchronized method in that. It is used to
acquire a lock on an object before performing an action.
The synchronized statement differs from a synchronized method in that. It can be used
with the lock of any object. The synchronized method can only be used with the lock of
object or class.
It also differs in a way that it applies to a statement block, rather than an entire
method.
The syntax of the synchronized statement is as follows:
synchronized (object) {
statement(s)
}
The statements enclosed by the braces are only executed when the current thread
acquires the lock for the object or class enclosed by parentheses.
Solution:
No. Once the run() method of a thread has completed, the thread can never be
restarted. In fact, at that point the thread moves into the dead state. In the dead state,
the thread has finished its run() method and can never be restarted. The Thread object
might still be on the heap, as a living object that you can call other methods on (if
appropriate), but the Thread object has permanently lost its ‘threadness’. In other
words, the Thread object is no longer a thread. It is just an object, at that point, like all
other objects.
But, there are design patterns, for making a pool of threads that you can keep using to
perform different jobs. But you do not do it by restarting a dead thread.
Summary
Synchronized methods prevent more than one thread from accessing an object’s
critical method code simultaneously.
You can use the synchronized keyword as a method modifier, or to start a
synchronized block of code.
To synchronize a block of code, you must specify an argument that is the object
whose lock you want to synchronize on.
While only one thread can be accessing synchronized code of particular instance,
multiple threads can still access the same object’s unsynchronized code.
Static methods can be synchronized, using the lock from the java.lang.Class instance
representing that class.
Page 280
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 281
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
List the Concurrency Utilities
Concurrency Utilities
The Concurrency Utilities are:
Task Scheduling Framework
Callable's and Future's
Synchronizers
Concurrent Collections
Atomic Variables
Locks
Nanosecond-granularity timing
Page 282
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
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.
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
}
// Don't do this!
new Thread(r).start();
}
}
}
Page 284
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
return result;
}
}
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 Returns immediately if semaphore count is greater than zero
o Blocks if count is zero until release() is called by different thread
o aquire() and release() are thread safe atomic operations
Semaphore Example
private Semaphore available;
private Resource[] resources;
private boolean[] used;
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
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
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();
Page 288
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that illustrates the usage of wait() and notify() methods in controlling access to a
shared resource.
Code:
class ThreadUsingWaitAndNotifyApp {
public static void main(String args[]) {
Resource resource = new Resource();
Thread controller = new Thread(new Controller(resource));
Thread[] user = new Thread[3];
for (int i = 0; i < user.length; ++i)
user[i] = new Thread(new User(i, resource));
controller.start();
for (int i = 0; i < user.length; ++i)
user[i].start();
boolean alive;
out: do {
alive = false;
// continued …
How It Works:
A Resource object is shared among a Controller object and several User objects.
The Resource object provides access to the console display.
The User objects execute as separate threads and use the Resource object to display
their output.
The Controller object also executes as a separate thread and controls access to the
Resource object, making it available for output every 10 seconds.
The displayOutput() method of the Resource object displays a message on the
console when okToSend is true.
Page 289
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
If a User thread invokes displayOutput() when okToSend is false, then it enters the
waiting pool.
The allowOutput() method of Resource is periodically invoked by the Controller to
allow a User thread to exit the waiting pool and display output by the Resource object.
Note that the wait() method, like the sleep() method of the Thread class, throws the
InterruptedException.
This exception is thrown when the interrupt() method of a thread is invoked while it is
in the waiting state.
Solution:
Blocked Waiting
Thread is waiting to get a lock on the monitor. Thread has been asked to wait. (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. (or a blocking i/o method)
wait call.
Can move to ready only when the lock is Can move to ready only when it gets notified (by
available. (or the i/o operation is complete) means of notify() or notifyAll() )
Summary
When a thread goes to sleep, its locks will be unavailable to other threads.
All three methods namely wait(), notify(), and notifyAll() must be called from within a
synchronized context! A thread invokes wait() or notify() on a particular object, and the
thread must currently hold the lock on that object.
Basically, a wait() call means “wait me in your pool,”, or “add me to your waiting list.”
Page 290
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The notify() method is used to signal to one and only one of the threads that are
waiting in that same object’s waiting pool.
The notify() method can NOT specify which waiting thread to notify.
Page 291
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define an I/O stream
Identify the types of streams
Explain the Stream class hierarchy
I/O Streams
An I/O Stream represents an input source or an output destination.
A stream can represent many different kinds of sources and destinations like disk files,
devices, other programs, a network socket, and memory arrays.
Streams support many different kinds of data like simple bytes, primitive data types,
localized characters, and objects.
Some streams simply pass on data, others manipulate and transform the data in
useful ways.
No matter how they work internally, all streams present the same simple model to
programs that use them. A stream is a sequence of data.
Input Stream
A program uses an input stream to read data from a source, one item at a time.
Page 292
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Output Stream
A program uses an output stream to write data to a destination, one item at time.
Page 293
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Streams
Streams are shown in the following diagram:
InputStream
OutputStream
Reader
Writer
Solution:
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set
uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using
8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
If you are running Java on English Windows platforms, then it is probably Cp1252. If
you are running Java on English Solaris platforms, then it is most likely 8859_1.
Page 294
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
The central building block of the Java I/O framework is the stream. “A stream is a
flowing sequence of characters”.
In other words, a stream is usually considered to be an abstraction for the capability to
move bytes from a source to a sink.
Input operations begin by opening a stream from the source and using a read()
method to obtain the data via the stream. Similarly, output operations begin by
opening a stream to the destination and using a write() method to send the data.
The package named java.io contains a set of input and output stream classes that can
be used to read and write data.
The java.io package also provides specialized InputStream and OutputStream
subclasses that are used for specialized types of input and output.
The InputStream class and OutputStream class are abstract superclasses that define
the behavior for sequential input and output streams in Java.
Classes in java.io package are designed to be “chained” or “wrapped”. (This is a
common use of the decorator design pattern.)
Page 295
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define InputStream and OutputStream abstract classes
Describe Reader and Writer abstract classes
Page 296
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 297
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 298
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 299
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 300
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 301
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Byte Stream
Programs use byte streams to perform input and output of 8-bit bytes.
All byte stream classes are descended from InputStream and OutputStream.
There are many byte stream classes like FileInputStream and FileOutputStream.
They are implemented in much the same way. They differ mainly in the way they are
constructed.
Page 302
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Character Stream
The Java platform stores character values using Unicode conventions.
Character stream I/O automatically translates this internal format to and from the local
character set. In Western locales, the local character set is usually an 8-bit superset of
ASCII.
Page 303
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
All character stream classes are descended from Reader and Writer.
As with byte streams, there are character stream classes of FileReader and FileWriter
that specialize in file I/O.
Reader and Writer are the abstract superclasses for character streams in java.io
package.
The Reader and Writer classes were added to JDK 1.1 to support internationalization.
The Reader and Writer classes make it possible to work with character streams rather
than byte streams.
To a large extent, these character-stream classes mirror the byte stream classes, so if
you know how to use one, it isn't too difficult to figure out how to use the other.
Page 304
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Line-Oriented I/O
Character I/O usually occurs in bigger units than single characters:
For the line-oriented I/O, one common single unit is the line that contains a string of
characters with a line terminator at the end.
A line terminator can be a carriage-return or linefeed sequence ("\r\n"), a single
carriage-return ("\r"), or a single line-feed ("\n").
String l;
while ((l = inputStream.readLine()) != null) {
System.out.println(l);
outputStream.println(l);
}
in.close();
out.close();
Buffered Streams
An unbuffered I/O means each read or write request is handled directly by the
underlying OS. This can make a program much less efficient, because each such
request often triggers disk access, network activity, or some other operation that is
relatively expensive.
To reduce this kind of overhead, the Java platform implements buffered I/O streams:
Buffered input streams read data from a memory area known as a buffer. The native
input API is called only when the buffer is empty
Similarly, buffered output streams write data to a buffer, and the native output API is
called only when the buffer is full.
Page 305
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Example:
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new BufferedWriter(new
FileWriter("characteroutput.txt"));
Data Streams
Data streams support binary I/O of primitive data type values (boolean, char, byte,
short, int, long, float, and double) as well as String values.
All data streams implement either the DataInput interface or the DataOutput interface.
DataInputStream and DataOutputStream are the implementations that are applied
most widely of these interfaces.
DataOutputStream
DataOutputStream can only be created as a wrapper for an existing byte stream object.
out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(dataFile)));
for (int i = 0; i < prices.length; i ++) {
out.writeDouble(prices[i]);
out.writeInt(units[i]);
Page 306
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
out.writeUTF(descs[i]);
}
DataInputStream
Like DataOutputStream, DataInputStream must be constructed as a wrapper for a
byte stream.
End-of-file condition is detected by catching EOFException, instead of testing for an
invalid return value.
in = new DataInputStream(
new BufferedInputStream(
new FileInputStream(dataFile)));
try {
double price = in.readDouble();
int unit = in.readInt();
String desc = in.readUTF();
} catch (EOFException e){
}
Object Streams
Object streams support I/O of objects:
Like Data streams support I/O of primitive data types
The object has to be of Serializable type
The object stream classes are ObjectInputStream and ObjectOutputStream:
These classes implement ObjectInput and ObjectOutput, which are sub interfaces of
DataInput and DataOutput
An object stream can contain a mixture of primitive and object values
The readObject method reads an object from the ObjectInputStream. The class of the object, the
signature of the class, and the values of the non-transient and non-static fields of the class and all
of its supertypes are read.
Default deserializing for a class can be overridden using the writeObject and readObject methods.
Write Object
The writeObject traverses the entire Web of object references and writes all objects in that Web
onto the stream.
A single invocation of writeObject can cause a large number of objects to be written to the stream.
Page 307
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Invoking writeObject(a) writes not just a, but all the objects necessary to reconstitute a, so the
other four objects in this Web are also written.
When a is read back by readObject, then the other four objects are read back as well, and all the
original object references are preserved.
Page 308
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 309
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
15 fn = new File(fileName);
16 fn.mkdir();
17 System.out.println(fileName +
18 (fn.exists()? "exists": "does not exist"));
19 System.out.println("Deleting temp directory...");
20 fn.delete();
21
24
25 System.out.println(fileName + " is a " +
26 (fn.isFile()? "file." :"directory."));
27
28 if (fn.isDirectory()) {
29 String content[] = fn.list();
30 System.out.println("The content of this directory:");
43 for (int i = 0; i < content.length; i++) {
44 System.out.println(content[i]);
45 }
46 }
35
36
36
37
38 if (!fn.canRead()) {
39 System.out.println(fileName
40 + " is not readable.");
41 return;
42 }
43
47 System.out.println(fileName + " is " + fn.length()
48 + " bytes long.");
49 System.out.println(fileName + " is " +
50 fn.lastModified() + " bytes long.");
51
52 if (!fn.canWrite()) {
53 System.out.println(fileName
54 + " is not writable.");
55 }
56 }
57 }
Page 310
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that illustrates the usage of InputStreamReader and BufferedReader classes that
are used to convert the standard input stream (System.in) from a byte stream to a character
stream.
Code:
import java.io.*;
Refer File Name: InputConversionApp.java to obtain soft copy of the program code
How It Works:
The InputConversionApp program converts the standard input stream (System.in)
from a byte stream to a character stream.
The input characters are echoed to standard output.
The program also prints out the encoding that is in effect on your system.
The following is an example of the output generated when the program is run on your
local desktop:
Encoding: Cp1252
>This is a test.
This is a test.
>
The Cp1252 encoding is the MS Windows Latin-1 character encoding. It is applied
with English and Western European languages.
Page 311
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Solutions:
The Reader and Writer class hierarchy is character-oriented, and the InputStream and
OutputStream class hierarchy is byte-oriented.
The ObjectInputStream class supports the reading of objects from input streams.
The read() method returns -1 when it has reached the end of a file.
The readLine() method returns null when it has reached the end of a file.
Summary
A new File object doesn’t mean there is a new file on your hard drive.
File objects can represent either a file or a directory.
FileWriter and FileReader are low-level I/O classes. You can use them to write and
read files respectively, but they should usually be wrapped.
The ObjectOutputStream.writeObject() method serializes objects, and
ObjectInputStream.readObject() method deserializes objects.
Page 312
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Apply Random Access Files
Problem Scenario
Consider the archive format known as ZIP. A ZIP archive contains files and is typically
compressed to save space. It also contain a directory entry at the end that indicates where the
various files contained within the ZIP archive begin, as shown in the following figure:
A ZIP archive
Suppose that you want to extract a specific file from a ZIP archive. If you use a sequential access
stream, then you have to:
Open the ZIP archive
Search through the ZIP archive until you locate the file you want to extract
Extract the file
Close the ZIP archive
Using the procedure referred in the earlier slide, on average, you would have to read half the ZIP
archive before finding the file that you want to extract.
You can extract the same file from the ZIP archive more efficiently by using the seek feature of a
random access file and following these steps:
Open the ZIP archive
Seek to the directory entry and locate the entry for the file you want to extract from the
ZIP archive
Seek (backward) within the ZIP archive to the position of the file to extract
Extract the file
Close the ZIP archive
Page 313
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
java.io.RandomAccessFile
The java.io.RandomAccessFile class implements both the DataInput and DataOutput
interfaces.
The java.io.RandomAccessFile class can be used for both reading and writing.
Unlike with the sequential classes, when you instantiate an object of RandomAccessFile, you must
indicate whether you will just be reading the file, or also writing to it. You must be able to read a file
before you can write to it.
File Pointer
RandomAccessFile supports the notion of a file pointer.
The file pointer indicates the current location in the file.
When the file is first created, the file pointer is set to zero, indicating the beginning of
the file.
Calls to the read and write methods adjust the file pointer by the number of bytes read
or written.
Page 314
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
RandomAccessFile Methods
RandomAccessFile contains the normal file I/O methods for implicitly manipulating the
file pointer.
RandomAccessFile also contains the following three methods for explicitly
manipulating the file pointer:
o int skipBytes(int) : Moves the file pointer forward the specified number of
bytes
o void seek(long) : Positions the file pointer just before the specified byte
o long getFilePointer() : Returns the current byte location of the file pointer
Try It Out
Problem Statement:
Write a program that illustrates the usage of RandomAccessFile.
Code:
import java.io.*;
Refer File Name: RandomIOApp.java to obtain soft copy of the program code
Page 315
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
How It Works:
The RandomIOApp program provides a simple demonstration of the capabilities of
random-access I/O.
It writes a boolean, int, char, and double value to a file and then uses the seek()
method to seek to offset location 1 within the file. This is the position after the first byte
in the file.
It then reads the int, char, and double values from the file and displays them to the
console window.
Next, it moves the file pointer to the beginning of the file and reads the boolean value
that was first written to the file.
This value is also written to the console window.
The output of the program is as follows:
123456
j
1234.56
True
Solution: The File class encapsulates the files and directories of the local file system. The
RandomAccessFile class provides the methods needed to directly access data contained in any
part of a file.
Summary
Random access files permit nonsequential, or random, access to the contents of a file.
The RandomAccessFile class implements both the DataInput and DataOutput
interfaces and therefore can be used for both reading and writing.
RandomAccessFile supports the notion of a file pointer.
RandomAccessFile contains the following three methods for explicitly manipulating the
file pointer.
o skipBytes: Moves the file pointer forward the specified number of bytes.
o seek: Positions the file pointer just before the specified byte.
o getFilePointer: Returns the current byte location of the file pointer.
Page 316
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define Serialization
Identify what is preserved when an object is serialized
Write Transient keyword
Describe the process of serialization
Explain the process of deserialization
Define Version control
Change the default protocol
Create your own protocol by Externalizable interface
Serialization
Serialization is an ability to read or write an object to a stream. It is the process of "flattening" an
object.
Serialization is used to save object to some permanent storage. Its state should be written in a
serialized form to a file such that the object can be reconstructed at a later time from that file.
Serialization is used to pass on to another object by the OutputStream class and can be sent over
the network.
Page 317
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Non-Serializable Objects
Most Java classes are serializable.
Objects of some system-level classes are not serializable:
Because the data that they represent, changes constantly:
Reconstructed object will contain different value anyway
For example, thread running in your JVM would be applying the memory of your
system. Persisting it and trying to run it in your JVM would make no sense at all.
A NotSerializableException is thrown if you try to serialize non-serializable objects
Page 318
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
The Object type returned should be typecasted to the appropriate class name before methods on
that class can be executed.
1 import java.io.*;
2 public class UnserializeBoolean {
3 UnserializeBoolean() {
4 Boolean booleanData = null;
5 try {
6 FileInputStream fis = new
7 FileInputStream("boolean.ser");
Page 319
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Unique Identifier
Why exception is thrown?
Because all classes that are capable of persistence have a unique identifier
automatically
If the identifier of the class does not equal the identifier of the flattened object, then the
exception will be thrown
However, if you really think about it, why should it be thrown just because I added a field? Could
not the field just be set to its default value and then written out next time?
Yes, but it takes a little code manipulation. The identifier that is part of all classes is maintained in
a field called serialVersionUID.
Page 320
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
If you wish to control versioning, then you simply have to provide the serialVersionUID field
manually and ensure that it is always the same, no matter what changes you make to the class
file.
Example:
serialver MyClass
MyClass static final long serialVersionUID = 10275539472837495L;
When you want to do only a part of the serialization/deserialization yourself, you MUST invoke the
defaultReadObject() and defaultWriteObject() methods to do the rest.
Externalizable Interface
The writeExternal and readExternal methods of the Externalizable interface can be implemented
by a class to give the class complete control over the format and contents of the stream for an
object and its super types.
These methods must explicitly coordinate with the super type to save its state.
Page 321
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that illustrates the usage of ObjectInputStream and ObjectOutputStream classes
in the process of serialization.
Code:
import java.io.*;
import java.util.*;
Refer File Name: ObjectIOApp.java to obtain soft copy of the program code
How It Works:
ObjectIOApp creates a File object that is used to perform I/O to the test.txt file.
The File object is used to create an object of class FileOutputStream.
This object is then used to create an object of class ObjectOutputStream, which is
assigned to the outStream variable.
Four objects are created and assigned to the t1 through t4 variables.
An object of class TestClass1 is assigned to the t1 variable, and an object of class
TestClass2 is assigned to the t2 variable.
A String object is assigned to t3, and a Date object is assigned to t4.
The objects referenced by the t1 through t4 variables are written to outStream using
the writeObject() method.
The stream and file are then closed.
The test.txt file is reopened as a FileInputStream object, which is then converted to an
ObjectInputStream object and assigned to the inStream variable.
Four objects are read from inStream, using the readObject() method, and they are
written to standard output.
The output of the program is as follows:
true 9 A 1.0E-4 java
0 true 2 j 1.234 Java false 7 J 2.468 JAVA
Page 322
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
This is a test.
Thu Mar 13 15:37:58 GMT+05:30 2008
Note that you will receive a different date value from this one.
TestClass1 and TestClass2 are dummy test classes that are used to make the
example work.
The toString() method is automatically invoked by the println() method to convert
objects to string values for printing.
Solution:
1. There are very few reasons, but you might for example, have a security issue where you
do not have a password object stored or you might have an object that makes no sense to
save, because its key instance variables are themselves not serializable, so there is no
useful way for you to make your class serializable.
2. Serialization is smart enough to know when two objects in the graph are the same. In that
case, only one of the objects is saved, and during deserialization, any references to that
single object are restored.
Summary
A class must implement the Serializable interface before its objects can be serialized.
If you mark an instance variable transient, it will not be serialized even though the rest
of the object’s state will be.
If a superclass implements Serializable, then its subclasses do automatically.
If a superclass doesn’t implement Serializable, then when a subclass object is
deserialized, the superclass constructor will run.
Page 323
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define JDBC
Apply JDBC API step by step
JDBC
JDBC is a standard Java API for accessing relational database and hides database specific details
from application.
JDBC API
The JDBC API is a Java API for accessing virtually any kind of tabular data.
The JDBC API consists of a set of classes and interfaces written in the Java
programming language that provide a standard API for tool/database developers and
makes it possible to write industrial-strength database applications entirely in the Java
programming language.
The Java programming language, being robust, secure, easy to use, easy to
understand, and automatically downloadable on a network, is an excellent language
basis for database applications.
What is needed is a way for Java applications to talk to a variety of different data
sources. The JDBC API provides the mechanism for doing this.
Majority of JDBC API is located in java.sql package, which are DriverManager,
Connection, ResultSet, DatabaseMetaData, ResultSetMetaData, PreparedStatement,
CallableStatement and Types
The javax.sql package provides many advanced functionalities.
o Example: DataSource
For example, an alternative to the DriverManager facility, a DataSource object is the
preferred means of getting a connection.
The DataSource interface is implemented by a driver vendor.
With a basic implementation, the connection obtained through a DataSource object is
identical to a connection obtained through the DriverManager facility.
JDBC Driver
JDBC driver is an implementation of JDBC interfaces that is specific to database. Every database
server has corresponding JDBC drivers.
Page 324
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
JDBC Driver
In simplest terms, a JDBC technology-based driver ("JDBC driver") makes it possible to do three
things:
Establish a connection with a data source
Send queries and update statements to the data source
Process the results
The following code fragment gives a simple example of these three steps:
Connection con = DriverManager.getConnection( "jdbc:myDriver:wombat",
"myLogin", "myPassword");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
Database URL
Database URL is used to make a connection to the database and can contain server, port,
protocol, and so on.
jdbc:subprotocol_name:driver_dependant_databasename: Oracle thin driver
jdbc:oracle:thin:@machinename:1521:dbname:Derby
jdbc:derby://localhost:1527/sample: Pointbase
jdbc:pointbase:server://localhost/sample
Your driver documentation will give you the class name to use.
Page 325
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
For instance, if the class name is jdbc.DriverXYZ, you would load the driver with the following line
of code:
Class.forName("jdbc.DriverXYZ");
You do not need to create an instance of a driver and register it with the DriverManager because
calling the method Class.forName will do that for you automatically.
If you were to create your own instance, you would be creating an unnecessary duplicate.
When you have loaded a driver, it is available for making a connection with a DBMS.
Using DataSource is a preferred means of getting a Connection object (You will talk about
DataSource in the next session)
Page 326
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Reading Results
Loop through ResultSet retrieving information:
java.sql.ResultSet:
boolean next()
xxx getXxx(int columnNumber)
xxx getXxx(String columnName)
void close()
The iterator is initialized to a position before the first row. You must call next() once to move it to
the first row.
Once you have the ResultSet, you can easily retrieve the data by looping through it
while (rs.next()){
// Wrong this will generate an error
String value0 = rs.getString(0);
// Correct!
String value1 = rs.getString(1);
int value2 = rs.getInt(2);
int value3 = rs.getInt(“ADDR_LN1");
}
When retrieving data from the ResultSet, use the appropriate getXXX() method:
getString()
getInt()
getDouble()
getObject()
Page 327
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
This gives valuable information about the data that you are retrieving or the database that you are
using.
ResultSetMetaData rsMeta = rs.getMetaData();
DatabaseMetaData dbmetadata = connection.getMetaData();
ResultSetMetaData Example
ResultSetMetaData meta = rs.getMetaData();
//Return the column count
int iColumnCount = meta.getColumnCount();
for (int i =1 ; i <= iColumnCount ; i++){
System.out.println(“Column Name: " + meta.getColumnName(i));
System.out.println(“Column Type" + meta.getColumnType(i));
System.out.println("Display Size: " +
meta.getColumnDisplaySize(i) );
System.out.println("Precision: " + meta.getPrecision(i));
System.out.println(“Scale: " + meta.getScale(i) );
}
Try It Out
Problem Statement:
Write a program that illustrates how to connect to a database by registering the JDBC driver using
the Class.forName() method.
Code:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ConnectionUsingClassForName {
Page 328
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
try {
System.out.print(" Loading JDBC Driver -> " + driverClass
+ "\n");
Class.forName(driverClass).newInstance();
// continued …
How It Works:
This program provides an example of how to connect to a database by registering the
JDBC driver using the Class.forName() method.
This complex expression is a tool for dynamically creating an instance of a class when
you have some variable representing the class name.
Because a JDBC driver is required to register itself whenever its static initializer is
called, this expression has the net effect of registering your driver for you.
This method is by far the best as in that it does not require hardcoded class names
and it runs well in all Java environments.
In real-world applications, you should apply this method along with a properties file
from which you load the name of the driver.
Solution:
When a connection is created using JDBC, by default it is in the auto-commit mode.
This means that each individual SQL statement is treated as a transaction by itself,
and will be committed as soon as its execution is finished.
Notice that for the SQL statements CREATE, INSERT, UPDATE, and DELETE, the
execution of the method executeUpdate() will change the state of the database.
Whenever the SQL statement will not fit on one line on the page, you have to split it
into two strings concatenated by a plus sign (+) so that it will compile.
Pay special attention to the space following “INSERT INTO tablename” to separate it
in the resulting string from “VALUES”.
Summary
Advantages of Java and JDBC technologies:
MIS managers like the combination of the Java platform and JDBC technology
because it makes disseminating information easy and economical.
Businesses can continue to use their installed databases and access information
easily even if it is stored on different database management systems or other data
sources.
Page 329
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 330
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define DataSource and Connection Pooling
Describe transaction
The benefit is that, because the properties of the data source can be changed, any code accessing
that data source does not need to be changed.
In the Sun Java System Application Server, a data source is called a JDBC resource.
Page 331
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 332
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Editing a sample
JDBC Resource
Page 333
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Because all resource JNDI names are in the java:comp/env subcontext, when you specify the
JNDI name of a JDBC resource, then enter only jdbc/name. For example, for a payroll database,
specify jdbc/BookDB.
Page 334
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Using connection pooling, a set of database connections are created at firsthand and
made available in the pool.
Then these connections are provided on requirement basis from the pool and finally
these connections are returned back to the pool.
The important advantage of connection pooling mechanism is that it cuts down the
overhead of creating and destroying database connections.
Example: PointBasePool
The Sun Java Application Server 8 is distributed with a connection pool named
PointBasePool, which handles connections to the PointBase database server.
Under Sun Java Application Server, each DataSource object is associated with a
connection pool.
Page 335
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
}
}
}
Transaction
One of the main benefits of using a PreparedStatement is executing the statements in
a transactional manner.
The committing of each statement when it is first executed is very time consuming.
By setting AutoCommit to false, the developer can update the database more then
once and then commit the entire transaction as a whole.
Also, if each statement is dependant on the other, the entire transaction can be rolled
back and the user is notified.
Page 336
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Transactions Example
Connection connection = null;
try {
connection =
DriverManager.getConnection("jdbc:oracle:thin:@machinename:1521:db
name","username","password");
connection.setAutoCommit(false);
PreparedStatement updateQty =
connection.prepareStatement("UPDATE STORE_SALES SET QTY = ? WHERE
ITEM_CODE = ? ");
int [][] arrValueToUpdate =
{ {123, 500} ,
{124, 250},
{125, 10},
{126, 350} };
int iRecordsUpdate = 0;
connection.commit();
System.out.println(iRecordsUpdate + " record(s) have been updated");
} catch(SQLException sqle) {
System.out.println("" + sqle);
}
try {
connection.rollback();
} catch(SQLException sqleRollback) {
System.out.println("" + sqleRollback);
} finally {
try {
connection.close();
}
catch(SQLException sqleClose) {
System.out.println("" + sqleClose);
}
}
Page 337
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that illustrates on how the database transaction statements such as commit and
rollback are handled in Java.
Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
"jdbc:oracle:thin:@machinename:1521:dbname",
"username", "password");
connection.setAutoCommit(false);
Refer File Name: TransactionExampleApp.java to obtain soft copy of the program code
How It Works:
The TransactionExampleApp program is given just for referencing how the database transaction
statements such as commit and rollback are handled in Java.
Solution:
The programmer sets a property namely, the transaction isolation level, which
determines the transaction isolation level given to the connection that the rowset
establishes.
The owner does not want to read any data that has not been committed, so the
programmer chooses the level TRANSACTION_READ_COMMITTED.
crset.setTransactionIsolation(Connection.TRANSACTION_READ_COMMI
TTED);
Page 338
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
DataSource
o The DataSource interface provides methods that allow a user to get and set the
character stream to which tracing and error logging will be written.
o A user can trace a specific data source on a given stream, or multiple data
sources can write log messages to the same stream provided that the stream is
set for each data source.
Connection Pooling
o Get the connection with a DataSource object
o Always close the connection in a finally block.
Distributed Transactions:
o Do not call the methods commit or rollback, and
o Do not set auto-commit mode to true.
Page 339
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Identify java.sql.PreparedStatement and java.sql.CallableStatement
PreparedStatement
The contained SQL is sent to the database and compiled or prepared beforehand.
From this point on, the prepared SQL is sent and this step is bypassed. The more
dynamic statement requires this step on every execution.
Depending on the DB engine, the SQL may be cached and reused even for a different
PreparedStatement and most of the work is done by the DB engine rather than the
driver.
Instances of PreparedStatement contain an SQL statement that has already been
compiled. This is what makes a statement "prepared.“
The SQL statement contained in a PreparedStatement object may have one or more
IN parameters.
An IN parameter is a parameter whose value is not specified when the SQL statement
is created.
Instead, the statement has a question mark (?) as a placeholder for each IN
parameter.
The ? is also known as a parameter marker or parameter placeholder.
An application must set a value for each parameter marker in a prepared statement
before executing the prepared statement.
Because PreparedStatement objects are precompiled, their execution can be faster
than that of Statement objects.
Consequently, an SQL statement that is executed many times is often created as a
PreparedStatement object to increase efficiency.
Being a subclass of Statement, PreparedStatement inherits all the functionality of
Statement.
In addition, it adds a set of methods that are needed for setting the values to be sent
to the database in place of the placeholders for IN parameters.
Also, the three methods execute, executeQuery, and executeUpdate are modified so
that they take no argument.
The Statement forms of these methods (the forms that take an SQL statement
parameter) cannot be used with a PreparedStatement object.
Page 340
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
PreparedStatement Steps
The steps of PreparedStatement object are:
1. You register the drive and create the db connection in the usual manner.
2. Once you have a db connection, create the prepared statement object.
Example:
PreparedStatement updateSales =
con.prepareStatement(“UPDATE OFFER_TBL SET
QUANTITY = ? WHERE ORDER_NUM = ? ");
// “?” are referred to as Parameter Markers
// Parameter Markers are referred to by number,
// starting from 1, in left to right order.
// PreparedStatement's setXXX() methods are used to set
// the IN parameters, which remain set until changed.
Once all the variables have been bound, then you execute the PreparedStatement.
int iUpdatedRecords = updateSales.executeUpdate();
If AutoCommit is set to true, then once the statement is executed, the changes are committed.
From this point forth, you can just re-use the PreparedStatement object.
updateSales.setInt(1, 150);
updateSales.setInt(2,10398002);
If the PreparedStatement object is a select statement, then you execute it, and loop through the
ResultSet object in the same way as in the basic JDBC example:
PreparedStatement itemsSold =
con.prepareStatement("select o.order_num,
o.customer_num, c.name, o.quantity from order_tbl o,
customer_tbl c where o.customer_num =
c.customer_num and o.customer_num = ?;");
itemsSold.setInt(1,10398001);
ResultSet rsItemsSold = itemsSold.executeQuery();
while (rsItemsSold.next()){
System.out.println( rsItemsSold.getString(“NAME") +
"sold "+ rsItemsSold.getString(“QUANTITY") + " unit(s)");
}
Page 341
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
CallableStatement
CallableStatement is the interface used to execute SQL stored procedures.
A stored procedure is a group of SQL statements that form a logical unit and perform a
particular task.
Stored procedures are used to encapsulate a set of operations or queries to execute
on a database server.
A CallableStatement object contains a call to a stored procedure. It does not contain
the stored procedure itself.
The following first line of code creates a call to the stored procedure
SHOW_SUPPLIERS using the connection con .
The part that is enclosed in curly braces is the escape syntax for stored procedures.
CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
CallableStatement Example
Here is an example using IN, OUT, and INOUT parameters.
// set int IN parameter
cstmt.setInt( 1, 333 );
// register int OUT parameter
cstmt.registerOutParameter( 2, Types.INTEGER );
// set int INOUT parameter
cstmt.setInt( 3, 666 );
// register int INOUT parameter
cstmt.registerOutParameter( 3, Types.INTEGER );
//You then execute the statement with no return value
cstmt.execute(); // could use executeUpdate()
// get int OUT and INOUT
int iOUT = cstmt.getInt( 2 );
int iINOUT = cstmt.getInt( 3 );
Try It Out
Problem Statement:
Write a program that illustrates the usage of CallableStatement.
Page 342
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Code:
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
Refer File Name: OracleCallableStmtApp.java to obtain soft copy of the program code
How It Works:
This is an Oracle specific example of a CallableStatement.
This program is given just for a reference.
Page 343
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
The SQL statement contained in a PreparedStatement object may have one or more
IN parameters.
An application must set a value for each parameter marker in a prepared statement
before executing the prepared statement.
Because PreparedStatement objects are precompiled, their execution can be faster
than that of Statement objects.
Consequently, an SQL statement that is executed many times is often created as a
PreparedStatement object to increase efficiency.
A CallableStatement object provides a way to call stored procedures in a standard
way for all RDBMSs.
A stored procedure is stored in a database; the call to the stored procedure is what a
CallableStatement object contains.
This call is written in an escape syntax that may take one of two forms: one form with
a result parameter and the other without a result parameter.
A result parameter, a kind of OUT parameter, is the return value for the stored
procedure.
Page 344
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define Garbage Collector
Explain the GC Designs
Identify the Memory Leaks
Garbage Collector
The Garbage Collector runs in a thread in the JVM. When the free memory drops under a
threshold the GC begins to run to eliminate unneeded objects. Exactly when it runs and for how
long, however, cannot be controlled by the user program.
Overview of GC Designs
The JVM Specification does not in fact specify very much about the GC. It leaves considerable
room for variation in implementation. Research continues in the computer science community for
fast and efficient GC algorithms. A GC must meet a number of difficult challenges:
Recognize and eliminate dead (unreferenced) objects from the heap
Keep the heap from becoming so fragmented that new objects do not easily fit
Minimize the processing time taken away from the application
Recognize circular cases where dead objects (that is, objects are no longer accessible
from the live thread processes or from static references) referencing each other and
so might give them the appearance of life
Page 345
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Generational:
Most objects in most programs only last for a brief time.
It is more efficient to concentrate on freeing up memory from the short-lived objects
and spend as little time as possible checking on old but stable objects.
The generational GC creates at least two sub-heap areas with one for short-lived
objects and the other for old objects.
A Mark and Sweep or other GC algorithm would work on the short-lived heap.
Those objects that last beyond a few cycles are moved to the long-lived heap, which is
only checked occasionally.
These types of algorithms (as discussed in earlier slides) must interrupt the application
threads and complete their job before returning control.
There are some algorithms that work in an incremental approach, rather than
completing a full clean-up at one go, and thus interfere less with the program.
Memory Leaks
Memory leak refers to the loss of free memory in the heap to unusable data as a
program runs.
This can lead to inefficient memory utilization and eventually to a crash of the program
when no free memory remains.
Even with the garbage collector, memory leaks can still occur in Java.
Page 346
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that illustrates the working of Garbage Collector.
Code:
public class GarbageDemo {
Garbage g;
int max;
public GarbageDemo(int n) {
max = n;
}
// continued …
Refer Files: Garbage.java, GarbageDemo.java to obtain soft copy of the program code
How It Works:
This program is designed to quickly use up all of your memory resources by creating
increasingly longer arrays of increasingly longer String objects.
The program takes an integer command-line argument, which you can use to specify
the amount of resources it applies.
You set the default to 15, which allows the program to execute to completion when
you run it under Windows XP Professional on a desktop with 2 GB of RAM.
If your computer has less RAM, then you may need to run the program with a value
less than 15. Start at 14 and work backwards until your program is able to execute
without running out of memory.
When you run the program on your desktop, it displays the following output:
11 is being collected.
Page 347
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
10 is being collected.
9 is being collected.
8 is being collected.
7 is being collected.
6 is being collected.
5 is being collected.
4 is being collected.
3 is being collected.
2 is being collected.
1 is being collected.
12 is being collected.
This output is displayed by the finalize() method of each Garbage object, indicating
that the Garbage Collector has determined that the object has become unreachable.
(The finalize() method is invoked on an object by the Garbage Collector so that the
object may perform cleanup before it is reclaimed by the Garbage Collector.)
The earlier output indicates that 12 Garbage objects were being finalized by the
Garbage Collector.
These objects had become unreachable because they no longer were referenced by
the g field variable of the GarbageDemo class.
To get an idea how this happened, look at the run() method:
void run() {
for(int i=1;i<max;++i) {
g = new Garbage(i);
}
}
With each iteration of the for statement, a new Garbage object is created and
assigned to the g variable. When a new object is assigned to the g variable, the earlier
object that was referenced by the g variable is no longer accessible by g or any other
variable or object. Hence, that object becomes subject to Garbage Collection.
Solution:
An object becomes eligible for Garbage Collection when its last live reference disappears.
Three ways to get rid of the reference:
The reference goes out of scope, permanently.
void go() {
Life z = new Life();
}
Here, the reference ‘z’ dies at the end of method
The reference is assigned another object.
Life z = new Life();
z = new Life();
Page 348
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
In Java, garbage collection (GC) provides automated memory management.
The purpose of GC is to delete objects that can’t be reached.
Only the JVM decides when to run the GC, you can only suggest it.
You can’t know the GC algorithm for sure.
Objects must be considered eligible before they can be garbage collected.
An object is eligible when no live thread can reach it.
To reach an object, you must have a live, reachable reference to that object.
Page 349
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Describe the important GC Performance Metrics
Identify the types of Garbage Collectors
Serial Collector
Serial Collector is used for most applications that are running on client-style machines,
which do not have low pause time requirement.
Serial Collector is the default for client-style machines in Java SE 5.
Serial Collector can be explicitly requested with XX:+UseSerialGC.
Parallel Collector
Parallel Collector is also known as Throughput Collector.
This is applied for Java applications, which run on machines with a lot of physical
memory and multiple CPUs and do not have low pause time requirement:
Infrequent but potentially long old generation GC can still occur
Examples: Batch applications, billing, payroll, scientific computing, and so on
Parallel Collector can be explicitly requested with XX:+UseParallelGC.
Page 350
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Applications with relatively large set of long-lived data (a large old generation) and run multi-CPU
machines
Page 351
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Solution:
It is not possible to force Garbage Collection. Invoking System.gc may start garbage
process.
Circular references do not prevent objects from being garbage collected.
All objects have a finalize() method. It is inherited from the Object class.
finalize() method is used to release system resources other than memory.
finalize() method is called only once for an object. If an exception is thrown in finalize
(), then the object is still eligible for Garbage Collection (at the discretion of gc).
gc keeps track of unreachable objects and garbage-collects them, but an unreachable
object can become reachable again by letting know other objects of its existence from
its finalize() method (when called by gc). This ‘resurrection’ can be done only once,
since finalize() is called only once for an object.
finalize() can be called explicitly, but it does not garbage collect the object.
Summary
Java applications can run out of memory.
Islands of objects can be garbage collected, even though they refer to each other.
Request garbage collection with System.gc(); (recommended).
Class Object has a finalize() method.
The finalize() method is guaranteed to run once and only once before the garbage
collector deletes an object.
The garbage collector makes no guarantees, fianlize() may never run.
You can uneligibilize an object for GC from within finalize().
Page 352
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define Annotation
Explain the importance of Annotation
Identify Built-in Annotations
Need of Annotation
Annotation enables “declarative programming” style:
Less coding because tool will generate the boiler plate code from annotations in the
source code
Easier to change
Annotation eliminates the need for maintaining "side files" that must be kept up to date with
changes in source files:
Information is kept in the source file
(example) Eliminate the need of deployment descriptor
Page 353
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Built-in Annotations
Java defines seven built-in annotations.
The following four are imported from java.lang.annotation:
@Retention
@Documented
@Target
@Inherited
@Retention
@Retention is designed to be used only as an annotation to another annotation.
Its general form is as follows:
@Retention(retention-policy)
Here, retention-policy must be one of the earlier discussed enumeration constants. If
no retention policy is specified for an annotation, then the default policy of CLASS is
used.
The following example uses @Retention to specify the RUNTIME retention policy.
Thus, the following annotation (MyAnno) will be available to the JVM during program
execution.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}
Page 354
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
@Documented
The @Documented annotation is a marker interface, which tells a tool that an
annotation is to be documented.
It is designed to be used only as an annotation to an annotation declaration.
@Target
The @Target annotation specifies the types of declarations to which an annotation
can be applied.
It is designed to be used only as an annotation to another annotation.
@Target takes one argument, which must be a constant from the ElementType
enumeration. This argument specifies the types of declarations to which the
annotation can be applied.
The following table shows the constants and the type of declaration to which they correspond:
CONSTRUCTOR Constructor
FIELD Field
METHOD Method
PACKAGE Package
PARAMETER Parameter
You can specify one or more of the values (as shown in the earlier slide) in a @Target
annotation.
To specify multiple values, you must specify them within a braces-delimited list.
For example, to specify that an annotation applies only to fields and local variables,
you can use this @Target annotation:
@Target( { ElementType.FIELD,ElementType.LOCAL_VARIABLE } )
@Inherited
@Inherited is a marker annotation that can be applied only on another annotation
declaration.
It affects only annotations that will be applied on class declarations.
@Inherited causes the annotation for a super class to be inherited by a subclass.
Page 355
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
@Override
@Override is a marker annotation that can be applied only on methods.
A method annotated with @Override must override a method from a super class. If it
does not, then a compile-time error will result.
It is used to ensure that a super class method is actually overridden, and not simply
overloaded.
@Deprecated
@Deprecated is a marker annotation.
It indicates that a declaration is obsolete and has been replaced by a new form.
@SuppressWarnings
@SuppressWarnings specifies that one or more warnings that might be issued by the
compiler are to be suppressed.
The warnings to suppress are specified by name, in string form.
This annotation can be applied to any type of declaration.
Solution:
Java 2, v5.0 adds a powerful new facility called metadata, which enables you to
embed supplemental information into a source file.
This information, called an annotation, does not change the actions of a program.
An annotation leaves the semantics of a program unchanged.
However, this information can be applied by various tools, during both development
and deployment.
For example, an annotation might be processed by a source-code generator.
Although Sun refers to this feature as metadata, the term program annotation facility is
also applied, and is more descriptive.
Summary
All annotation types automatically extend the Annotation interface.
Thus Annotation is a super-interface of all annotations.
The Annotation interface is declared within the java.lang.annotation package.
It overrides hashCode(), equals(), and toString(), which are defined by Object.
It also specifies annotationType(), which returns a Class object that represents the
invoking annotation.
Page 356
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 357
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Define an annotation
Apply an annotation
Page 358
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Marker Annotation
A marker annotation is a special kind of annotation that contains no members.
Because a marker annotation contains no members, determining the existence of the
marker annotation is sufficient.
The best way to determine whether a marker annotation exists is to use the method
isAnnotationPresent(), which is defined by the AnnotatedElement interface. This
interface is available in Class, Field, Method, Constructor, and Package.
Example:
import java.lang.annotation.*;
// A marker annotation.
@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker { }
class Marker {
// Annotate a method using a marker.
// Notice that no parentheses ‘( )’ is needed.
@MyMarker
…
…
Page 359
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
/**
* Associates a copyright notice with the annotated API element.
*/
public @interface Copyright {
String value();
}
Usage: Can omit the element name and equals sign (=).
@Copyright("2008 Cognizant Technology Solutions")
public class SomeClass { ... }
Normal Annotation
Definition:
public @interface RequestForEnhancement {
int id();
String synopsis();
String engineer() default "[unassigned]";
String date(); default "[unimplemented]";
}
Usage:
@RequestForEnhancement(
id = 2868724,
synopsis = "Enable time-travel",
engineer = "Mr. Peabody",
date = "4/1/3007"
)
public static void travelThroughTime(Date destination) { ... }
Page 360
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Note: The preceding annotation (Accessor) has a member with default value. The default value
can be given for an annotation member if no value is specified when the annotation is applied.
Reflection
Reflection is a feature that enables information about a class to be obtained at run
time.
The reflection API is contained in the java.lang.reflect package.
There are a number of a ways to apply reflection.
The first step for applying a reflection is to obtain a Class object that represents the
class whose annotation you want to obtain.
If you want to obtain the annotations associated with a specific item declared within a
class, then you must first obtain an object that represents that item.
From a Class, Method, Field, Constructor, or Package object, you can obtain a
specific annotation associated with that object by calling getAnnotation() as shown in
the following code:
<T extends Annotation> T getAnnotation(Class<T> annoType)
Here, annoType is a Class object that represents the annotation in which you are
interested. It returns a reference to the annotation. Using the reference, you can obtain
the values associated with the members of the annotation.
This interface supports reflection for annotations and is implemented by the classes Method, Field,
Constructor, Class, and Package.
AnnotatedElement defines the methods as shown in the following slide. Therefore, these methods
are available to any object to which annotations can be applied.
Method Description
<T extends Annotation> T Returns the annotation of type annoType associated with
getAnnotation(Class<T> annoType) the invoking object.
Returns an array containing all annotations associated with
Annotation[ ] getAnnotations()
the invoking object.
Annotation[ ] Returns an array containing all noninherited annotations
getDeclaredAnnotations() associated with the invoking object.
boolean isAnnotationPresent Returns true if an annotation specified by annoType is
Class<? extends Annotation> associated with the invoking object. It returns false
annoType) otherwise.
Page 361
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Try It Out
Problem Statement:
Write a program that applies a Marker annotation.
Code:
import java.lang.annotation.*;
import java.lang.reflect.*;
// A marker annotation
@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker { }
class Marker {
Refer File Name: Marker.java to obtain soft copy of the program code
How It Works:
The preceding example applies a marker annotation. It implements
isAnnotationPresent() to determine if the marker is present.
Because a marker interface contains no members, simply determining its existence is
sufficient.
The following output confirms that @MyMarker is present:
Page 362
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
MyMarker is present.
In the program, notice that you do not need to follow @MyMarker with parentheses
when it is applied. Thus MyMarker is applied simply by applying its name like this:
@MyMarker
It is not wrong to supply an empty set of parentheses, but they are not needed.
Solution:
There are a number of restrictions that apply to annotation declarations.
First, no annotation can inherit another.
Second, all methods declared by an annotation must be without parameters.
Furthermore, they must return one of the following:
A simple type, such as int or double
An object of type String or Class
An enum type
Another annotation type
An array of one the preceding types
Annotations cannot be generic. In other words, they cannot take parameters.
Finally, they cannot specify a throws clause.
Summary
Java 2, v5.0 adds a powerful new facility called metadata, which enables you to
embed supplemental information into a source file. This information called an
annotation, does not change the actions of a program.
Metadata is created through a mechanism based on the interface.
You can give annotation members default values that will be used if no value is
specified when the annotation is applied. A default value is specified by adding a
default clause to a member’s declaration.
A marker annotation is a special kind of annotation that contains no members and its
sole purpose is to mark a declaration.
A single-member annotation is another special kind of annotation that contains only
one member.
Java defines seven built-in annotations. They are: @Retention, @Documented,
@Target, @Inherited, @Override, @Deprecated and @SuppressWarnings.
Page 363
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Learning Objectives
After completing this session, you will be able to:
Describe the key features of Java SE (Standard Edition) 6 (JDK 1.6)
Page 364
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
// evaluate a script
engine.eval("alert(\"Hello World!\")");
API Support
Java SE 6 provides support for the JAX- WS Web services stack.
For the client side: Service class for creating proxy
For the server side: Endpoint class for publication
Page 365
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Java DB
Java DB is based on Apache Derby:
JDBC conformant all-Java relational database
Bundled and pre-configured in JDK
Desktop APIs
AWT (Abstract Window Toolkit) improvements are:
Tray icon
Splash screen
Desktop class
Dialog Modality enhancements and API
Text printing
Swing improvement:
GroupLayout: Basis for NetBeans GUI Builder (Matisse)
JTable sorting and filtering
SwingWorker
Tray Icon
Tray icon lets you to access the system tray in your Java application:
SystemTray
TrayIcon
Tray icon gives you the ability to add graphics, popup menus, and floating tip functionality to the
system tray.
Page 366
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Painting: You can change the image shown after the splash screen is loaded, but before the
application starts.
SplashScreen splash = SplashScreen.getSplashScreen();
Graphics2D g = splash.createGraphics();
// your painting code here
splash.update();
Desktop APIs
GUI developers get a large number of new tricks to play like the ever popular yet
newly incorporated SwingWorker utility to help you with threading in GUI apps, JTable
sorting and filtering, and a new facility for quick splash screens to quiet impatient
users.
Desktop class has an enumeration of actions that may be supported for a file or URI
like BROWSE, EDIT, MAIL, OPEN, and PRINT.
File processing: Opening, editing, and printing files with applications registered in
native system
Browsing: Opening a URL with the default browser
Email: Sending a message with the default mail client
Page 367
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Modality Types
The modality types are:
modeless: Does not block any other window
document-modal: Blocks input to all top-level windows from the same document
application-modal: Blocks all windows from the same application
toolkit-modal: Blocks all windows that run in the same toolkit
Sample
dialog
boxes
Text Printing
Text printing easily print a Swing text component:
o Prints the entire contents of the text component
o Does not have to be visible
o javax.swing.text.JTextComponent.print();
Text printing reformats for printed page.
It optionally displays print dialog and progress box.
It supports optional header or footer.
It will not split lines in half!
Page 368
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
SwingWorker
SwingWorker makes it easy to offload work to separate threads.
It makes use of concurrency package.
It makes it more generic.
It supports partial results.
It supports PropertyChangeListener.
More information: http://java.sun.com/docs/books/tutorial/uiswing/concurrency/
javax.swing.GroupLayout Class
This class is a new layout manager to support new Matisse GUI builder that is
NetBeans™ IDE ships with Matisse
Can also apply GroupLayout in J2SE 1.5 software implementing stand-alone library
This has more capabilities for relative positioning of components.
This works with horizontal and vertical layout separately.
Compiler Access:
Compiler access opens up programmatic access to javac for in process compilation of
dynamically generated Java code.
This is really aimed at people who create tools for Java development and for
frameworks:
Page 369
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
JavaServer Pages (JSP) or PHP construction kit engines that need to generate a
bunch of classes on demand
Average developers will benefit indirectly from faster performing tool
The compiler API is not directly intended for the everyday developer, but for those of
you deafened by your screaming inner geek, roll up your sleeves and give it a try.
Pluggable Annotations
JSR 175 of JDK 5 standardized how annotations are declared in Java code but annotation
processing details were relegated as an implementation detail.
Java tool and framework vendors (and you) can define annotations and have core API support for
plugging in and executing the processors that do the heavy lifting. It seamlessly integrates your
custom annotations.
Processing API standardizes annotation processing as well. The annotation processors act as
plug-ins to the compiler, hence "pluggable annotation processing”.
Desktop Deployment
Desktop deployment improved actual performance: Graphics hardware acceleration
on Windows
It perceived performance: True double buffering
It improved the native look and feels:
o Updated Swing Look and Feel Windows/Unix
o LCD text rendering
It revamped Java Web Start and JRE installations: No more scary security dialog
Page 370
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Sample screen
shot on Vista with
Java 2, v5.0
Page 371
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Sample screen
shot on Vista
with Java 2, v6
Security
Security added important new APIs:
XML Digital Signature (XMLDSig) API (JSR 105)
Smart Card I/O API (JSR 268)
Java SE 6 has simplified the job of its security administrators by providing various new ways to
access platform-native security services, such as native Public Key Infrastructure (PKI) and
cryptographic services on Microsoft Windows for secure authentication and communication, Java
Generic Security Services (Java GSS) and Kerberos services for authentication, and access to
LDAP servers for authenticating users.
Page 372
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Performance Improvement
Client Benchmark: SwingMark
Page 373
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Summary
The key features of Java SE 6 (Mustang) (JDK 1.6) are:
o Scripting
o Web Services
o Database (JDBC 4.0, Java DB)
o More Desktop APIs
o Monitoring and Management
o Compiler Access
o Pluggable Annotations
Page 374
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
o Desktop Deployment
o Security
o Quality, Compatibility, and Stability
Page 375
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Glossary
Page 376
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
Page 377
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
References
Websites
http://java.sun.com
http://www.javapassion.com
http://www.jspwiki.org/wiki/ExternalClassProblemInJUnit
http://www.stanford.edu/class/cs193j/slidesSummer2003/
http://www.particle.kth.se/~lindsey/JavaCourse/Book/courseMap.html
Books
Head First Java – 2nd edition – Kathy Sierra & Bert Bates
Java 2, v5.0 (Tiger) New Features – Herbert Schildt
Essentials of Java Programming – C.Muthu
Sun Certified Programmer for Java 5 - Exam Study Guide - Kathy Sierra & Bert Bates
Page 378
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - Core Java
STUDENT NOTES:
Page 379
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected