BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java – String Class and Methods with examples

By Chaitanya Singh | Filed Under: java

String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable object which means it is constant and can cannot be changed once it is created. In this tutorial we will learn about String class and String methods with examples.

Creating a String

There are two ways to create a String in Java

  1. String literal
  2. Using new keyword

1. String literal

A string literal is a sequence of characters enclosed in double quotation marks (” “). In java, Strings can be created by assigning a String literal to a String instance:

String str1 = "BeginnersBook";
String str2 = "BeginnersBook";
Java String


The problem with this approach: As I stated in the beginning that String is an object in Java. However we have not created any string object using new keyword in the above statements.

The compiler does this internally and looks for the string in the memory (this memory is often referred as string constant pool). If the string is not found, it creates an object with the string value, which is “Welcome” in this example and assign a reference to this string.

In our example, a reference to string “BeginnersBook” is copied to the string str1, however for str2, the compiler finds the string in string constant pool and doesn’t create the new object, rather assigns the same old reference to the string str2.

What if we want to have two different object with the same string? For that we would need to create strings using new keyword.

2. Using New Keyword

To create a new instance of a string, we use new keyword. When we create a string using new keyword, it gets created in heap memory rather than string constant pool as shown in the following diagram. When we create a string using new keyword, it always create a new string irrespective of whether the string is already present or not in the heap memory.

String str3 = new String("BeginnersBook");
String str4 = new String("BeginnersBook");
Java String Creating new String

In this case compiler would create two different object in heap memory with the same string.

Example 1: Java String vs new String

Let’s write a java string program to understand the difference of two different ways of creating a string in java.

class JavaExample
{
  public static void main(String args[])
  {
    //creating string using string literal
    String s1 = "BeginnersBook";
    String s2 = "BeginnersBook";

    //creating strings using new keyword
    String s3 = new String("BeginnersBook");
    String s4 = new String("BeginnersBook");

    if(s1 == s2){
      System.out.println("String s1 and s2 are equal");
    }else{
      System.out.println("String s1 and s2 are NOT equal");
    }

    if(s3 == s4){
      System.out.println("String s3 and s4 are equal");
    }else{
      System.out.println("String s3 and s4 are NOT equal");
    }

  }
}

Output:

Java String output

Now that our concept is clear, let’s see few examples of String class:

Example 2: A Simple Java String Example

public class JavaExample{
  public static void main(String args[]){
    String str = "Beginnersbook";

    //declaring a char array
    char arrCh[]={'h','e','l','l','o'};

    //converting char array arrCh[] to string str2
    String str2 = new String(arrCh);

    //creating another java string str3 by using new keyword
    String str3 = new String("Java String Example");

    //Displaying all the three strings
    System.out.println(str);
    System.out.println(str2);
    System.out.println(str3);
  }
}

Output:

Beginnersbook
hello
Java String Example

Example 3: Displaying first and last character of a String

For this, we are using charAt() method and length() method of string class. We have discussed all the methods in detail and links to these guides are provided after these examples.

public class JavaExample {
  public static void main(String[] args) {
    String str = "Welcome to BeginnersBook.com";

    //finding length of the string using length() method.
    int len = str.length();

    // First character of the string
    System.out.println("First character: "+ str.charAt(0));

    // Last character
    System.out.println("Last character: "+ str.charAt(len-1));
  }
}

Output:

First character: W
Last character: m

Example 4: Comparing the string vs new string using equals()

As we have seen when we compared the strings using == operator, it compared the references of the strings. To compare the value of the strings, you can use equals() method of string class.

public class JavaExample {
  public static void main(String[] args) {
    String str = "Hello"; //creating using literal
    String str2 = new String("Hello"); //using new keyword

    if(str.equals(str2)){
      System.out.println("Strings str and str2 are equal");
    }else{
      System.out.println("Strings str and str2 are NOT equal");
    }
  }
}

Output:

Strings str and str2 are equal

Example 5: String concatenation

public class JavaExample {
  public static void main(String[] args) {
    String str = "Welcome";
    String str2 = "Home";
    System.out.println(str.concat(" ").concat(str2));
  }
}

Output:

Welcome Home

Java String Methods

