321 61 4MB
English Pages 205 Year 2020
3140705 Object Oriented Programming - I
Unit-1 Introduction to Java & Elementary Programming Prof. Hardik A. Doshi 9978911553 [email protected]
Java Around the World
Unit Unit –– 1: 1: Introduction Introduction
22
Darshan Darshan Institute Institute of of Engineering Engineering & &
What Java is used for?
Unit Unit –– 1: 1: Introduction Introduction
33
Darshan Darshan Institute Institute of of Engineering Engineering & &
What Java is used for? Banking: To deal with transaction management. Retail: Billing applications that you see in a store/restaurant are completely written in Java. Information Technology: Java is designed to solve implementation dependencies. Android: Applications are either written in Java or use Java API. Financial services: It is used in server-side applications. Stock market: To write algorithms as to which company they should invest in. Big Data: Hadoop MapReduce framework is written using Java. Scientific and Research Community: To deal with huge amount of data. Unit Unit –– 1: 1: Introduction Introduction
44
Darshan Darshan Institute Institute of of Engineering Engineering & &
History of Java James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan (Green Team) at Sun Microsystems, Inc. conceived Java in 1991. Initially named as Oak language.
Oak
Unit Unit –– 1: 1: Introduction Introduction
Renamed in 1995
55
Java
Darshan Darshan Institute Institute of of Engineering Engineering & &
What is Java? Concurrent • executes many statements instead of sequentially executing it Object Oriented • supports encapsulation, inheritance and polymorphism Independent • follows the logic of “Write once, Run anywhere”
Unit Unit –– 1: 1: Introduction Introduction
66
Darshan Darshan Institute Institute of of Engineering Engineering & &
Java Buzzwords Simple: Java inherits C/C++ syntax and many objectoriented features of C++. Object Oriented: “Everything is an object” paradigm, which possess some state, behavior and all the operations are performed using these objects. Robust: Java has a strong memory management system. It helps in eliminating error as it checks the code during compile and runtime. Multithreaded: Java supports multiple threads of execution, including a set of synchronization primitives. This makes programming with threads much easier. Darshan Darshan Institute Institute of of Engineering Engineering & & 7
Unit Unit –– 1: 1: Introduction Introduction
7
Java Buzzwords Architectural Neutral: Java is platform independent which means that any application written on one platform can be easily ported to another platform. Interpreted: Java is compiled to bytecodes, which are interpreted by a Java run-time environment. High Performance: Java achieves high performance through the use of bytecode which can be easily translated into native machine code. With the use of JIT (Just-In-Time) compilers, Java enables high performance. Unit Unit –– 1: 1: Introduction Introduction
88
Darshan Darshan Institute Institute of of Engineering Engineering & &
Java Buzzwords Distributed: Java provides a feature which helps to create distributed applications. Using Remote Method Invocation (RMI), a program can invoke a method of another program across a network and get the output. You can access files by calling the methods from any machine on the internet. Dynamic: Java has ability to adapt to an evolving environment which supports dynamic memory allocation due to which memory wastage is reduced and performance of the application is increased.
Unit Unit –– 1: 1: Introduction Introduction
99
Darshan Darshan Institute Institute of of Engineering Engineering & &
Java’s Magic : Bytecode Source code .java file (Program)
Bytecode is a highly optimized set of instructions designed to be executed by the Java Virtual Machine(JVM). Bytecode makes Java Platform
Compile r
independent language.
Unit Unit –– 1: 1: Introduction Introduction
Bytecode
.class file
JVM (Windows )
JVM (Linux)
JVM (Mac)
Machine Code
Machine Code
Machine Code
10 10
Darshan Darshan Institute Institute of of Engineering Engineering & &
Components of Java Java Virtual Machine (JVM) Java Runtime Environment (JRE) Java Development Kit (JDK) [Current Version: JDK 13.0.1]
Unit Unit –– 1: 1: Introduction Introduction
11 11
Darshan Darshan Institute Institute of of Engineering Engineering & &
Java Virtual Machine (JVM) JVM is • An abstract machine • Provides a run-time environment to execute bytecode
It follows 3 notations 1. Specification 2. Implementation 3. Runtime Instance
It performs following operation: •
Loads code
•
Verifies code
•
Executes code
•
Provides runtime environment
Unit Unit –– 1: 1: Introduction Introduction
12 12
Darshan Darshan Institute Institute of of Engineering Engineering & &
Java Runtime Environment (JRE) JRE refers to a runtime environment in which Java bytecode can be executed. It implements the JVM (Java Virtual Machine) and provides all the class libraries and other support files that JVM uses at runtime. Basically, it is an implementation of the JVM which physically exists.
Unit Unit –– 1: 1: Introduction Introduction
13 13
Darshan Darshan Institute Institute of of Engineering Engineering & &
Java Development Kit (JDK) It is the tool necessary to •
Compile
•
Document
•
Package Java programs
The JDK completely includes programmers. Along with JRE, it includes an
JRE
•
compiler (javac)
•
application launcher (java / appletviewer)
•
interpreter/loader
•
archiver (jar)
•
documentation generator (javadoc)
•
other tools needed in Java development.
which
contains
tools
for
Java
In short, it contains JRE + development tools. The Java Development Kit is
freeware available on https://www.oracle.com/technetwork/java/javase/downloads/index.html
Unit Unit –– 1: 1: Introduction Introduction
14 14
Darshan Darshan Institute Institute of of Engineering Engineering & &
JVM vs JRE vs JDK
Unit Unit –– 1: 1: Introduction Introduction
15 15
Darshan Darshan Institute Institute of of Engineering Engineering & &
JDK Version History Version
Release Date
Version
Release Date
JDK Beta
1995
Java SE 7
July 2011
JDK 1.0
January 1996
Java SE 8 (LTS) March 2014
JDK 1.1
February 1997
Java SE 9
J2SE 1.2
December 1998
September 2017
Java SE 10
March 2018
Java SE 11 (LTS)
September 2018
Java SE 12
March 2019
Java SE 13
September 2019
J2SE 1.3
May 2000
J2SE 1.4
February 2002
J2SE 5.0
September 2004
Java SE 6
December 2006
Unit Unit –– 1: 1: Introduction Introduction
16 16
Darshan Darshan Institute Institute of of Engineering Engineering & &
Installing JDK Download JDK for Windows platform (.exe) from https://www.oracle.com/technetwork/java/javase/downloads/index.html
Install the executable of JDK Set the path variable of System variables by performing following steps •
Go to "System Properties" (Right click This PC → Properties → Advanced System Settings)
•
Click on the "Environment variables" button under the "Advanced" tab
•
Then, select the "Path" variable in System variables and click on the "Edit" button
•
Click on the "New" button and add the path where Java is installed, followed by \ bin. By default, Java is installed in C:\Program Files\Java\jdk-13.0.1 (If nothing else was specified when you installed it). In that case, You will have to add a new path with: C:\Program Files\Java\jdk-11.0.1\bin
•
Then, click "OK", and save the settings
•
At last, open Command Prompt (cmd.exe) and type java -version to see if Java is running on your machine
Unit Unit –– 1: 1: Introduction Introduction
17 17
Darshan Darshan Institute Institute of of Engineering Engineering & &
1
3 2
4
First Simple Program class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } } The program prints “Hello World” on the console.
Unit Unit –– 1: 1: Introduction Introduction
19 19
Darshan Darshan Institute Institute of of Engineering Engineering & &
How to execute Java Program? 1. Save the program with the same name that of class which contains public static void main(String[] args).
Unit Unit –– 1: 1: Introduction Introduction
20 20
Darshan Darshan Institute Institute of of Engineering Engineering & &
How to execute Java Program? 2. Open command prompt (cmd) / terminal & navigate to desired directory / folder.
3. Compile the “.java” file with javac command.
4. Execute the “.class” file with java command without extension.
Unit Unit –– 1: 1: Introduction Introduction
21 21
Darshan Darshan Institute Institute of of Engineering Engineering & &
Closer look at First Sample Program All Java applications begin class keyword that execution athat newisclass iscalling being HelloWorld isdeclares an identifier theby name of main() defined the class
class HelloWorld { public args)
static
void
main(String[]
{ System. out.println("Hello public keyword iscompiler an access modifier which makes void keyword tells args ismain() an that array main() command does not line return static keyword allows toofbe called without main() outside of its class when program is ainstantiating value be called arguments World"); an instance of the class out is the output stream connected the access to started System isdisplays a predefined class that provides println the string which isto passed } to console system it } Unit Unit –– 1: 1: Introduction Introduction
22 22
Darshan Darshan Institute Institute of of Engineering Engineering & &
Lexical Issues Whitespace • It is a space, tab or newline
Identifiers • They are used for class names, method names and variable names. • An identifier may be any descriptive sequence of • uppercase(A…Z) and lowercase(a..z) letters • Numbers(0..9) • Underscore(_) and dollar-sign($) characters AvgTemp count a4 $test this_is_ok 2count
hightemp
Unit Unit –– 1: 1: Introduction Introduction
Not/ok
23 23
Darshan Darshan Institute Institute of of Engineering Engineering & &
Lexical Issues Literals • Constant value in Java is created using literal representation. 100
98.6
‘X’
“This is a test”
Comments • There are 3 types of comment in Java 1. Single-line → // 2. Multiline → starts with /* and ends with */ 3. Documentation → starts with /** and ends with */
Unit Unit –– 1: 1: Introduction Introduction
24 24
Darshan Darshan Institute Institute of of Engineering Engineering & &
Lexical Issues Separators ()
Parenthesis
{}
Braces
[]
Brackets
‒ Used to contain list of parameters in method definition and invocation. ‒ Used for defining precedence in expressions, containing expressions in control statements and surrounding cast ‒ Used types. to contain values of automatically initialized arrays. ‒ Used to define block of code for classes, methods and local scopes. ‒ Used to declare array types.
;
Semicolon
‒ Terminates statements.
,
Comma
.
Period
‒ Separates consecutive identifiers in ‒ declaration Used to separate package names from
Unit Unit –– 1: 1: Introduction Introduction
subpackages and classes. ‒ Used to separate variable or method from a reference variable. Darshan Institute of Engineering & 25 25 Darshan Institute of Engineering &
Lexical Issues Java Keywords • 50 keywords • Cannnot be used as names for variables, class or method abstract
continue
for
new
switch
assert
default
goto
package
synchronize d
Boolean
do
if
private
this
break
double
implements
protected
throw
byte
else
import
public
throws
case
enum
instanceof
return
transient
catch
extends
int
short
try
char
final
interface
static
void
class
finally
long
strictfp
volatile
const float Unit Unit –– 1: 1: Introduction Introduction
native 26 26
super while Darshan Institute Engineering Darshan Institute of of Engineering & &
Data Types Java Datatypes
Primitiv e
Integer s
Floatingpoint numbers
Unit Unit –– 1: 1: Introduction Introduction
Nonprimitive
Characte rs
27 27
Boolea n
Clas s
Darshan Darshan Institute Institute of of Engineering Engineering & &
Primitive Data Types Data Type
Size
Range
Example
byte
1 Byte
-128 to 127
byte a = 10;
short
2 Bytes
-32,768 to 32,767
short a = 200;
int
4 Bytes
-2,147,483,648 to 2,147,483,647
int a = 50000;
long float
8 Bytes 4 Bytes
-9,223,372,036,854,775,808 long a = 20; to 9,223,372,036,854,775,807 1.4e-045 to 3.4e+038 float a = 10.2f;
double
8 Bytes
4.9e-324 to 1.8e+308
double a = 10.2;
char
2 Bytes
0 to 65536 (Stores ASCII of character)
char a = ‘a’;
true or false
boolean a = true;
boolean
Not defined Unit Unit –– 1: 1: Introduction Introduction
28 28
Darshan Darshan Institute Institute of of Engineering Engineering & &
Escape Sequences Escape sequences in general are used to signal an alternative interpretation of a series of characters. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. System.out.println("Good Morning \"Jack\""); Escape Sequence
Description
\’
Single quote
\”
Double quote
\\
Backslash
\r
Carriage return
\n
New Line
\t
Tab
Unit Unit –– 1: 1: Introduction Introduction
29 29
Darshan Darshan Institute Institute of of Engineering Engineering & &
Type Casting Assigning a value of one type to a variable of another type is known as Type Casting. In Java, type casting is classified into two types, •
Widening/Automatic Type Casting (Implicit)
•
Narrowing Type Casting(Explicitly done)
Unit Unit –– 1: 1: Introduction Introduction
30 30
Darshan Darshan Institute Institute of of Engineering Engineering & &
Automatic Type Casting When one type of data is assigned to other type of variable , an automatic type conversion will take place if the following two conditions are satisfied: • The two types are compatible • The destination type is larger than the source type
Such type of casting is called “widening conversion”. Example: int can always hold values of byte and short public static void main(String[] args) { byte b = 5; // √ this is correct int a = b; } Unit Unit –– 1: 1: Introduction Introduction
31 31
Darshan Darshan Institute Institute of of Engineering Engineering & &
Casting Incompatible Types To create a conversion between two incompatible types, you must use a cast A cast is an explicit type conversion. Such type is called “narrowing conversion”. Syntax: (target-type) value
Example: public static void main(String[] args) { int a = 5; // × this is not correct byte b = a; // √ this is correct byte b = (byte)a ; } Darshan Institute of Engineering & 32 Unit 32 Darshan Institute of Engineering & Unit –– 1: 1: Introduction Introduction
Operators 1.
Arithmetic Operators
2.
Relational Operators
3.
Bitwise Operators
4.
Logical Operators
5.
Assignment Operators
6.
Conditional / Ternary Operator
7.
Instance of Operator
Unit Unit –– 1: 1: Introduction Introduction
33 33
Darshan Darshan Institute Institute of of Engineering Engineering & &
Arithmetic Operator Operator Description
Note : A = 10 & B = 20
Example
+
Addition
A + B = 30
-
Subtraction
A - B = -10
*
Multiplication
A * B = 200
/
Division
B/A=2
%
Modulus
B%A=0
++
Increment
B++ = 21
--
Decrement
B-- = 19
Unit Unit –– 1: 1: Introduction Introduction
34 34
Darshan Darshan Institute Institute of of Engineering Engineering & &
Relational Operators Operator Description
Note : A = 10 & B = 20
Example
==
Equals
(A == B) is not true.
!=
Not Equals
(A != B) is true.
>
Greater than
(A > B) is not true.
=
Greater than equals
(A >= B) is not true.
c) It is used to search the specified collection in the collection.
6
boolean equals(Object obj) Returns true if invoking collection and obj are equal. Otherwise returns false.
int hashCode() Returns the hashcode for the invoking collection. Darshan Institute Darshan Institute of of Engineering Engineering & & 4 Unit 4 Unit –– 10: 10: Collection Collection Framework Framework 7
Collection Interface - Methods Sr.
Method & Description
8
boolean isEmpty() Returns true if the invoking collection is empty. Otherwise returns false.
9
Iterator iterator() It returns an iterator.
10
boolean remove(Object obj) Removes one instance of obj from the invoking collection. Returns true if the element was removed. Otherwise, returns false.
11
boolean removeAll(Collection c) It is used to delete all the elements of the specified collection from the invoking collection.
12
boolean retainAll(Collection c) It is used to delete all the elements of invoking collection except the specified collection.
13
int size() It returns the total number of elements in the collection.
Unit Unit –– 10: 10: Collection Collection Framework Framework
55
Darshan Darshan Institute Institute of of Engineering Engineering & &
Collection Interface - Methods Sr.
Method & Description
14
Object[] toArray() Returns an array that contains all the elements stored in the invoking collection. The array elements are copies of the collection elements.
Unit Unit –– 10: 10: Collection Collection Framework Framework
66
Darshan Darshan Institute Institute of of Engineering Engineering & &
List Interface The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. A list may contain duplicate elements. List is a generic interface with following declaration interface List where E specifies the type of object.
Unit Unit –– 10: 10: Collection Collection Framework Framework
77
Darshan Darshan Institute Institute of of Engineering Engineering & &
List Interface (example) import java.util.*; public class CollectionsDemo { public static void main(String[] args) { List a1 = new ArrayList(); a1.add("Sachin"); Here ArrayList a1.add("Sourav"); & LinkedList a1.add("Shami"); implements System.out.println("ArrayList Elements"); List Interface System.out.print("\t" + a1); List l1 = new LinkedList(); l1.add("Mumbai"); l1.add("Kolkata"); l1.add("Vadodara"); System.out.println(); System.out.println("LinkedList Elements"); System.out.print("\t" + l1); } } Unit Unit –– 10: 10: Collection Collection Framework Framework
88
Darshan Darshan Institute Institute of of Engineering Engineering & &
List Interface - Methods Sr.
Method & Description
1
void add(int index, Object obj) Inserts obj into the invoking list at the index passed in index. Any preexisting elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten.
2
boolean addAll(int index, Collection c) Inserts all elements of c into the invoking list at the index passed in index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. Returns true if the invoking list changes and returns false otherwise.
3
Object get(int index) Returns the object stored at the specified index within the invoking collection.
4
int indexOf(Object obj) Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list, .1 is returned.
int lastIndexOf(Object obj) Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, -1 is returned. Darshan Institute of Engineering & 99 Darshan Institute of Engineering & Unit Unit –– 10: 10: Collection Collection Framework Framework 5
List Interface (methods) (cont.) Sr.
Method & Description
6
ListIterator listIterator( ) Returns an iterator to the start of the invoking list.
7
ListIterator listIterator(int index) Returns an iterator to the invoking list that begins at the specified index.
8
Object remove(int index) Removes the element at position index from the invoking list and returns the deleted element. The resulting list is compacted. That is, the indexes of subsequent elements are decremented by one
9
Object set(int index, Object obj) Assigns obj to the location specified by index within the invoking list.
10
List subList(int start, int end) Returns a list that includes elements from start to end-1 in the invoking list. Elements in the returned list are also referenced by the invoking object.
Unit Unit –– 10: 10: Collection Collection Framework Framework
10 10
Darshan Darshan Institute Institute of of Engineering Engineering & &
Iterator Iterator interface is used to cycle through elements in a collection, eg. displaying elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time. To use an iterator to cycle through the contents of a collection, follow these steps: 1.
Obtain an iterator to the start of the collection by calling the collection's iterator( ) method.
2.
Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
3.
Within the loop, obtain each element by calling next( ).
Unit Unit –– 10: 10: Collection Collection Framework Framework
11 11
Darshan Darshan Institute Institute of of Engineering Engineering & &
Iterator - Example import java.util.*; public class IteratorDemo { public static void main(String args[]) { ArrayList al = new ArrayList(); al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); System.out.print("Contents of list: "); Iterator itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } } } Unit Unit –– 10: 10: Collection Collection Framework Framework
12 12
Darshan Darshan Institute Institute of of Engineering Engineering & &
Iterator - Methods Sr. Method & Description 1 boolean hasNext() Returns true if there are more elements. Otherwise, returns false. 2 E next() Returns the next element. Throws NoSuchElementException if there is not a next element. 3 void remove() Removes the current element. Throws IllegalStateException if an attempt is made to call remove() that is not preceded by a call to next()
Unit Unit –– 10: 10: Collection Collection Framework Framework
13 13
Darshan Darshan Institute Institute of of Engineering Engineering & &
Comparator Comparator interface is used to set the sort order of the object to store in the sets and lists. The Comparator interface defines two methods: compare( ) and equals( ). int compare(Object obj1, Object obj2) obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned. boolean equals(Object obj) obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false. Unit Unit –– 10: 10: Collection Collection Framework Framework
14 14
Darshan Darshan Institute Institute of of Engineering Engineering & &
import java.util.*; class Student { String name; int age; Student(String name, int age){ this.name = name; this.age = age; } }
class AgeComparator implements Comparator{ public int compare(Object o1,Object o2){ Student s1=(Student)o1; Student s2=(Student)o2; if(s1.age==s2.age) return 0; else if(s1.age>s2.age) return 1; else return -1; } }
public class ComparatorDemo { public static void main(String args[]){ ArrayList al=new ArrayList(); al.add(new Student("Vijay",23)); al.add(new Student("Ajay",27)); al.add(new Student("Jai",21)); System.out.println("Sorting by age"); Collections.sort(al,new AgeComparator()); Iterator itr2=al.iterator(); while(itr2.hasNext()){ Student st=(Student)itr2.next(); System.out.println(st.name+" "+st.age); } } }
Vector Class Vector implements a dynamic array. It is similar to ArrayList, but with two differences: • Vector is synchronized. • Vector contains many legacy methods that are not part of the collection framework
Vector proves to be very useful if you don't know the size of the array in advance or you just need one that can change sizes over the lifetime of a program. Vector is declared as follows: Vector = new Vector;
Unit Unit –– 10: 10: Collection Collection Framework Framework
16 16
Darshan Darshan Institute Institute of of Engineering Engineering & &
import java.util.*; public class VectorDemo { public static void main(String args[]) { //Create an empty vector with initial capacity 4 Vector vec = new Vector(4); //Adding elements to a vector vec.add("Tiger"); vec.add("Lion"); vec.add("Dog"); vec.add("Elephant"); //Check size and capacity System.out.println("Size is: "+vec.size()); System.out.println("Default capacity is: "+vec.capacity()); //Display Vector elements System.out.println("Vector element is: "+vec); vec.addElement("Rat"); vec.addElement("Cat"); vec.addElement("Deer"); //Again check size and capacity after two insertions System.out.println("Size after addition: "+vec.size()); System.out.println("Capacity after addition is: "+vec.capacity()); //Display Vector elements again System.out.println("Elements are: "+vec); //Checking if Tiger is present or not in this vector if(vec.contains("Tiger")) { System.out.println("Tiger is present at the index " +vec.indexOf("Tiger")); } else { System.out.println("Tiger is not present in the list."); } //Get the first element System.out.println("The first animal of the vector is = "+vec.firstElement()); //Get the last element System.out.println("The last animal of the vector is = "+vec.lastElement()); }
Vector - Constructors Sr. Constructor & Description 1 Vector( ) This constructor creates a default vector, which has an initial size of 10 2 Vector(int size) This constructor accepts an argument that equals to the required size, and creates a vector whose initial capacity is specified by size: 3 Vector(int size, int incr) This constructor creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward 4 Vector(Collection c) creates a vector that contains the elements of collection c
Unit Unit –– 10: 10: Collection Collection Framework Framework
18 18
Darshan Darshan Institute Institute of of Engineering Engineering & &
Vector - Methods Sr. Method & Description 7 boolean containsAll(Collection c) Returns true if this Vector contains all of the elements in the specified Collection. 8 Enumeration elements() Returns an enumeration of the components of this vector. 9 Object firstElement() Returns the first component (the item at index 0) of this vector. 10 Object get(int index) Returns the element at the specified position in this Vector. 11 int indexOf(Object elem) Searches for the first occurence of the given argument, testing for equality using the equals method. 12 boolean isEmpty() Tests if this vector has no components. Unit Unit –– 10: 10: Collection Collection Framework Framework
19 19
Darshan Darshan Institute Institute of of Engineering Engineering & &
Vector - Methods (cont.) Sr. Method & Description 13 Object lastElement() Returns the last component of the vector. 14 int lastIndexOf(Object elem) Returns the index of the last occurrence of the specified object in this vector. 15 Object remove(int index) Removes the element at the specified position in this Vector. 16 boolean removeAll(Collection c) Removes from this Vector all of its elements that are contained in the specified Collection. 17 Object set(int index, Object element) Replaces the element at the specified position in this Vector with the specified element. 18 int size() Returns the number of components in this vector.
Unit Unit –– 10: 10: Collection Collection Framework Framework
20 20
Darshan Darshan Institute Institute of of Engineering Engineering & &
Stack Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector and adds several of its own. Stack is declared as follows: Stack st = new Stack(); where E specifies the type of object.
Unit Unit –– 10: 10: Collection Collection Framework Framework
21 21
Darshan Darshan Institute Institute of of Engineering Engineering & &
import java.util.*; public class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println("push(" + a + ")"); System.out.println("stack: " + st); } static void showpop(Stack st) { System.out.print("pop -> "); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println("stack: " + st); } public static void main(String args[]) { Stack st = new Stack(); System.out.println("stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println("empty stack"); } } }
Stack - Methods Stack includes all the methods defined by Vector and adds several methods of its own. Sr. Method & Description 1
boolean empty() Returns true if the stack is empty, and returns false if the stack contains elements.
2
E peek() Returns the element on the top of the stack, but does not remove it.
3
E pop() Returns the element on the top of the stack, removing it in the process.
4
E push(E element) Pushes element onto the stack. Element is also returned.
5
int search(Object element) Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, -1 is returned.
Unit Unit –– 10: 10: Collection Collection Framework Framework
23 23
Darshan Darshan Institute Institute of of Engineering Engineering & &
Queue Queue interface extends Collection and declares the behaviour of a queue, which is often a first-in, first-out list. LinkedList and PriorityQueue are the two classes which implements Queue interface Queue is declared as follows: Queue q = new LinkedList(); Queue q = new PriorityQueue(); where E specifies the type of object.
Unit Unit –– 10: 10: Collection Collection Framework Framework
24 24
Darshan Darshan Institute Institute of of Engineering Engineering & &
Queue Example import java.util.*; public class QueueDemo { public static void main(String[] args) { Queue q = new LinkedList(); q.add("Tom"); q.add("Jerry"); q.add("Mike"); q.add("Steve"); q.add("Harry"); System.out.println("Elements in Queue:"+q); System.out.println("Removed element: "+q.remove()); System.out.println("Head: "+q.element()); System.out.println("poll(): "+q.poll()); System.out.println("peek(): "+q.peek()); System.out.println("Elements in Queue:"+q); } } Darshan Darshan Institute Institute of of Engineering Engineering & &
Unit Unit –– 10: 10: Collection Collection Framework Framework
25 25
Queue - Methods Sr. Method & Description 1
E element() Returns the element at the head of the queue. The element is not removed. It throws NoSuchElementException if the queue is empty.
2
boolean offer(E obj) Attempts to add obj to the queue. Returns true if obj was added and false otherwise.
3
E peek() Returns the element at the head of the queue. It returns null if the queue is empty. The element is not removed.
4
E poll() Returns the element at the head of the queue, removing the element in the process. It returns null if the queue is empty.
5
E remove() Returns the element at the head of the queue, returning the element in the process. It throws NoSuchElementException if the queue is empty.
Unit Unit –– 10: 10: Collection Collection Framework Framework
26 26
Darshan Darshan Institute Institute of of Engineering Engineering & &
PriorityQueue PriorityQueue extends AbstractQueue and implements the Queue interface. It creates a queue that is prioritized based on the queue's comparator. PriorityQueue is declared as follows: PriorityQueue = new PriorityQueue; It builds an empty queue with starting capacity as 11.
Unit Unit –– 10: 10: Collection Collection Framework Framework
27 27
Darshan Darshan Institute Institute of of Engineering Engineering & &
PriorityQueue - Example import java.util.*; public class PriorityQueueExample { public static void main(String[] args) { PriorityQueue numbers = new PriorityQueue(); numbers.add(750); numbers.add(500); numbers.add(900); numbers.add(100); while (!numbers.isEmpty()) { System.out.println(numbers.remove()); } } }
Unit Unit –– 10: 10: Collection Collection Framework Framework
28 28
Darshan Darshan Institute Institute of of Engineering Engineering & &
PriorityQueue - Constructors Sr. Constructor & Description 1
PriorityQueue() Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
2
PriorityQueue(Collection