Get Methods from an Object Example

Example

package com.vinod.test;

import java.lang.reflect.Method;

public class ReflectionExample {

public static void main(String[] args) {
Class<Integer> className = java.lang.Integer.class;
Method methods[] = className.getMethods();
for (int i = 0; i < methods.length; i++) {
System.out.println(methods[i]);
}
}

}

Output

public static int java.lang.Integer.numberOfLeadingZeros(int)
public static int java.lang.Integer.numberOfTrailingZeros(int)
public static int java.lang.Integer.bitCount(int)
public boolean java.lang.Integer.equals(java.lang.Object)
public static java.lang.String java.lang.Integer.toString(int,int)
public java.lang.String java.lang.Integer.toString()
public static java.lang.String java.lang.Integer.toString(int)
public static int java.lang.Integer.hashCode(int)
public int java.lang.Integer.hashCode()
public static int java.lang.Integer.min(int,int)
public static int java.lang.Integer.max(int,int)
public static int java.lang.Integer.reverseBytes(int)
public int java.lang.Integer.compareTo(java.lang.Integer)
public int java.lang.Integer.compareTo(java.lang.Object)
public byte java.lang.Integer.byteValue()
public short java.lang.Integer.shortValue()
public int java.lang.Integer.intValue()
public long java.lang.Integer.longValue()
public float java.lang.Integer.floatValue()
public double java.lang.Integer.doubleValue()
public static java.lang.Integer java.lang.Integer.valueOf(int)
public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String) throws java.lang.NumberFormatException
public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String,int) throws java.lang.NumberFormatException
public static java.lang.String java.lang.Integer.toHexString(int)
public static java.lang.Integer java.lang.Integer.decode(java.lang.String) throws java.lang.NumberFormatException
public static int java.lang.Integer.compare(int,int)
public static int java.lang.Integer.reverse(int)
public static int java.lang.Integer.sum(int,int)
public static long java.lang.Integer.toUnsignedLong(int)
public static int java.lang.Integer.parseInt(java.lang.String) throws java.lang.NumberFormatException
public static int java.lang.Integer.parseInt(java.lang.String,int) throws java.lang.NumberFormatException
public static java.lang.String java.lang.Integer.toUnsignedString(int)
public static java.lang.String java.lang.Integer.toUnsignedString(int,int)
public static java.lang.String java.lang.Integer.toOctalString(int)
public static java.lang.String java.lang.Integer.toBinaryString(int)
public static int java.lang.Integer.parseUnsignedInt(java.lang.String) throws java.lang.NumberFormatException
public static int java.lang.Integer.parseUnsignedInt(java.lang.String,int) throws java.lang.NumberFormatException
public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,int)
public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String)
public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,java.lang.Integer)
public static int java.lang.Integer.compareUnsigned(int,int)
public static int java.lang.Integer.divideUnsigned(int,int)
public static int java.lang.Integer.remainderUnsigned(int,int)
public static int java.lang.Integer.highestOneBit(int)
public static int java.lang.Integer.lowestOneBit(int)
public static int java.lang.Integer.rotateLeft(int,int)
public static int java.lang.Integer.rotateRight(int,int)
public static int java.lang.Integer.signum(int)
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()

 

 

 

 

How to get class name from a Java object?

Example

package com.vinod.test;

public class GetClassName {

    public static void main(String[] args) {
         Integer integer=new Integer("10");
         System.out.println("Created Object "+integer);
         Class<? extends Integer> className=integer.getClass();
         System.out.println("Objects class Name "+className);
    }

}
 

Output

Created Object 10

Objects class Name class java.lang.Integer


Java Map: HashTable Example

HashTabls is Same as HashMap except that its methods are synchronized
The class Hashtable was introduced in JDK 1.0 and uses Enumerations instead of Iterators
 
The Hashtable constructors are shown here:
 
Hashtable( )
Hashtable(int size)
Hashtable(int size, float fillRatio)
Hashtable(Map m)
 

Example

package mycollectiontest;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;

public class CollectionExample {

public static void main(String[] args) {
Map<String, Integer> hashtable = new Hashtable<String, Integer>();
hashtable.put("One", new Integer(1));
hashtable.put("Two", new Integer(2));
hashtable.put("Three", new Integer(3));
Enumeration<String> e = ((Hashtable<String, Integer>) hashtable).keys();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
}

}

