Docsity

Advanced Java Notes: Generics, Collections, Lambda Expressions, JSP & JavaBeans, Study notes of Java Programming

Toggle sidebar
bg1
1. What are Generics in Java? Explain the need, advantages and basic syntax of
Generics with suitable examples.
Generics in Java are a feature that enables you to create reusable and type-safe code.
They allow you to define classes, interfaces and methods with a type parameter (i.e., a
placeholder for a specific type) instead of using a fixed type like Object.
Need for Generics
To remove type casting - Without generics, we often have to cast objects to the
required type, which can lead to ClassCastException at runtime.
To achieve type safety - Generics provide compile-time checking, so you catch
type errors early.
To write reusable code - The same class or method can work with different types
without modification.
To avoid code duplication - It reduces the need for multiple versions of the same
class for different types.
Advantages of Generics
Type safety - Prevents ClassCastException at compile time.
Eliminates the need for explicit type casting.
Promotes code reusability and flexibility.
Improves code readability and maintainability.
Better performance - No runtime type checking is required.
Basic Syntax of Generics
The most common syntax is to use a type parameter inside angle brackets <>.
class ClassName<T> {
//use T as a type
}
T (Type) is a common type parameter name.
You can use any name like E, K, V, N, etc.
Generics can be used with classes, interfaces and methods.
Examples
1. Generic Class
A simple generic class that stores a value of a given type.
class Box<T> {
private T value;
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c

Partial preview of the text

Download Advanced Java Notes: Generics, Collections, Lambda Expressions, JSP & JavaBeans and more Study notes Java Programming in PDF only on Docsity!

1. What are Generics in Java? Explain the need, advantages and basic syntax of Generics with suitable examples. Generics in Java are a feature that enables you to create reusable and type-safe code. They allow you to define classes, interfaces and methods with a type parameter (i.e., a placeholder for a specific type) instead of using a fixed type like Object. Need for Generics  To remove type casting - Without generics, we often have to cast objects to the required type, which can lead to ClassCastException at runtime.  To achieve type safety - Generics provide compile-time checking, so you catch type errors early.  To write reusable code - The same class or method can work with different types without modification.  To avoid code duplication - It reduces the need for multiple versions of the same class for different types. Advantages of Generics  Type safety - Prevents ClassCastException at compile time.  Eliminates the need for explicit type casting.  Promotes code reusability and flexibility.  Improves code readability and maintainability.  Better performance - No runtime type checking is required. Basic Syntax of Generics The most common syntax is to use a type parameter inside angle brackets <>. class ClassName { //use T as a type }  T (Type) is a common type parameter name.  You can use any name like E, K, V, N, etc.  Generics can be used with classes, interfaces and methods. Examples

  1. Generic Class A simple generic class that stores a value of a given type. class Box { private T value;

public void setValue(T value) { this.value value; } public T getValue() { return value; } }

  1. Generic Interface An interface with a type parameter can be implemented by different types. interface Comparable { int compare(T 01, T o2); } Example implementation: class Student implements Comparable { private String name; @Override public int compare (Student s1, Student s2) { return s1.name.compareTo(s2.name); } }
  2. Generic Method A method can also use a type parameter. public class Utilities { public static void printArray (T[ ] array) { for (T element : array) { System.out,println(element); } }

System.out.println(stringBox.getValue()); // Output: Hello // Using Box (Parameterized type) Box intBox = new Box<>(); intBox.setValue(100); System.out.println(intBox.getValue()); // Output: 100 Difference Between Generic Types and Parameterized Types Generic Types Parameterized Types A class, interface or method declared with type parameters (e.g., , ). A specific type created by supplying an actual type (e.g., , ) to a generic type. Abstract/template. Concrete / specific type. At the time of declaration. At the time of creating an object or using the type. class Box { ... } Box box new Box<>(); Defines the structure to work with different types. Specifies the actual type to be used.

3. Explain Generic Classes and Generic Methods in Java with suitable examples. Generic Classes  A generic class is a class that is defined with a type parameter (placeholder) at the class level.  The type parameter is specified inside angle brackets () after the class name.  It allows the class to work with different types, providing type safety and code reusability.  The actual type is provided when creating an object of the class. Syntax: class ClassName { //class members } Example: Generic Class class Box { private T value; public void setValue(T value) { this.value = value;

Public T getValue() { Return value; } } Here, T is the type parameter. The class can store any type of value (Integer, String, etc.). Using the Generic Class public class Main { public static void main(String[] args) { Box intBox = new Box <>(); int Box.setValue(10); } System.out.println (intBox.getValue()); // } The type (Integer) is provided when creating the object. Generic Methods  A generic method is a method that is defined with a type parameter (placeholder) at the method level.  The type parameter is specified before the return type of the method.  It can be used in any class (generic or non-generic).  It allows the method to work with different types without being tied to a specific type. Syntax: ReturnType methodName (T parameter) { //method body } Example: Generic Method class Utils { // Generic method to find the maximum of two values public static > T findMax (T a, T b) {

Example: public static void printList (List list) { for (Object elem: list) { System.out.println (elem + " "); } } List li = Arrays.asList(1, 2, 3); printList (li);

  1. Upper-Bounded Wildcards (? extends Type)  Restricts the unknown type to be a specific type or its subtypes.  Use ‘? extends T’. It is useful for reading from a structure. Example: public static double sumOfList (List list) { double s 0.0; for (Number n list) { s += n.doubleValue(); } return s; } List li = Arrays.asList(1, 2, 3); double sum sumOfList (li);
  2. Lower-Bounded Wildcards (? super Type)  Restricts the unknown type to be a specific type or its supertypes.  Use ‘? super T’. It is useful for writing or adding to a structure. Example: public static void add Numbers (List list) { for (int i = 1; i <= 3; i++) { list.add(i); // OK, adding Integer } } List numList = new ArrayList<>(); add Numbers (numList);

Stack: LIFO used for stack operations (legacy). HashSet: Uses hash table. No duplicates. Not ordered. LinkedHashSet: Maintains insertion order. TreeSet: Sorted set (uses Red-Black tree). HashMap: Hash table. No order. LinkedHashMap: Maintains insertion order. TreeMap: Sorted map (uses Red-Black tree). Hashtable Synchronized map (legacy). No null keys/values. Example import java.util.*; public class Example { public static void main(String[] args) { List list = new ArrayList<>(); List. add ("Apple"); list. add ("Banana"); list. add ("Cherry"); System.out.println(list); // [Apple, Banana, Cherry] } }

6. Explain the basic operations performed on Collections in Java with suitable examples. Include:  Adding elements  Removing elements  Searching  Checking size  Checking whether an element exists  Accessing elements

  1. Adding elements

 Collections provide methods to add elements into the collection. The exact method depends on the type of collection (e.g., add(), addAll()).  add() is used to add a single element.  addAll() is used to add multiple elements from another collection. Example: List list = new ArrayList<>(); List.add("Apple"); list.add("Banana"); // add single elements List.add("Cherry"); List moreFruits = Arrays.asList("Mango", "Orange"); list.addAll (more Fruits); // add multiple elements

  1. Removing elements  Elements can be removed using remove() method.  remove (Object o) removes the first occurrence of the specified element.  remove (int index) removes the element at the specified index (for List).  For other collections, methods like remove(Object o) and clear() are also used. Example: List list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry")); list.remove("Banana"); // removes first occurrence of "Banana" list.remove(1); // removes element at index 1 ("Cherry") list.clear(); // removes all elements
  2. Searching  Search operations help us find elements in a collection.  For List, we can use methods like indexOf() and contains().  For Set, we can use contains(): Example: List list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry")); int index = list. indexOf ("Banana"); // returns 1 boolean is Present = list.contains("Cherry"); // returns true
  3. Checking size  The size() method returns the number of elements in the collection.  It is useful when we need to know how many elements are present. Example: List list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry")); int size list.size(); // returns 3

Bulk operations are methods in the Collection interface that perform an operation on all the elements of a collection at once. They are useful for working with multiple elements efficiently and reduce the need for manual iteration.

  1. addAll()  Adds all elements from the specified collection to the current collection.  Returns true if the collection is modified.  Useful for merging two collections. Example: List list1 = new ArrayList<>(Arrays.asList(1, 2, 3)); List list2 = new ArrayList<>(Arrays.asList(4, 5, 6)); list1.addAll (list2); System.out.println (list1);
  2. removeAll()  Removes all elements from the collection that are present in the specified collection.  Returns true if the collection is modified.  Useful for deleting multiple elements at once. Example: List list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); List list2 = new ArrayList<>(Arrays.asList(2, 4)); list1.removeAll (list2); System.out.println (list1);
  3. retainAll()  Retains only the elements that are present in the specified collection.  Returns true if the collection is modified.  Useful for finding common elements between two collections. Example: List list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); List list2 = new ArrayList<>(Arrays.asList(3, 4, 5, 6)); list1. retainAll (list2); System.out.println (list1);
  4. containsAll()  Checks if the collection contains all elements of the specified collection.

 Returns true if all elements are present, otherwise false. Useful for checking multiple elements at once. Example: List list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); List list2 = new ArrayList<>(Arrays.asList(2, 4)); boolean result = list1.contains All (list2); System.out.println(result);

  1. clear()  Removes all elements from the collection.  The collection becomes empty after this operation.  Returns void (no value). Example: List list = new ArrayList<>(Arrays. as List (10, 20, 30)); list.clear(); System.out.println(list); 8. Explain Iteration in Java Collections. Discuss different ways of iterating through a collection with suitable examples. Include:  for loop  enhanced for loop  Iterator  ListIterator  forEach() Iteration means accessing each element of a collection one by one, so that we can perform some operation on those elements. Java Collections Framework provides different ways to iterate through a collection. The choice of iteration depends on the type of collection and the requirement (e.g., need to remove elements, need to go backward, need to modify elements, etc.).
  2. for Loop
  1. ListIterator  Is a specialized iterator for List implementations.  Works only with List (not with Set, Queue, etc.).  Allows forward and backward traversal.  Can modify elements (set(), add(), remove()). Example List fruits = new ArrayList<>(List.of("Apple", "Banana", "Cherry")); ListIterator listIt = fruits. listIterator(); while (listIt.hasNext()) { String fruit = listIt.next(); System.out.println(fruit); if (fruit.equals("Banana")) { listIt.set("Blueberry"); // modify element } }
  2. forEach()  Introduced in Java 8.  Uses lambda expression or method reference.  Simple and concise (read only). Example List fruits = new ArrayList<>(List.of("Apple", "Banana", "Cherry")); fruits.forEach (fruit -> System.out.println(fruit)); 9. Explain the List interface in Java Collection Framework. Discuss its important implementations, features and operations with examples. Include:  ArrayList  LinkedList  Vector  Stack

The List interface is a part of the Java Collection Framework and extends the Collection interface. It represents an ordered collection of elements (allows duplicate elements). Elements are accessed by their index (position). It provides methods to add, remove, replace and access elements by index. Declaration: public interface List extends Collection {} Key Features of List  Ordered  maintains the order in which elements are added.  Allows duplicates  same element can be added multiple times.  Index-based access  elements can be accessed using an index.  Supports all optional operations of Collection interface (add, remove, contains, etc.). Operations  add (E element)  Adds element at end.  add (int index, E element)  Adds element at specific index.  get (int index)  Returns element at index.  set (int index, E element)  Replaces element at index.  remove (int index)  Removes element at index.  remove (Object o)  Removes first occurrence.  size ()  Returns number of elements.  isEmpty()  Checks if list is empty.  contains (Object o)  Checks if element exists.  indexOf (Object o)  Returns first index of element.  lastIndexOf (Object o)  Returns last index of element. Important Implementations

  1. ArrayList - resizable array, fast access, good for read operations.
  2. LinkedList - doubly linked list, fast insertions/deletions.
  3. Vector - synchronized (thread-safe), legacy class.
  4. Stack - extends Vector, provides LIFO (Last In First Out). I. ArrayList  Resizable array implementation.  Uses a dynamic array internally.  Provide fast random access internally.  Not synchronized (not thread-safe). Example import java.util.*; public class ArrayListExample {

vector.add(20); vector.add(30); System.out.println(vector); } } IV. Stack  Extends Vector class.  Provides LIFO (Last In First Out) behavior.  Used for undo/redo, expression evaluation, etc. Example: import java.util.*; public class StackExample { public static void main(String[] args) { Stack stack = new Stack<>(); Stack.push("First"); Stack.push ("Third"); stack.push("Second"); System.out.println(stack.pop()); System.out.println(stack.peek()); } }

10. Explain the Set interface in Java Collection Framework. Discuss its important implementations and characteristics with examples. Include:  HashSet  LinkedHashSet  TreeSet  The Set interface is a part of the Java Collection Framework and extends the Collection interface.  It represents a collection that does not allow duplicate elements.  It does not maintain any specific order (except for LinkedHashSet and TreeSet).  Common methods: add(), remove(), contains(), size(), isEmpty(), clear(), iterator().

public interface Set extends Collection { // no additional methods } Characteristics of Set  No Duplicates: each element must be unique.  Unordered (by default): HashSet does not maintain order.  Allows at most one null: allow a single null value.  Supports all Collection operations - add(), remove(), contains(), size(), etc. HashSet  Based on Hash Table (uses hashing).  No guaranteed order of elements.  Allows only one null element.  Provides constant time performance for basic operations (add, remove, contains). Example: import java.util.*; public class HashSetExample { public static void main(String[] args) { Set set = new HashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Cherry"); set.add("Apple"); set.add(null); System.out.println(set); System.out.println(set.size()); } } LinkedHashSet  Extends HashSet.  Maintains insertion order of elements.