Top Banner
Java Programming Java Programming
129
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java Programming

Java ProgrammingJava Programming

Page 2: Java Programming

Exception HandlingException Handling Types of errorsTypes of errors1.1. Compile time errorsCompile time errors2.2. Run-time errorsRun-time errors

Page 3: Java Programming

Compile time errorsCompile time errors All syntax errors will be detected and All syntax errors will be detected and

displayed by the Java compiler and therefore displayed by the Java compiler and therefore these errors are known as compile-time errors. these errors are known as compile-time errors.

Whereever the compiler displays an error, it Whereever the compiler displays an error, it will not create the .class file.will not create the .class file.

Page 4: Java Programming

Compile time errorsCompile time errors1.1. Missing semicolonsMissing semicolons2.2. Missing( or mismatch of) brackets in classes and Missing( or mismatch of) brackets in classes and

methodsmethods3.3. Misspelling of identifiers and keywordsMisspelling of identifiers and keywords4.4. Missing double quotes in stringsMissing double quotes in strings5.5. Use of undeclared variablesUse of undeclared variables6.6. Incompatible types in assignments/initializationIncompatible types in assignments/initialization7.7. Bad references to objectsBad references to objects8.8. Use of = in place of == operator etc.Use of = in place of == operator etc.

Page 5: Java Programming

Run time errorsRun time errors1.1. Dividing an integer by zeroDividing an integer by zero2.2. Accessing an element that is out of the bounds of an arrayAccessing an element that is out of the bounds of an array3.3. Trying to cast an instance of a class to one of its subclasses.Trying to cast an instance of a class to one of its subclasses.4.4. Passing a parameter that is not in a valid range or value for a Passing a parameter that is not in a valid range or value for a

method.method.5.5. Trying to illegally change the state of a threadTrying to illegally change the state of a thread6.6. Using a null object reference as a legitimate object Using a null object reference as a legitimate object

reference to access a method or a variablereference to access a method or a variable7.7. Converting an invalid string to a numberConverting an invalid string to a number8.8. Accessing a character that is out of bounds of a stringAccessing a character that is out of bounds of a string

Page 6: Java Programming

ExceptionsExceptions An Exception is a condition that is caused by a run time An Exception is a condition that is caused by a run time

error in the program. When the java interpreter encounters error in the program. When the java interpreter encounters an error such as dividing an integer by zero,, it creates an an error such as dividing an integer by zero,, it creates an exception object and throws it(ie. It informs that an error has exception object and throws it(ie. It informs that an error has occurred)occurred)

The purpose of exception handling mechanism is to provide The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional circumstances” a means to detect and report an “exceptional circumstances” so that appropriate action can be taken..so that appropriate action can be taken..

There are three stesp in exception handling.There are three stesp in exception handling.1.1. Find the problem(Hit the exception)Find the problem(Hit the exception)2.2. Inform that an error has occurred(Throw the exception)Inform that an error has occurred(Throw the exception)3.3. Receive the error information(Catch the exception)Receive the error information(Catch the exception)4.4. Take corrective actions(Handle the exception)Take corrective actions(Handle the exception)

Page 7: Java Programming

Common java exceptionsCommon java exceptions Arithmetic Exception: caused by math errors such as division by zeroArithmetic Exception: caused by math errors such as division by zero ArrayIndexOutOfBoundsException: caused by bad array indicesArrayIndexOutOfBoundsException: caused by bad array indices ArrayStoreException: caused when a program tries to store the wrong type ArrayStoreException: caused when a program tries to store the wrong type

of data in an arrayof data in an array FileNotFoundException: caused by an attempt to access a nonexistent fileFileNotFoundException: caused by an attempt to access a nonexistent file IOException: caused by general I/O failures, such as inability to read from IOException: caused by general I/O failures, such as inability to read from

a filea file NullPointerException: caused by referencing a null object.NullPointerException: caused by referencing a null object. NumberFormatException:Caused when a conversion between strings and NumberFormatException:Caused when a conversion between strings and

number fails.number fails. OutOfMemoryException:Caused when there is not enough memory to OutOfMemoryException:Caused when there is not enough memory to

allocate an Objectallocate an Object

Page 8: Java Programming

SecurityException: Caused when an applet SecurityException: Caused when an applet tries to perform an action not allowed by the tries to perform an action not allowed by the browser’s security setting.browser’s security setting.

StackOverflowException: Caused when the StackOverflowException: Caused when the system runs out of stack space.system runs out of stack space.

StringIndexOutOfBoundsException:Caused StringIndexOutOfBoundsException:Caused when a program attempts to access a non-when a program attempts to access a non-existent character position in string.existent character position in string.

Page 9: Java Programming

Try-catch statement.Try-catch statement.

Page 10: Java Programming

Different Types of ProgrammingDifferent Types of Programming Proceedure Oriented Programming(POP)Proceedure Oriented Programming(POP) Object Oriented Programming System(OOPS)Object Oriented Programming System(OOPS)

Page 11: Java Programming

Procedure Oriented Programming(POP)Procedure Oriented Programming(POP)

It gives more emphasis on procedure than data.It gives more emphasis on procedure than data. Main() is the most important part of POPMain() is the most important part of POP Main() controls the entire programMain() controls the entire program To reduce the complexity it can be modularised in to more To reduce the complexity it can be modularised in to more

than one sub functions.than one sub functions. The main() controls the activities of entire sub functions.The main() controls the activities of entire sub functions. There has communication between main function and sub There has communication between main function and sub

functions each other.functions each other. The main function determines which sub function has to be The main function determines which sub function has to be

functioned and which has to be stopped their activities.functioned and which has to be stopped their activities. It is simple and needs less memory storage.It is simple and needs less memory storage.

Page 12: Java Programming

Disadvantages of POPDisadvantages of POP Less data security.Less data security.

Page 13: Java Programming

Object Oriented Programming Object Oriented Programming System(OOPS)System(OOPS)

Data is the most important factor in OOPS Data is the most important factor in OOPS rather than function(procedure)rather than function(procedure)

Provides high data securityProvides high data security Programs are divided into what are known as Programs are divided into what are known as

ObjectsObjects Data structures are designed such that they Data structures are designed such that they

characterize the objectscharacterize the objects Methods that operate on the data of an object Methods that operate on the data of an object

are tied together in the data structureare tied together in the data structure

Page 14: Java Programming

