Monday, March 16, 2026

Java StampedLock With Examples

Introduced in Java 8, the StampedLock in Java is a powerful concurrency utility designed to improve performance in multi-threaded applications. Unlike the traditional ReentrantReadWriteLock in Java, the StampedLock not only provides distinct read and write locks, but also supports optimistic locking for read operations, allowing threads to read data without blocking, as long as no write occurs concurrently.

Another key advantage of StampedLock in Java is its ability to upgrade a read lock to a write lock, a feature missing in ReentrantReadWriteLock. This makes it especially useful in scenarios where a read operation may need to transition into a write operation seamlessly.

Every locking method in StampedLock returns a stamp (a long value) that uniquely identifies the lock state. These stamps are then used to release locks, validate lock states, or convert between lock modes.

Here’s a simple example of acquiring and releasing a write lock using StampedLock in Java-

StampedLock sl = new StampedLock();
//acquiring writelock
long stamp =  sl.writeLock();
try{
 ...
 ...
}finally {
 //releasing lock
 sl.unlockWrite(stamp);
}

String Length in Python - len() Function

The len() function in Python is the simplest and most efficient way to determine the length of a string, list, tuple, dictionary, or any other iterable. When applied to a string, the len() function returns the total number of characters, including spaces and special symbols.

Syntax of len() function

len(object)

object can be a string, list, tuple, dictionary, or any iterable.

The function returns an integer representing the number of items or characters (in case of string) contained in the object.

String length using len() in Python

str = "netjs"
print(len(str))

str = "Hello World!"
strLen = len(str)
print('length of String- ',strLen)

Output

5
length of String-  12

That's all for this topic String Length in Python - len() Function. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. String Slicing in Python
  2. Python String split() Method
  3. Python Program to Check if Strings Anagram or Not
  4. Class And Object in Python
  5. Inheritance in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. Namespace And Variable Scope in Python
  3. List in Python With Examples
  4. Tuple in Python With Examples
  5. Access Modifiers in Java
  6. How to Convert Date And Time Between Different Time-Zones in Java
  7. Spring Component Scan Example
  8. Installing Hadoop on a Single Node Cluster in Pseudo-Distributed Mode

Sunday, March 15, 2026

Python String join() Method

When working with text in Python, you’ll often need to combine multiple strings into one. The Python String join() method is the most efficient way to achieve this. It takes an iterable (like a list, tuple, set, dictionary, or even another string) and concatenates all its elements into a single string, inserting a specified separator between them

join() method syntax

str.join(iterable)

Here iterable is an object which can return its element one at a time like list, tuple, set, dictionary, string.

str represents a separator that is used between the elements of iterable while joining them.

All the values in iterable should be String, a TypeError will be raised if there are any non-string values in iterable.

Python join() method examples

1. join method with a tuple.

cities = ('Chicago','Los Angeles','Seattle','Austin')
separator = ':'
city_str = separator.join(cities)
print(city_str)

Output

Chicago:Los Angeles:Seattle:Austin

2. Python join() method with a list of strings.

cities = ['Chicago','Los Angeles','Seattle','Austin']
separator = '|'
city_str = separator.join(cities)
print(city_str)

Output

Chicago|Los Angeles|Seattle|Austin

3. TypeError if non-string instance is found.

cities = ['Chicago','Los Angeles','Seattle','Austin', 3]
separator = '|'
city_str = separator.join(cities)
print(city_str)

Output

    city_str = separator.join(cities)
TypeError: sequence item 4: expected str instance, int found

In the list there is an int value too apart from strings therefore TypeError is raised while attempting to join the elements of the list.

4. Python join() method with a Set. Since set is an unordered collection so sequence of elements may differ.

