Tuesday, March 24, 2026

Java Pass by Value or Pass by Reference

Parameter passing in Java is pass by value or pass by reference is one question which causes a bit of confusion so let's try to clarify it in this post.

Before going into whether Java is pass by value or pass by reference let's first see what do these terms actually mean.

  • Pass by value- In this case actual value of the variable is copied into the method’s parameter. This means two independent variables exist, each with its own memory space.
  • Pass by reference- In this case instead of copying the value, the memory address of the variable is passed to the parameter of the method. Thus anytime method is using its parameter it is actually referencing the original variable.

How Java Handles Parameter Passing

Let us be clear on one thing in the beginning itself. In Java, everything is pass by value, whether you’re dealing with primitive types or objects. Java does not support true pass by reference because it doesn’t expose memory addresses or pointers.

Passing primitive types as method parameter

At least there is no confusion with primitive data types as it is easy to see that primitives are passed by value in Java. For primitive data types (int, double, char, etc.), Java simply copies the value into the method parameter. Any modification inside the method does not affect the original variable. Let's see it with an example-

public class A {
 
 void displayData(int i){  
  //value of the passed primitive variable changed
  i++;
  System.out.println("Value of i inside method "  + i);
 }  
 public static void main(String args[]){ 
  A a = new A();
  int i = 5;
  // Sending variable i as param
  a.displayData(i);  
  System.out.println("Value of i inside main "  + i);
 }  
}

Output of the program

Value of i inside method 6
Value of i inside main 5

In the code when the displayData() method is called-

  • Copy of variable i is made.
  • That copy is sent to the displayData() method.
  • Any change made to variable i with in displayData() method is local to that method and that copy of the variable.

Thus it can be seen that the changing of the passed int value in the method doesn't affect the original value.

Passing class object as method parameter

When object is passed as a method parameter, people have some confusion whether it's pass by value or pass by reference in Java.

The confusion arises because, when an object is passed as parameter in Java and any instance variable of that object is changed when in the method that change is reflected globally i.e. same value is reflected every where. Let's see an example-

public class A {
 private int i;
 //constructor
 A(int i){
  this.i = i;
 }

 void displayData(A obj){ 
  // object manipulated 
  obj.setI(7);
  System.out.println("Value of i inside method "  + obj.getI());
 }  
 public static void main(String args[]){ 
  A a = new A(5);
  System.out.println("Value of i inside main before method call "  + a.getI());
  a.displayData(a);  
  System.out.println("Value of i inside main after method call "  + a.getI());
 }
 //getter
 public int getI() {
  return i;
 }
//setter
 public void setI(int i) {
  this.i = i;
 }  
}

Output of the program

Value of i inside main before method call 5
Value of i inside method 7
Value of i inside main after method call 7

It can be seen from the output that changes done to the object in the method displayData() are reflected globally. When value of i is printed after the method call it is changed. If java is pass by value then why that?

It is because when we say

A a = new A();

The new operator allocates memory for the created object and returns a reference to that memory which is then assigned to the variable of the class type.

So, it can be said “a” is a variable which is holding a value and that value happens to be the reference to the memory address.

When the method is called with

a.displayData(a); 

copy of the reference value is created and passed into the other object which means in method void displayData(A obj), obj parameter holds the copy of the reference value thus a and obj both are references to the same memory given to the object. Refer below image to have clarity.

pass by value or pass by reference

So to make it clear, in the case of object Java copies and passes the reference by value, not the actual reference itself. That is why any manipulation of the object in the method will alter the object, since the references point to the original objects. At the same time if reference itself is changed for the object that change is not reflected to the original object, which would have happened in case of pass by reference.

Let's write a Java program to understand this statement "If reference itself is changed for the obejct that change is not reflected to the original object" in detail.

public class A {
 private int i;
 A(int i){
  this.i = i;
 }
 void displayData(A obj){
  // change the reference
  obj = new A(8);
  System.out.println("Value of i inside method "  + obj.getI());
 }  
 public static void main(String args[]){ 
  A a = new A(5);
  System.out.println("Value of i inside main before method call "  + a.getI());
  a.displayData(a);  
  System.out.println("Value of i inside main after method call "  + a.getI());
 }
 
 // getter
 public int getI() {
  return i;
 }
 // setter
 public void setI(int i) {
  this.i = i;
 }  
}

In this program the reference of the object which was copied and passed as value to the parameter in method displayData() has been changed

obj = new A(8);

but it can be seen from the output that it doesn't change the original reference as it retains the original value of the variable i.

Value of i inside main before method call 5
Value of i inside method 8
Value of i inside main after method call 5

I hope I am able to make it clear that in Java, whether primitives or objects, everything is pass by value. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Why main Method static in Java
  2. Constructor in Java
  3. static Keyword in Java With Examples
  4. Primitive Data Types in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Abstraction in Java
  2. Method overriding in Java
  3. Difference Between Abstract Class And Interface in Java
  4. What are JVM, JRE and JDK in Java
  5. Can we Start The Same Thread Twice in Java
  6. How HashMap Works Internally in Java
  7. Angular First App - Hello world Example
  8. Dependency Injection in Spring Framework

Python Exception Handling Tutorial

This Python exception handling tutorial gives an overview of Python exceptions and how to handle exceptions using Python exception handling.

Types of errors

Errors in your Python programs can be categorized into atleast two types-

  • Syntax errors
  • Exceptions

Syntax error

Syntax errors or compile time errors are the errors due to which your program fails to compile. Such errors are detected at the compile time itself, file name, line number and error description is displayed so you know where to look for the error and how to correct it.

For example if you don’t write colon after if statement-

def check_equality(str1, str2):
  if str1 > str2
    print(str1, 'is greater than', str2)

Then you get the compile time error as shown here-

Output

  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 2
    if str1 > str2
                 ^
SyntaxError: invalid syntax

Exceptions

Even if a statement or expression is syntactically correct it may result in an error at run time. Errors detected during runtime are called exceptions and they disrupt the normal execution flow of the program.

For example in the following program there is an attempt to divide by zero which results in ZeroDivisionError at runtime.

def divide_num(num1, num2):
  return num1/num2

divide_num(10, 0)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 4, in <module>
    divide_num(10, 0)
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 2, in divide_num
    return num1/num2
ZeroDivisionError: division by zero

When these types of runtime errors occur in Python code, an exception object is created and raised. If there is no exception handling code to handle it then the error message is displayed that shows the context where the exception happened, in the form of a stack traceback. The exception type (at least in case of built-in exception) is printed as part of the message.

Python 3 exception hierarchy

In Python all exceptions are represented as classes and derive from BaseException class. The class hierarchy for built-in exceptions in Python is as follows.

Python 3 exception hierarchy

As you can see from the Python Exception hierarchy all built-in, non-system-exiting exceptions are derived from Exception class. All user-defined exceptions should also be derived from this class.

Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program.

Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program. Warnings unlike exceptions are not fatal and don't terminate the program. Warning is the base class for warning categories.

Python exception handling

While writing robust code we should provide checks for the eventuality where program may fail at run time because of some condition like zero division, file not found, type error.

Default behavior for handling such exceptions in Python is for the interpreter to print the full stack traceback, that includes the exception type (at least in case of built-in exception) and error message, and then terminate the program.

By providing your own exception handling you can display an appropriate message and then continue with the program rather than terminating the program.

To handle exception in Python you can use the following procedure-

  1. Use try block to enclose code that might throw an exception.
  2. Use except block to handle the raised exceptions.
  3. Use finally clause to perform clean up like closing the opened file.

Together these three keywords constitute the Python exception handling. General form of exception handling in Python is as follows.

try: 
 try suite
               
except Exception1:
 handler suite
except Exception2:
 handler suite
else:
 else suite
finally: 
 finally suite

