Wednesday, March 18, 2026

Getting Substring in Python String

When it comes to getting substring in Python string, many developers instinctively look for a built-in substring() method, as found in other languages. However, Python takes a different approach, there is no dedicated method for substrings. Instead, Python uses the powerful concept of string slicing, which is both flexible and concise.

Format of String slicing is as follows-

Stringname[start_position: end_position: increment_step]

start_position is the index from which the string slicing starts, start_position is included.

end_position is the index at which the string slicing ends, end_position is excluded.

increment_step indicates the step size. For example if step is given as 2 then every alternate character from start_position is accessed.

All three parameters are optional-

  • If start_position is omitted, slicing starts from index 0.
  • If end_position is omitted, slicing continues to the last character.
  • If step is omitted, the default is 1.

Getting substring through Python string slicing examples

1. A simple example where substring from index 2..3 is required.

s = "Test String"
print(s[2: 4: 1])
st

Here slicing is done from index 2 (start_pos) to index 3 (end_pos-1). Step size is 1.

2. Access only the month part from a date in dd/mm/yyyy format. Python makes this simple using string slicing combined with the find() method.

s = "18/07/2019"
month = s[s.find("/")+1: s.rfind("/") : 1]
print('Month part of the date is-', month)
Month part of the date is- 07

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

>>>Return to Python Tutorial Page


Related Topics

  1. Accessing Characters in Python String
  2. Python count() method - Counting Substrings
  3. Comparing Two Strings in Python
  4. Convert String to int in Python
  5. Functions in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. self in Python
  3. Polymorphism in Python
  4. Python while Loop With Examples
  5. Zipping Files And Folders in Java
  6. Java Collections Interview Questions And Answers
  7. Spring Object XML Mapping (OXM) JAXB Example
  8. How to Create Ubuntu Bootable USB

Is String Thread Safe in Java

We do know that String objects are immutable. It is also true that immutable objects are thread-safe so by transitive law string objects are thread-safe. So, if you are asked the question "Is String Thread Safe in Java?", the short answer is yes.

But let’s go deeper into why this holds true. To understand whether String in Java is thread-safe, we first need to break down two key concepts: immutability and thread safety.

Immutable object- An immutable object is one whose state cannot be modified after creation. Thus immutable object can only be in one state and that state can not be changed after creation of the object.

Thread safety– I’ll quote "Java concurrency in practice" book here– "A class is thread-safe if it behaves correctly when accessed from multiple threads, where correctness means that a class conforms to its specification".

Thread safety in String

String in Java, being immutable, has the specification that its values are constant and cannot be changed once created.

But there is a little confusion with many users when it comes to this question Is String thread safe in Java. Many people think that string is immutable so thread safety here should mean even if multiple threads are accessing the same string those threads should not be able to change the content of the string at all as the String being immutable can't be modified.

In reality, immutability ensures that no thread can ever change the content of an existing String. Any operation that appears to modify a String—such as concatenation, replacement, or substring- actually creates a new String object. The reference is updated to point to this new object, while the original remains unchanged.

So even in a multi-threaded environment, if several threads are working with the same String, they are all safely accessing an immutable value. If one thread performs an operation that "changes" the string, it simply receives a new reference, leaving the original untouched. This behavior guarantees that String in Java is inherently thread-safe.

Java String thread safe example

Let’s try to see this with an example. In this example three threads are created and all of them share the same string object. In each of these thread, thread name is appended to the string and then that string is printed. Thread class' join() method is also used here to wait for all of the threads to finish and then the string object is printed again.

public class StrThread implements Runnable {
  private String s;
  //Constructor
  public StrThread(String s){
    this.s = s;
  }
  @Override
  public void run() {
    System.out.println("in run method " + Thread.currentThread().getName());        
        
    try {
      // introducing some delay
      Thread.sleep(50);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }  
    // Adding to String  
    s = s + Thread.currentThread().getName();
    System.out.println("String " + s);
  }
    
  public static void main(String[] args) {
    String str = "abc";
    // Three threadss
    Thread t1 = new Thread(new StrThread(str));
    Thread t2 = new Thread(new StrThread(str));
    Thread t3 = new Thread(new StrThread(str));
    t1.start();
    t2.start();
    t3.start();
    // Waiting for all of them to finish
    try {
      t1.join();
      t2.join();
      t3.join();
    } catch (InterruptedException e) {    
      e.printStackTrace();
    }
    System.out.println("String is " + str.toString());
  }
}