The back bone of OOPSThe back bone of OOPS OOPS is working on the basis of 8 main factorsOOPS is working on the basis of 8 main factors1.1. ObjectObject2.2. ClassClass3.3. Data EncapsulationData Encapsulation4.4. Data AbstractionData Abstraction5.5. Poly morphismPoly morphism6.6. InheritanceInheritance7.7. Dynamic BindingDynamic Binding8.8. Message PassingMessage Passing

Page 15: Java Programming

ObjectObject It is a basic runtime entity. Any living and It is a basic runtime entity. Any living and

non-living things can be referred as entity.non-living things can be referred as entity. It represents properties of entity.It represents properties of entity.

Page 16: Java Programming

ClassClass It is a user-defined data type.It is a user-defined data type. Object can be referred as an instance of classObject can be referred as an instance of class It is used to keep the data of an object safely.It is used to keep the data of an object safely. The each object of a class has same properties.The each object of a class has same properties.

Page 17: Java Programming

Data EncapsulationData Encapsulation Data Encapsulation is the process of keeping Data Encapsulation is the process of keeping

data from external functions, by class.data from external functions, by class. For this purpose class uses access specifiers For this purpose class uses access specifiers

such as private, public, and protected.such as private, public, and protected.

Page 18: Java Programming

Data AbstractionData Abstraction Data Abstraction is the process of providing Data Abstraction is the process of providing

the data to the external function, by class.the data to the external function, by class. It provides the copy of the data , which is It provides the copy of the data , which is

useful for the execution of the external useful for the execution of the external functions.functions.

The original data will be kept in the class The original data will be kept in the class itself.itself.

Page 19: Java Programming

PolymorphismPolymorphism It is the process of operators and functions to It is the process of operators and functions to

execute an extra task besides its original task.execute an extra task besides its original task. There are two types of polymorphism.There are two types of polymorphism.1.1. Compile Time PolymorphismCompile Time Polymorphism2.2. Run Time PolymorphismRun Time Polymorphism If the polymorphism occurs during compilation, it If the polymorphism occurs during compilation, it

is known as compile time polymorphismis known as compile time polymorphism If the polymorphism occurs in runtime, it is known If the polymorphism occurs in runtime, it is known

as runtime polymorphismas runtime polymorphism

Page 20: Java Programming

InheritanceInheritance Inheritance is the process of deriving a class Inheritance is the process of deriving a class

from another class.from another class. The derived class is known as child class or The derived class is known as child class or

sub class sub class The class, from which the child class has been The class, from which the child class has been

derived, is known as parent class or base class.derived, is known as parent class or base class. During inheritance, the child class inherits all During inheritance, the child class inherits all

the properties of parent class. the properties of parent class.

Page 21: Java Programming

Different types of inheritanceDifferent types of inheritance The different types of inheritance are:The different types of inheritance are:1.1. Simple inheritanceSimple inheritance2.2. Multiple inheritanceMultiple inheritance3.3. Multilevel inheritanceMultilevel inheritance4.4. Hierarchical inheritanceHierarchical inheritance5.5. Hybrid inheritanceHybrid inheritance

Page 22: Java Programming

Simple inheritance Simple inheritance When a single child class inherits from a When a single child class inherits from a

single parent class, it is known as simple single parent class, it is known as simple inheritance.inheritance.

Class A

Class B

Page 23: Java Programming

Multiple inheritanceMultiple inheritance When a single class inherits from a pair of When a single class inherits from a pair of

parent classes, it is known as multiple parent classes, it is known as multiple inheritance.inheritance.

Class A Class B

Class C

Page 24: Java Programming

Multilevel inheritanceMultilevel inheritance When a class inherits from another class, When a class inherits from another class,

which is already a child class of another class, which is already a child class of another class, the process is known as multilevel inheritance.the process is known as multilevel inheritance.

Class A

Class B

Class C

Page 25: Java Programming

Hierarchical inheritanceHierarchical inheritance This type of inheritance forms a hierarchy.This type of inheritance forms a hierarchy. There is a root class, from which more than There is a root class, from which more than

one class will be generated.one class will be generated. Another set of sub classes will be generated Another set of sub classes will be generated

from the above sub classes and goes on.from the above sub classes and goes on.

Page 26: Java Programming

Class A

Class B Class C

Class D Class E Class F Class G

Page 27: Java Programming

Hybrid inheritanceHybrid inheritance It is the inheritance, which is a combination of It is the inheritance, which is a combination of

multiple and hierarchical inhertiances.multiple and hierarchical inhertiances. A root class generates two sub classes and A root class generates two sub classes and

from these sub classes another sub class is from these sub classes another sub class is generated. Thus it forms cyclic. generated. Thus it forms cyclic.

Class A

Class D

Class BClass C

Page 28: Java Programming

Dynamic BindingDynamic Binding It is the process of connecting objects each It is the process of connecting objects each

other and its corresponding function other and its corresponding function calls ,when the program is running.calls ,when the program is running.

Page 29: Java Programming

Message PassingMessage Passing It is the process of communication done It is the process of communication done

among the objects, with in the program.among the objects, with in the program.

Page 30: Java Programming

Features of JavaFeatures of Java Java was developed by James Gosling in Sun Java was developed by James Gosling in Sun

Microsystems in USA in 1991.Microsystems in USA in 1991. The main features of Java are:The main features of Java are:1.1. Compiled and interpretedCompiled and interpreted2.2. Platform-Independent and PortablePlatform-Independent and Portable3.3. Object OrientedObject Oriented4.4. Robust and SecureRobust and Secure5.5. DistributedDistributed6.6. Familiar, Simple and smallFamiliar, Simple and small7.7. Multithreaded and interactiveMultithreaded and interactive8.8. High PerformanceHigh Performance9.9. Dynamic and ExtensibleDynamic and Extensible

Page 31: Java Programming

Compiled and InterpretedCompiled and Interpreted Java has compiler and interpretorJava has compiler and interpretor The java compiler compiles the java program The java compiler compiles the java program

and convert it to a class file.and convert it to a class file. The class file contains byte codesThe class file contains byte codes The class file can be runnable in any operating The class file can be runnable in any operating

systemsystem The java interpretor runs the java program and The java interpretor runs the java program and

the class file is converted to .exe file, which is the class file is converted to .exe file, which is not persistent.not persistent.

Page 32: Java Programming

Platform independent and portablePlatform independent and portable

Java is platform independent language.Java is platform independent language. Ie. It can be run in any operating system.Ie. It can be run in any operating system. The byte codes of class file is accessible to all The byte codes of class file is accessible to all

operating system and java can be run in any operating system and java can be run in any operating system.operating system.

By the term portability, we mean that java can By the term portability, we mean that java can work with the different kind of environments work with the different kind of environments provided by various operating systems.provided by various operating systems.