There can be more than one except block, based on the type of the exception raised appropriate except block is executed. Read more in this post- Python Exception Handling - try,except,finally

If no exception is raised then the statements in the else block are executed.

Statements inside the finally block are always executed whether an exception is raised or not.

Python exception handling example

def divide_num(num1, num2):
  try:
    print('Result-',num1/num2)
  except ZeroDivisionError:
    print('Division by zero')
    print('Zero is not a valid argument here')
  else:
    print('in else block')

divide_num(10, 0)
divide_num(10, 2)

Output

Division by zero
Zero is not a valid argument here
Result- 5.0
in else block

As you can see in the first call to function 0 is passed as divisor which results in ‘ZeroDivisionError’ so the except block handles that exception. Since the exception handling is done so the program doesn’t terminate and the second function is also executed. This time there is no error so an optional else block is executed.

Apart from try, except and finally other keywords used in Python exception handling are-

  • raise- Allows you to force a specified exception to occur.
  • assert- The assert statement enables you to verify if a certain condition is true or not. If it not true then it raises AssertionError.

Python built-in exceptions

Python language has several built-in exceptions, some of the important one are listed below.

Exception Class Description
ArithmeticError The base class for those built-in exceptions that are raised for various arithmetic errors: OverflowError, ZeroDivisionError, FloatingPointError.
AssertionError Raised when an assert statement fails.
EOFError Raised when the input() function hits an end-of-file condition (EOF) without reading any data.
ImportError Raised when the import statement has troubles trying to load a module.
IndexError Raised when a sequence subscript is out of range.
KeyError Raised when a mapping (dictionary) key is not found in the set of existing keys.
OverflowError Raised when the result of an arithmetic operation is too large to be represented.
RuntimeError Raised when an error is detected that doesn’t fall in any of the other categories.
SyntaxError Raised when the parser encounters a syntax error.
IndentationError Base class for syntax errors related to incorrect indentation. This is a subclass of SyntaxError.
SystemError Raised when the interpreter finds an internal error, but the situation does not look so serious to cause it to abandon all hope.
TypeError Raised when an operation or function is applied to an object of inappropriate type.
ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.
FileNotFoundError Raised when a file or directory is requested but doesn’t exist.

That's all for this topic Python Exception Handling Tutorial. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. User-defined Exceptions in Python
  2. self in Python
  3. Python return Statement With Examples
  4. Constructor in Python - __init__() function
  5. Nonlocal Keyword in Python With Examples

You may also like-

  1. Changing String Case in Python
  2. Class And Object in Python
  3. Python Generator, Generator Expression, Yield Statement
  4. Convert String to int in Python
  5. What Are JVM, JRE And JDK in Java
  6. Java Concurrency Interview Questions And Answers
  7. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
  8. How to Handle Missing And Under Replicated Blocks in HDFS

HashSet in Java With Examples

HashSet in Java is one of the most widely used implementations of the Set interface. It represents an unordered collection of unique elements, meaning that duplicate values are not allowed and the insertion order is not preserved. If you’re working with collections where uniqueness matters, HashSet is a go-to choice.

Following are the key features of HashSet in Java.

  1. Part of the Java Collections Framework: HashSet is part of Java Collections framework. HashSet class extends AbstractSet and implements Set, Cloneable and Serializable interfaces.
  2. Unordered collection: HashSet is an unordered collection. Elements are stored based on their hash values. The hashing mechanism decides the bucket location, so the order of insertion is not maintained.
  3. Ensures uniqueness: HashSet only stores unique elements, meaning duplicates are nor allowed.
  4. Allows one null value: HashSet permits one null element to be added.
  5. Not synchronized: HashSet implementation is not synchronized hence not thread safe. If HashSet is to be used in a multi-threaded environment where it is accessed and modified concurrently then it must be synchronized externally. That can be done by wrapping the set with in Collections.synchronizedSet method.
  6. Fail-fast iterators: The iterators returned by HashSet's iterator method are fail-fast. if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException.

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