Sunteți pe pagina 1din 136

03/11/2011

Tata Consultancy Services

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

Tata Consultancy Services

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

enterprise applications and Mobile applications.

9/7/2012

Tata Consultancy Services

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

Tata Consultancy Services

Java features platform independence


Java is a language that is platform independent. A platform is the hardware and software environment

in which a program runs


Once compiled, code will run on any platform without

recompiling or any kind of modification.


Write Once Run Anywhere
This is made possible by making use of a Java Virtual

Machine commonly known as JVM


9/7/2012 Tata Consultancy Services 6

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

Byte code will be in a file with extension .class

9/7/2012

Tata Consultancy Services

Compilation & Execution


Java Program (.java)

Java Complier (javac)

Byte Code (.class file)

Interpreter (java)

Interpreter (java)

Interpreter (java)

Win 32

Linux

Mac

Java Virtual Machine (1 of 3)


The byte code is in the machine language format of a

machine known as the Java Virtual Machine or the


JVM
Needs a JVM to execute the byte code JVM is not a real machine, it is just a virtual machine;

implemented in software
9/7/2012 Tata Consultancy Services 9

Java Virtual Machine(2 of 3)


The source code of Java will be stored in file with extension .java The Java compiler (javac) compiles a .java file into byte code The byte code will be in a file with extension .class

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)

The byte code is interpreted by the JVM


JVM can be considered as a processor purely implemented with

software
9/7/2012 Tata Consultancy Services 10

Java Virtual Machine(3 of 3)


The interface that the JVM has to the .class file remains the

same irrespective of the underlying platform.


This makes platform independence possible

The JVM interprets the .class file to the machine language

of the underlying platform.


The underlying platform processes the commands given by

the JVM.
9/7/2012 Tata Consultancy Services 11

Java Architecture
Source File (HelloWorld.java)

JVM

Class Loader

Byte Code Verifier

Compiler (javac)

Interpreter

JIT Code Generator

Runtime

Machine Code or Byte code (HelloWorld.class)

Operating System Hardware

9/7/2012

Tata Consultancy Services

12

Java Run Time Environment(JRE) 1 of 3

9/7/2012

Tata Consultancy Services

13

Java Run Time Environment(JRE) 2 of 3

9/7/2012

Tata Consultancy Services

14

Java Run Time Environment(JRE) 3 of 3


The Java Virtual Machine forms part of a large system,

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,

a platform for developing stand alone and console based applications.


Java ME Java Mobile Edition. An application

platform for mobile devices.


Java EE Java Enterprise Edition. It is used developing

web based programs using Java.


9/7/2012 Tata Consultancy Services 16

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.

Each object has its own memory made up of other objects.

9/7/2012

Tata Consultancy Services

17

Objects A bike object

9/7/2012

Tata Consultancy Services

18

Objects..
Software objects are conceptually similar to real-world objects:

they too consist of state and related behavior.


An object stores its state in fields (variables in some

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

behave when the object is created or instantiated

9/7/2012

Tata Consultancy Services

20

Installing and using Java


Before we begin, something on installation
Java 5.0(v1.5 and up) Can be downloaded freely from

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Setting Environment variables for Java


Environment Variable:
A variable that describes the operating environment of the process. Common environment variables describe the home directory, command search path

etc.

9/7/2012

Tata Consultancy Services

21

Environment variables used by JVM


JAVA_HOME: Java Installation directory
This environment variable is used to derive all other env. variables used by JVM In Windows: set JAVA_HOME=C:\jdk1.5

CLASSPATH
In Windows: set CLASSPATH=%CLASSPATH%;%JAVA_HOME%\lib\tools.jar;.

PATH

Path variable is used by OS to locate executable files

In Windows: set PATH=%PATH%;%JAVA_HOME%\bin

This approach helps in managing multiple versions of Java Changing

JAVA_HOME will reflect on CLASSPATH and PATH as well.


Set these environment variables in a batch file.
9/7/2012 Tata Consultancy Services 22

Source File Layout - Hello World


We will have the source code first Type this into any text editor
public class HelloWorld { public static void main(String[]args){

System.out.println(Hello World!);
} }

Save this as HelloWorld.java Important : Take care!! CaSe of file name matters

9/7/2012

Tata Consultancy Services

23

To Compile
Open a command prompt
Set Environment variables (explained earlier)

Go to the directory in which you have saved your program


Type javac HelloWorld.java If it says bad command or file name then check the path setting. If it does not say anything, and you get the prompt, then the compilation was successful.
9/7/2012 Tata Consultancy Services 24

To execute
Type in the command prompt

java HelloWorldApp
The result

9/7/2012

Tata Consultancy Services

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

Tata Consultancy Services

26

Java Keywords (For Reference Only)


The reserved keywords defined in the Java language
abstract boolean break byte case catch char class true const continue float default do double else extends final finally for if import false interface long goto new implements instanceof null int return package private protected native public throw short super switch
synchronized

this transient void volatile while

static try throws

Data Types in Java


Java is a Strongly typed language What is typecasting? Impossible to typecast incompatible types
Two types of variables Primitive type Reference type

9/7/2012

Tata Consultancy Services

28

Primitive Data Types in Java


Notes:
Integer data types

byte (1 byte) short (2 bytes) int (4 bytes) long (8 bytes)

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

float (4 bytes) double (8 bytes)

Textual

char (2 bytes)

Logical

boolean (1 byte) (true/false)


9/7/2012 Tata Consultancy Services

covers all known scripts and


language in the world
29

Reference Types in Java (1 of 2)


A reference variable (object reference variable)is similar to a pointer

(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

Tata Consultancy Services

30

Reference Types in Java (2 of 2)


A reference type cannot be cast to primitive type
A reference type can be assigned null to show that it is

not referring to any object


null is a keyword in Java

9/7/2012

Tata Consultancy Services

31

Variables in Java
Using primitive data types is similar to other languages
int count; int max=100;

In Java variables can be declared anywhere in the program


for (int count=0; count < max; count++) { int z = count * 10; }

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

Tata Consultancy Services

32

Variables -- declaration and initialization (1 of 2)


Variables must have a type
Variables must have a name

int count

name

type

9/7/2012

Tata Consultancy Services

33

Variables -- declaration and assignment (2 of 2)


Assigning a value to the variable

count =10;
Declaration and initialization may be combined in a

single step int count =10;

9/7/2012

Tata Consultancy Services

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

Tata Consultancy Services

35

Typecasting of primitive data types


Automatic, non-explicit type changing is known as Conversion Variable of smaller capacity can be assigned to another variable of bigger capacity
int i = 10;

double d; d = i;

Whenever a larger type is converted to a smaller type, we have to

explicitly specify the type cast operator


double d = 10

Type cast operator

int i; i = (int) d; This prevents accidental loss of data

9/7/2012

Tata Consultancy Services

36

Operators and Assignments


Arithmetic Operators
The Bitwise operators Relational Operators Boolean Logical operators The ternary operator

9/7/2012

Tata Consultancy Services

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

Data Members (State/Structure)

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,

compiler initializes member variables to its default values. Examples:


numeric data types are set to 0

char data types are set to null character(\0)


reference variables are set to null

9/7/2012

Tata Consultancy Services

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; }

Lifetime of objects (1obj1 2) of


1 heap 2 obj2

Student obj1 = new student(); Student obj2 = new student(); The two Student objects are now

living on the heap -- References: 2 -- Objects: 2


Student obj3 = obj2;

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

-- Active References: 2 -- null references: 1 -- Reachable Objects: 1

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

An object which is not referred by any reference variable is removed from

memory by the garbage collector


Primitive types are not objects. They cannot be assigned null
9/7/2012 Tata Consultancy Services 47

Variables and their scope (1 of 3)


Instance variables (Also known as member variables) Declared inside a class Outside any method or constructor Belong to the object Stored in the heap area along with the object to which they belong Lifetime depends on the lifetime of the object Local variables (Also known as stack variables) Declared inside a method Method parameters are also local variables Stored in the program stack along with method calls and live until the call ends
9/7/2012 Tata Consultancy Services 48

Variables and their scope (2 of 3)


class Student{ int rollNo; String name; public void display (int z){ int x = z+10; } } rollNo and name are instance variables, to be stored in the heap

z and x are local variables to be stored in the stack

9/7/2012

Tata Consultancy Services

49

Variables and their scope (3 of 3)

9/7/2012

Tata Consultancy Services

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

String Methods are listed at: http://java.sun.com/javase/6/docs/api/java/lang/String.html


9/7/2012 Tata Consultancy Services 51

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

Tata Consultancy Services

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

Tata Consultancy Services

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

Example: int intArray[]; Pizza[] mediumPizza, largePizza;


9/7/2012 Tata Consultancy Services 54

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];