Output

One
Three
Two

Java Map: TreeMap Example

·         Tree based implementation of the SortedMap interface
·         The keys are ordered according to their natural order
·         Less efficient than HashMap for insertion and mapping
·         Its methods are not synchronized
 

Example

package mycollectiontest;

import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;

public class CollectionExample {

public static void main(String[] args) {
TreeMap<String, String> treeMap = new TreeMap<String, String>();

// add key value pairs
treeMap.put("1", "Java");
treeMap.put("2", ".Net");
treeMap.put("3", "Oracle");
treeMap.put("4", "PHP");
treeMap.put("5", "MainFrame");
treeMap.put("6", "C++");

Collection<String> c = treeMap.values();

// Iterating
Iterator<String> itr = c.iterator();

// iterate through TreeMap values iterator
while (itr.hasNext())
System.out.println("TreeMap element " + itr.next());
}

}

Output

TreeMap element Java
TreeMap element .Net
TreeMap element Oracle
TreeMap element PHP
TreeMap element MainFrame
TreeMap element C++

Java Map: LinkedHashMap Example

·         Hash table and linked list implementation of the Map interface
·         LinkedHashMap differs from HashMap in that the order is maintained
·         Performance is below that of HashMap, due to the expense of maintaining the linked list
·         Its methods are not synchronized
 

Example

package com.vinod.collections;

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {

    public static void main(String[] args) {
        Map<Object, String> lHashm = new LinkedHashMap<Object, String>();
        lHashm.put(1, "Bangalore");
        lHashm.put(2, "Chennai");
        lHashm.put(3, "Cochin");
        lHashm.put(4, "Hydrabad");
        System.out.println("The Elements are : " + lHashm);
        for (Map.Entry<Object, String> entry : lHashm.entrySet()) {
            System.out.println(entry.getKey() + "   :" + entry.getValue());
        }

    }

}
 

Output

The Elements are : {1=Bangalore, 2=Chennai, 3=Cochin, 4=Hydrabad}

1   :Bangalore

2   :Chennai

3   :Cochin

4   :Hydrabad

 

 

Java Collections: HashMap Example

🧩 Understanding Java HashMap — Internal Working Explained Step by Step

The HashMap is one of the most powerful and widely used data structures in Java.
It stores key–value pairs, allowing fast lookups, insertions, and deletions — on average, in O(1) time.


⚙️ Key Features of HashMap

  • ✅ Stores key–value pairs

  • 🚫 Duplicate keys are not allowed (latest value replaces old)

  • Fast put() and get() operations

  • 🔄 Order is not maintained

  • ⚠️ Not synchronized (use ConcurrentHashMap for thread safety)

  • 💾 Allows one null key and multiple null values


💡 Internal Data Structure

Internally, a HashMap is an array of buckets,
and each bucket holds a linked list (or red-black tree, since Java 8) of entries.

Each entry (also called a Node) stores:

  • key

  • value

  • hash (calculated from the key)

  • next (a pointer to the next node — used when multiple entries fall into the same bucket)

Array (buckets) ↓ [0][Key=10, Val=A][Key=26, Val=B] → null [1][Key=12, Val=C] → null [2] → null

This chaining structure is the key to how HashMap handles collisions — when two different keys map to the same bucket index.


🧮 Step-by-Step: How put() Works

Let’s take an example:

map.put("Apple", "Red");

Step 1️⃣ Compute Hash Code

HashMap calls the hashCode() method of the key:

int hash = key.hashCode();

For "Apple", this produces an integer (e.g., 63043).

Then HashMap spreads the hash bits using an internal formula to reduce collisions:

hash = hash ^ (hash >>> 16);

Step 2️⃣ Find the Bucket Index

The index is computed using modulo on the array size:

index = hash % array_length;

If the array size is 16, and hash = 63043 →
index = 63043 % 16 = 3

So this entry goes into bucket 3.


Step 3️⃣ Check for Collision

If bucket 3 is empty → insert a new node directly.

If not empty → traverse the linked list using the next pointer and compare keys using .equals():

  • If key already exists → replace its value.

  • Otherwise → attach the new entry at the end of the list.

This is why each node has a next pointer — it allows HashMap to connect multiple entries inside the same bucket.


Step 4️⃣ Store the Entry

Each entry looks like this internally:

class Node<K,V> { final int hash; final K key; V value; Node<K,V> next; }

When "Apple" is inserted:

table[3][hash=63043, key="Apple", value="Red", next=null]

If "Mango" also hashes to index 3:

table[3][Apple, Red][Mango, Yellow] → null

Step 5️⃣ Resize if Needed

When the number of stored entries exceeds the load factor threshold (default = 0.75 × capacity),
the HashMap doubles its capacity and rehashes all entries to new buckets.

This process ensures performance stays close to O(1).


🧩 Step-by-Step: How get() Works

When you call:

map.get("Apple");

Here’s what happens:

1️⃣ Compute hash for "Apple" again.
2️⃣ Find bucket index using hash % array_length.
3️⃣ Go to that bucket and check the first node:

  • If key matches → return value.

  • If not → follow next pointer to check the next node.
    4️⃣ Continue until key is found or next == null.

✅ Result: Returns "Red".


🔗 Why the Linked List (and next Pointer) Is Needed

Let’s imagine two different keys produce the same index:

Keyhash(key)index
"Apple"630433
"Mango"753953

Both fall into bucket 3 — this is a hash collision.

To prevent overwriting existing entries,
HashMap connects them using a linked list.

Bucket[3][Key="Apple", Val="Red"] → [Key="Mango", Val="Yellow"] → null

When get("Mango") is called, HashMap checks the first node (Apple), finds no match, then follows the next pointer to Mango and retrieves "Yellow".

👉 Without the linked list, only one entry could exist per bucket — collisions would cause data loss.


🌳 Tree Optimization (Since Java 8)

If too many nodes end up in the same bucket (default threshold = 8),
HashMap converts the linked list into a Red-Black Tree.

Why?

  • Linked list lookup = O(n)

  • Tree lookup = O(log n)

Before (Linked List) [Apple][Mango][Banana][Grape] After (Tree) [Mango] / \ [Apple] [Banana]

This significantly improves performance in worst-case scenarios.


🧠 Summary of Internal Workflow

OperationDescriptionComplexity
put()Hash → Index → Insert/Replace → Rehash if neededO(1) avg, O(n) worst
get()Hash → Index → Traverse linked list/treeO(1) avg, O(log n) tree
remove()Hash → Index → Remove nodeO(1) avg
Collision HandlingLinked list (or tree) per bucketO(n) or O(log n)
ResizingDoubles capacity when threshold exceededO(n) (rehash)

🧾 Quick Example

Map<Integer, String> cities = new HashMap<>(); cities.put(1, "Bangalore"); cities.put(2, "Chennai"); cities.put(3, "Cochin"); cities.put(4, "Hyderabad"); System.out.println(cities.get(1)); // Output: Bangalore

Output

Bangalore Key 1 Value Bangalore Key 2 Value Chennai Key 3 Value Cochin Key 4 Value Hyderabad

🧩 Text-Based Visualization

HashMap Internal View --------------------- +-------------------------------------------------+ | HashMap Buckets | +-------------------------------------------------+Index 0null Index 1 → [Key=1, Value="Bangalore"] → null Index 2 → [Key=2, Value="Chennai"] → null Index 3 → [Key=3, Value="Cochin"] → [Key=19, Value="Goa"] → null Index 4 → [Key=4, Value="Hyderabad"] → null

If keys 3 and 19 hash to the same bucket,
they are connected using the next pointer to form a chain.


⚠️ Important Notes

  • HashMap is not thread-safe — concurrent writes can cause corruption.

  • Load factor (default = 0.75) controls how full the table can get before resizing.

  • You can specify both initial capacity and load factor when creating:

    Map<K,V> map = new HashMap<>(32, 0.8f);

✅ Final Takeaways

ConceptPurpose
Bucket ArrayPrimary storage of entries
Linked List / TreeHandles collisions
next PointerConnects entries within the same bucket
RehashingRedistributes keys when capacity grows
O(1) Average TimeThanks to hash distribution & chaining
O(n) Worst CaseIf many keys land in same bucket

Java Collections: TreeSet Example

·         Stores the elements in a balanced binary tree
·         A binary tree is a tree in which each node has at most two children
·         TreeSet elements are ordered
·         Less efficient than HashSet in insertion due to the use of a binary tree
·         Its methods are not synchronized
 