Page 33: Java Programming

Object OrientedObject Oriented Java is purely object oriented.Java is purely object oriented.

Page 34: Java Programming

Robust and secureRobust and secure Java is a robust languageJava is a robust language It provides many safeguards to ensure reliable It provides many safeguards to ensure reliable

codescodes Java systems not only verify all memory Java systems not only verify all memory

access but also ensure that no viruses are access but also ensure that no viruses are communicated with an applet.communicated with an applet.

Page 35: Java Programming

DistributedDistributed It is used for creating network applications.It is used for creating network applications.

Page 36: Java Programming

Simple, Small and Simple, Small and FamiliarFamiliar

It is simple when we compare with c ,c++It is simple when we compare with c ,c++ Some of its statements are familiar with c,c++Some of its statements are familiar with c,c++

Page 37: Java Programming

Multithreaded and InteractiveMultithreaded and Interactive Multithreading is the process of handling Multithreading is the process of handling

multiple tasks simultaneously.multiple tasks simultaneously.

Page 38: Java Programming

High PerformanceHigh Performance Java is an impressive for an interpreted Java is an impressive for an interpreted

language due to the use of intermediate byte language due to the use of intermediate byte code.code.

Page 39: Java Programming

Dynamic and ExtensibleDynamic and Extensible Java is a dynamic language.Java is a dynamic language. It dynamically links with new class libraries, It dynamically links with new class libraries,

methods and objects.methods and objects.

Page 40: Java Programming

Differences between Java and CDifferences between Java and C Java does not include statements goto, sizeof, Java does not include statements goto, sizeof,

and typedefand typedef Java does not contain the data types struct, Java does not contain the data types struct,

union, and enumunion, and enum Java does not define the type modifiers Java does not define the type modifiers

keywords auto, extern, register, signed and keywords auto, extern, register, signed and unsignedunsigned

Java does not support explicit pointer type.Java does not support explicit pointer type.

Page 41: Java Programming

Java does not have preprocessor statements. So we Java does not have preprocessor statements. So we cannot use #define, #include, and #ifdef statementscannot use #define, #include, and #ifdef statements

Java does not support any mechanism for defining Java does not support any mechanism for defining variable arguments to functions.variable arguments to functions.

Java requires that the functions with no arguments Java requires that the functions with no arguments must be declared with empty parenthesis and not with must be declared with empty parenthesis and not with the void keyword as done in Cthe void keyword as done in C

Java adds new operators such as instanceof and>>>Java adds new operators such as instanceof and>>> Java adds labelled break and continue statements.Java adds labelled break and continue statements. Java adds many features required for object-oriented Java adds many features required for object-oriented

programming.programming.

Page 42: Java Programming

Differences between java and C++Differences between java and C++

Java does not support operator overloadingJava does not support operator overloading Java does not have template classes as in c++Java does not have template classes as in c++ Java does not support multiple inheritance of classes. Java does not support multiple inheritance of classes.

It has been implemented by “interface”It has been implemented by “interface” Java does not support global variables. Java does not support global variables. Java does not use pointers.Java does not use pointers. Java has replaced the destructor function with a Java has replaced the destructor function with a

finalize() function.finalize() function. There are no header files in java.There are no header files in java.

Page 43: Java Programming

Java Development KitJava Development Kit Javac: used for java compilation( java compiler)Javac: used for java compilation( java compiler) Java: used for java interpretation( running the Java: used for java interpretation( running the

program)program) Javadoc:creates HTML format documentation from Javadoc:creates HTML format documentation from

java source code files.java source code files. Javah: produces header files for use with native Javah: produces header files for use with native

methods.methods. Javap: java disassembler, which enables us to convert Javap: java disassembler, which enables us to convert

bytecode files into a program descriptionbytecode files into a program description Jdb: java debugger, which helps us to find errors in Jdb: java debugger, which helps us to find errors in

our programs.our programs.

Page 44: Java Programming

Application Program Interface(API)Application Program Interface(API)

It provides the environment to work java in a It provides the environment to work java in a particular platform. particular platform.

It contains a lot of classes and methods. It is a It contains a lot of classes and methods. It is a class library.class library.

These class libraries are generally known as These class libraries are generally known as “packages”;“packages”;

Two types of packages:Two types of packages:1.1. User-defined packageUser-defined package2.2. Built-in packageBuilt-in package

Page 45: Java Programming

User-defined packages are the packages which User-defined packages are the packages which are created by user himself.are created by user himself.

Built-in packages are those packages, which Built-in packages are those packages, which are already defined in the APIare already defined in the API

Page 46: Java Programming

Different types of APIsDifferent types of APIs Language support package: A collection of classes and Language support package: A collection of classes and

methods required for implementing basic features of Javamethods required for implementing basic features of Java Utilities package: Contains a collection of classes to provide Utilities package: Contains a collection of classes to provide

utility functions such as date and time functions.utility functions such as date and time functions. Input/output package: Contains a collection of classes used for Input/output package: Contains a collection of classes used for

input/output operations.input/output operations. Networking package: Contains a collection of classes used for Networking package: Contains a collection of classes used for

network operations.network operations. AWT package: Contains a collection of classes used for AWT package: Contains a collection of classes used for

graphics.graphics. Applet package: Contains a collection of classes used for Applet package: Contains a collection of classes used for

applet programming.applet programming.

Page 47: Java Programming

Different types of Java applicationsDifferent types of Java applications

Stand alone applicationsStand alone applications Web-Applets.Web-Applets.

Page 48: Java Programming

Java TokensJava Tokens Smallest individual units of a java program is Smallest individual units of a java program is

known as tokens.known as tokens. Java language has 5 types of tokens.Java language has 5 types of tokens.1.1. Reserved keywordsReserved keywords2.2. IdentifiersIdentifiers3.3. LiteralsLiterals4.4. OperatorsOperators5.5. SeperatorsSeperators

Page 49: Java Programming

Reserved keywordsReserved keywords It is an essential part of java programming It is an essential part of java programming

language.language.

Page 50: Java Programming

IdentifiersIdentifiers They are programmer designed tokens, They are programmer designed tokens,

which are used for naming classes, variables, which are used for naming classes, variables, objects, labels, packages, and interfaces in a objects, labels, packages, and interfaces in a program. Rules for naming are:program. Rules for naming are:

1.1. They can have alphabets, digits, and the They can have alphabets, digits, and the underscore and dollar sign characters.underscore and dollar sign characters.

2.2. They must not begin with a digitThey must not begin with a digit3.3. Uppercase and lowercase letters are distinct.Uppercase and lowercase letters are distinct.4.4. They can be of any length.They can be of any length.

Page 51: Java Programming

Names of all public methods and instance variables start with Names of all public methods and instance variables start with a leading lowercase letter. Eg: average, suma leading lowercase letter. Eg: average, sum

When more than one word are used in a name, the second and When more than one word are used in a name, the second and subsequent words are marked with a leading uppercase letters. subsequent words are marked with a leading uppercase letters. Example:dayTemperature, firstDayofMonth etcExample:dayTemperature, firstDayofMonth etc

All private and local variables use only lowercase letters All private and local variables use only lowercase letters combined with underscores. Examples:length, batch_strengthcombined with underscores. Examples:length, batch_strength

All classes and interfaces start with a leading uppercase All classes and interfaces start with a leading uppercase letter(and each subsequent word with a leading uppercase letter(and each subsequent word with a leading uppercase letter)letter)

Variables that represent constant values use all uppercase Variables that represent constant values use all uppercase letters and underscores between words.letters and underscores between words.

Page 52: Java Programming

LiteralsLiterals Literals in java are a sequence of characters(digits, Literals in java are a sequence of characters(digits,

letters, and other characters) that represent constant letters, and other characters) that represent constant values to be stored in variables.values to be stored in variables.

The different literals used in java are:The different literals used in java are:1.1. Integer literalsInteger literals2.2. Floating_point literalsFloating_point literals3.3. Character literalsCharacter literals4.4. String literalsString literals5.5. Boolean literalsBoolean literals

Page 53: Java Programming

OperatorsOperators They include They include 1.1. Arithmetic operatorsArithmetic operators2.2. Relational operatorsRelational operators3.3. Logical operatorsLogical operators4.4. Assignment operatorsAssignment operators5.5. Increment and decrement operatorsIncrement and decrement operators6.6. Conditional operatorsConditional operators7.7. Bitwise operatorsBitwise operators8.8. Special operatorsSpecial operators

Page 54: Java Programming

Arithmetic operatorsArithmetic operators Used for arithmetic operations such as Used for arithmetic operations such as

addition, subtraction, multiplication and addition, subtraction, multiplication and division.division.

The arithmetic operators are “+,-,*, / and %”.The arithmetic operators are “+,-,*, / and %”.

Page 55: Java Programming

Relational operatorsRelational operators They are used for expressing relationships.They are used for expressing relationships. They are:<, <=, >,>=,==,!=They are:<, <=, >,>=,==,!=

Page 56: Java Programming

Logical operatorsLogical operators The logical operators are: &&, ||,!The logical operators are: &&, ||,! &&-> logical and operator. &&-> logical and operator. ||-> logical or operator||-> logical or operator !-> logical not operator.!-> logical not operator.

Page 57: Java Programming

Assignment operatorsAssignment operators It is used to assign the values to a variable.It is used to assign the values to a variable. ““=“ is the assignment operator.=“ is the assignment operator.

Page 58: Java Programming

Increment and Decrement OperatorsIncrement and Decrement Operators

They are used to increment and decrement the They are used to increment and decrement the values of a variable by 1.values of a variable by 1.

There are two types of increment operators:There are two types of increment operators:1.1. Post increment operators Eg: i++Post increment operators Eg: i++2.2. Pre increment operators. Eg:++iPre increment operators. Eg:++i Similarly there are two types of decrement Similarly there are two types of decrement

operators:operators:1.1. Post decrement operators Eg.:i--Post decrement operators Eg.:i--2.2. Pre decrement operators.Eg.:--iPre decrement operators.Eg.:--i

Page 59: Java Programming

Conditional operatorsConditional operators Otherwise known as Ternary operatorOtherwise known as Ternary operator The pair of operators “? :” are known as The pair of operators “? :” are known as

Ternary operators.Ternary operators. It is used in conditional expressions.It is used in conditional expressions.

Page 60: Java Programming

Bitwise operatorsBitwise operators Bitwise operators are used for manipulation of Bitwise operators are used for manipulation of

data at values of bit level.data at values of bit level. These operators are used for testing the bits, or These operators are used for testing the bits, or

shifting them to the right or left. Bitwise shifting them to the right or left. Bitwise operators may not be applicable to float or operators may not be applicable to float or double.double.

Page 61: Java Programming

OperatorOperator MeaningMeaning

&& Bitwise ANDBitwise AND

!! Bitwise ORBitwise OR

^̂ Bitwise exclusive ORBitwise exclusive OR

~~ One’s complementOne’s complement

<<<< Shift leftShift left

>>>> Shift rightShift right

>>>>>> Shift right with zero fillShift right with zero fill

Page 62: Java Programming

Special operatorsSpecial operators Java supports two special operatorsJava supports two special operators Instanceof operator: This is an object Instanceof operator: This is an object

reference operator and returns true if the object reference operator and returns true if the object on the left hand side is an instance of the class on the left hand side is an instance of the class given on the right hand side.given on the right hand side.

Example: person instanceof StudentExample: person instanceof Student Dot operator: It is used to access the instance Dot operator: It is used to access the instance

variables and methods of class objects.variables and methods of class objects.

Page 63: Java Programming

ConstantConstant Constants are values to be stored in a variable.Constants are values to be stored in a variable.

Page 64: Java Programming

VariablesVariables It is a memory space where the constant values It is a memory space where the constant values

are stored.are stored.

Page 65: Java Programming

Data Types in JavaData Types in JavaData types in JAVA

Premitive(Intrinsic) Non Primitive(Derived)

Numeric Non-numeric Classes Arrays

Integer Float Character Boolean Interface

Page 66: Java Programming

Different types of Control StructuresDifferent types of Control Structures

Control Structure explains the flow of data in Control Structure explains the flow of data in a program.a program.

There are 4 types of control structures:There are 4 types of control structures:1.1. Sequential structureSequential structure2.2. Decision structureDecision structure3.3. Loop structureLoop structure4.4. Case structure.Case structure.

Page 67: Java Programming

Sequential Control StructureSequential Control Structure It is the normal programming style.It is the normal programming style. In this case the execution of program takes In this case the execution of program takes

place line by line.place line by line.

Page 68: Java Programming

Decision StructureDecision Structure In this case a particular condition has to be satisfied, In this case a particular condition has to be satisfied,

to execute a particular block of statements.to execute a particular block of statements. If the condition is true, then the entire block of If the condition is true, then the entire block of