Output

in run method Thread-0
in run method Thread-1
in run method Thread-2
String abcThread-1
String abcThread-2
String abcThread-0
String is abc

Here note that every thread changes the content of the string but in the process where str refers to is also changed, so effectively each thread gets its own string object. Once all the threads finish, str is printed in the main method again and it can be seen that the original string's value remains unchanged meaning original reference with the original content remains intact.

With this program you can see that String is immutable so original String won't be changed but String reference can still be changed with multiple threads. So Java Strings are thread safe here means when the shared String is changed it creates a new copy for another thread that way original String remains unchanged.

To see what may happen with a mutable object let us use StringBuffer in the place of String.

public class StrThread implements Runnable {
  private StringBuffer s;
  //Constructor
  public StrThread(StringBuffer s){
    this.s = s;
  }
  @Override
  public void run() {
    System.out.println("in run method " + Thread.currentThread().getName());        
      
    try {
      // introducing some delay
      Thread.sleep(50);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }    
    s.append(Thread.currentThread().getName());
    System.out.println("String " + s);
  }
    
  public static void main(String[] args) {
    StringBuffer str = new StringBuffer("abc");
    // Three threadss
    Thread t1 = new Thread(new StrThread(str));
    Thread t2 = new Thread(new StrThread(str));
    Thread t3 = new Thread(new StrThread(str));
    t1.start();
    t2.start();
    t3.start();
    // Waiting for all of them to finish
    try {
      t1.join();
      t2.join();
      t3.join();
    } catch (InterruptedException e) {    
      e.printStackTrace();
    }
    System.out.println("String is " + str.toString());
  }
}

Output

in run method Thread-0
in run method Thread-1
in run method Thread-2
String abcThread-0
String abcThread-0Thread-2
String abcThread-0Thread-2Thread-1
String is abcThread-0Thread-2Thread-1

Note– output may vary in different runs

Here it can be seen that shared StringBuffer object is modified.

That's all for this topic Is String Thread Safe in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. String in Java Tutorial
  2. String Comparison in Java equals(), compareTo(), startsWith() Methods
  3. Java trim(), strip() - Removing Spaces From String
  4. StringBuilder Class in Java With Examples
  5. Java String Interview Questions And Answers

You may also like-

  1. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  2. Deadlock in Java Multi-Threading
  3. Interface Default Methods in Java
  4. Effectively Final in Java 8
  5. Java BlockingQueue With Examples
  6. Callable and Future in Java With Examples
  7. Access Modifiers in Java - Public, Private, Protected and Default
  8. Try-With-Resources in Java With Examples

Changing String Case in Python- Methods and Examples

If you’ve ever worked with text in Python, you’ve likely needed to adjust its case. In this tutorial, we’ll explore all the built-in methods for changing string case in Python- from converting text to lowercase or uppercase, to formatting titles and capitalizing words.

Python provides several powerful and easy-to-use string methods for case conversion and case checking. Here’s a quick summary of the most commonly used ones:

  1. str.lower()- Returns a copy of the string with all characters converted to lowercase.
  2. str.upper()- Returns a copy of the string with all characters converted to uppercase.
  3. str.capitalize()- Returns a copy of the string with the first character capitalized and the rest lowercased.
  4. str.title()- Returns a titlecased version of the string, where each word starts with an uppercase character and the remaining characters are lowercase.

Along with methods for changing string case in Python, the language also provides handy built-in functions to check the case of a string. These methods are useful when you want to verify whether case conversion is needed before performing operations like formatting or normalization.

Here are the most commonly used case-checking methods:

  1. str.islower()- Returns True if all cased characters in the string are lowercase and there is at least one cased character; otherwise returns False.
  2. str.isupper()- Returns True if all cased characters in the string are uppercase and there is at least one cased character; otherwise returns False.
  3. str.istitle()- Returns True if the string is in title case (each word starts with an uppercase letter followed by lowercase letters) and contains at least one character.

Changing String case in Python examples

1. Changing String to all lower case or to all upper case.

s = "This is a TEST String"
print('String in all lower case-',s.lower())
s = "This is a Test String"
print('String in all upper case-', s.upper())

