0% found this document useful (0 votes)
4 views

Java IA1 v2

The document provides an overview of the Java Collections Framework (JCF), detailing its components, including interfaces, classes, and algorithms for managing collections of objects. It explains methods available in the Collection interface, various collection classes like ArrayList and LinkedList, and how to access collections using iterators. Additionally, it covers specific interfaces such as List, Set, SortedSet, and Queue, as well as methods in the Map interface and string comparison methods.

Uploaded by

ranjananjadhav12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java IA1 v2

The document provides an overview of the Java Collections Framework (JCF), detailing its components, including interfaces, classes, and algorithms for managing collections of objects. It explains methods available in the Collection interface, various collection classes like ArrayList and LinkedList, and how to access collections using iterators. Additionally, it covers specific interfaces such as List, Set, SortedSet, and Queue, as well as methods in the Map interface and string comparison methods.

Uploaded by

ranjananjadhav12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

1. Define Collection Framework.

Explain the methods available in collection interface


• The Java Collections Framework (JCF) is a set of classes and interfaces that provide a standard way to
handle collections in Java.
• It's like a toolkit that Java developers use to work with groups of objects efficiently.
• The Java Collections Framework provides a unified architecture for handling collections of objects in
Java.
• It includes interfaces, implementations, utility classes, and algorithms to make working with
collections easier and more efficient.
• By using the Java Collections Framework, developers can write code that is more reusable, flexible, and
maintainable.
Key Components of the Java Collections Framework:

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

• boolean add(E e);


o Adds the specified element to the collection. Returns true if added
• boolean addAll(Collection<? extends E> c);
o Adds all of the elements in the specified collection to this collection. Returns true if added
• void clear();
o Removes all of the elements from this collection
• boolean contains(Object o);
o Returns true if this collection contains the specified element
• boolean containsAll(Collection<?> c);
o Returns true if this collection contains all of the elements in the specified collection
• boolean equals(Object o);
o Compares the specified object with this collection for equality
• int hashCode();
o Returns the hash code value for this collection
• boolean isEmpty();
o Returns true if this collection contains no elements
• Iterator<E> iterator();
o Returns an iterator over the elements in this collection
• boolean remove(Object o);
o Removes a single instance of the specified element from this collection, if it is present
• boolean removeAll(Collection<?> c);
o Removes all of this collection's elements that are also contained in the specified collection
• boolean retainAll(Collection<?> c);
o Retains only the elements in this collection that are contained in the specified collection
• int size();
o Returns the number of elements in this collection
• Object[] toArray();
o Returns an array containing all of the elements in this collection
• <T> T[] toArray(T[] a);
o Returns an array containing all of the elements in this collection;
Program Example:

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

Some standard classes provided in these are:

• AbstractCollection • HashSet
• AbstractList • LinkedHashSet
• AbstractSequentialist • TreeSet
• LinkedList • AbstractMap
• ArrayList • HashMap
• AbstractSet • AbstractQueue

Some concrete classes provided are:

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 has the constructors shown here:

ArrayList( )

ArrayList(Collection<? extends E> c)

ArrayList(int capacity)

First method creates empty array, second method makes an array out of collection passed, third
method initializes array with specified capacity.

ii. The LinkedList Class

The LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue
interfaces. It provides a linked-list data structure.

LinkedList is a generic class that has this declaration:

class LinkedList<E>

LinkedList has the two constructors shown here:

LinkedList( )

LinkedList(Collection<? extends E> c)

First method creates an empty Linked List, second methods creates linked list with items of existing
collection “c”

iii. The TreeSet Class

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.

TreeSet is a generic class that has this declaration:

class TreeSet<E>
TreeSet has the following constructors:

TreeSet( )

TreeSet(Collection<? extends E> c)

TreeSet(Comparator<? super E> comp)

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

iv: The PriorityQueue Class

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 defines the seven constructors shown here:

PriorityQueue( )

PriorityQueue(int capacity)

PriorityQueue(Comparator<? super E> comp)

PriorityQueue(int capacity, Comparator<? super E> comp)

PriorityQueue(Collection<? extends E> c)

PriorityQueue(PriorityQueue<? extends E> c)

PriorityQueue(SortedSet<? extends E> c)

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.

v. The ArrayDeque Class

The ArrayDeque class extends AbstractCollection and implements the Deque interface.

Declaration:

class ArrayDeque<E>

ArrayDeque defines the following constructors:

ArrayDeque( )

ArrayDeque(int size)

ArrayDeque(Collection<? extends E> c)

The first constructor builds an empty deque.

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:

There are 3 possible ways to iterate through collections they are:

i. Using iterator Interface:

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.

