Monday, March 23, 2026

Java Program to Reverse a Number

Java Program to Reverse a Number is a classic interview question often asked to test a developer’s logical thinking and understanding of core programming concepts. Though how to reverse a string program is applicable for numbers also by treating the numbers as String, interviewers frequently emphasize reversing a number without converting it into a string or using any library functions. This ensures you demonstrate mastery of loops, recursion and mathematical operators.

Reversing number in Java can be done in two ways

  • By iterating through digits of the number and using mathematical operators like divide and multiply.
  • Using recursive function.

Iterative logic for reversing a number

In iterative approach, you repeatedly divide the number by 10 to extract its digits (obtained using the modulo operator %). You also need another int variable for storing the reversed number (initially initialized to 0). In each iteration, add the extracted digit to this variable, while also multiplying that variable by 10. Multiplication is required to move place values in the reversed number. Divide the original number by 10 too to get to the next digit.

For example, if original number is 189 then first iteration will give remainder as 9 and quotient as 18. Which stores the value (0 * 10) + 9 = 9 in the reverseNum variable. In the second iteration remainder will be 8 and quotient 1. After second iteration reverseNum variable will have value (9 * 10) + 8 = 98. Same for third iteration where remainder will be 1 and quotient 0. Thus making it (98 * 10) + 1 = 981. Which is the reversed number.

Recursive logic for reversing number

In recursive method, the method calls itself with the number divided by 10 in each step, while printing or storing the remainder (num % 10). This technique naturally handles digit extraction but also preserves leading zeros. For example, input 200 will output 002 using recursion, whereas the iterative method would return 2.

Java program to reverse a number

import java.util.Scanner;

public class ReverseNumber {

 public static void main(String[] args) {
  System.out.println("Please enter a number : ");
  Scanner sc = new Scanner(System.in);
  int scanInput = sc.nextInt();
  // Using recursion
  reverseRec(scanInput);
  System.out.println();
  System.out.println("------------------");
  // Using while loop
  reverseNum(scanInput);
 }
 
 // Method for reversing number using recursion
 public static void reverseRec(int num){
  //System.out.println("num" + num);
  if(num == 0)
   return;
  System.out.print(num % 10);
  reverseRec(num/10);
 }
 
 // Iterative method for reversing number  
 public static void reverseNum(int num){
  int reversedNum = 0;
  int mod = 0;
  while(num != 0){
   mod = num % 10;
   reversedNum = (reversedNum * 10) + mod;
   num = num/10;
  }
  System.out.println("reversedNum -- " + reversedNum);
 }
}

Output

Please enter a number : 
91346
64319
------------------
reversedNum -- 64319

That's all for this topic Java Program to Reverse a Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Display Prime Numbers
  2. Convert float to int in Java
  3. Arrange Non-Negative Integers to Form Largest Number - Java Program
  4. How to Run Threads in Sequence in Java
  5. Print Odd-Even Numbers Using Threads And wait-notify Java Program

You may also like-

  1. How to Untar a File in Java
  2. How to Append to a File in Java
  3. String in Java Tutorial
  4. Constructor Chaining in Java
  5. Difference Between Encapsulation And Abstraction in Java
  6. Difference Between HashMap And ConcurrentHashMap in Java
  7. Difference Between Comparable and Comparator in Java
  8. Java Stream API Tutorial

Strings in Python With Method Examples

String which represents a sequence of characters is one of the most used type in most of the applications. So programming languages generally ensure that String is well optimized and has an extensive API with methods to cover most of the String operations. Python is no different and String in Python also has many optimization features and a rich set of built-in methods for common operations such as trimming, splitting, joining, and formatting.

Python String

In Python, every string literal is an object of the built-in str class. Strings in Python are arrays of bytes, representing unicode characters. Unlike some programming languages, Python does not have a separate character type, meaning even a single character is treated as a string of length 1. This design choice makes string handling consistent and powerful across different use cases.


Creating a String in Python

You can create a String in Python by enclosing a group of characters in either single quotes or double quotes.

Both of the following are valid and work in similar way-

s = 'Hello'

s = "Hello"

You can also create String in Python using tripe single quotes or triple double quotes. This way of creating String is useful if you have a multiline String.

s = '''This tutorial on String in Python gives examples of 
creating strings, string optimizatin features and examples
of functions in String.'''

print(s)

Output

This tutorial on String in Python gives examples of 
creating strings, string optimizatin features and examples
of functions in String.

Showing quotes as part of String in Python

If you have to show quotes as part of string then you can use another type of quote to enclose string and the quote which has to be part of string in the inner string.

For example if you have to show text – This isn’t part of the original deal
then use double quotes to enclose the String and single quote as part of the text.

s = "This isn't part of the deal"
print(s)

Output

This isn't part of the deal

If you have to show text- He said “May I come in”
then use single quotes to enclose the String and double quotes as part of the text.

s = 'He said "May I come in"'
print(s)

Output

He said "May I come in"

Escape characters in a String

You can also use escape characters with a String in Python.

Some of the escape characters that can be used in Strings are-

Escape character Description
\aBell or alert
\bBackspace
\nNew line
\rCarriage return (enter)
\sSpace
\tHorizontal tab space
\vVertical tab space

For example-

s = "This text has \t spaces and goes to \n next line"
print(s)

Output

This text has   spaces and goes to 
 next line

Backslash (\) is also used as an escape sequence in Python. If you want double or single quote with in a String then you can also put a backslash followed by a quote (\" or \').

s = "He said \"this looks good\" to his colleague"
print(s)

Output

He said "this looks good" to his colleague

Since backslash is used as an escape sequence so you’d need two backslashes (\\) if you have to display backslash as part of String. One for displaying and another as escape sequence.

print("C:\\Python\\")
print(s)

Output

C:\Python\

Accessing characters in String (String indexing)

Since String in Python is stored as an array so array indexing can be used to access characters of a String. Index is 0 based so first character is at index 0, second is at index 1 and so on.

In Python you can also use negative indexing. When negative number is used as index String is accessed backward so -1 refers to the last character, -2 second last and so on.

String in Python

Example to access characters of a String

s = "Hello World"
#first character
print(s[0])
#last character
print(s[10])
#last character
print(s[-1])
#first character
print(s[-11])

Output

H
d
d
H

Trying to use an index which is out of range results in IndexError. Using any other type except integer as index results in TypeError.

s = "Hello World"
#index out of range
print(s[12])

Output

    print(s[12])
IndexError: string index out of range

If you want to access a part of a String then you use slicing operator. Slicing is done using “[:]” operator.

For example if you want to access characters between index 3 and 7.

s = "Hello World"
#slicing String
print(s[3:7])

Output

lo W

For more examples of Python String slicing please refer this post- String Slicing in Python

Strings in Python are immutable

String in Python is immutable which means content of String object can’t be modified once assigned.

Trying to modify a String by updating or deleting any character results in error as Strings are immutable.

Updating String

s = "Hello World"
#changing String
s[3] = 't'

Output

    s[3] = 't'
TypeError: 'str' object does not support item assignment

Deleting character in a String

s = "Hello World"
#deleting char
del s[3]

Output

    del s[3]
TypeError: 'str' object doesn't support item deletion

Note that; though content can’t be changed for an immutable object but the reference can be changed. So a string object can be made to reference a new String.

s = "Hello World"
print(id(s))
s = "Hi"
print(s)
print(id(s))

Output

2976589114032
Hi
2976587746472

id function in CPython implementation returns the address of the object in memory. As you can see s starts referencing to the new memory location when a new String is assigned.

String interning in Python

String interning means that two string objects that have the same value share the same memory. If you have one string object with some value and you create second string object with the same value then the second string object shares the reference with the first string object. By interning strings memory is saved.

String interning is possible in Python as Strings are immutable so content can't be changed.

s1 = "Hello"
s2 = "Hello"
print(s1 is s2)
print(id(s1))
print(id(s2))

Output

True
1347382642256
1347382642256

In the example two string objects are created having the same value. As you can see when is operator is used to check whether both the operands refer to the same object or not true is returned.

Also id() function returns the same memory address for both the objects.

Operators used with String

Following operators are used with String in Python-

1. + operator-‘+’ operator when used with Strings in Python acts as a concatenation operator . It is used to append one string at the end of another string.

s1 = "Hello"
s2 = " World"
print(s1 + s2)

Output

Hello World

2. * operator- * operator is the repetition operator and used to repeat the string for the given number of times.

s1 = '*'
for i in range (1, 5):
    print(s1*i)

Output

*
**
***
****

3. in and not in operators- These operators are used for checking whether the given string or character is part of another String.

4. Slice operator- Slice operator ([:]) is used to access a substring with in a string. See more about Python string slicing here.

Python String methods

In this section Python String methods are compiled functionality wise.

  1. Getting String length in Python- For getting string length in Python, len() function is used. Refer String Length in Python - len() Function to see examples of len() function with strings.
  2. Checking String membership- To check if String present in another string in Python you can use membership operators ‘in’ and ‘not in’ or use find() or index() methods. Refer Check if String Present in Another String in Python to see examples of String membership checking.
  3. Comparing two Strings in Python- For comparing two Strings in Python you can use relational operators (==, <, <=, >, >=, !=). Refer Comparing Two Strings in Python to see examples of String comparison.
  4. Removing spaces from String in Python- To rempve spaces in String you can use str.lstrip(), str.rstrip() and str.strip() methods. Refer Removing Spaces From String in Python to see examples of removing spaces from string.
  5. Python count() method- If you want to count the number of occurrences of a specific substring in a string in Python then you can use count() method to do that. Refer Python count() method - Counting Substrings to see examples of count() method.
  6. Changing String case in Python- If you want to change string to lower case or upper case you can use one of the methods provided in str- str.lower(), str.upper(), str.capitalize(), str.title() to do that. Refer Changing String Case in Python to see examples of string case changing.
  7. split() Method- If you want to split a String in Python that can be done using split() method. Refer Python String split() Method to see examples of splitting a String using split() method.
  8. join() Method- If you want to join a sequence of Strings in Python that can be done using join() method. Refer Python String join() Method to see examples of join() method.
  9. str.isspace() Method- This method returns true if there are only whitespace characters in the string and there is at least one character. Refer Check String Empty or Not in Python to see example of isspace() method.
  10. isdigit() Method-The isdigit() method in Python String class is used to check if all the characters in the string are digits or not. Refer Python String isdigit() Method to see example of isdigit() method.
  11. isnumeric() Method-The isnumeric() method in Python String class is used to check if all the characters in the string are numeric characters or not. Refer Python String isnumeric() Method to see example of isnumeric() method.

That's all for this topic Strings in Python With Method Examples. 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. Getting Substring in Python String
  3. Python Program to Count Number of Words in a String
  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. instanceof Operator in Java
  5. Difference Between ArrayList And LinkedList in Java
  6. Semaphore in Java Concurrency
  7. Spring Setter Based Dependency Injection
  8. Transaction Management in Spring

Sunday, March 22, 2026

Python String replace() Method

Python String replace() method is used to replace occurrences of the specified substring with the new substring.

Syntax of replace() method

Syntax of replace() method is-

str.replace(old, new, count)

old- Specifies a substring that has to be replaced.

new- Specifies a substring that replaces the old substring.

count- count argument is optional if it is given, only the first count occurrences are replaced. If count is not specified then all the occurrences are replaced.

Return values of the method is a copy of the string with all occurrences of substring old replaced by new.

Replace() method Python examples

1. Replacing specified substring with new value.

def replace_sub(text):
    text = text.replace('30', 'thirty')
    print(text)

replace_sub('His age is 30')

Output

His age is thirty

2. replace() method with count parameter to replace only specified occurrences.

def replace_sub(text):
    text = text.replace('is', 'was')
    print(text)
    # replacing only one occurrence
    print(text.replace('was', 'is', 1))

replace_sub('His age is 30')

Output

Hwas age was 30
His age was 30

3. Replacing character with space.

def replace_sub(text):
    text = text.replace('H', '')
    print(text)

replace_sub('His age is 30')

Output

is age is 30

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

>>>Return to Python Tutorial Page


Related Topics

  1. Removing Spaces From String in Python
  2. String Slicing in Python
  3. Python String isdigit() Method
  4. Python String isnumeric() Method
  5. Local, Nonlocal And Global Variables in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Installing Anaconda Distribution On Windows
  3. Python while Loop With Examples
  4. Multiple Inheritance in Python
  5. BigDecimal in Java
  6. Java Stream API Tutorial
  7. Difference Between Two Dates in Java
  8. Transaction Management in Spring

Accessing Characters in Python String

Python String is an ordered sequence of unicode characters and stored as an array. In order to access characters in a String you need to specify string name followed by index in the square brackets. Since Python uses zero-based indexing, the first character of a string is at position 0, and for a string of length n, valid indices range from 0 to n-1.

In String in Python you can also use negative indexing which allows you to access characters starting from the end of the string. For example, -1 refers to the last character, -2 to the second last, and so on.

Here is an illustration of accessing characters in a Python string using both positive (left to right) and negative (right to left) indexing.

Accessing characters from String in Python

Getting characters from a string in Python example

s = "Hello World"
#first character
print(s[0])
#3rd character
print(s[2])
print('length of String', len(s))
#last character
print(s[len(s)-1])

Output

H
l
length of String 11
d

Getting characters using negative indexing

s = "Hello World"
# last character
print(s[-1])
print('length of String', len(s))
# first character by making the index negative
print(s[-(len(s))])

Output

d
length of String 11
H

That's all for this topic Accessing Characters 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. Removing Spaces From String in Python
  2. Check String Empty or Not in Python
  3. String Length in Python - len() Function
  4. Python while Loop With Examples
  5. Multiple Inheritance in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Python Program to Find Factorial of a Number
  3. Python Functions : Returning Multiple Values
  4. Tuple in Python With Examples
  5. BigDecimal in Java
  6. Java ThreadLocal Class With Examples
  7. Difference Between Two Dates in Java
  8. Transaction Management in Spring

Saturday, March 21, 2026

Removing Spaces From String in Python

Removing spaces from string in Python is a common task when cleaning or formatting text data. Python provides several built-in string methods that make this process simple and efficient. Depending on whether you want to remove leading spaces, trailing spaces, both ends, or even spaces inside the string, you can choose from the following options:

  • str.lstrip()- Using this method you can remove the leading whitespaces from a String. See example.
  • str.rstrip()- using this Python String method you can remove the trailing whitespaces from a String. See example.
  • str.strip()- This method helps in removing both leading and trailing whitespaces from a String in Python. See example.
  • re.sub()- By using re (Regular Expression) module's re.sub() function and passing the regular expression for spaces and replacement as a single space you can remove spaces in between words too apart from both leading and trailing whitespaces. See example.

It’s important to note that strings in Python are immutable, meaning these methods return a new string rather than modifying the original one. To keep the modified version, you must assign the result to a variable.

lstrip() - Removing leading whitepaces from String in Python

To remove spaces from the start of the String lstrip() method can be used.

string = "    String with leading spaces"
print(string)
print(string.lstrip())

Output

    String with leading spaces
String with leading spaces

rstrip() - Removing trailing whitepaces from String in Python

To remove spaces from the end of the String rstrip() method can be used.

string = "String with trailing spaces    "
print(string)
print(string.rstrip())

Output

String with trailing spaces     
String with trailing spaces

strip() - Removing both leading and trailing whitespaces from String in Python

To remove spaces from both start and end of the String strip() method can be used.

string = "       String with leading and trailing spaces    "
print(string)
print(string.strip())

Output

       String with leading and trailing spaces    
String with leading and trailing spaces

Using re.sub() function in Python

You need to import re module to use this function. Function re.sub() replaces one or many matches with a replacement string.

In the function “//s+” is passed as a regular expression to match any number of spaces. As a replacement for those matches you can pass “” when removing leading and trailing spaces and a single space (“ ”) when removing spaces in between words.

^- represents start of the String

$- represents end of the String

string = "       String with    leading and    trailing spaces    "
print(string)
# removing leading and trailing spaces
string = re.sub("^\\s+|\\s+$", "", string)
# replacing more than one space between words with single space
string = re.sub("\\s+", " ", string)
print(string)

Output

       String with    leading and    trailing spaces    
String with leading and trailing spaces

That's all for this topic Removing Spaces From 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. Comparing Two Strings in Python
  2. String Slicing in Python
  3. Getting Substring in Python String
  4. Operator Overloading in Python
  5. Polymorphism in Python

You may also like-

  1. Class And Object in Python
  2. pass Statement in Python
  3. Python Generator, Generator Expression, Yield Statement
  4. Python Exception Handling - try,except,finally
  5. Conditional Operators in Java
  6. HashSet in Java With Examples
  7. Race Condition in Java Multi-Threading
  8. Different Bean Scopes in Spring

Thursday, March 19, 2026

Python count() method - Counting Substrings

If you want to count the number of occurrences of a specific substring in a string in Python, the most efficient way is to use the built-in count() method.

The general syntax of the Python count() method is as follows-

str.count(sub, start, end)

Parameters:

  • sub- The substring you want to count in the String str.
  • start (optional)- The starting index of the search range.
  • end (optional)- The ending index of the search range.

If start and end are not provided, Python counts occurrences across the entire string. When they are specified, only the substring occurrences within that slice are counted.

Python string count() method example

1. Using count() method with no start and end parameters.

s = "This a test string to test count method"
print('Count-', s.count("test"))

Output

Count- 2

2. Using count() method with start and end parameters.

s = "This a test string to test count method"
# passing range for search 
count = s.count("test", s.find("test"), s.rfind("test"))
print('Count-', count)

Output

Count- 1

In the example range for search is passed using find() and rfind() methods, find() returns the lowest index in the string where substring is found and rfind() returns the highest index in the string where substring sub is found.

3. Calculating count of character ‘o’ in the String.

s = "This a test string to test count method"
count = s.count("o")
print('Count-', count)

Output

Count- 3

That's all for this topic Python count() method - Counting Substrings. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Check if String Present in Another String in Python
  2. Removing Spaces From String in Python
  3. Python Program to Count Number of Words in a String
  4. Passing Object of The Class as Parameter in Python
  5. raise Statement in Python Exception Handling

You may also like-

  1. Python return Statement With Examples
  2. Global Keyword in Python With Examples
  3. Python Conditional Statement - if, elif, else Statements
  4. Python Program to Display Prime Numbers
  5. final Keyword in Java With Examples
  6. Binary Tree Traversal Using Depth First Search Java Program
  7. Spring Profiles With Examples
  8. Input Splits in Hadoop

How ArrayList Works Internally in Java

When it comes to Java Collections, ArrayList stands alongside HashMap as one of the most widely used data structures. In fact, most Java developers rely on ArrayList almost daily to store and manage objects efficiently. Earlier, I explained how HashMap works internally in Java; in this article, we’ll dive deep into how ArrayList works internally in Java, a topic that frequently appears in interviews and is crucial for mastering the Collections Framework.

At its core, ArrayList is a resizable-array implementation of the List interface. Unlike a traditional array, which has a fixed size, ArrayList can grow dynamically as elements are added. This flexibility is achieved through an internal mechanism that ensures there’s always room for new elements without manual resizing.

So, let's try to get clear idea about the following points-

  • How ArrayList is internally implemented in Java.
  • What is the backing data structure for an ArrayList.
  • How it grows dynamically and ensures that there is always room to add elements.

Because of all these side questions it is also a very important Java Collections interview question.

Note that the code of ArrayList used here for reference is from Java 25


Where does ArrayList internally store elements

Backing data structure used by Java ArrayList to store its elements is an array of Object class, which is defined as follows-

transient Object[] elementData;

This elementData array is where all objects are actually stored. The keyword transient is important here: it tells the JVM not to serialize this field by default. You might wonder, if the core storage is transient, how does serialization of an ArrayList still work? The answer lies in the fact that ArrayList overrides the writeObject and readObject methods. These custom implementations ensure that the contents of elementData are properly serialized and deserialized, even though the field itself is marked transient.

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

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