0% found this document useful (0 votes)
2 views13 pages

Constructor in Java

The document provides an overview of various constructors for Java classes such as String, StringBuffer, StringBuilder, ArrayList, LinkedList, HashSet, TreeSet, LinkedHashSet, and PriorityQueue. It details how to create instances of these classes, including options for initial capacity and handling collections. Additionally, it explains the behavior of these classes regarding capacity growth and ordering of elements.

Uploaded by

aditya8328419985
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)
2 views13 pages

Constructor in Java

The document provides an overview of various constructors for Java classes such as String, StringBuffer, StringBuilder, ArrayList, LinkedList, HashSet, TreeSet, LinkedHashSet, and PriorityQueue. It details how to create instances of these classes, including options for initial capacity and handling collections. Additionally, it explains the behavior of these classes regarding capacity growth and ordering of elements.

Uploaded by

aditya8328419985
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

String Class Constructor in java

// Creates an empty string


String emptyString = new String();
String() Creates an empty string ("")
[Link](emptyString); // Output: (empty)
[Link]([Link]()); // Output: 0
// Creates a copy of another string
String original = "Hello";
String copy = new String(original);
[Link](copy); // Output: Hello
String(String str) Creates a string from another string

// Note: This creates a new object in heap memory


[Link](original == copy); // Output: false (different objects)
[Link]([Link](copy)); // Output: true (same content)

char[] charArray = {'H', 'e', 'l', 'l', 'o'};


String(char[] ch) Converts a character array into a string String fromCharArray = new String(charArray);
[Link](fromCharArray); // Output: Hello
char[] chars = {'J', 'a', 'v', 'a', 'P', 'r', 'o', 'g', 'r', 'a', 'm'};
String(char[] ch, int start, int length) Creates string from a subset of char array String portion = new String(chars, 4, 7); // offset 4, length 7
[Link](portion); // Output: Program

byte[] bytes = {72, 101, 108, 108, 111}; // ASCII values for "Hello"
String fromBytes = new String(bytes);
[Link](fromBytes); // Output: Hello

// With specified charset


String(byte[] bytes) Converts byte array into string try {
String withCharset = new String(bytes, "UTF-8");
[Link](withCharset); // Output: Hello
} catch ([Link] e) {
[Link]();
}
byte[] data = {65, 66, 67, 68, 69, 70}; // A,B,C,D,E,F
String(byte[] bytes, int start, int length) Creates string from a part of byte array String bytePortion = new String(data, 2, 3); // offset 2, length 3
[Link](bytePortion); // Output: CDE
StringBuffer sb = new StringBuffer("Welcome");
String(StringBuffer sb) Creates string from StringBuffer String s6 = new String(sb);
[Link](s6); // Welcome
StringBuilder sb2 = new StringBuilder("Java");
String(StringBuilder sb) Creates string from StringBuilder String s7 = new String(sb2);
[Link](s7); // Java
// Using Unicode code points
int[] codePoints = {72, 101, 108, 108, 111}; // Unicode for "Hello"
String fromCodePoints = new String(codePoints, 0, [Link]);
[Link](fromCodePoints); // Output: Hello

// With emoji and special characters


int[] emojiPoints = {0x1F600, 0x1F604, 0x1F609}; // Smiley emojis
String emojis = new String(emojiPoints, 0, [Link]);
[Link](emojis); // Output: 😀😄😉

StringBuffer Class Constructor in java


StringBuffer sb = new StringBuffer();
[Link]([Link]()); // Output: 16 (default capacity)
Creates an empty buffer with default capacity (16)
StringBuffer()
characters
Creates an empty StringBuffer with initial capacity of 16 characters
Capacity automatically grows when needed
StringBuffer sb = new StringBuffer(30);
[Link]([Link]()); // Output: 30
StringBuffer(int capacity) Creates an empty buffer with the specified capacity.
Creates empty StringBuffer with specified initial capacity
Useful when you know approximate size needed
Creates a buffer initialized with the given string (capacity StringBuffer sb = new StringBuffer("Hello");
StringBuffer(String str)
= [Link]() + 16). [Link]([Link]()); // Output: 21 (string length + 16)
CharSequence cs = "Java";
StringBuffer(CharSequence seq) Creates a buffer initialized with the given CharSequence StringBuffer sb = new StringBuffer(cs);
[Link](sb); // Output: Java

StringBuilder Class Constructor in java


StringBuilder sb1 = new StringBuilder();
Creates an empty StringBuilder with initial capacity of 16
[Link]([Link]()); // Default: 16
StringBuilder() characters
Most commonly used constructor

StringBuilder sb = new StringBuilder(int capacity);

StringBuilder sb2 = new StringBuilder(50);


StringBuilder(int capacity) Constructor with Initial Capacity [Link]([Link]()); // 50

Creates an empty StringBuilder with specified initial capacity


Useful when you know approximately how many characters you'll need
StringBuilder sb = new StringBuilder(String str);

StringBuilder(String str) Creates a StringBuilder initialized with the given string StringBuilder sb3 = new StringBuilder("Hello");
[Link](sb3); // Output: Hello
[Link]([Link]()); // 16 + length("Hello") = 21

Creates a StringBuilder with the specified CharSequence


Key Points:
StringBuilder sb = new StringBuilder(CharSequence seq);
CharSequence is an interface implemented by:
String
StringBuilder(CharSequence seq) CharSequence cs = "Java Programming";
StringBuilder
StringBuilder sb4 = new StringBuilder(cs);
StringBuffer
[Link](sb4); // Output: Java Programming
CharBuffer
And other character sequence classes

ArrayList Class Constructor in java


Creates an empty ArrayList with default initial capacity ArrayList<String> list1 = new ArrayList<>();
ArrayList()
(10) ArrayList<Integer> list2 = new ArrayList<Integer>(); // Older syntax

ArrayList(int initialCapacity) Creates an ArrayList with specified initial capacity


ArrayList<String> list = new ArrayList<>(50); // Initial capacity of 50
List<String> existingList = [Link]("Apple", "Banana", "Cherry");
Creates an ArrayList containing elements of the specified ArrayList<String> newList = new ArrayList<>(existingList);
ArrayList(Collection<? extends E> c)
collection
Set<Integer> numberSet = new HashSet<>([Link](1, 2, 3));
ArrayList<Integer> listFromSet = new ArrayList<>(numberSet);
newCapacity = oldCapacity + (oldCapacity / 2)
Example of capacity growth
Old Capacity Increase New Capacity
10 (default) 5 15
15 7 22
22 11 33
33 16 49

LinkedList Class Constructor in java


LinkedList() Creates an empty LinkedList. LinkedList<String> list = new LinkedList<>();
// From ArrayList
List<String> arrayList = [Link]("A", "B", "C");
LinkedList<String> list1 = new LinkedList<>(arrayList);

Creates a LinkedList containing the elements of the // From another LinkedList


LinkedList(Collection<? extends E> c)
specified collection in the same order. LinkedList<String> list2 = new LinkedList<>(list1);

// From Set
Set<Integer> set = new HashSet<>([Link](1, 2, 3));
LinkedList<Integer> list3 = new LinkedList<>(set);
✅ Conclusion

LinkedList does not have capacity.


It grows by adding nodes — no capacity increase like ArrayList.

HashSet Class Constructor in java


Creates an empty HashSet with default capacity (16)
and load factor (0.75).
Default: HashSet<String> set = new HashSet<>();
Initial Capacity = 16 [Link]("Apple");
HashSet()
Load Factor = 0.75 [Link]("Banana");
Threshold = 16 × 0.75 = 12 elements [Link]("Orange");
So when you insert the 13th element, capacity grows
(doubles).
HashSet<Integer> numbers = new HashSet<>(50);
// Useful when you know approximately how many elements you'll store
HashSet(int initialCapacity) Creates HashSet with the specified initial capacity.
Creates an empty HashSet with specified initial capacity
Default load factor (0.75) is used
Creates HashSet with specified initial capacity and load HashSet<Double> values = new HashSet<>(100, 0.6f);
HashSet(int initialCapacity, float loadFactor)
factor. // Initial capacity: 100, Load factor: 0.6
List<String> list = [Link]("A", "B", "C", "A", "B");
HashSet<String> set = new HashSet<>(list);
Creates HashSet and adds all elements from given // Result: ["A", "B", "C"] - duplicates removed
HashSet(Collection<? extends E> c)
collection (removes duplicates).
Creates a HashSet containing the elements of the specified collection
Duplicates are automatically removed
How capacity grows

HashSet doubles the capacity when current size exceeds threshold.


New Capacity = Old Capacity × 2
Example Growth : 16 → 32 → 64 → 128 → ...
Initial Settings
Property Default Value
Initial Capacity 16
Load Factor 0.75
Threshold capacity × loadFactor = 16 × 0.75 = 12
So when you try to insert the 13th element, the HashSet resizes.

Threshold changes accordingly:


16 × 0.75 = 12
32 × 0.75 = 24
64 × 0.75 = 48
❗Important Notes

Resizing is expensive (re-hashing all elements).


To avoid frequent resize, set initialCapacity if you know data size.
HashSet<Integer> set = new HashSet<>(100);

TreeSet Class Constructor in java


TreeSet<String> treeSet = new TreeSet<>();
[Link]("Banana");
Creates an empty TreeSet with natural ordering (e.g.,
TreeSet() [Link]("Apple");
ascending order for numbers/strings).
[Link]("Cherry");
// Elements will be sorted: ["Apple", "Banana", "Cherry"]
List<Integer> list = [Link](5, 2, 8, 1, 9);
Creates a TreeSet and adds all elements from the given
TreeSet(Collection<? extends E> c) TreeSet<Integer> treeSet = new TreeSet<>(list);
collection (sorted automatically).
// Result: [1, 2, 5, 8, 9]
// Custom comparator for descending order
TreeSet<Integer> treeSet = new TreeSet<>([Link]());
Creates an empty TreeSet with a custom comparator to [Link](5);
TreeSet(Comparator<? super E> comparator)
define your sorting order. [Link](2);
[Link](8);
// Elements will be sorted: [8, 5, 2]

Creates a TreeSet with elements from another SortedSet, TreeSet<Integer> original = new TreeSet<>([Link](5, 2, 8, 1));
TreeSet(SortedSet<E> s) TreeSet<Integer> copy = new TreeSet<>(original);
keeping the same sorting order.
// Copy will have same elements and ordering

📌 Interview Answer

TreeSet does not have capacity expansion, because it uses a Red-Black Tree internally.
Every insertion creates a new node and the tree rebalances itself.
There is no resizing like ArrayList or HashSet.

LinkedHashSet Class Constructor in java


LinkedHashSet<String> names = new LinkedHashSet<>();
[Link]("Alice");
[Link]("Bob");
Creates an empty LinkedHashSet with default capacity
LinkedHashSet() [Link]("Charlie");
(16) & load factor (0.75)
// Order: Alice, Bob, Charlie

Creates an empty LinkedHashSet with default initial capacity (16) and load factor (0.75)
Maintains insertion order
LinkedHashSet<Integer> numbers = new LinkedHashSet<>(50);
// Initial capacity for 50 elements
LinkedHashSet(int initialCapacity) Creates LinkedHashSet with given capacity
Creates an empty LinkedHashSet with specified initial capacity
Default load factor (0.75)

LinkedHashSet<Double> values = new LinkedHashSet<>(100, 0.8f);


// Initial capacity: 100, Load factor: 0.8
LinkedHashSet(int initialCapacity, float loadFactor) Creates LinkedHashSet with given capacity & load factor
Creates an empty LinkedHashSet with specified initial capacity and load factor
Load factor determines when the set should be resized

List<String> list = [Link]("Apple", "Banana", "Cherry");


LinkedHashSet<String> fruitSet = new LinkedHashSet<>(list);
Creates a LinkedHashSet containing elements of given // Contains: Apple, Banana, Cherry in that order
LinkedHashSet(Collection c)
collection
Creates a LinkedHashSet containing elements from the specified collection
Maintains the iteration order of the original collection

✅ Default Capacity & Load Factor

Default initial capacity: 16


Default load factor: 0.75
LinkedHashSet uses HashMap internally, so capacity grows similarly:
New Capacity = Old Capacity × 2 (doubles)

Interview Tip

LinkedHashSet = HashSet + LinkedList ordering


Best used when you need fast performance + predictable iteration order.
PriorityQueue Constructors in Java
In Java, the PriorityQueue class is part of [Link] and works on min-heap by default (smallest element has the highest priority).

If you want, I can also give:


PriorityQueue custom comparator example
Max-heap implementation example
PriorityQueue<Integer> pq = new PriorityQueue<>();
Creates an empty PriorityQueue with default capacity
PriorityQueue()
(11) and natural ordering.
Creates a PriorityQueue with default initial capacity (11) and natural ordering.
Creates a queue with given initial capacity and natural
PriorityQueue(int initialCapacity) PriorityQueue<Integer> pq = new PriorityQueue<>(20);
ordering.
PriorityQueue(int initialCapacity, Comparator<?
Given capacity and custom comparator. PriorityQueue<Integer> pq = new PriorityQueue<>(20, [Link]());
super E> comparator)
List<Integer> list = [Link](5, 3, 8, 1, 2);
Creates a queue containing elements of a given PriorityQueue<Integer> pq = new PriorityQueue<>(list);
PriorityQueue(Collection<? extends E> c)
collection.
Creates a PriorityQueue containing elements from another collection.
PriorityQueue<Integer> original = new PriorityQueue<>();
[Link](5);
[Link](3);
PriorityQueue(PriorityQueue<? extends E> c) Creates a queue using another priority queue.
PriorityQueue<Integer> copy = new PriorityQueue<>(original);

Creates a PriorityQueue from another PriorityQueue.


Creates a priority queue with a custom Comparator to PriorityQueue<Integer> pq = new PriorityQueue<>([Link]());
Constructor with Comparator
define the ordering of elements. // Max-heap
Capacity Growth Pattern Table

11 × 2 + 2 = 24 After adding 12th element


24 + (24 ÷ 2) = 36 After adding 25th element
36 + (36 ÷ 2) = 54 After adding 37th element
54 + (54 ÷ 2) = 81 After adding 55th element
81 + (81 ÷ 2) = 121 After adding 82nd element
Capacity: 11 → 24 → 36 → 54 → 81 → 121 → ...
↑ ↑ ↑ ↑ ↑ ↑
Size: 11 24 36 54 81 121
↓ ↓ ↓ ↓ ↓ ↓
Trigger: 12th 25th 37th 55th 82nd 122nd
elem elem elem elem elem elem

What Happens During Resizing

Create new array with the new capacity


Copy all elements from old array to new array
Replace the internal queue array with the new larger array

ArrayDeque Constructors in Java


ArrayDeque<String> deque = new ArrayDeque<>();
Creates an empty deque with default capacity (initially // Initial capacity is 16, expands dynamically as needed
ArrayDeque()
16).
Creates an empty deque with an initial capacity of 16.

ArrayDeque<Integer> deque = new ArrayDeque<>(50);


Creates a deque with initial capacity sufficient to hold // Starts with capacity 50, optimized for 50+ elements
ArrayDeque(int numElements)
numElements
Creates an empty deque with a specified initial capacity.
Use this to avoid resizing overhead if you know the expected number of elements.

List<String> list = [Link]("A", "B", "C");


ArrayDeque<String> deque = new ArrayDeque<>(list);
Creates a deque containing elements of the given // Deque now contains [A, B, C]
ArrayDeque(Collection<? extends E> c)
collection (in iteration order).
Creates a deque containing elements from the specified collection.
Elements are added in the order returned by the collection’s iterator.
📌 Capacity Increase Rule in ArrayDeque

ArrayDeque grows automatically.


When full, capacity doubles (similar to ArrayList but no fixed formula exposed).
ArrayDeque never shrinks automatically
ArrayDeque<String> deque = new ArrayDeque<>(2);
[Link]("A"); // Capacity: 2, Size: 1
[Link]("B"); // Capacity: 2, Size: 2 - FULL
[Link]("C"); // TRIGGER RESIZE: Capacity → 4
[Link]("D"); // No resize
[Link]("E"); // TRIGGER RESIZE: Capacity → 8

ArrayDeque<String> deque = new ArrayDeque<>(2);


[Link]("A"); // Capacity: 2, Size: 1
[Link]("B"); // Capacity: 2, Size: 2 - FULL
[Link]("C"); // TRIGGER RESIZE: Capacity → 4
[Link]("D"); // No resize
[Link]("E"); // TRIGGER RESIZE: Capacity → 8

How capacity increases in ArrayDeque


newCapacity = oldCapacity * 2

HashMap Constructors in Java


HashMap<K, V> map = new HashMap<>();
Creates an empty HashMap with default capacity (16)
HashMap()
and load factor (0.75) Initial Capacity: 16 (default).
Load Factor: 0.75 (default).

HashMap<K, V> map = new HashMap<>(initialCapacity);


Creates a HashMap with given initial capacity and default
HashMap(int initialCapacity) initialCapacity: Initial size of the hash table (use powers of 2 for efficiency).
load factor
Load Factor: 0.75 (default).
Use Case: When the approximate number of entries is known to avoid rehashing.

HashMap(int initialCapacity, float loadFactor) Creates a HashMap with given capacity and load factor
HashMap<String, Integer> map3 = new HashMap<>(20, 0.8f);

Creates a HashMap and copies key-value pairs from Map<String, Integer> existingMap = [Link]("A", 1, "B", 2);
HashMap(Map<? extends K, ? extends V> m) HashMap<String, Integer> map4 = new HashMap<>(existingMap);
another map
[Link](map4); // Output: {A=1, B=2}
Default Values
Initial Capacity: 16
Load Factor: 0.75 (75% full → capacity doubles)

How Capacity Increases in HashMap?


newCapacity = oldCapacity * 2
Default capacity = 16

Load factor = 0.75


Threshold = 16 × 0.75 = 12
After 12 items, HashMap resizes to 32.

LinkedHashMap Constructors in Java


LinkedHashMap<K, V> map = new LinkedHashMap<>();

Creates an empty LinkedHashMap with default capacity


LinkedHashMap() Default initial capacity: 16
(16) and load factor (0.75).
Default load factor: 0.75
Insertion-order iteration (default).
LinkedHashMap<K, V> map = new LinkedHashMap<>(int initialCapacity);

LinkedHashMap(int initialCapacity) Creates a LinkedHashMap with given initial capacity.


Specifies a custom initial capacity.
Uses the default load factor (0.75) and insertion-order iteration.

LinkedHashMap<K, V> map = new LinkedHashMap<>( int initialCapacity, float loadFactor );


LinkedHashMap(int initialCapacity, float Creates a LinkedHashMap with specified capacity and
loadFactor) load factor.
Allows setting both initial capacity and load factor.
Maintains insertion-order iteration.
LinkedHashMap<K, V> map = new LinkedHashMap<>(
int initialCapacity,
float loadFactor,
boolean accessOrder
LinkedHashMap(int initialCapacity, float
Maintains access order when true (used in LRU cache). );
loadFactor, boolean accessOrder)

accessOrder controls iteration order:


true: Access-order (entries are ordered by last access, suitable for LRU caches).
false: Insertion-order (default).
LinkedHashMap<K, V> map = new LinkedHashMap<>(Map<? extends K, ? extends V> m);
LinkedHashMap(Map m) Creates a LinkedHashMap by copying another map.
Initializes the LinkedHashMap with the same mappings as the specified Map.
Uses default load factor (0.75) and insertion-order iteration.

Resizing Process
New Capacity = Current Capacity × 2
Recalculate Threshold = New Capacity × Load Factor
Rehash all entries into new buckets
Maintain linked list order (insertion/access order is preserved)

LinkedHashMap<String, Integer> map = new LinkedHashMap<>(4, 0.75f); // Initial: Capacity = 4, Threshold = 3


[Link]("A", 1); // Size = 1
[Link]("B", 2); // Size = 2
[Link]("C", 3); // Size = 3 → Threshold reached!
[Link]("D", 4); // Size = 4 → RESIZE! New capacity = 8, threshold = 6
[Link]("E", 5); // Size = 5
[Link]("F", 6); // Size = 6 → Threshold reached!
[Link]("G", 7); // Size = 7 → RESIZE! New capacity = 16, threshold = 12

TreeMap Constructors in Java


TreeMap<Integer, String> map = new TreeMap<>();
[Link](2, "B");
[Link](1, "A");
TreeMap() Creates an empty TreeMap sorted by natural order of keys [Link](3, "C");
[Link](map); // {1=A, 2=B, 3=C}

Default Constructor (Natural Ordering)


TreeMap<Integer, String> map = new TreeMap<>([Link]());
[Link](10, "Ten");
[Link](5, "Five");
TreeMap(Comparator<? super K> comparator) Creates an empty TreeMap with a custom comparator [Link](1, "One");
[Link](map); // {10=Ten, 5=Five, 1=One}

Using Comparator (Custom Sorting - Reverse Order)


HashMap<Integer, String> hashMap = new HashMap<>();
[Link](3, "C");
[Link](1, "A");
Creates a TreeMap and copies entries from another map [Link](2, "B");
TreeMap(Map<? extends K, ? extends V> m)
(sorted by natural order) TreeMap<Integer, String> treeMap = new TreeMap<>(hashMap);
[Link](treeMap); // {1=A, 2=B, 3=C}

Copy another Map


SortedMap<Integer, String> sortedMap = new TreeMap<>();
[Link](100, "Hundred");
[Link](50, "Fifty");
Creates a TreeMap using another SortedMap (keeps
TreeMap(SortedMap<K, ? extends V> m) TreeMap<Integer, String> treeMap = new TreeMap<>(sortedMap);
same sorting order)
[Link](treeMap); // {50=Fifty, 100=Hundred}

Using Another SortedMap


How does TreeMap store data internally?

Uses Red-Black Tree (self-balancing BST)


Keys are always sorted
No null keys allowed, but null values allowed

Interview Tip

TreeMap → Sorted, ordered (Red-Black Tree)


HashMap → Unordered (Hash Buckets)
LinkedHashMap → Insertion order (Hash + Doubly Linked List)

You might also like