AGENDA
Basics of Java and its features The Java Architecture Concept of Objects The Basic constructs in Java Inheritance
Interfaces
Packages Access specifiers Jar Files Java Class Libraries Exception Handling Collections
9/7/2012
What is Java?
Java is a powerful OO programming language developed by Sun
Microsystems Java is based on the first successful OO language called Smalltalk. A Virtual machine(run time environment) that can be embedded in web browsers (e.g. Netscape Navigator, Microsoft Internet Explorer) and Operating Systems. A set of standardized Class libraries (packages), that support
Creating user interfaces Communicating over network etc
9/7/2012 Tata Consultancy Services 3
Introduction to Java
Java is an object oriented language.
Java was developed initially for consumer devices Now it is a popular platform to develop web based
9/7/2012
Java features
Object-oriented Simple language Compared to earlier OO languages like C++, it is simple Designed considering the pitfalls of earlier languages Robust and Secure Architecture Neutral / Portable Example: Java code compiled on Windows can be run on Unix without recompilation Secure Built -in security features like absence of pointers and confinement of the java program within its runtime environment Support for Multithreading at language level so high
performance.
9/7/2012
Java Compiler
The source code of Java will be stored in a file with
extension .java
The Java compiler compiles a .java file into byte code
9/7/2012
Interpreter (java)
Interpreter (java)
Interpreter (java)
Win 32
Linux
Mac
implemented in software
9/7/2012 Tata Consultancy Services 9
The .class file that is generated is the machine code of this processor
Byte code is in binary language which consists of opcodes (operation
codes)
software
9/7/2012 Tata Consultancy Services 10
the JVM.
9/7/2012 Tata Consultancy Services 11
Java Architecture
Source File (HelloWorld.java)
JVM
Class Loader
Compiler (javac)
Interpreter
Runtime
9/7/2012
12
9/7/2012
13
9/7/2012
14
the Java Runtime Environment (JRE). Each operating system and CPU architecture requires a different JRE. The JRE comprises a set of base classes, which are an implementation of the base Java API, as well as a JVM The portability of Java comes from implementations on a variety of CPUs and architectures. Without an available JRE for a given environment, it is impossible to run Java software.
9/7/2012 Tata Consultancy Services 15
Java Products
Java SE Java Standard Edition. This is the Core Java,
Introduction to Objects
Characteristics of object oriented programming:
Everything is an object.
They're software programming models
An object has a state, behavior and identity. A program is a bunch of objects telling each other what to do
by passing messages.
9/7/2012
17
9/7/2012
18
Objects..
Software objects are conceptually similar to real-world objects:
programming languages) and exposes its behavior through methods (functions in some programming languages).
Hiding internal state and requiring all interaction to be
performed through an object's methods is known as data encapsulation a fundamental principle of object-oriented programming
9/7/2012 Tata Consultancy Services 19
What is a class?
A class is a software construct that defines the data (state) and
methods (behavior) .
Fields are normally specific to an object--that is, every object
constructed from the class definition will have its own copy of the field. Such fields are known as instance variables.
A class in and of itself is not an object
A class is like a blueprint that defines how an object will look and
9/7/2012
20
http://www.oracle.com/technetwork/java/javase/downloads/index.html
etc.
9/7/2012
21
CLASSPATH
In Windows: set CLASSPATH=%CLASSPATH%;%JAVA_HOME%\lib\tools.jar;.
PATH
System.out.println(Hello World!);
} }
Save this as HelloWorld.java Important : Take care!! CaSe of file name matters
9/7/2012
23
To Compile
Open a command prompt
Set Environment variables (explained earlier)
To execute
Type in the command prompt
java HelloWorldApp
The result
9/7/2012
25
Best Practices
One .java file must contain only one class declaration The name of the file must always be same as the name of the class Stand alone Java program must have a public static void main
defined
it is the starting point of the program Not all classes require public static void main
Code should be adequately commented Must follow indentation and coding standards
9/7/2012
26
9/7/2012
28
All numeric data types are signed The size of data types remain the same on all platforms (standardized) char data type in Java is 2 bytes because it uses UNICODE character set UNICODE is a character set which
Floating Type
Textual
char (2 bytes)
Logical
(stores memory address of an object). Hence holds bits that represent a way to access an object
Objects, Arrays are accessed using reference variables in Java
9/7/2012
30
9/7/2012
31
Variables in Java
Using primitive data types is similar to other languages
int count; int max=100;
In Java, if a local variable is used withoutprogram onlythe compiler will BEST PRACTICE: Declare a variable in initializing it, when showan error
required.
9/7/2012
32
int count
name
type
9/7/2012
33
count =10;
Declaration and initialization may be combined in a
9/7/2012
34
Give it a try.
What will be the output of the following code snippet when you try to compile and run it?
class Sample{ public static void main (String args[]){ int count; System.out.println(count); } }
9/7/2012
35
double d; d = i;
9/7/2012
36
9/7/2012
38
Constituents of a Class
public class Student { private int rollNo; private String name; Student(){ //initialize data members } Student(String nameParam){ name = nameParam; } public int getrollNo (){ return rollNo; } }
9/7/2012 Tata Consultancy Services
Constructor
Method (Behavior)
41
Constructors (1 of 3)
A constructor is a special method that is used to initialize a
newly created object Called just after the memory is allocated for the object Can be used to initialize the objects to required or default values at the time of object creation It is not mandatory for the coder to write a constructor for the class When writing a constructor, remember that:
It has the same name as the class It does not return a value not even void It may or may not have parameters (arguments) Constructors cannot be abstract, final, native, static, or synchronized.
Tata Consultancy Services 42
9/7/2012
Constructors (2 of 2)
If no user defined constructor is provided for a class,
9/7/2012
43
Constructors (3 of 3)
Class Complex{ private float real; private float imaginary; public Complex(float x, float y){ real = x; imaginary = y; } public Complex(float real, float imaginary){ this.real = real; this.imaginary = imaginary; }
Student obj1 = new student(); Student obj2 = new student(); The two Student objects are now
obj1 1
obj3
heap
-- References: 3 -- Objects: 2
9/7/2012
obj2
Tata Consultancy Services 45
Lifetime of objects (2 of 2)
obj1 1 2 heap ob3
obj3 = obj1;
-- References: 3 -- Objects: 2
obj2 = null;
obj2
obj1 1 2
ob3
heap This object can be garbage collected (Can be Removed from memory)
9/7/2012
Null reference
obj2
Tata Consultancy Services
46
Garbage Collection
In Java, JVM will automatically do the memory de-allocation
Called Garbage collection However programmer has to ensure that reference to the object is released
If a reference variable is declared within a function, the reference is invalidated soon as the function call ends Other way of explicitly releasing the reference is to set the reference variable to null Setting a reference variable to null means that it is not referring to any object
9/7/2012
49
9/7/2012
50
Strings in Java
String is a system defined class in Java. It represents character strings. All string literals in Java programs, such as "abc", are implemented as
instances of this class and returns reference to them String is defined in the Java API under the package java.lang
The fully qualified name of String class in Java is java.lang.String
Strings are constant; their values cannot be changed after they are created
For example: String str = "abc"; is equivalent to: char data[] = {'a', 'b', 'c'}; String str = new String(data);
Coding standards and Best practices for naming classes and variables
Class name should begin with uppercase and camel casing Eg. Student, ArrayList Name should tell what the variable, method or class does No short form of words Variable name should start with lower case and to follow camel casing Eg. int numberOfStudents; Method names should begin with lowercase and follow camel casing Eg. void displayUserChoice()
9/7/2012
52
Control Statements
The syntax of the control statements in Java are the
following:
if if-else
for
while do-while switch break continue
9/7/2012
53
Arrays in Java (2 of 7)
Declaring Array Variables
<elementType>[] <arrayName>; or <elementType> <arrayName>[]; where <elementType> can be any primitive data type or reference type
Arrays in Java (3 of 7)
Constructing an Array
<arrayName> = new <elementType>[<noOfElements>];
Example:
int intArray[]; Pizza mediumPizza[], largePizza[]; intArray = new int[10]; mediumPizza = new Pizza[2]; largePizza = new Pizza[6];
Arrays in Java (1 of 7)
An array is a data structure which defines an ordered
collection of a fixed number of homogeneous data elements The size of an array is fixed and cannot increase to accommodate more elements Arrays in Java are objects and can be of primitive data types or reference variable type
20 50 45 100 70 An array holding 5 int elements
Arrays in Java (4 of 7)
Declaring and Initializing an Array
<elementType>[] <arayName> = {<arrayInitializerCode>};
Example:
int intArray[] = {1, 2, 3, 4}; char charArray[] = {a, b, c}; Pizza pizzaArray[] = {new Pizza(), new Pizza()};
9/7/2012
57
Arrays in Java (5 of 7)
Java checks the boundary of an array while accessing
an element in it Java will not allow the programmer to exceed its boundary If x is a reference to an array, x.length will give you the length of the array So setting up a for loop as follows is very common in Java
for(int i = 0; i < x.length; ++i){ x[i] = 5; }
9/7/2012 Tata Consultancy Services 58
Arrays in Java (6 of 7)
Multidimensional arrays are arrays of arrays.
To declare a multidimensional array variable, specify
9/7/2012
59
static (1 of 4)
static keyword can be used in 3 scenarios: For class variables For methods For a block of code
9/7/2012
60
static (2 of 4)
static variable
It is a variable which belongs to the class A single copy to be shared by all instances of the class For using static variables, creation of instance is not necessary Accessed using <class-name>.<variable-name> unlike instance variables which are accessed as
<object-name>.<variable-name>
static method
It is a class method Accessed using class name.method name For using static methods, creation of instance is not necessary A static method can only access other static data and methods. It cannot access non-static members
9/7/2012
61
Class Duck {
static (3 of 4)
private int size; private static int duckCount;
The static duckCount variable is initialised to 0, ONLY when the class is first loaded, NOT each time a new instance is made
public Duck(){
duckCount++; } public void setSize (int s){ size = s; } public int getSize (int s){ return size; } public static void main(String args[]){ System.out.println(Size of the duck is; + size); } }
Each time the constructor is invoked i.e. an object gets created, the static variable duckCount will be incremented thus keeping a count of the total no of Duck objects created
Which duck? Whose size? A static method cannot access anything non-static
Compilati on error
9/7/2012 Tata Consultancy Services 62
static (4 of 4)
static block The static block is a block of statement inside a Java class that will be executed when a class is first loaded and initialized
Method overloading (1 of 2)
More than one method within the same class having
the same name but differing in method signature are termed overloaded methods Calls to overloaded methods will be resolved during compile time
Also known as static polymorphism
Argument list could differ via: - No of parameters - Data type of parameters - Sequence of parameters - Return type provided parameter list is also changed
9/7/2012 Tata Consultancy Services 64
Method overloading (1 of 2)
Ex.
void void void void add add add add (int (int (int (int a, a, a, a, int b) float b) float b) int b, float c)
Overloaded methods
9/7/2012
65
Constructor overloading
Constructors can also be overloaded
Class Sample{ int Number1,Number2; Sample(){ Number1 = 10; Number2 = 10; } Sample (int Temp1, Temp2){ Number1 = Temp1; Number2 = Temp2; } }
9/7/2012
66
Inheritance
When is a relationship exists between two classes, we use inheritance The parent class is termed super class and the inherited class is the sub class The keyword extends is used by the sub class to inherit the features of super class
class Person{ /*attributes and functionality of Person defined*/ } class Student extends Person{ /*inherits the attributes and functionalities of Person and in addition add its own specialties*/ }
A subclass cannot access the private members of its super class. Inheritance leads to reusability of code
9/7/2012
multiple inheritance
GrandParent Paternal Maternal
Parent
Child
Allowed in Java
9/7/2012 Tata Consultancy Services
Child
Not Allowed in Java
68
Multi-Level Inheritance
A class can be further inherited from a derived class
The new class inherits all the member of all its ancestor classes
9/7/2012
69
Multiple Inheritance
Concept of a class inheriting from more than one base class
A Hybrid car can inherit from FuelCar and BatteryCar Multiple inheritance is rarely used because of the complexities it brings in
Inheritance
9/7/2012
70
Method overriding
superclass
1)Sachin overrides field() method ie gives a new definition to the method 2) Adds one new method
Cricketer
field() Play()
1)Bhajji adds one new instance variable 2) Adds one new method
9/7/2012
71
TermInsurancePolicy -term : int +setTerm(in term : int) : void +getTerm() : int +getBenifit() : double
More on Inheritance
Any number of sub classes can be created from a base class Consider a class EndowmentPolicy EndowmentPolicy is a Policy; EndowmentPolicy is extended from Policy Extra data members and methods are added
public class EndowmentPolicy extends Policy{ //Data Members and Methods }
9/7/2012
73
different classes
class
class Policy represents generalization Common data and methods of all types of policies are in Policy
represent specialization Specific functionality has been achieved by extending the Policy class
9/7/2012 Tata Consultancy Services 74
Specialization
Generalization
TermInsurancePolicy -term : int +setTerm(in term : int) : void +getTerm() : int +getBenifit() : double
EndowmentPolicy
9/7/2012
75
Method overriding (2 of 3)
Redefining a super class method in a sub class is
called method overriding Calls play method of the Cricketer class Cricketer cricketerObj= new Cricketer(); cricketerObj.play() Sachin sachObj = new Sachin ); Calls play method of the Sachin class sachObj.play()
9/7/2012
76
Method overriding (3 of 3)
Some rules in overriding The method signature i.e. method name, parameter list and return type have to match exactly The overridden method can widen the accessibility but not narrow it. This is applicable to default and protected methods but not to private methods
9/7/2012
77
Dynamic Binding
Can we do this?
Cricketer obj = new Sachin();
A reference to a super class can refer to a sub class object Now when we say obj.play(), which version of the method is called?
It calls Sachins version of the play() method as the reference is pointing to a Sachin
object
If a base class reference is used to call a method, the method to be invoked is decided by the JVM, depending on the object the reference is pointing to
For example, even though obj is a reference to Cricketer, it calls the method
9/7/2012
78
super
What if the play method in the Sachin class wants to
do the functionality defined in Cricketer class and then perform its own specific functionality? The play method in the Sachin class could be written as: play(){ This calls the super class version of play() and then super.play(); comes back to do the sub//add code specific to Sachin class specific stuff }
9/7/2012 Tata Consultancy Services 79
Polymorphism
STATIC
Function Overloading
within same class more than one method having same name but differing in signature
DYNAMIC
Function Overriding
keeping the signature and return type same, method in the base class is redefined in the derived class
Resolved during compilation time Return type is not part of method signature
9/7/2012
80
Abstract (1 of 4)
Consider a scenario where you consider a generalized class
Shape which has two subclasses Circle and Rectangle Circle and Rectangle have their own way to calculate area So, Shape class cannot decide how to calculate the area
it only provides the guideline to the child classes that such a
super class i.e. the method signature has been provided but the implementation has been deferred abstract public void Shape calculateArea(); Circle
9/7/2012 Tata Consultancy Services
Rectangle
81
Abstract (2 of 4)
The abstract keyword can be used for method and class
An abstract method signifies it has no body (implementation), only
If a class has one or more abstract methods declared inside it, the class
an abstract class
Reference of an abstract class can point to objects of its sub-classes
Abstract
abstract class Shape{ abstract public void calculateArea(); public void setColor(){ //code to color the shape } }
Note: An abstract class may also have concrete (complete) methods For design purpose, a class can be declared abstract even if it does not contain any abstract methods
9/7/2012 Tata Consultancy Services 83
slide)
9/7/2012
84
Final
final modifier has a meaning based on its usage For member data and local data in methods
Primitives: read-only (constant)
9/7/2012
85
Interfaces in Java
Let us consider a design option: class Dhoni has been designed
which is a sub-class of Cricketer Dhoni is also a Captain and it needs the behaviors of a captain So, should we place the functionalities of a Captain in class Dhoni? Then what happens when we design a class Cook which extends Cricketer and is also a Captain? Should we repeat the Captain functionalities again in Cook class? Object oriented feature of reusability of code is not being followed
9/7/2012
86
Interfaces in Java
So what is the solution?
What if we separate out the functionalities of Captain
Dhoni
So class Dhoni now extends from 2 base classes Cricketer
and Captain This too will not work as Multiple Inheritance is not supported in Java
9/7/2012 Tata Consultancy Services 87
Interfaces in Java
Interface can rescue us Interface is similar to an abstract class that contains
Captain
Dhoni
So class Dhoni now extends class Cricketer and
9/7/2012
88
Interface Characteristics
Interface methods are implicitly public and abstract Interface variables must be public, static and final Interface methods are not static
9/7/2012
89 89
Interfaces in Java
All methods in an interface are implicitly public and
abstract
interface Captain{ void doCaptaincy(); void play(); } class Dhoni extends Cricketerimplements Captain{ public void doCaptaicy(){ //functionality } public void play(){ //functionality } //other functions }
Interfaces in Java
An interface may define data members and these are
implicitly public, final and static An interface cannot have private or protected members An interface can extend from one or many interfaces A class can extend only one class but implement any number of interfaces
class Person extends LivingBeing implements Employee, Friend interface RidableAnimal extends Animal, Vehicle
9/7/2012 Tata Consultancy Services 91
Interfaces in Java
An interface cannot be instantiated
An interface reference can point to objects of its
implementing classes The same interface can be implemented by classes from different inheritance trees
Example, Parrot is a Bird but also a Pet class Parrot extends Bird implements Pet { }
9/7/2012
92
9/7/2012
93
Youll end up spending your precious time and energy and finally land up with huge amounts of code with you!
9/7/2012
94
9/7/2012
95
Concept of Packages
In Java, the code which can be reused by other
together as groups.
9/7/2012 Tata Consultancy Services 96
Features of Packages
Organize your classes into smaller units and make it
Creating a Package
In Java Packages are created in the following manner : package package_name ;
mypackage
class Calculator is inside the package
package mypackage ; public class Calculator { public int add(int x, int y) { return( x + y ) ; } }
9/7/2012
98
Importing a Package (1 of 1)
How can a class which is not a part of a package reuse the classes in
the package?
Use this class as <package_name>.<class_name> Referring to a class always by its fully qualified name becomes
cumbersome
following manner :
import <package_name>.<class_name>;
import mypackage.mysubpackage.MyClass;
follows :
9/7/2012 Tata Consultancy Services 99
9/7/2012
100
Yes
Yes
Yes
No
Yes
No
No
Yes
No
No
No
9/7/2012
101 101
Applicable To
Data members and methods
protected
All classes in the same package as well as all sub classes ie even sub classes residing in a different package
Any class
public
jar utility
All the .class files and associated files eg. .jpg files
can be combined and compressed together and handed over to the client as a single jar file JAR stands for Java Archive A JAR file is created using the jar utility If the client needs to run the application directly from the jar a manifest file needs to be created in the form of a .txt file The manifest file follows a specific format and contains the name of the main class ie starter class
9/7/2012 Tata Consultancy Services 103
Java.
You dont need to explicitly import this package. It is always imported for you. The String class, System class, Thread class, Wrapper classes etc, belong to this
package.
java.io
Input/Output operations in Java is handled by the java.io package.
java.util
Contains classes and interfaces that provide additional utility. Example : creating lists, calendar, date etc.
9/7/2012
104
9/7/2012
105
StringBuffer class
StringBuffer class is present in java.lang package as String Class
is. String is an object of the String class represents a fixed length, immutable sequence of characters. E.g. String str = "abc"; is equivalent to: char data[] = {'a', 'b', 'c'}; String str = new String(data); The prime difference between String and StringBuffer class is that the StringBuffer represents a string that can be dynamically modified. String Buffer's capacity could be dynamically increased even though its initial capacity is specified Whenever string manipulation like appending, inserting etc is required, this class should be used
Tata Consultancy Services 106
9/7/2012
Wrapper Classes (1 of 2)
There are many generic methods that take in
Objects and not primitive data types as parameters. We need some mechanism to convert the primitive data type to Objects to use these generic methods The wrapper classes in java.lang package help us to do this To create a Wrapper class object
int primitiveInt = 500; Integer wrapperInt = new Integer(primitiveInt); int value = wrapperInt.intValue(); //gives back the primitive data type int
107
Wrapper Classes (2 of 2)
Data Type Wrapper Class Data Type Wrapper Class
boolean
Boolean
byte
Byte
char
Character
short
Short
long
Long
int
Integer
float
Float
double
Double
9/7/2012
109
Exception Handling in Java (3 of 3) an error occurs, the program throws an exception When
The exception object that is thrown contains
information about the exception, including its type and the state of the program when the error occurred. The runtime environment attempts to find the Exception Handler The exception handler can attempt to recover from the error or, if it determines that the error is unrecoverable, provide a gentle exit from the program. Helpful in separating the execution code from the error handler
9/7/2012 Tata Consultancy Services 111
The Hierarchy
Object
Throwable
Error
Exception
Runtime Exception
..
..
handle
9/7/2012
113
Try Catch
try { } catch (exceptionType name) { } finally { } class ExceptionExample { public static void main(String argx[]) { int n,i; try { i=0; n=12/i; System.out.println("This line will not be printed"); catch(ArithmeticException e) { System.out.println("Division by zero" + e); } System.out.println("After catch statement"); } }
9/7/2012 Tata Consultancy Services
114
Finally Block
The finally statement is associated with a try statement
and identifies a block of statements that are executed regardless of whether or not an exception occurs within the try block.
Defines the code that is executed always
In the normal execution it is executed after the try block
device independent The classes for performing input and output operations are available in the package java.io
9/7/2012
117
Streams
Streams are channels of communication between
destination Abstract away the details of the communication path from I/O operation Streams hide the details of what happens to the data inside the actual I/O devices Streams can read/write data from/to blocks of memory, files and network connections
9/7/2012 Tata Consultancy Services 118
Streams(Contd)
Reads Source Stream Program
9/7/2012
119
of data
Bytes
Characters
Byte Oriented System
Byte I/O
Byte-Oriented System
9/7/2012
121
Methods in InputStream
int available()
void close() void mark(int numberofBytes) boolean markSupported() int read() int read(byte buffer[]) int read(byte buffer[], int offset, int numberofBytes) void reset() long skip(long numberofBytes)
9/7/2012 Tata Consultancy Services 122
Methods in OutputStream
void close()
void flush() void write(int b) void write(byte buffer[]) void write(byte buffer[], int offset, int numberofBytes)
9/7/2012
123
9/7/2012
124
9/7/2012
125
BufferedReader: Buffered input character stream InputStreamReader: Input stream that translates bytes to characters FilterReader :Filtered reader PushbackReader : Input stream that allows characters to be returned to the input stream CharArrayReader : Input stream that reads from a character array InputStreamReader : Input stream that translates bytes to characters FileReader :Input stream that reads from a file PipedWriter: Output pipe BufferedWriter: Buffered Output character stream OutputStreamWriter: Output stream that translates characters to bytes FilterWriter :Filtered writer CharArrayWriter : Output stream that writes to a character array FileWriter :Output stream that writes to a file
9/7/2012
126
buffering mechanism
FileOutputStream fileOutputStream=new FileOutputStream(Data); BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(fileOutputStream); byte data1 = 65, data2 = 66, data3 = 67; bufferedOutputStream.write(data1); bufferedOutputStream.write(data2); bufferedOutputStream.write(data3); bufferedOutputStream.close();
9/7/2012
127
Collections Framework
What is a collection framework?
A collection 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.
9/7/2012
128
Collections Framework
The core collection interfaces encapsulate different
types of collections and form the foundation of the Java Collections Framework. The core collection interfaces form a hierarchy as can be seen below.
Collection Map
Set
List
Queue
SortedMap
SortedSet
Iterable<E>
Iterator<E>
ListIerator<E>
PriorityQueue<E>
ArrayList<E> LinkedList<E>
TreeSet<E>
LinkedHashSet<E> Map<K,V> EnumMap<K,V> SortedMap<K,V> WeakHashMap<K,V> HashMap<E> TreeMap<K,V>
LinkedHashMap<K,V>
130
9/7/2012
Generic Types
Generic Class/Interface Type The Iterator<T> interface type Description Declares methods for iterating through elements of a collection, one at a time.
Supports an array-like structure for storing any type of object. The number of objects to be stored increases automatically as necessary. Supports the storage of any type of object in a pushdown stack. Supports the storage of any type of object in a doubly-linked list, which is a list that you can iterate though forwards or backwards. Supports the storage of an object of type V in a hash table, sometimes called a map. The object is stored using an associated key object of type K. To retrieve an object you just supply its associated key. Tata Consultancy Services 131
9/7/2012
Collections Framework
enhancements to the Java language called Generics. The <E> syntax signifies that the interface is Generic. What Generic actually means is that when you declare a Collection instance one can and should specify the type of the object contained in the Collection.
9/7/2012
132
Collections Framework
Iterator<E> iterator()
9/7/2012
133
Collections Framework
//optional //optional
//optional
Array Operations
Object[ ] toArray()
9/7/2012
<T> T[ ] toArray(T[ ] a)
Tata Consultancy Services 134
Collections Framework
keys to values. A Map cannot contain duplicate keys and each key can map to at most one value. The definition of Map interface: public interface Map<K,V>
9/7/2012
135
Collection Framework
int size()
boolean isEmpty()
9/7/2012 Tata Consultancy Services 136
Collections framework
Methods in Map interface continued 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()
9/7/2012
137
Collections Framework
9/7/2012
138
Collections Framework
Iterator interface
This interface has the methods to iterate through a Collection and also remove elements from the collection. Iterator takes the place of Enumeration in the Java Collection Framework. public interface Iterator<E>
boolean hasNext()
E next()
void remove()
9/7/2012
139
References
Herbert Schildt, The Complete Reference, Java J2SE 5
Edition, Tata McGraw Edition Sierra, Kathy and Bates, Bert, Head First Java, 2nd Edition, Shroff Publishers Thinking in Java by Bruce Eckel
9/7/2012
140
The contents of this document are proprietary and confidential to Tata Consultancy Services Ltd. and may not be disclosed in whole or in part at any time, to any third party without the prior written consent of Tata Consultancy Services Ltd.
9/7/2012
141