Java Module1
Java Module1
JAVA
BCS613D
- Dr. SANTOSH K C
ASSOCIATE PROFESSOR
Dept. of C S & E
BIET, DAVANGERE
MODULE-1
The collections and Framework:
Collections Overview, The Collection Interfaces.
The Collection Classes, accessing a collection Via an
Iterator.
Storing User Defined Classes in Collections, The
Random Access Interface.
Working with Maps, Comparators, The Collection
Algorithms.
Arrays, The legacy Classes and Interfaces.
Parting Thoughts on Collections.
The History and Evolution of Java
■ Java’s Lineage
Java is related to C++, which is a direct descendant of
C. Much of the character of Java is inherited from these
two languages. From C, Java derives its syntax. Many of
Java’s object oriented features were influenced by C++.
■ FORTRAN, BASIC
■ The Birth of Modern Programming:
C, C++
■ The Stage Is Set for Java
■ The Creation of Java
Java was conceived by James Gosling, Patrick Naughton,
Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems,
Inc. in 1991.
-Portable, Platform-independent
-Internet version of C++
How Java Impacted the Internet
• Java Applets
• Security
• Portability
The Java Buzzwords
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
An Overview of Java
■ The Three OOP Principles
i. Encapsulation: Encapsulation is the mechanism that
binds together code and the data it manipulates, and keeps both
safe from outside interference and misuse.
ii. Inheritance: Inheritance is the process by which one
object acquires the properties of another object.
iii. Polymorphism: Polymorphism (from Greek, meaning
“many forms”) is a feature that allows one interface to be used for
a general class of actions.
■ Polymorphism, Encapsulation, and Inheritance Work
Together
■ A First Simple Program
/* This is a simple Java program.
Call this file "[Link]". */
class Example { // Your program begins with a call to main().
public static void main(String[ ] args)
{
[Link]("This is a simple Java program.");
}
}
A Second Short Program
/* Here is another short example.
Call this file "[Link]". */
class Example2
{
public static void main(String[ ] args)
{
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
[Link]("This is num: " + num);
num = num * 2;
[Link]("The value of num * 2 is ");
[Link](num);
}
}
■ Two Control Statements
The if Statement
The Java if statement works much like the IF statement in any
other language. It determines the flow of execution based on
whether some condition is true or false. Its simplest form is
shown here:
• Syntax: if(condition) statement;
type name(parameter-list)
{
// body of method
}
// This program includes a method inside the box class.
class Box
{
double width; double height;
double depth;
// display volume of a box
void volume()
{ [Link]("Volume is ");
[Link](width * height * depth);
}
}
class BoxDemo3 {
public static void main(String[] args)
{
Box mybox = new Box();
[Link] = 10;
[Link] = 20;
[Link] = 15;
// display volume of box
[Link]();
}
}
Garbage Collection
• Since objects are dynamically allocated by using the new operator.
• delete operator used in C++.
• Deallocation done automatically in java.
How Garbage Collection Works
An object becomes eligible for garbage collection when:
• It has no reference pointing to it
• It becomes unreachable in the program
[Link]
The Collections Framework
What is [Link]?
[Link] is a built-in package in Java that contains many ready-
made classes and interfaces. These help programmers do common
tasks easily instead of writing everything from scratch.
Inside [Link], there is a very powerful system called
the Collections Framework. It helps to manage groups of objects.
For example:
■ Storing multiple student names
■ Keeping a list of numbers
■ Managing sets of data
It includes:
■ Interfaces (like rules or blueprints)
■ Classes (ready-made implementations)
Examples:
■ ArrayList
■ HashSet
■ HashMap
These make storing and handling data much easier and more efficient.
import [Link];
import [Link];
public class CollectionExample {
public static void main(String[] args) {
// Collection interface reference
Collection<String> names = new ArrayList<>();
// Adding elements
[Link](”Amar");
[Link]("Akbar");
[Link](”Anthony");
// Displaying elements
[Link]("Student Names: " + names);
// Checking size
[Link]("Total Students: " + [Link]());
// Removing an element
[Link]("Anthony");
[Link]("After Removal: " + names);
}
}
What This Program Shows:
• Collection<String> → Using Collection Interface
• ArrayList<> → Implementation class
• add() → Adds elements
• size() → Returns number of elements
• remove() → Removes element
Collections Overview
Why Collections Were Introduced?
In early Java (before J2SE 1.2), there were classes like:
• Vector
• Stack
• Dictionary
• Properties
Example:
Collection<String> names;
Collection<Integer> numbers;
Relationship with Iterable
Collection extends Iterable, every collection can be used in a
for-each loop.
Example:
for(String name : names)
{
[Link](name);
}
Core Methods of Collection
All collections (like List, Set, Queue) inherit these common methods.
➤ Adding Elements
• add(E e) → Adds one element
• addAll(Collection c) → Adds all elements from another collection
Example:
[Link]("Java");
[Link](otherList);
Removing Elements
• remove(Object o) → Removes one element
• removeAll(Collection c) → Removes all matching elements
• retainAll(Collection c) → Keeps only specified elements
• removeIf(Predicate) → Removes elements based on condition
• clear( ) → Removes everything
Example:
[Link]("Java");
[Link]();
Checking Elements
• contains(Object o) → Checks if element exists
• containsAll(Collection c) → Checks if all elements exist
• isEmpty() → Checks if collection is empty
• size( ) → Returns number of elements
Example:
if([Link]("Java")) {
[Link]("Found!");
}
➤ Iteration Methods
• iterator( ) → Returns Iterator
• spliterator( ) → Used for parallel processing
• stream( ) → Returns Stream
• parallelStream( ) → Returns parallel Stream
Example:
[Link]().forEach([Link]::println);
Possible Exceptions
Some methods may throw exceptions:
O/P:
Java
Python
C++
The SortedSet Interface
• The SortedSet interface extends Set and declares the behavior of
a set sorted in ascending order.
SortedSet is a generic interface that has this declaration:
interface SortedSet<E>
• Here, E specifies the type of objects that the set will hold.
Ex 1:
SortedSet<Integer> nums = new
TreeSet<>();
[Link](50);
[Link](10);
[Link](30);
[Link](10); // duplicate
[Link](nums);
O/P:
EX 2:
SortedSet<Integer> nums = new TreeSet<>();
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]([Link]());
[Link]([Link]());
[Link]([Link](30));
O/P:
10
40
10, 20
The NavigableSet Interface
• The NavigableSet interface extends SortedSet and declares the
behavior of a collection that supports the retrieval of elements
based on the closest match to a given value or values.
• NavigableSet is a generic interface that has this declaration:
interface NavigableSet<E>
NavigableSet<Integer> nums = new TreeSet<>();
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]([Link](25));
[Link]([Link](20));
[Link]([Link](25));
[Link]([Link](30));
O/P:
20
20
30
40
The Queue Interface
The Queue interface extends Collection and declares the behavior
of a queue, which is often a first-in, first-out list
interface Queue<E>
import [Link];
import [Link];
// Demonstrate ArrayList.
import [Link].*; //Import Statement
class ArrayListDemo { //Declares a class named ArrayListDemo.
public static void main(String args[])
{ //Creating an ArrayList
ArrayList al = new ArrayList();
[Link]("Initial size of al: " + [Link]());
// Add elements to the array list.
[Link]("C");
[Link]("A");
[Link]("E");
[Link]("B");
[Link]("D");
[Link]("F"); // Adds elements "C", "A", "E", "B", "D", "F" sequentially.
[Link](1, "A2");
[Link]("Size of al after additions: " + [Link]());
// Display the array list
[Link]("Contents of al: " + al);
// Remove elements from the array list.
[Link]("F"); //Removes element "F" from the list.
[Link](2);
[Link]("Size of al after deletions: " + [Link]());
[Link]("Contents of al: " + al);
}
}
Output:
● For the sake of simplicity, the foregoing examples have stored built-
in objects, such as String or Integer, in a collection. Of course,
collections are not limited to the storage of built-in objects.
● For example, consider the following example that uses a LinkedList
to store mailing addresses:
class MailList {
// A simple mailing list example.
public static void main(String args[]) {
import [Link].*;
LinkedList<Address> ml = new
class Address {
LinkedList<Address>();
private String name, street, city, state, code;
Address(String n, String s, String c,
// Add elements to the linked list.
String st, String cd) {
[Link](new Address("J.W. West", "11 Oak Ave",
name = n;
"Urbana", "IL", "61801"));
street = s;
city = c;
[Link](new Address("Ralph Baker", "1142 Maple
state = st;
Lane", "Mahomet", "IL", "61853"));
code = cd;
}
[Link](new Address("Tom Carlton", "867 Elm St",
public String toString()
"Champaign", "IL", "61820"));
{
return name + "\n" + street + "\n" +
// Display the mailing list.
city + " " + state + " " + code;
for(Address element : ml)
}
[Link](element + "\n");
}
[Link]();
}
}
The RandomAccess Interface
The RandomAccess is a special interface in Java used in the Java
Collections Framework. But it is a marker interface.
[Link]([Link](1));
Working with Maps
A map is an object that stores associations between keys and values, or
key/value pairs. Given a key, you can find its value.
Both keys and values are objects. The keys must be unique, but the values
may be duplicated. Some maps can accept a null key and null values,
others cannot.
Maps don’t implement the Iterable interface.
We can’t obtain an iterator to a map.
The Map Interfaces
The Map Interface
The Map interface maps unique keys to values. A key is an object that we
use to retrieve a value at a later date.
Given a key and a value, we can store the value in a Map object. After the
value is stored, we can retrieve it by using its key.
Map is generic and is declared as shown here:
interface Map <K, V>
Here, K specifies the type of keys, and V specifies the type of values.
Maps methods
Map stores Key–Value pairs
A Map stores data like this:
Key → Value
Example in Java:
Map<Integer, String> map = new HashMap< >( );
[Link](1, "Java");
[Link](2, "Python");
[Link](3, "C++");
Keys must be unique
In a Map, keys cannot be duplicated.
Example:
[Link](1, "Java");
[Link](1, "Python");
Comparators
Example logic:
compare(5,3) → positive
compare(3,5) → negative
compare(4,4) → 0
The Collection Algorithms
The Collections Framework defines several algorithms that can be applied
to collections and maps. These algorithms are defined as static methods
within the Collections class. They are summarized in Table 20-15.
Arrays
In Java, the Arrays class provides ready-made static methods to work
easily with arrays.
These methods help perform common operations like searching, copying,
comparing, and converting arrays to lists.
■ Think of it as a toolbox for arrays 🧰
asList( ) Method
Purpose
Converts an array into a List.
Method:
static <T> List asList(T... array)
Example:
■ import [Link].*;
public class Example {
public static void main(String[] args) {
String[] arr = {"Java", "Python", "C++"};
List<String> list = [Link](arr);
[Link](list);
}
}
binarySearch( ) – Search an Element
This method searches an element in a sorted array using Binary Search.
Example:
import [Link];
[Link]([Link](newArr));
Output
■ 1, 2, 3, 4, 0, 0
copyOfRange( ) – Copy Part of Array
Copies a specific range of elements.
Example
int arr[] = {10,20,30,40,50};
[Link]([Link](newArr));
Some other Methods in Arrays
• equals( ) – Compare Two Arrays
• fill( ) – Fill Array with One Value
• mismatch( )
Finds the first position where arrays differ.
Example
Array1 = [1,2,3]
Array2 = [1,5,3]
Outupt:
1
Legacy Classes and Interfaces in Java
■ In the Java Collections Framework, the term Legacy Classes means old
classes that were used before the Collections Framework was introduced.
So Java provided some separate classes to store and manage objects.
These older classes are called Legacy Classes.
Examples of legacy classes:
• Vector
• Stack
• Hashtable
• Dictionary
• Enumeration
In Java 1.2, Java introduced the Collections Framework.
New and better classes were added, such as:
• ArrayList
• HashMap
• HashSet
These modern classes are:
• easier to use
• faster
• more flexible
What happened to old classes?
Java did not remove the old classes because old programs were still using
them.
Instead:
• They were modified to work with the Collections Framework
• So they still exist but are called legacy classes
Vector
What is Vector?
Vector is a class in Java that stores a group of objects in a dynamic array.
• Dynamic array means the size can increase automatically when more
elements are added.
• It is similar to ArrayList, but there are some differences.
Vector Declaration
class Vector<E>
• E represents the type of elements stored
Example:
Vector<Integer> v = new Vector<Integer>();
■ This means the vector will store Integer objects.
Example Program using Vector
import [Link].*;
class Example {
public static void main(String args[]) {
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");
[Link](10);
[Link](20);
[Link](30);
[Link]("Top element: " + [Link]());
[Link]("Removed: " + [Link]());
[Link]("Removed: " + [Link]());
}
}
Parting Thoughts on Collections
End of Module-01