Steps to use an iterator:

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

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.

Removes the current element. Throws IllegalStateException if an attempt is made to call


void remove()
remove() method before calling next() method atleast once.

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

iii. The For-Each Alternative to Iterators

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>

Methods provided by List interface are:

• void add(int index , E obj ) • E set(int index , E obj )


• E get(int index ) • List<E> subList(int start , int end )
• int indexOf(Object obj ) • boolean addAll(int index , Collection<?
• int lastIndexOf(Object obj ) extends E> c )
• E remove(int index )
Program example:
Output:

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

• boolean add(): • Iterator iterator()


• void clear() • Object remove(object E)
• boolean contains(object E) • int size()
• boolean isEmpty()

Output:
iii. Sorted Set:

The SortedSet interface extends Set and declares the behaviour of a set, sorted in ascending order.

Declaration:

interface SortedSet<E>

Methods provided by sorted set:

• E first() • SortedSet tailSet(Object start)


• E last() • SortedSet subSet(Object start,
• SortedSet headSet(Object end) Object end)

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>

Methods provided by queue interface:

• 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:

interface Map<K, V>

Methods provided by Map interface:

Object put (Object Key, Object Value)

It is used to insert an entry in this map.

void putAll(Map map)

It is used to insert the specified map in this map

Object remove(Object key)

It is used to return the value for the specified key.

Object get(Object key)

It is used to return the value for the specified key.

boolean containsKey(Object key)

It is used to search the specified key from this map.

Void clear()

Removes all key/values pairs from the invoking map.

boolean containsvalues(Object key)

Returns true if the map contains value. otherwise false.

Boolean equals(Object obj)

Returns true if theobj is a map and contains the same entries. otherwise false

Int size()

Returns the number of key/value pairs in the map.

Collection<v> values()

Returns a collection containing the value in the map.

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:

interface Map<K, V>

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.

Some methods declared by map are:

• Object put (Object Key, Object • Void clear()


Value) • boolean containsvalues(Object key)
• void putAll(Map map) • Boolean equals(Object obj)
• Object remove(Object key) • Int size()
• Object get(Object key) • Collection<v> values()
• boolean containsKey(Object key)

The SortedMap Interface

The SortedMap interface extends Map. It ensures that the entries are maintained in ascending order based on
the keys.

It is declared as:

interface SortedMap<K, V>

Methods provided by SortedMap are:

• 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()

i. equals() and equalsIgnoreCase()

• To compare two strings for equality, use equals( )


• To perform a comparison that ignores case differences, call equalsIgnoreCase( ).

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:

boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)


boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars)
Example;

Output:

iii. startsWith() and endsWith()

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:

boolean startsWith(String str)


boolean startsWith(String str, int startIndex)
boolean endsWith(String str)
Examples:

"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:

8 b. Construct a java program using Valueof() method in Data conversion

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:

StringBuffer append(String str)

StringBuffer append(int num)

StringBuffer append(Object obj)

Example:
Output:

a=42!

ii. insert( )

The insert( ) method inserts one string into another.

Forms:

StringBuffer insert(int index, String str)

StringBuffer insert(int index, char ch)

StringBuffer insert(int index, Object obj)

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( ).

These methods are:

StringBuffer delete(int startIndex, int endIndex)

StringBuffer deleteCharAt(int loc)

Example:

Output:

v. replace()

You can replace one set of characters with another set inside a StringBuffer object by calling replace( ).

Syntax:

StringBuffer replace(int startIndex, int endIndex, String str)

Example

Output:

After replace: This was a test.


10. Explain the following StringBuffer methods (10M)

a. StringBuffer Constructors c. ensureCapacity() e. charAt() and setCharAt()

b. lengh() and capacity d. setLength() f. getChars()

a. StringBuffer Constructors

StringBuffer defines these four 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.

b. length( ) and capacity( )

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

char charAt(int where)

void setCharAt(int where, char ch)

• 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

Example for setLength, charAt and setCharAt

Output:

f. getChars( )

To copy a substring of a StringBuffer into an array, use the getChars( ) method.

Syntax:

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

• 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.

11 b. Explain two key swing features

1. Swing Components Are Lightweight:

• With very few exceptions, Swing components are lightweight.


• This means that they are written entirely in Java. Thus, lightweight components are more efficient and more
flexible.
• Furthermore, because lightweight components do not use hardware/OS specific commands, the look and
feel of each component is determined by Swing, not by the underlying operating system.
• As a result, each component will work in a consistent manner across all platforms.

2. Swing Supports a Pluggable Look and Feel:

• 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.

12. Duplicate question of 11th Question

You might also like