Java IA1 v2
Java IA1 v2
a. Interfaces: These define the types of collections and the operations you can perform on them. They
are like blueprints or contracts that specify what methods a collection must have. They include:
Collection, List, Set, Queue, Map
b. Classes: These are concrete implementations of the interfaces. They provide the actual data
structures to store the elements. Some classes are: ArrayList, LinkedList, HashSet, etc…
c. Algorithms: The Collections class provides various static methods for operating on collections.
Includes algorithms for sorting (sort()), searching (binarySearch()), shuffling (shuffle()), etc. These
methods are useful for manipulating collections without the need for writing custom code.
Methods provided by collection interface: //Write any 8-10 Methods
Output:
2. Explain the methods available in collection classes
Java provides a set of standard collection classes that implement Collection interfaces. Some of the classes
provide full implementations that can be used as-is and others are abstract class
• AbstractCollection • HashSet
• AbstractList • LinkedHashSet
• AbstractSequentialist • TreeSet
• LinkedList • AbstractMap
• ArrayList • HashMap
• AbstractSet • AbstractQueue
i. ArrayList Class:
The ArrayList class extends AbstractList and implements the List interface. ArrayList is a generic class
that has this declaration:
class ArrayList<E>
An ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically
increase or decrease in size.
ArrayList( )
ArrayList(int capacity)
First method creates empty array, second method makes an array out of collection passed, third
method initializes array with specified capacity.
The LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue
interfaces. It provides a linked-list data structure.
class LinkedList<E>
LinkedList( )
First method creates an empty Linked List, second methods creates linked list with items of existing
collection “c”
TreeSet extends AbstractSet and implements the NavigableSet interface. It creates a collection that uses a
tree for storage. Objects are stored in sorted, ascending order.
class TreeSet<E>
TreeSet has the following constructors:
TreeSet( )
TreeSet(SortedSet<E> ss)
First method generates empty tree set, second methods makes a set with items of “c”, third method
generates a set with different comparator for sorting, fourth method makes TreeSet from Existing Sorted
Set
PriorityQueue extends AbstractQueue and implements the Queue interface. It creates a queue that is
prioritized based on the queue’s comparator
Declarations:
class PriorityQueue<E>
PriorityQueue( )
PriorityQueue(int capacity)
The first constructor builds an empty queue. The second constructor builds a queue with specific
capacity. The third constructor specifies a comparator, and the fourth specifies both comparator and
capacity. The last three constructors create queues with existing elements of the collection passed in c.
The ArrayDeque class extends AbstractCollection and implements the Deque interface.
Declaration:
class ArrayDeque<E>
ArrayDeque( )
ArrayDeque(int size)
The second constructor builds a deque that has the specified initial capacity.
The third constructor creates a deque that is initialized with the elements of the collection passed in c
3. Explain how collections can be accessed using iterator:
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.
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.
Methods in iterator:
Method Description
boolean
Returns true if there are more elements in the collection. Otherwise, returns false.
hasNext()
Returns the next element present in the collection. Throws NoSuchElementException if there
E next()
is not a next element.
Program Example:
Output: abcd
ii. Using ListIterator interface:
ListIterator interface enables you to cycle through a List, obtaining or removing elements. ListIterator
extends Iterator to allow bidirectional traversal of a list, and the modification of elements. ListIterator is
generic interfaces which is declared as shown here:
interface ListIterator<E>
Program: Output
In forward direction:
abcd
In backward direction
dcba
If you won’t be modifying the contents of a collection or obtaining elements in reverse order, then the
for-each version of the for loop is often a more convenient alternative to cycling through a collection
than is using an iterator. Program:
Output:
abcd
4. Explain the following collection interfaces: i) List ii) Set iii) Sorted Set iv) Queue
i. List
List interface extends collection and handles sequence of objects. Duplicates are allowed.
Declaration:
interface List<E>
1234
ii. Set
The Set interface defines a set. It extends Collection and specifies the behaviour of a collection that does not
allow duplicate elements.
Declaration:
interface Set<E>
Methods provided by set Interface: //Same from collection interface nothing new
Output:
iii. Sorted Set:
The SortedSet interface extends Set and declares the behaviour of a set, sorted in ascending order.
Declaration:
interface SortedSet<E>
Example Program:
Output:
iv. Queue
The Queue interface extends Collection and declares the behavior of a queue, which is often a first-in, first-out
list.
Declaration:
interface Queue<E>
• E element() • E poll()
• boolean offer(E obj) • E remove()
• E peek()
Program:
Output:
5. Explain the methods available in Map interface.
The Map interface maps unique keys to values. Its declared using following syntax:
Void clear()
Returns true if theobj is a map and contains the same entries. otherwise false
Int size()
Collection<v> values()
Example program:
Output:
6. Explain the following Map interfaces: i) Map Interface ii) Sorted Map
The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later time.
Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by
using its key. Its declared using following syntax:
Maps revolve around two basic operations: get( ) and put( ). To put a value into a map, use put( ), specifying the
key and the value. To obtain a value, call get( ), passing the key as an argument. The value is returned.
The SortedMap interface extends Map. It ensures that the entries are maintained in ascending order based on
the keys.
It is declared as:
• Comparator<? super K> comparator(): Returns the invoking sorted map's comparator.
• K firstKey(): Returns the first key in the invoking map.
• K lastKey(): Returns the last key in the invoking map.
• SortedMap<K, V> headMap(K end): Returns a sorted map with keys that are less than end.
• SortedMap<K, V> tailMap(K start): Returns a map with keys that are greater than or equal to start.
• SortedMap<K, V> subMap(K start, K end): Returns a map containing those entries with keys that are
greater than or equal to start and less than end.
Example Program:
Output:
7. Explain the following string comparison methods with examples i)equals() and equalsIgnoreCase()
ii)regionMatches() iii)startsWith() and endsWith()
Example:
Output:
ii. regionMatches()
The regionMatches( ) method compares a specific region inside a string with another specific region in
another string. It is also overloaded to ignore case.
Syntax:
Output:
The startsWith( ) method determines whether a given String begins with a specified string. And
endsWith( ) determines whether the String in question ends with a specified string.
Declarations:
"Foobar".startsWith("Foo") //true
"Foobar".endsWith("bar") //true
"Foobar".startsWith("bar", 3) //true
8 a. Develop java program to demonstrate indexOf() and LastindexOf() method.
Output:
Output:
9. Explain the following methods with example
i) append() ii) insert() iii) reverse() iv) delete() and deleteCharAt() v) replace()
i. append():
The append( ) method concatenates the string representation of any other type of data to the end of the
invoking StringBuffer object.
Different forms:
Example:
Output:
a=42!
ii. insert( )
Forms:
Example:
Output:
I Like Java
iii. reverse()
You can reverse the characters within a StringBuffer object using reverse( ).
Example:
Output:
iv. delete() and deleteCharAt()
You can delete characters within a StringBuffer by using the methods delete( ) and deleteCharAt( ).
Example:
Output:
v. replace()
You can replace one set of characters with another set inside a StringBuffer object by calling replace( ).
Syntax:
Example
Output:
a. StringBuffer Constructors
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
• The default constructor (the one with no parameters) reserves room for 16 characters without reallocation.
• The second version accepts an integer argument that explicitly sets the size of the buffer.
• The third version accepts a String argument that sets the initial contents of the StringBuffer object.
• The fourth version acts same as 3rd but takes CharSequence as input.
The current length of a StringBuffer can be found via the length( ) method, while the total allocated
capacity can be found through the capacity( ) method.
Example:
Output:
Capacity is generally “length at start” + 16, here length is 5, therefore capacity is 21.
c. ensureCapacity()
If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed,
you can use ensureCapacity( ) to set the size of the buffer.
Syntax:
void ensureCapacity(int minCapacity)
• Here minCapacity is minimum size of buffer.
d. setLength( )
To set the length of the string within a StringBuffer object, use setLength( ).
Syntax:
void setLength(int len)
• Here, len specifies the length of the buffer. This value must be nonnegative.
• When you increase the size of the buffer, null characters are added to the end of the existing buffer.
• If you call setLength() with a value less than the current value returned by length(), then the characters
stored beyond the new length will be lost.
e. charAt() and setCharAt( )
The value of a single character can be obtained from a StringBuffer via the charAt()method. You can set the
value of a character within a StringBuffer using setCharAt().
Syntax
• For charAt(), where specifies the index of the character being obtained.
• For setCharAt(), where specifies the index of the character being set, and ch specifies the new value of that
character
Output:
f. getChars( )
Syntax:
• Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index
that is one before the end of substring.
• This means that the substring contains the characters from sourceStart through sourceEnd–1.
• The array that will receive the characters is specified by target. The index within target at which the
substring will be copied is passed in targetStart.
• Care must be taken to assure that the target array is large enough to hold the number of characters in the
specified substring.
11 a. List the differences between Java AWT and Java swing.
• Swing supports a pluggable look and feel (PLAF), allowing the appearance of components to be changed
independently of their logic.
• This enables seamless switching between different styles, including platform-independent (e.g., Metal) and
platform-specific designs.
• Java provides built-in look-and-feels like Metal and Nimbus, with Metal being the default.
• PLAF allows dynamic changes at runtime and supports custom designs, ensuring flexibility and
consistency across platforms.