Output

String in all lower case- this is a test string
String in all upper case- THIS IS A TEST STRING

2. Capitalizing the String. First character will be capitalized, if there is any other upper case character in the String that is lower cased.

s = "this is a TEST String"
print('String Capitalized-',s.capitalize())

Output

String Capitalized- This is a test string

3. String title cased. Using title() method you can title cased a String. This method capitalizes the first character of every word.

s = "this is a TEST String"
print('String Title cased-',s.title())

Output

String Title cased- This Is A Test String

4. Checking the case before changing. You can also check the case before changing the case of the String and change the case only if needed. This is an optimization because any String modification method results in a creation of a new String as String is immutable in Python.

s = "this is a test string"
#change only if not already in lower case
if not s.islower():
    s = s.lower()
else:
    print('String already in lower case')
print(s)

Output

String already in lower case
this is a test string
s = "This is a test String"
#change only if not already in upper case
if not s.isupper():
    s = s.upper()
else:
    print('String already in upper case')
print(s)

Output

THIS IS A TEST STRING

That's all for this topic Changing String Case in Python- Methods and Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Getting Substring in Python String
  2. String Slicing in Python
  3. String Length in Python - len() Function
  4. Convert String to float in Python
  5. Python Program to Check Armstrong Number

You may also like-

  1. Python continue Statement With Examples
  2. Encapsulation in Python
  3. Class And Object in Python
  4. List in Python With Examples
  5. Just In Time Compiler (JIT) in Java
  6. Bucket Sort Program in Java
  7. Spring MVC Exception Handling Tutorial
  8. What is Hadoop Distributed File System (HDFS)

Tuesday, March 17, 2026

Java Stream - concat() With Examples

The concat() method in the Java Stream API allows you to merge two streams into a single stream. It takes two streams as arguments and returns a new stream containing all elements of the first stream followed by all elements of the second. This makes it a convenient way to combine data sources while working with Java’s functional programming features.

Syntax of concat() method

concat(Stream<? extends T> a, Stream<? extends T> b)

Here parameters are-

  • a- the first stream
  • b- the second stream

Return Value: A new stream that represents the concatenation of both input streams.

Important Notes:

  • The resulting stream is ordered if both input streams are ordered.
  • It is parallel if either of the input streams is parallel.
  • Since streams in Java are consumed once, the concatenated stream should be used immediately to avoid losing data.

concat() method Java examples

1. Using concat() method to merge two streams of integers.

import java.util.stream.Stream;

public class StreamConcat {

  public static void main(String[] args) {
    Stream<Integer> stream1 = Stream.of(1, 2, 3);
      Stream<Integer> stream2 = Stream.of(4, 5, 6);
      Stream<Integer> mergedStream = Stream.concat(stream1, stream2);
      mergedStream.forEach(System.out::println);
  }
}

Output

1
2
3
4
5
6

2. Merging two Collections (Lists) by using concat() method of Java Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamConcat {

  public static void main(String[] args) {
    List<String> strList1 = Arrays.asList("A","B","C","D");
    List<String> strList2 = Arrays.asList("E","F","G","H");
    // Getting streams using Lists as source
    Stream<String> stream1 = strList1.stream();
    Stream<String> stream2 = strList2.stream();
    
      Stream<String> mergedStream = Stream.concat(stream1, stream2);
      mergedStream.forEach(System.out::println);
  }
}

Output

A
B
C
D
E
F
G
H

3. You can also use concat() method along with other methods of the Java Stream, for example you can write a program to merge 2 lists while removing duplicates which can be done by using distinct() method.

public class StreamConcat {

  public static void main(String[] args) {
    List<String> strList1 = Arrays.asList("A","B","C","D");
    List<String> strList2 = Arrays.asList("E","B","G","A");
    // Getting streams using Lists as source
    Stream<String> stream1 = strList1.stream();
    Stream<String> stream2 = strList2.stream();
    
      Stream<String> mergedStream = Stream.concat(stream1, stream2).distinct();
      mergedStream.forEach(System.out::println);
  }
}

Output

A
B
C
D
E
G

4. Using concat() to merge multiple streams. You can also merge more than two streams by nesting the concat method.

public class StreamConcat {