Declaration and Construction combined


int intArray[] = new int[10]; Pizza mediumPizza[] = new Pizza[5];
9/7/2012 Tata Consultancy Services 55

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

All elements in the array must be of the same data type


An array holding 4 rabbit objects
9/7/2012 Tata Consultancy Services 56

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

Tata Consultancy Services

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

each additional index using another set of square brackets.


-- Ex: int twoD[ ][ ] = new int[4][5] ;

9/7/2012

Tata Consultancy Services

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

Tata Consultancy Services

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

Tata Consultancy Services

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

A class is not loaded until an explicit request is made to the jvm.

class Test{ static { //Code goes here } }

A static block helps to initialize the static data members just

like constructors help to initialize instance members


9/7/2012 Tata Consultancy Services 63

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

void add (int a, float b) int add (int a, float b)

Not overloading. Compiler error.

9/7/2012

Tata Consultancy Services

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

Tata Consultancy Services

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*/ }

Person is more generalised

A subclass cannot access the private members of its super class. Inheritance leads to reusability of code

Student is a Person and is more specialized


67

9/7/2012

Tata Consultancy Services

Multi-level inheritance is allowed in Java but not

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

Tata Consultancy Services

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

Modern OO languages like Java and C# dont support Multiple

Inheritance

9/7/2012

Tata Consultancy Services

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

subclasses Sachin Bhajji spinBowling field() Bat() bowlSpin()

9/7/2012

Tata Consultancy Services

71

Is-A Relationship Inheritance


Policy -premium : double -maturityValue : double +setPremium(in premium : double) : void +getPremium() : double +setMaturityValue(in maturityValue : double) : void +getMaturityValue(in Amount : double) : void

TermInsurancePolicy -term : int +setTerm(in term : int) : void +getTerm() : int +getBenifit() : double

Note: Inheritance is represented by a triangle head arrow in UML Class diagrams


9/7/2012 Tata Consultancy Services 72

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

Tata Consultancy Services

73

Generalization and Specialization


To use inheritance One has to identify the similarities in different classes Move common data and methods to base class Generalization: Process of identifying the similarities among

different classes
class

class Policy represents generalization Common data and methods of all types of policies are in Policy

Specialization: Process of creating classes for specific need from

a common base class

Derived classes TermInsurancePolicy and EndowmentPolicy

represent specialization Specific functionality has been achieved by extending the Policy class
9/7/2012 Tata Consultancy Services 74

Generalization and Specialization Example


Policy -premium : double -maturityValue : double +setPremium(in premium : double) : void +getPremium() : double +setMaturityValue(in maturityValue : double) : void +getMaturityValue(in Amount : double) : void

Specialization

Generalization

TermInsurancePolicy -term : int +setTerm(in term : int) : void +getTerm() : int +getBenifit() : double

EndowmentPolicy

9/7/2012

Tata Consultancy Services

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

Tata Consultancy Services

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

Tata Consultancy Services

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

of Sachin, as it points to a Sachin object

This is decided during run-time and termed dynamic or run-time polymorphism

9/7/2012

Tata Consultancy Services

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

Resolved during run time


Which method to be invoked is decided by the object that the reference points to and not by the type of the reference

9/7/2012

Tata Consultancy Services

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

method should be implemented in them

calculateArea() method has been declared abstract in the

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

declaration of the method followed by a semicolon


abstract public double calculateArea();

If a class has one or more abstract methods declared inside it, the class

must be declared abstract


An abstract class cannot be instantiated ie objects cannot be created from

an abstract class
Reference of an abstract class can point to objects of its sub-classes

thereby achieving run-time polymorphism


9/7/2012 Tata Consultancy Services 82

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

Abstract Rules to follow (4 of 4)


The following cannot be marked with abstract modifier
Constructors Static methods Private methods Methods marked with final modifier (Explained in the next

slide)

9/7/2012

Tata Consultancy Services

84

Final
final modifier has a meaning based on its usage For member data and local data in methods
Primitives: read-only (constant)

Objects: reference is read-only

For methods: no overriding For classes: no inheritance

9/7/2012

Tata Consultancy Services

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

Tata Consultancy Services

86

Interfaces in Java
So what is the solution?
What if we separate out the functionalities of Captain

into a separate class?


Cricketer 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

only abstract methods The functionalities of Captain can be placed in an interface


Cricketer
extends implements

Captain

Dhoni
So class Dhoni now extends class Cricketer and
9/7/2012

implements Captain Services Tata Consultancy

88

Interface Characteristics
Interface methods are implicitly public and abstract Interface variables must be public, static and final Interface methods are not static

Interface can extend one or more interfaces


Interfaces cannot extend or implement classes Interfaces cannot implement interfaces

9/7/2012

Tata Consultancy Services

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 }

The class which implements the interface needs to

provide functionality for the methods declared in the interface


A class needs to be declared abstract if at least one of the

methods in the interface is left undefined


9/7/2012 Tata Consultancy Services 90

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 { }

interface Pet is being used by both Dog and Parrot

9/7/2012

Tata Consultancy Services

92

Abstract Class vs Interface Design Choice


Use an abstract class when a template needs to be

defined for a group of sub-classes


ensure that no objects need to be created from it

Use an interface when a role needs to be defined for

other classes, regardless of the inheritance tree of these classes

9/7/2012

Tata Consultancy Services

93

Just think of writing the code

Packages in Java Why ? What ? (1 of 2)


from the scratch, each time you create an application

Youll end up spending your precious time and energy and finally land up with huge amounts of code with you!

9/7/2012

Tata Consultancy Services

94

Packages in Java Why ? What Reusability of code is one of the ? (2 of 2)


most important requirements in the software industry.
Reusability saves time, effort

and also ensures consistency.


A class once developed can be reused by any number of programs wishing to incorporate the class in that particular program.

9/7/2012

Tata Consultancy Services

95

Concept of Packages
In Java, the code which can be reused by other

programs is put into a Package.


A Package is a collection of classes, interfaces

and/or other packages.


Packages are essentially a means of organizing classes

together as groups.
9/7/2012 Tata Consultancy Services 96

Features of Packages
Organize your classes into smaller units and make it

easy to locate and use the appropriate class file.


Avoid naming conflicts
Package names can be used to identify your classes.

Packages allow you to protect your classes, data and

methods in a larger way than on a class-to-class basis.


9/7/2012 Tata Consultancy Services 97

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

Tata Consultancy Services

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

In Java, the Packages can be imported into a program in the

following manner :
import <package_name>.<class_name>;

import mypackage.mysubpackage.MyClass;

Suppose we wish to use a class say My_Class whose location is as

follows :
9/7/2012 Tata Consultancy Services 99

9/7/2012

Tata Consultancy Services

100

Class Member Visibility


Visibility From the same class From any class in the same package From a subclass in the same package From a subclass outside the same package From any nonsubclass outside the package Public Yes Yes Protected Yes Yes Default Yes Yes Private Yes No

Yes

Yes

Yes

No

Yes

Yes, through inheritance

No

No

Yes

No

No

No

9/7/2012

Tata Consultancy Services

101 101

Access Specifiers (3 of 3) Keyword


private

Applicable To
Data members and methods

Who can Access


All members within the same Class only All classes in the same package

(No keyword, usually we call it default)

Data members, methods, classes and interfaces

protected

Data members and methods

All classes in the same package as well as all sub classes ie even sub classes residing in a different package
Any class

public

Data members, methods, classes and interfaces

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

Standard Java Packages


java.lang
Contains classes that form the basis of the design of the programming language of

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

Tata Consultancy Services

104

Standard Java Packages


java.net This package provides classes and interfaces for TCP/IP network programming. java.awt This package is useful to create GUI applications. java.applet This package consists of classes that you need, to write programs to add more features to a web page.

9/7/2012

Tata Consultancy Services

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

Wrapper Class -> True Object Oriented


9/7/2012

implementation of the primitive data types


Tata Consultancy Services

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

Exception Handling in Java (1 of 3)


int i = 5/0;
What happens when the above code is executed ? Exception is thrown (an object is thrown) How to recover from this ? (handle it !)

9/7/2012

Tata Consultancy Services

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

..

..

Exceptions and Errors


Exceptions are situations within the control of an

application, that it should try to handle


Errors indicate serious problems and abnormal

conditions that most applications should not try to

handle

9/7/2012

Tata Consultancy Services

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

When an exception occurs, it is executed after the

handler if any or before propagation as the case may be


9/7/2012 Tata Consultancy Services 116

Input and Output Streams


The Java Input/Output system is designed to make it

device independent The classes for performing input and output operations are available in the package java.io

9/7/2012

Tata Consultancy Services

117

Streams
Streams are channels of communication between

programs and source/destination of data


A stream is either a source of bytes or a destination for bytes.

Provide a good abstraction between the source and

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

Writes Program Stream Destination

9/7/2012

Tata Consultancy Services

119

Javas Input-Output System


The basic I/O system of Java can handle only two types

of data
Bytes
Characters
Byte Oriented System

Java Input/Output System

Character oriented System

Byte I/O
Byte-Oriented System

The following are the two abstract classes provided for

reading and writing bytes


InputStream OutputStream

- Reading bytes - Writing bytes

For performing I/O operations, we are dependent on the

sub classes of these two classes

9/7/2012

Tata Consultancy Services

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

Tata Consultancy Services

123

Reader Hierarchy Reader


CharArrayReader
BufferedReader FilteredReader PushbackReader InputStreamReader FileReader

9/7/2012

Tata Consultancy Services

124

Writer Hierarchy Writer


CharArrayWriter
BufferedWriter PrintWriter OutputStreamWriter FileWriter

9/7/2012

Tata Consultancy Services

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

Tata Consultancy Services

126

Example- Writing to a stream


The following code snippet writes bytes to a file using

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

Tata Consultancy Services

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.

Advantages Reduces programming effort Increases performance Fosters software reuse

9/7/2012

Tata Consultancy Services

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

Note that the hierarchy consists of two distinct trees.

The Map is not a not a true collection.


9/7/2012 Tata Consultancy Services 129

Type Trees for Collections

Iterable<E>

Iterator<E>

Collection<E> Set<E> SortedSet<E> Queue<E> EnumSet<E> HashSet<E> List<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

Tata Consultancy Services

The Collections Framework


The Java collection framework is a set of generic types that are used to create collection classes that support various ways to store and manage objects of any kind in memory. A generic type for collection of objects: To get static checking by the

compiler for whatever types of objects to want to manage.

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.

The Vector<T> type

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

The Stack<T> type The LinkedList<T> type

The HashMap<K,V> type

9/7/2012

Collections Framework

The definition of collection interface:


public interface Collection<E>extends Iterable<E>

The <E> syntax is very important and part of Java 5

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

Tata Consultancy Services

132

Collections Framework

Methods in collection interface Basic Operations


int size() boolean isEmpty() boolean contains(Object element) boolean add(E element) //Optional boolean remove(Object element) //optional

Iterator<E> iterator()

9/7/2012

Tata Consultancy Services

133

Collections Framework

Methods in collection interface continued


Bulk Operations
boolean containsAll(Collection<?> c) boolean addAll(Collection<? extends E> c) //optional boolean removeAll(Collection<?> c) boolean retainAll(Collection<?> c) void clear();

//optional //optional

//optional

Array Operations
Object[ ] toArray()

9/7/2012

<T> T[ ] toArray(T[ ] a)
Tata Consultancy Services 134

Collections Framework

The Map interface represents an object that maps

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

Tata Consultancy Services

135

Collection Framework

Methods in Map interface Basic operations


V put(K key V value) V get(Object key) V remove(Object key) boolean containsKey(Object key) boolean containsValue(Object value)

int size()
boolean isEmpty()
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

Tata Consultancy Services

137

Collections Framework

Methods in Map interface continued Interface for entrySet elements


K getKey() V getValue() V setValue(V value)

9/7/2012

Tata Consultancy Services

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

Tata Consultancy Services

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

Tata Consultancy Services

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

Tata Consultancy Services

141

S-ar putea să vă placă și