statement will be executed.statement will be executed. There are 4 types of Decision statements: There are 4 types of Decision statements: 1.1. If statementIf statement2.2. If-else statementIf-else statement3.3. Nested if statementNested if statement4.4. Else if ladderElse if ladder

Page 69: Java Programming

If statementIf statement If the condition is true the entire block of statements If the condition is true the entire block of statements

is executed and thereafter control goes to the is executed and thereafter control goes to the statement coming after if-block.statement coming after if-block.

If the condition is false, the entire block of statement If the condition is false, the entire block of statement will be skipped and control goes to the line which will be skipped and control goes to the line which comes after the ‘if ‘ block is executed.comes after the ‘if ‘ block is executed.

Syntax is : if(condition){Syntax is : if(condition){ statement;statement; }}

Page 70: Java Programming

If-else statementIf-else statement In this case, if the condition is true the entire block is executed In this case, if the condition is true the entire block is executed

and goes to the statement coming after the if-else statement.and goes to the statement coming after the if-else statement. If the condition is false, the contol goes to the else block and If the condition is false, the contol goes to the else block and

executes it. Thereafter the control goes to the statement executes it. Thereafter the control goes to the statement coming after the if-else statement.coming after the if-else statement.

Syntax: if(condition){Syntax: if(condition){ statement1;statement1;

}} elseelse {{ statement2;statement2; }}

Page 71: Java Programming

Wrapper classesWrapper classes Prmitive data types may be converted into Prmitive data types may be converted into

object types by using wrapper classes.object types by using wrapper classes.

Page 72: Java Programming

Simple typeSimple type Wrapper classWrapper class

BooleanBoolean BooleanBoolean

CharChar CharacterCharacter

DoubleDouble DoubleDouble

FloatFloat FloatFloat

IntInt IntegerInteger

LongLong LongLong

Page 73: Java Programming

Primitive values to objectsPrimitive values to objects Integer IntVal=new Integer(i);Integer IntVal=new Integer(i); Float FloatVal=new Float(f);:Float FloatVal=new Float(f);: Double DoubleVal=new Double(d);Double DoubleVal=new Double(d); Long LongVal=new Long(l);Long LongVal=new Long(l);

Page 74: Java Programming

StringString String is a class. String is a class. It is used to store all types of characters including It is used to store all types of characters including

space.space. The difference of char and String is that in char only The difference of char and String is that in char only

one character, which is a variable, can be stored at a one character, which is a variable, can be stored at a time.time.

But in String we can store not only a single character, But in String we can store not only a single character, but also a word or sentence which includes space.but also a word or sentence which includes space.

Syntax is: String stringName = new String(“string”);Syntax is: String stringName = new String(“string”);

Page 75: Java Programming

String ArraysString Arrays It is used to store more than one string objects It is used to store more than one string objects

at a time.at a time. Syntax is:Syntax is:String item[]=new String[size];String item[]=new String[size];

Page 76: Java Programming

String methodsString methods The various methods, that are using in String class areThe various methods, that are using in String class areS2=s1.toLowerCase;-S2=s1.toLowerCase;-Converts the string s1 to all Converts the string s1 to all

lowercaselowercaseS2=s1.toUpperCase;-S2=s1.toUpperCase;-Converts the string s1 to all Converts the string s1 to all

uppercaseuppercaseS2=s1.replace(‘x’,’y’);--S2=s1.replace(‘x’,’y’);--Replace all appearances of x Replace all appearances of x

with y;with y;S2=s1.trim();--S2=s1.trim();--Remove white spaces at the beginning Remove white spaces at the beginning

and end of the string s1.and end of the string s1.

Page 77: Java Programming

S1.equals(s2);-S1.equals(s2);-Returns ‘true’ if s1 is equal to s2.Returns ‘true’ if s1 is equal to s2. S1.equalsIgnoreCase(s2);-S1.equalsIgnoreCase(s2);-Returns ‘true’ if s1=s2, ignoring Returns ‘true’ if s1=s2, ignoring

the case of characters.the case of characters. S1.length();-S1.length();-Gives the length of s1.Gives the length of s1. S1.charAt(n);-S1.charAt(n);-Gives nth character of s1.Gives nth character of s1. S1.compareTo(s2);-S1.compareTo(s2);-Returns negative if s1<s2, positive if Returns negative if s1<s2, positive if

s1>s2, and zero if s1 is equal s2s1>s2, and zero if s1 is equal s2 S1.concat(s2);-S1.concat(s2);-Concatenates s1 and s2.Concatenates s1 and s2. S1.substring(n);-S1.substring(n);-Gives substring starting from nth character.Gives substring starting from nth character. S1.substring(n,m);-S1.substring(n,m);-Gives substring starting from nth Gives substring starting from nth

character upto mth(not including mth)character upto mth(not including mth) String.valueOf(p);-String.valueOf(p);-creates a string object of the parameter creates a string object of the parameter

p(simple type or object)p(simple type or object)

Page 78: Java Programming

P.toString();-P.toString();-Creates a string representation Creates a string representation of the object p.of the object p.

S1.indexOf(‘x’);-S1.indexOf(‘x’);-Gives the position of the Gives the position of the first occurrence of ‘x’ in the string s1.first occurrence of ‘x’ in the string s1.

S1.indexOf(‘x’,n);-S1.indexOf(‘x’,n);-Gives the position of ‘x’ Gives the position of ‘x’ that occurs after nth position in the string s1.that occurs after nth position in the string s1.

Page 79: Java Programming

StringBufferStringBuffer StringBuffer creates strings of flexible length StringBuffer creates strings of flexible length

that can be modified in terms of both length that can be modified in terms of both length and content.and content.

We can insert characters and substrings in the We can insert characters and substrings in the middle of a string, or append another string to middle of a string, or append another string to the end.the end.

Page 80: Java Programming

Methods using StringBuffer classMethods using StringBuffer class S1.setCharAt(n,’x’)-S1.setCharAt(n,’x’)-Modifies the nth Modifies the nth

character to xcharacter to x S1.append(s2)-S1.append(s2)- Appends the string s2 to s1. Appends the string s2 to s1. S1.insert(n,s2)S1.insert(n,s2)Inserts the string s2 at the Inserts the string s2 at the

position n of the string s1position n of the string s1 S1.setLength(n)S1.setLength(n)Sets the length of the string Sets the length of the string

s1 to n. If n<s1.length() is truncated. If s1 to n. If n<s1.length() is truncated. If n>s1.length() zeros are added to s1.n>s1.length() zeros are added to s1.

Page 81: Java Programming

VectorVector

Page 82: Java Programming

Syntax to access class membersSyntax to access class members Objectname.variablename;Objectname.variablename; Objectname.methodName();Objectname.methodName();

Page 83: Java Programming

ConstructorsConstructors They are member methods, which are used to They are member methods, which are used to

initialize the objects dynamically.initialize the objects dynamically. The name of constructor is the class name itself.The name of constructor is the class name itself. Constructor does not return any datatype even void.Constructor does not return any datatype even void. Constructor accepts parameters, from the object Constructor accepts parameters, from the object

definition.definition. The constructor which accepts parameters is known The constructor which accepts parameters is known

as parameterized constructor.as parameterized constructor.

Page 84: Java Programming

Polymorphism:Polymorphism: Methods overloading Methods overloading

It is the process of defining extra task, besides It is the process of defining extra task, besides its original taskits original task

Java does not support operator overloadingJava does not support operator overloading

Page 85: Java Programming

Inheritance in javaInheritance in java Inheritance is the process of derTiving a class Inheritance is the process of derTiving a class

from other classfrom other class Java does not support Multiple inheritance and Java does not support Multiple inheritance and

hybrid inheritancehybrid inheritance To show inheritance java uses the keyword To show inheritance java uses the keyword

“extends”“extends”

Page 86: Java Programming

Native methodsNative methods Native methods are those methods which calls Native methods are those methods which calls

the functions, which are defined in other the functions, which are defined in other programming language like c,c++ etc.programming language like c,c++ etc.

Page 87: Java Programming

Garbage collectorGarbage collector Garbage collection is the process of automatically freeing Garbage collection is the process of automatically freeing

objects that are no longer referenced by the program.objects that are no longer referenced by the program. This frees the programmer from having to keep track of when This frees the programmer from having to keep track of when

to free allocated memory, thereby, preventing many potential to free allocated memory, thereby, preventing many potential bugs. bugs.

Thus making programmers more productive as they can now Thus making programmers more productive as they can now put more effort in coding rather than worrying about memory put more effort in coding rather than worrying about memory management.management.

The disadvantage of garbage collector is it adds overheads. The disadvantage of garbage collector is it adds overheads. Because the JVM has to keep the constant track of the objects Because the JVM has to keep the constant track of the objects which are not referenced and then free these unreferenced which are not referenced and then free these unreferenced objects on fly. This whole process has slight impact on the objects on fly. This whole process has slight impact on the application performance. application performance.

Page 88: Java Programming

Super()Super() It is the subclass constructor method which is It is the subclass constructor method which is

used to call the super class constructor and its used to call the super class constructor and its members.members.

The syntax is “super(parameter-list);”The syntax is “super(parameter-list);” Super() must always be the first statement Super() must always be the first statement

executed inside a subclass constructor.executed inside a subclass constructor. The second form of super() always refers the The second form of super() always refers the

super class of the subclass in which it is used. super class of the subclass in which it is used. The syntax is “super.member”The syntax is “super.member”

Page 89: Java Programming

Method overridingMethod overriding Method overriding is a process of executing Method overriding is a process of executing

the member function of sub class by the member function of sub class by eliminating the result of the member function, eliminating the result of the member function, which has same name and which has been which has same name and which has been defined in the base class.defined in the base class.

Page 90: Java Programming

Final VariablesFinal Variables The final variables are those variables , which The final variables are those variables , which

can not be changed further.can not be changed further. Syntax is : final datatype variablename;Syntax is : final datatype variablename;

Page 91: Java Programming

Final MethodsFinal Methods Final methods are can not be redefined Final methods are can not be redefined

further.ie, They can not be overriddenfurther.ie, They can not be overridden Syntax:Syntax:Final returntype methodName()Final returntype methodName(){ statements;}{ statements;}

Page 92: Java Programming

Final classesFinal classes Final classes are those classes which can not Final classes are those classes which can not

be inherited further(It may be a sub class of be inherited further(It may be a sub class of parent class)parent class)

Syntax:Syntax:Final class ClassNameFinal class ClassName{{

Statements;Statements;}}

Page 93: Java Programming

Abstract methodsAbstract methods The abstract methods are those methods, The abstract methods are those methods,

which must be redefined.which must be redefined.Syntax:Syntax:Abstract returntype methodName()Abstract returntype methodName(){{

statement;statement;}}

Page 94: Java Programming

Abstract classesAbstract classes

Abstract classes are those classes which must Abstract classes are those classes which must be inherited further.be inherited further.

Syntax:Syntax:Abstract class shapeAbstract class shape{{

statements;statements;}}

Page 95: Java Programming

Class loadersClass loaders Java was designed by thinking platform Java was designed by thinking platform

independency in mind.independency in mind. In order to work API, on different platform, In order to work API, on different platform,

the class libraries of each package should be the class libraries of each package should be loaded to the operating system not only from loaded to the operating system not only from file system but also from FTP and HTTP.file system but also from FTP and HTTP.

Class loaderClass loader is the class responsible for finding is the class responsible for finding and loading classes at runtime.and loading classes at runtime.

Page 96: Java Programming

Types of class loadersTypes of class loaders There are three types of class loadersThere are three types of class loaders1.1. BootStrap Class loader, also called as BootStrap Class loader, also called as

primordial class loaderprimordial class loader2.2. Extenstion Class loaderExtenstion Class loader3.3. System Class loaderSystem Class loader

Page 97: Java Programming

BootStrap class loaderBootStrap class loader BootStrap class loader loads those classes which are BootStrap class loader loads those classes which are

essential for JVM to function properly.essential for JVM to function properly. BootStrap classes are responsible for loading all core BootStrap classes are responsible for loading all core

java classes for instance java.lang.*, Java.io.*. Etc. java classes for instance java.lang.*, Java.io.*. Etc. BootStrap class loader finds these necessary classes BootStrap class loader finds these necessary classes

from “jdk/jre/lib/rt.jar”.from “jdk/jre/lib/rt.jar”. BootStrap class loader can not be instantiated from BootStrap class loader can not be instantiated from

Java code and is implemented natively inside JVM.Java code and is implemented natively inside JVM.

Page 98: Java Programming

Extension class loaderExtension class loader The Extension class loader is also termed as The Extension class loader is also termed as

the standard extensions class loader is a child the standard extensions class loader is a child of the BootStrap class loader.of the BootStrap class loader.

Its primary objective is to load classes from Its primary objective is to load classes from the extension directories, normally located the the extension directories, normally located the “jre/lib/ext” directory. “jre/lib/ext” directory.

Page 99: Java Programming

System class loaderSystem class loader The System class loader , also termed as The System class loader , also termed as

application class loader, is the class loader application class loader, is the class loader responsible for loading code from the path responsible for loading code from the path specified by the CLASSPATH environment specified by the CLASSPATH environment variable.variable.

It is also used to load an applications entry It is also used to load an applications entry point class that is the “static void main()” point class that is the “static void main()” method in a class.method in a class.

Page 100: Java Programming

Working of class loadersWorking of class loaders

Application requests a class

BootStrap class loader

Extension class loader

System class loader

Page 101: Java Programming

Reflection APIReflection API It is a member of corejava.lang package. It is a member of corejava.lang package. The methods provided by the Reflection API The methods provided by the Reflection API

obtain information about a class, such as the obtain information about a class, such as the fields, constructors, methods, and super classes fields, constructors, methods, and super classes of the class. of the class.

In addition, we can obtain the interfaces In addition, we can obtain the interfaces implemented by the class. implemented by the class.

Page 102: Java Programming

Java Native Interface(JNI)Java Native Interface(JNI) This also is used to execute a java program by This also is used to execute a java program by

using the functions , which are defined in other using the functions , which are defined in other programming languages, like Java Native programming languages, like Java Native Methods.Methods.

Page 103: Java Programming

JIT(Just In Time) compilationJIT(Just In Time) compilation When JVM compiles the class file, it does not When JVM compiles the class file, it does not

compile the full class file in one shot. compile the full class file in one shot. Compilation is done on function basis or file basis.Compilation is done on function basis or file basis. Advantage gained from this is that heavy parsing of Advantage gained from this is that heavy parsing of

original source code is avoided.original source code is avoided. Depending on need basis the compilation is done.Depending on need basis the compilation is done.

Such type of compilation is termed as JIT or just-in-Such type of compilation is termed as JIT or just-in-time compilation.time compilation.

Page 104: Java Programming

Multi threadingMulti threading It is a conceptual programming paradigm where a It is a conceptual programming paradigm where a

program(process) is divided into two or more sub program(process) is divided into two or more sub programs(processes), which can be implemented at the same programs(processes), which can be implemented at the same time in parallel.time in parallel.

A program that contains multiple flows of control is known as A program that contains multiple flows of control is known as multithreaded program.multithreaded program.

It is a powerful programming tool that makes Java distinctly It is a powerful programming tool that makes Java distinctly different from its fellow programming languages. different from its fellow programming languages. Multithreading is useful in a number of ways.Multithreading is useful in a number of ways.

It enables programmers to do multiple things at one time.It enables programmers to do multiple things at one time. They can divide a long program(Containing operations that are They can divide a long program(Containing operations that are

conceptually concurrent) into threads and execute them in conceptually concurrent) into threads and execute them in parallel.parallel.

Page 105: Java Programming

ThreadThread A thread is a similar to a program that has a A thread is a similar to a program that has a

single flow of control. It has a beginning, a single flow of control. It has a beginning, a body, and an end and executes commands body, and an end and executes commands sequentially.sequentially.

All main programs in our earlier examples can All main programs in our earlier examples can be called single-threaded programs. be called single-threaded programs.

Page 106: Java Programming

Main Thread

Thread A Thread B Thread C

start startstart

switching switching

Page 107: Java Programming

Creation of ThreadsCreation of Threads A new thread can be created in two ways.A new thread can be created in two ways.1.1. By creating thread class: Define a class that By creating thread class: Define a class that

extends Thread class and override its run() extends Thread class and override its run() method with the code required by the thread.method with the code required by the thread.

2.2. By converting a class to a thread: Define a By converting a class to a thread: Define a class that implements Runnable interface. class that implements Runnable interface. The Runnable interface has only one method, The Runnable interface has only one method, run(), that is to be defined in the method with run(), that is to be defined in the method with the code to be executed by the thread.the code to be executed by the thread.

Page 108: Java Programming

Extending Thread classExtending Thread class Syntax:Syntax:Class MyThread extends ThreadClass MyThread extends Thread{{

statements;statements;}}

Page 109: Java Programming

Life cycle of a threadLife cycle of a thread During the life time of a thread, there are During the life time of a thread, there are

many states it can enter. They includemany states it can enter. They include1.1. New born stateNew born state2.2. Runnable stateRunnable state3.3. Running stateRunning state4.4. Blocked stateBlocked state5.5. Dead stateDead state

Page 110: Java Programming

New born

Running Runnable

Blocked

Dead

start

suspend sleep wait

Resumenotify

yield

stop

stop

stop

Page 111: Java Programming

New Born stateNew Born state When we create a thread object, the thread is born When we create a thread object, the thread is born

and is said to be in newborn state. and is said to be in newborn state. But the thread is not under running stateBut the thread is not under running state In order to activate a thread, we have to apply start()In order to activate a thread, we have to apply start() In order to kill the thread we have to apply stop()In order to kill the thread we have to apply stop() In order to create a thread , create the thread object.In order to create a thread , create the thread object. By using thread object, we can start and stop thread.By using thread object, we can start and stop thread.

Page 112: Java Programming

Eg: class MyThread extends ThreadEg: class MyThread extends Thread{ {

public void run()public void run(){{

statements;statements;}}

}}MyThread t1=new MyThread();MyThread t1=new MyThread();t1.start();t1.start();t1.stop()t1.stop()

Page 113: Java Programming

Runnable stateRunnable state The runnable state means that the thread is ready for The runnable state means that the thread is ready for

execution and is waiting for the availability of the execution and is waiting for the availability of the processor.processor.

Ie. The thread has joined the queue of threads that are Ie. The thread has joined the queue of threads that are waiting for execution.waiting for execution.

If all threads have equal priority, then they are given If all threads have equal priority, then they are given time slots for execution in round robin fashion.time slots for execution in round robin fashion.

The thread that relinquishes control joins the queue at The thread that relinquishes control joins the queue at the end and again waits for its turn. This process of the end and again waits for its turn. This process of assigning time to threads is known as time slicing.assigning time to threads is known as time slicing.

Page 114: Java Programming

Running stateRunning state Running state means that the processor has Running state means that the processor has

been given its time to the thread for its been given its time to the thread for its execution. execution.

The thread runs until it relinquishes control on The thread runs until it relinquishes control on its own or it is preempted by a higher priority its own or it is preempted by a higher priority thread.thread.

Page 115: Java Programming

A running thread can be relinquished in the A running thread can be relinquished in the following situations.following situations.

1.1. By using suspend(): It has been suspended using By using suspend(): It has been suspended using suspend(). A suspended thread can be revived by suspend(). A suspended thread can be revived by using resume();using resume();

2.2. By using sleep(): We can put a thread to sleep for a By using sleep(): We can put a thread to sleep for a specified time period using the method sleep(time) specified time period using the method sleep(time) where time is in milliseconds. where time is in milliseconds.

3.3. By using wait(): It has been told to wait until some By using wait(): It has been told to wait until some event occurs. This is done using wait(). The thread event occurs. This is done using wait(). The thread can be scheduled to run again using the notify().can be scheduled to run again using the notify().

Page 116: Java Programming

Blocked stateBlocked state A thread is said to be blocked when it is A thread is said to be blocked when it is

prevented from entering into the runnable prevented from entering into the runnable state and subsequently the running state.state and subsequently the running state.

This happens when the thread is suspended, This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain sleeping, or waiting in order to satisfy certain requirements.requirements.

A blocked state is considered “not runnable” A blocked state is considered “not runnable” but not dead and therefore fully qualified to but not dead and therefore fully qualified to run again.run again.

Page 117: Java Programming

Dead StateDead State A running thread ends its life when it has A running thread ends its life when it has

completed executing its run() method. completed executing its run() method. We can stop an active thread by applying We can stop an active thread by applying

stop(). stop().

Page 118: Java Programming

Thread PriorityThread Priority Each thread is assigned a priority, which affects the Each thread is assigned a priority, which affects the

order in which it is scheduled for running.order in which it is scheduled for running. The syntax to set the priority is: The syntax to set the priority is:

threadObject.setPriority(number);threadObject.setPriority(number); The number is an integer value to which the thread’s The number is an integer value to which the thread’s

priority is set. priority is set. The thread class defines several priority constants:The thread class defines several priority constants:MIN_PRIORITY=1MIN_PRIORITY=1NORM_PRIORITY=5NORM_PRIORITY=5MAX_PRIORITY=10MAX_PRIORITY=10 The default setting priority is NORM_PRIORITYThe default setting priority is NORM_PRIORITY

Page 119: Java Programming

Difference between runnable and Difference between runnable and extending Thread classextending Thread class

Thread is a class and runnable is an interface in javaThread is a class and runnable is an interface in java If a class is not extending another class we can use If a class is not extending another class we can use

either extending Thread class or implementing either extending Thread class or implementing Runnable interface. If our class is already extending Runnable interface. If our class is already extending another class we can’t extend Thread class because another class we can’t extend Thread class because java does not support multiple inheritance so we have java does not support multiple inheritance so we have left only one choice that is implementing Runnable left only one choice that is implementing Runnable interfaceinterface

When we extend a thread each of our threads has a When we extend a thread each of our threads has a unique object associated with it, whereas with unique object associated with it, whereas with Runnable, many threads share the same object Runnable, many threads share the same object instance.instance.

Page 120: Java Programming

SynchronizationSynchronization If threads try to use data and methods outsides If threads try to use data and methods outsides

themselves, they may compete for the same themselves, they may compete for the same resources and may lead to serious problems.resources and may lead to serious problems.

Java enables to overcome this problem using Java enables to overcome this problem using the technique “Synchronization”the technique “Synchronization”

The keyword “synchronized” helps to solve The keyword “synchronized” helps to solve such problems by keeping a watch on such such problems by keeping a watch on such locations.locations.

Page 121: Java Programming

When we declare a method synchronized, java When we declare a method synchronized, java creates a “monitor” and hands it over to the creates a “monitor” and hands it over to the thread that calls the method first time.thread that calls the method first time.

As long as the thread holds the monitor, no As long as the thread holds the monitor, no other thread can enter the synchronized section other thread can enter the synchronized section of code.of code.

A monitor is like a key and the thread that A monitor is like a key and the thread that holds the key can only open the lock.holds the key can only open the lock.

Page 122: Java Programming

Eg: synchronized void update()Eg: synchronized void update(){{

statements;statements;}}

Page 123: Java Programming

Runnable interfaceRunnable interface Runnable interface is used to implement the Runnable interface is used to implement the

features of Thread.features of Thread. It declares the run() that is required for It declares the run() that is required for

implementing threads in programs.implementing threads in programs.

Page 124: Java Programming

CollectionCollection It is an interface defined in java.util packageIt is an interface defined in java.util package It is a group of objectsIt is a group of objects Collection framework standardizes the way in Collection framework standardizes the way in

which groups of objects are handled by the which groups of objects are handled by the programs.programs.

Collection framework was designed to meet several Collection framework was designed to meet several goals.goals.

1.1. The framework had to be high-performance.ie the The framework had to be high-performance.ie the implementations for the fundamental( such as implementations for the fundamental( such as dynamic arrays, linked lists, trees, hash tables) are dynamic arrays, linked lists, trees, hash tables) are highly efficient.highly efficient.

Page 125: Java Programming

2) The framework had to allow different types of 2) The framework had to allow different types of collections to work in a similar manner and collections to work in a similar manner and with a high degree of interoperability.with a high degree of interoperability.

3)Extending or adapting a collection had to be 3)Extending or adapting a collection had to be easy.easy.

Page 126: Java Programming

Collection interfaceCollection interface

Collection

List Set

Sorted set

Page 127: Java Programming

CollectionCollection Enables to work with Enables to work with groups of objects; it is at groups of objects; it is at the top of the collections the top of the collections hierarchyhierarchy

ListList Extends Collection to Extends Collection to handle sequences(list of handle sequences(list of objects)objects)

SetSet Extends Collection to Extends Collection to handle sets, which must handle sets, which must contain unique elementscontain unique elements

SortedSetSortedSet Extends Set to handle Extends Set to handle sorted setssorted sets

Page 128: Java Programming

Besides these interfaces Collection also use the Besides these interfaces Collection also use the Comparator, Iterator, and ListIterator Comparator, Iterator, and ListIterator interfacesinterfaces

Comparator defines how two objects are Comparator defines how two objects are comparedcompared

Iterator and ListIterator enumerate the objects Iterator and ListIterator enumerate the objects with in a collectionwith in a collection

Page 129: Java Programming

Collection interface includes two types of methods, Collection interface includes two types of methods, which are optional, to provide flexibility.which are optional, to provide flexibility.

1.1. Modifiable methodsModifiable methods2.2. Unmodifiable methodsUnmodifiable methods Modifiable methods are those methods used to Modifiable methods are those methods used to

modify the contents of Collectionmodify the contents of Collection Unmodifiable methods are those methods , which Unmodifiable methods are those methods , which

do not allow the modification of the contents of do not allow the modification of the contents of Collection. Collection.