  public static void main(String[] args) {
      Stream<Integer> stream1 = Stream.of(1, 2);
      Stream<Integer> stream2 = Stream.of(3, 4, 5);
      Stream<Integer> stream3 = Stream.of(7, 8, 9);
      Stream<Integer> stream4 = Stream.of(10, 11);
      Stream<Integer> mergedStream = Stream.concat(stream1, 
              Stream.concat(Stream.concat(stream2, stream3), stream4));
      mergedStream.forEach(e -> System.out.print(e + " "));
  }
}

Output

1 2 3 4 5 7 8 9 10 11 

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

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - count() With Examples
  2. Java Stream - boxed() With Examples
  3. Java Stream - findFirst() With Examples
  4. Java Stream - sorted() With Examples
  5. Java Stream - skip() With Examples

You may also like-

  1. Reflection in Java - Getting Class Information
  2. Java do-while Loop With Examples
  3. strictfp in Java
  4. Count Number of Times Each Character Appears in a String Java Program
  5. Stack Implementation in Java Using Linked List
  6. Class And Object in Python
  7. Spring WebFlux Example Using Functional Programming - Spring Web Reactive
  8. Highlight Currently Selected Menu Item Angular Routing Example

How to Convert float to int in Java

When working with numbers in Java, you may often need to display values without decimal points. In such cases, converting a float to an int becomes essential. This guide will walk you through how to convert float to int in Java, explaining the different approaches and their implications.

While performing this conversion, two main concerns arise:

  • Range limitations: A float can represent a much larger range than an int. If the float value exceeds the int range, you need to understand how Java handles overflow
  • Rounding behavior: Converting a float with decimal places to an int will truncate the fractional part. Knowing whether you want truncation, rounding, or another strategy is crucial for accurate results.

In the sections below, we’ll explore the available options for converting float to int in Java, demonstrate code examples, and explain how these concerns are addressed in Java.


1. Using Float.intValue() method

You can use the intValue() method of the Float wrapper class to convert float to int. Description of the intValue() method is as following.

  • intValue()- Returns the value of this Float as an int after a narrowing primitive conversion.
public class FloatToInt {
 public static void main(String[] args) {
  Float f = new Float(567.678);
  int val = f.intValue();
  System.out.println("int value " + val);
 }
}

Output

int value 567

Here you can see that rounding doesn’t happen while converting, just the digits after the decimal points are removed. You will get the same result if you use type casting instead.

2. Conversion from float to int Using typecasting

public class FloatToInt {
 public static void main(String[] args) {
  float fVal = 567.678f;
  // type casting
  int val1 = (int)fVal;
  System.out.println("int value " + val1);
 }
}

Output

int value 567

Here again you can see by type casting digits after the decimal are removed and there is no rounding. The only difference between using Float.intValue() and explicit casting is you need Float object for using intValue() where as typecasting can be done with a primitive float data type.

3. Using Math.round() method

As you have seen above methods of converting float to int are just giving the whole part of the number but mostly you will also like to do rounding. For that you can use Math.round method which takes float as argument and returns the value of the argument rounded to the nearest int value.

There are also some special cases–

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

Conversion from float to int - Math.round() example

If we take the same float value as used above

public class FloatToInt {

 public static void main(String[] args) {  
  float fVal = 567.678f;
  int rVal = Math.round(fVal);
  System.out.println("int value " + rVal);
 }
}

Output

int value 568

Here you can see that the value is rounded to the nearest int value.

Example with Some more values-

public class FloatToInt {
 public static void main(String[] args) {
  float f1 = -10.78f;
  float f2 = 4.4999f;
  float f3 = 105.12f;
  int i1 = Math.round(f1);
  int i2 = Math.round(f2);
  int i3 = Math.round(f3);
  System.out.println("float value: " + f1 + "int value: " + i1);
  System.out.println("float value: " + f2 + "int value: " + i2);
  System.out.println("float value: " + f3 + "int value: " + i3);
 }
}

Output

float value: -10.78int value: -11
float value: 4.4999int value: 4
float value: 105.12int value: 105

If float value out of range

If float value that has to be converted to int is out of range then the following rules are applied-

  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.
public class FloatToInt {
 public static void main(String[] args) {
  Float f = new Float(567678865544.678);
  int val = f.intValue();
  System.out.println("int value " + val);
  
  float fVal = 567678865544.678f;
  int val1 = (int)fVal;
  System.out.println("int value " + val1); 
 }
}

Output

int value 2147483647
int value 2147483647

Here it can be seen that integer value is equal to Integer.MAX_VALUE as float value is greater than Integer.MAX_VALUE

Same way you can check for minimum value.

That's all for this topic How to convert float to int in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert String to int in Java
  2. Convert double to int in Java
  3. How to Convert String to Date in Java
  4. Factorial Program in Java
  5. Arrange Non-Negative Integers to Form Largest Number - Java Program

You may also like-

  1. Java Program to Find First Non-Repeated Character in a Given String
  2. How to Find Common Elements Between Two Arrays Java Program
  3. Java Program to Get All DB Schemas
  4. Spring NamedParameterJdbcTemplate Select Query Example
  5. final Vs finally Vs finalize in Java
  6. Encapsulation in Java
  7. Constructor Overloading in Java
  8. Java Collections Interview Questions And Answers

Python String split() Method

In Python, the split() method is one of the most commonly used string operations. It allows you to break a string into a list of substrings based on a specified delimiter. If no delimiter is provided, the method defaults to splitting on whitespace, treating consecutive spaces as a single separator. This makes the Python String split() Method especially useful for parsing text data.

split() method syntax

str.split(separator, maxsplit)

Both of the parameters are optional.

separator- The delimiter on which the string will be split. If not specified, whitespace is used by default.

maxsplit- Defines the maximum number of splits. If omitted or set to -1, there is no limit.

Python also provides rsplit() method, which works like split() but performs splits starting from the right when maxsplit is specified.

Python split() method examples

1. Using the split method with default parameters (not passing any parameter explicitly).

s = "This is a    test   String"
#break String on spaces
list = s.split()
print(list)

Output

['This', 'is', 'a', 'test', 'String']

Since no parameter is passed with split() method so whitespace is used as separator. Note that consecutive whitespaces are regarded as a single separator when default is used.

2. Splitting on custom delimiters like comma (,) or pipe symbol (|).

s = "Chicago,Los Angeles,Seattle,Austin"
#break String on ,
list = s.split(',')
print(list)

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.split('|')
print(list)

Output

['Chicago', 'Los Angeles', 'Seattle', 'Austin']
['Chicago', 'Los Angeles', 'Seattle', 'Austin']

3. Split string on backslash (\) symbol. With backslash it is better to use escape sequence (\\).

s = "c:\\users\\netjs\\python"
#break String on ,
list = s.split('\\')
print(list)

Output

['c:', 'users', 'netjs', 'python']

4. Limiting the splits using maxsplit parameter. Here split is done for max 2 items.

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.split('|', 2)
print(list)

Output

['Chicago', 'Los Angeles', 'Seattle|Austin']

5. Using rsplit() method.

s = "Chicago|Los Angeles|Seattle|Austin"
#break String on |
list = s.rsplit('|', 2)
print(list)

Output

['Chicago|Los Angeles', 'Seattle', 'Austin']

6. Parsing CSV data with Python string split() method

One of the most practical applications of the Python String split() Method is parsing CSV (Comma-Separated Values) data. CSV files are widely used for storing tabular data such as user records, product catalogs etc. While Python provides a built-in csv module for robust handling, the split() method offers a quick and lightweight way to process simple CSV strings.

data = "Name,Age,Location"
row = "Ram,30,New Delhi"

# Split header and row using comma as delimiter
headers = data.split(',')
values = row.split(',')

# Combine into dictionary for easy access
record = dict(zip(headers, values))
print(record)

Output

{'Name': 'Ram', 'Age': '30', 'Location': 'New Delhi'}

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

>>>Return to Python Tutorial Page


Related Topics

  1. Changing String Case in Python
  2. Python count() method - Counting Substrings
  3. Python Program to Reverse a String
  4. Operator Overloading in Python
  5. Abstract Class in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. self in Python
  3. Namespace And Variable Scope in Python
  4. raise Statement in Python Exception Handling
  5. PermGen Space Removal in Java 8
  6. String join() Method And StringJoiner Class in Java
  7. Spring Web MVC Java Configuration Example
  8. Data Compression in Hadoop

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);
}