image
 

Example

package mycollectiontest;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class CollectionExample {

public static void main(String[] args) {
Set<String> tset = new TreeSet<String>();

// Adding objects
tset.add("Java");
tset.add("PHP");
tset.add("Jboss");
tset.add(".Net");
tset.add("Oracle");

System.out.println("treeset values = " + tset);

Iterator<String> i = tset.iterator();
while (i.hasNext()) {
System.out.println("Elements " + i.next());
}

}

}

Output

treeset values = [.Net, Java, Jboss, Oracle, PHP]
Elements .Net
Elements Java
Elements Jboss
Elements Oracle
Elements PHP

Java Collections: LinkedHashSet Example

·         Hash table and linked list implementation of the Set interface
·         LinkedHashSet differs from HashSet in that the order is maintained
·         Performance is below that of HashSet, due to the expense of maintaining the linked list
·         Its methods are not synchronized
 
 
image

Example

package mycollectiontest;

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetExample {

public static void main(String[] args) {
// Create a LinkedHashSet
Set<String> lHashSet = new LinkedHashSet<String>();
lHashSet.add("Bangalore");
lHashSet.add("Chennai");
lHashSet.add("Cochin");
System.out.println(lHashSet);

// Iterating
Iterator<String> it = lHashSet.iterator();

while (it.hasNext())
System.out.println("Elements " + it.next());
}
}

Output

[Bangalore, Chennai, Cochin]
Elements Bangalore
Elements Chennai
Elements Cochin

Java Collections: HashSet Example

  • HashSet is a good choice for representing sets if order of the elements is not important
  • HashSet methods are not synchronized
  • HashSet not allowing duplicate elements

image
 

Example

package mycollectiontest;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CollectionExample {

public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("Bangalore");
set.add("Chennai");
set.add("Mumbai");
set.add("Hydrabad");
// Printing set
System.out.println(set);
// Iterating and set
Iterator<String> it = set.iterator();
while (it.hasNext()) {
System.out.println("Elements " + it.next());
}

// Trying to add duplicate;
set.add("Bangalore");
System.out.println(set);
}

}

Output

[Chennai, Hydrabad, Mumbai, Bangalore]
Elements Chennai
Elements Hydrabad
Elements Mumbai
Elements Bangalore
[Chennai, Hydrabad, Mumbai, Bangalore]

 

Java Collections: Stack Example


          The Stack class represents a last-in-first-out (LIFO) stack of objects
          The common push and pop operations are provided
          As well as a method to peek at the top item on the stack is also provided
image
 

Example

package mycollectiontest;

import java.util.Stack;

public class CollectionExample {

public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
stack.push("First Person");
stack.push("Second Person");
stack.push("Third Person");
System.out.println("Total contents" + stack);
System.out.println("Total Size" + stack.size());
System.out.println("Pop 1" + stack.pop());
System.out.println("Pop 2 " + stack.pop());
System.out.println("Total contents after poping : " + stack);
System.out.println("Total Size after poping :" + stack.size());
}

}

Output

Total contents[First Person, Second Person, Third Person]
Total Size3
Pop 1Third Person
Pop 2 Second Person
Total contents after poping : [First Person]
Total Size after poping :1

Java Collections: Vector Example

          Same as the class ArrayList
          The main difference is that the methods of Vector are synchronized
image

Example

package mycollectiontest;

import java.util.Enumeration;
import java.util.Vector;

public class CollectionExample {

public static void main(String[] args) {
Vector<String> vector = new Vector<String>();
// Adding objects
vector.add("Java");
vector.add("PHP");
vector.add(".Net");
vector.add("Android");
vector.add("Windows");
vector.add("Linux");
System.out.println("Fetching elements");
System.out.println(vector.get(0));
System.out.println(vector.get(1));
System.out.println(vector.get(2));
System.out.println(vector.get(3));
System.out.println(vector.get(4));
System.out.println(vector.get(5));
System.out.println("Size of vectoror : " + vector.size());
Enumeration vectorElementsEnum = vector.elements();
while (vectorElementsEnum.hasMoreElements())
System.out.println(vectorElementsEnum.nextElement());
}

}

Output

Fetching elements
Java
PHP
.Net
Android
Windows
Linux
Size of vectoror : 6
Java
PHP
.Net
Android
Windows
Linux

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts