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.