cities = {'Chicago','Los Angeles','Seattle','Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)

Output

Austin-Los Angeles-Chicago-Seattle

5. join() method with a Dictionary. In case of dictionary keys are joined not the values.

cities = {'1':'Chicago','2':'Los Angeles','3':'Seattle','4':'Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)

Output

1-2-3-4

That's all for this topic Python String join() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python String split() Method
  2. Check if String Present in Another String in Python
  3. pass Statement in Python
  4. Namespace And Variable Scope in Python
  5. Interface in Python

You may also like-

  1. Python Installation on Windows
  2. Class And Object in Python
  3. Keyword Arguments in Python
  4. Bubble Sort Program in Python
  5. JVM Run-Time Data Areas - Java Memory Allocation
  6. final Keyword in Java With Examples
  7. BeanPostProcessor in Spring Framework
  8. How to Write a Map Only Job in Hadoop MapReduce

Check if String Present in Another String in Python

When working with text, you’ll often need to check if a string is present in another string in Python. Thankfully, Python provides multiple simple and efficient ways to perform this task:

  • Use Python membership operators 'in' and 'not in'. This is the most Pythonic way to check substring existence. See example.
  • Using find() method to check if string contains another string. See example.
  • Using index() method to get the index of the substring with in the String. See example.

Python membership operators - in and not in

To check if a string exists inside another string in Python or not, you can use 'in' and 'not in' membership operators.

  • 'in' operator- Returns true if the string is part of another string otherwise false.
  • 'not in' operator- Returns true if the string is not part of another string otherwise false.

Python in operator example

def check_membesrship(str1, str2):
  if str2 in str1:
    print(str2, 'found in String')
  else:
    print(str2, 'not found in String')

str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String
That not found in String

Python not in operator example

def check_membesrship(str1, str2):
  if str2 not in str1:
    print(str2, 'not found in String')
  else:
    print(str2, 'found in String')

str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, 'That')
#another call
check_membesrship(str1, str2)

Output

That not found in String
Python found in String

Using find() method to check if substring exists in string

Using find() method in Python you can check if substring is part of the string or not. If found, this method returns the index of the first occurrence of the substring otherwise -1 is returned.

Python find() method example

def check_membesrship(str, substr):
  loc = str.find(substr)
  if loc == -1:
    print(substr, 'not found in String')
  else:
    print(substr, 'found in String at index', loc)


str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String at index 8
That not found in String

Using index() method to check if substring exists in string

Using index() method in Python you can check if substring is part of the string or not. This method is similar to find() and returns the location of the first occurrence of the substring if found. If not found then index() method raises ‘ValueError’ exception that's where it differs from find().

Python index() method example

def check_membesrship(str, substr):
  # Catch ValueError exception
  try:
    loc = str.index(substr)
  except ValueError:
    print(substr, 'not found in String')
  else:
    print(substr, 'found in String at index', loc)


str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String at index 8
That not found in String

That's all for this topic Check if String Present in Another String in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. String Slicing in Python
  2. Accessing Characters in Python String
  3. Python String join() Method
  4. Magic Methods in Python With Examples
  5. Nonlocal Keyword in Python With Examples

You may also like-

  1. Name Mangling in Python
  2. Operator Overloading in Python
  3. Passing Object of The Class as Parameter in Python
  4. Difference Between Function and Method in Python
  5. instanceof Operator in Java
  6. Java Exception Handling Tutorial
  7. Checking Number Prime or Not Java Program
  8. Spring Setter Based Dependency Injection

Saturday, March 14, 2026

Java Map putIfAbsent() With Examples

Introduced in Java 8, the putIfAbsent() method is part of the java.util.Map interface and is widely used to simplify conditional insertions. It allows you to insert a new value for a given key only if that key is not already associated with a value or is currently mapped to null. This makes it a cleaner alternative to manually checking for key existence before updating a map.

The default implementation for putIfAbsent() is as given below. As you can see just by using single method putIfAbsent() you get the logic of checking whether the key is already present or not in the map and putting the value in case key is not there (or associated value is null).

 V v = map.get(key);
 if (v == null)
     v = map.put(key, value);
 return v;

Alongside putIfAbsent(), there is also a computeIfAbsent() method in Java, which also puts a value if specified key is not already associated with a value but with one key difference, instead of directly inserting a value, it computes the value using a provided mapping function if the key is not already present.

Syntax of the putIfAbsent () method is as given below.

V putIfAbsent(K key, V value)

Parameters are as-

  • key- key with which the specified value is to be associated
  • value- value to be associated with the specified key

Method returns the previous value if the specified key is already associated with the value.

Returns null if specified key is not already present in the Map, which actually means key is absent and the method is inserting the given key, value pair in the Map. It may also mean that the key is present but associated with null value.

putIfAbsent() Java examples

1. In the first example we'll have a map of cities and we'll try to insert a new city with a key which already exists in the HashMap.

import java.util.HashMap;
import java.util.Map;

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    String val = cityMap.putIfAbsent("4", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- Berlin
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}

Since key already exists and mapped with a value in the HashMap so putIfAbsent() method won't replace the previous value with new value for the same key. Also notice the return value of the method which is the value associated with the specified key.

2. In this example we'll try to insert a new city with a key which is not already there in the Map.

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    String val = cityMap.putIfAbsent("5", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- null
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin, 5=London}

Since key is not there in the Map so a new entry is added to the HashMap. Also notice the return value of the putifAbsent() method which is null this time because there was no mapping for the key.

3. In this example we'll take the scenario when the key exists in the HashMap but mapped with null.

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", null);
    String val = cityMap.putIfAbsent("4", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- null
{1=New York City, 2=New Delhi, 3=Mumbai, 4=London}

Since the key is mapped to null so putIfAbsent() method associates the key with a new value.

That's all for this topic Java Map putIfAbsent() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map merge() With Examples
  2. Java Map getOrDefault() Method With Examples
  3. Map.Entry Interface in Java
  4. EnumSet in Java With Examples
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Java StampedLock With Examples
  2. CopyOnWriteArraySet in Java With Examples
  3. Garbage Collection in Java
  4. Difference Between Checked And Unchecked Exceptions in Java
  5. How to Read Excel File in Java Using Apache POI
  6. Spring Boot StandAlone (Console Based) Application Example
  7. Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example
  8. Angular @HostBinding Decorator With Examples

isAlive() And join() Methods in Java Multi-Threading

In this tutorial we'll see what are isAlive() and join() methods in Java, which give you precise control over thread lifecycle management, ensuring smoother synchronization and more predictable program behavior.

When working with multiple threads in Java, developers typically create threads and invoke the start() method to begin execution. Once started, the Java Virtual Machine (JVM) automatically calls the run() method when system resources and CPU are available. The thread then executes its task and eventually transitions to the terminated state.

But what if you need to trigger further processing only after a specific thread has finished? How can you reliably check whether a thread is still running or has ended?

This is where the isAlive() and join() methods in Java come into play. These two powerful methods in Java’s multithreading API allow you to:

  • isAlive()– Quickly verify if a thread is still active.
  • join()– Pause the execution of the current thread until the target thread completes.

isAlive() method in Java

isAlive() method is the member of the Thread class and its general form is–

public final boolean isAlive()

The isAlive() method in Java is used to check whether a thread is currently active. A thread is considered alive if it has been started using the start() method and has not yet reached the terminated state. When you call isAlive() on a thread object, it returns:

  • true- if the thread is still running or in a runnable state.
  • false- if the thread has finished execution or has not been started

This makes the isAlive() method a simple yet powerful way to monitor thread lifecycle and ensure that your program executes tasks in the correct order. By combining isAlive() with other multithreading techniques, developers can build more predictable and synchronized applications.

join() method in Java

Join() method is used when you want to wait for the thread to finish. Its general form is–

public final void join() throws InterruptedException

This method waits until the thread on which it is called terminates. There are three overloaded join functions.

  • public final void join()- Waits indefinitely for this thread to die.
  • public final void join(long millis)-Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
  • public final void join(long millis, int nanos)- Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.

Java Example code using join and isAlive()

Imagine a situation where your application spawns multiple threads to perform heavy computations. You want the user to see the message "Processing is done" only after all threads have completed their tasks.

In such cases, the join() method in Java is the ideal solution. By calling join() on a thread, the current thread (often the main thread) pauses execution until the specified thread finishes. This ensures that your program doesn’t move forward prematurely and that the final message is displayed only after all computations are complete

Now first let’s try to do something like this without using join() method.

class MyRunnableClass implements Runnable{
  @Override
  public void run() {
    for(int i = 0; i < 5 ; i++){
      System.out.println(Thread.currentThread().getName() + " i - " + i);
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }    
}
public class JoinExample {
  public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnableClass(), "t1");
    Thread t2 = new Thread(new MyRunnableClass(), "t2");
    Thread t3 = new Thread(new MyRunnableClass(), "t3");
     
    t1.start();
    t2.start();
    t3.start();
        
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());
        
    /*try {
        t1.join();        
        t2.join();
        t3.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }        
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());*/        
    System.out.println("Processing finished");
  }
}

Output

t1 Alive - true
t2 Alive - true
t3 Alive - true
Processing finished
t3 i - 0
t1 i - 0
t2 i - 0
t3 i - 1
t1 i - 1
t2 i - 1
t2 i - 2
t1 i - 2
t3 i - 2
t3 i - 3
t1 i - 3
t2 i - 3
t3 i - 4
t1 i - 4
t2 i – 4

Here it can be seen that the message is displayed much before the actual processing has finished.

Now let’s uncomment the code related to join and run the program again.

class MyRunnableClass implements Runnable{
  @Override
  public void run() {
    for(int i = 0; i < 5 ; i++){
      System.out.println(Thread.currentThread().getName() + " i - " + i);
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
}
public class JoinExample {
  public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnableClass(), "t1");
    Thread t2 = new Thread(new MyRunnableClass(), "t2");
    Thread t3 = new Thread(new MyRunnableClass(), "t3");
     
    t1.start();
    t2.start();
    t3.start();
    
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());
        
    try {
      t1.join();        
      t2.join();
      t3.join();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
        
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());
    
    System.out.println("Processing finished");
  }
}

Output

t1 Alive - true
t2 Alive - true
t3 Alive - true
t2 i - 0
t3 i - 0
t1 i - 0
t1 i - 1
t2 i - 1
t3 i - 1
t3 i - 2
t1 i - 2
t2 i - 2
t1 i - 3
t2 i - 3
t3 i - 3
t2 i - 4
t3 i - 4
t1 i - 4
t1 Alive - false
t2 Alive - false
t3 Alive - false
Processing finished

Now see how message is displayed only when the processing is actually finished and all the threads are terminated. The second print statements using isAlive() method confirms that the threads are not running any more.

That's all for this topic isAlive() And join() Methods in Java Multi-Threading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between sleep And wait in Java Multi-Threading
  2. Creating a Thread in Java
  3. Synchronization in Java - Synchronized Method And Block
  4. Race Condition in Java Multi-Threading
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. Creating Custom Exception Class in Java
  2. Interface Static Methods in Java
  3. Fail-Fast Vs Fail-Safe Iterator in Java
  4. Java Lambda Expression And Variable Scope
  5. Find All Permutations of a Given String Java Program
  6. Abstraction in Java
  7. Java ReentrantReadWriteLock With Examples
  8. Bean Scopes in Spring With Examples

Friday, March 13, 2026

static Method Overloading or Overriding in Java

One of the most frequently asked interview questions in Java is: Can we overload static methods in Java? Can we override static methods in Java? These questions often confuse developers, yet understanding them is essential for mastering object-oriented programming concepts.

In this tutorial, we’ll explore the rules and limitations of static method overloading and static method overriding in Java. To set the stage, we’ll first revisit the basics of method overloading and method overriding in Java, and then dive into how these concepts apply specifically to static methods.

  • Method Overloading- When two or more methods with in the same class or with in the parent-child relationship classes have the same name, but the parameters are different in types or number the methods are said to be overloaded.
    Refer Method overloading in Java for better understanding.
  • Method Overriding- In a parent-child relation between classes, if a method in subclass has the same signature as the parent class method then the method is said to be overridden by the subclass and this process is called method overriding.
    Refer Method overriding in Java for better understanding.

Static method overloading in Java

In Java, static methods can be overloaded just like instance methods. This means you can define two or more static methods with the same name, as long as their parameter lists differ in type or number. Overloading static methods works exactly the same way as overloading non-static methods, and it is resolved at compile time.