Here are the list of the methods available in the Java String class. These methods are explained in the separate tutorials with the help of examples. Links to the tutorials are provided below:

  1. char charAt(int index): It returns the character at the specified index. Specified index value should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if index<0||>= length of String.
  2. boolean equals(Object obj): Compares the string with the specified string and returns true if both matches else false.
  3. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the case while comparing strings. It does a case insensitive comparison.
  4. int compareTo(String string): This method compares the two strings based on the Unicode value of each character in the strings.
  5. int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the case during comparison.
  6. boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the specified offset index) is having the specified prefix or not.
  7. boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes then it returns true else false.
  8. boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.
  9. int hashCode(): It returns the hash code of the string.
  10. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the string.
  11. int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in the string from the specified fromIndex.
  12. int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.
  13. int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts search from fromIndex.
  14. int indexOf(String str): This method returns the index of first occurrence of specified substring str.
  15. int lastindexOf(String str): Returns the index of last occurrence of string str.
  16. String substring(int beginIndex): It returns the substring of the string. The substring starts with the character at the specified index.
  17. String substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.
  18. String concat(String str): Concatenates the specified string “str” at the end of the string.
  19. String replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar with the newChar.
  20. boolean contains(CharSequence s): It checks whether the string contains the specified sequence of char values. If yes then it returns true else false. It throws NullPointerException of ‘s’ is null.
  21. String toUpperCase(Locale locale): Converts the string to upper case string using the rules defined by specified locale.
  22. String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
  23. public String intern(): This method searches the specified string in the memory pool and if it is found then it returns the reference of it, else it allocates the memory space to the specified string and assign the reference to it.
  24. public boolean isEmpty(): This method returns true if the given string has 0 length. If the length of the specified Java String is non-zero then it returns false.
  25. public static String join(): This method joins the given strings using the specified delimiter and returns the concatenated Java String
  26. String replaceFirst(String regex, String replacement): It replaces the first occurrence of substring that fits the given regular expression “regex” with the specified replacement string.
  27. String replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular expression regex with the replacement string.
  28. String[] split(String regex, int limit): It splits the string and returns the array of substrings that matches the given regular expression. limit is a result threshold here.
  29. String[] split(String regex): Same as split(String regex, int limit) method however it does not have any threshold limit.
  30. String toLowerCase(Locale locale): It converts the string to lower case string using the rules defined by given locale.
  31. public static String format(): This method returns a formatted java String
  32. String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()).
  33. String trim(): Returns the substring after omitting leading and trailing white spaces from the original string.
  34. char[] toCharArray(): Converts the string to a character array.
  35. static String copyValueOf(char[] data): It returns a string that contains the characters of the specified character array.
  36. static String copyValueOf(char[] data, int offset, int count): Same as above method with two extra arguments – initial offset of subarray and length of subarray.
  37. void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): It copies the characters of src array to the dest array. Only the specified range is being copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
  38. static String valueOf(): This method returns a string representation of passed arguments such as int, long, float, double, char and char array.
  39. boolean contentEquals(StringBuffer sb): It compares the string to the specified string buffer.
  40. boolean regionMatches(int srcoffset, String dest, int destoffset, int len): It compares the substring of input to the substring of specified string.
  41. boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len): Another variation of regionMatches method with the extra boolean argument to specify whether the comparison is case sensitive or case insensitive.
  42. byte[] getBytes(String charsetName): It converts the String into sequence of bytes using the specified charset encoding and returns the array of resulted bytes.
  43. byte[] getBytes(): This method is similar to the above method it just uses the default charset encoding for converting the string into sequence of bytes.
  44. int length(): It returns the length of a String.
  45. boolean matches(String regex): It checks whether the String is matching with the specified regular expression regex.
  46. int codePointAt(int index):It is similar to the charAt method however it returns the Unicode code point value of specified index rather than the character itself.

Popular Java String Examples

I have shared several tutorials on the String in java. Here are the links to the popular Java String tutorials.

  • Convert String to int in Java
  • Convert int to String
  • Convert String to Double in Java
  • Double to String conversion
  • Convert String to Long
  • Long to String conversion
  • InputStream to String Conversion – example
  • String vs StringBuffer
  • Convert String to boolean primitive
  • boolean to String conversion
  • Convert String object to Boolean object
  • Remove trailing spaces of a String
  • Left pad a String with zeros/spaces
  • Right pad a String with zeros/spaces
  • Program to find duplicate characters in a String
  • Convert char to String and vice versa
  • Convert a char array to String
  • String to Date conversion
  • Date to String conversion
  • ASCII to String conversion
  • float to String conversion
  • StackTrace to String conversion
  • Writer to String conversion
  • Convert String to ArrayList
  • Java 8 – StringJoiner Example
  • Program to reverse words of a String in Java
  • Program to reverse a String in Java using Recursion
❮ PreviousNext ❯

Comments

  1. Philip John says

    September 10, 2015 at 8:39 AM

    Thanks for the list of methods! I was looking for that a long time!

    Reply
  2. Roshan says

    March 27, 2016 at 1:06 PM

    Really nice website… It has all about Strings any beginner should be familier with

    Reply
  3. Tobe says

    April 8, 2016 at 9:40 AM

    Pls can I have all this information in pdf…Thank you so much.

    Reply
  4. Ktam says

    August 28, 2016 at 8:46 PM

    The way you explained the String literals nd the concept of the creation of object is appreciable…. Excellent job.
    It’s very rare to be found in such an easy way as you done.
    Although it was already known to. Me. But as u explained i was unable to restrict myself to give a feedback.

    Reply
  5. vijay says

    September 10, 2016 at 2:41 AM

    please send pdf file of java because the information which your providing is very good every one can understand quickly

    Reply
  6. Gabe says

    November 28, 2016 at 3:18 PM

    If only you wrote my text books! Thank you so much for sharing your skills with us! The layout is very easy to follow and zoom in for what you are looking for. I even used your search and found exactly what I was looking for. I concept that most websites seem to struggle with.

    Keep up the great work Chaitanya!

    Reply
  7. William says

    August 22, 2017 at 10:05 PM

    I appreciate the effort and precision that was put into this!

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap