What is String in java

String in java

What is String in java

String is fundamental aspect of most programming languages, not just java. If we describe String in simple way, String is just a sequence of characters. When we connect different words together, it becomes a String. In this tutorial, we will discuss about String in java. How we can handle string with some great examples. We will also cover some important methods of string to manipulate it and much more.

But before we begin, it is important to understand the term String in java programming. So let’s get started.

What is String

Although we know that String is the sequence of characters but in java it is more than that. In Java, String is a class which can be used to crate the object of String type. Each character in java is a 16 bit Unicode character, a rich set of international characters represented in Unicode system.

One thing which is more important to understand about String is that, String is immutable in java programming. Once you crated an String object, you can not modify it’s content again on the same object.

Let’s understand it by creating a simple String object.

String string = new String("Java String");

Let’s discuss what’s happening inside when we are creating a new string in java and it’s memory structure.

what is string in java


Loot at the above diagram how String object is being created in Heap area.

Generally we create lot of string objects in our project or program during run time. So to make this process faster, Java though let’s create a separate area where we can create String objects faster to make our program response time faster. This separate space is called “String Constant Pool” or we can say “String Literal Pool”.

String constant pool basically stores the String literals which can be reused by other String objects.

Let’s take the above syntax to understand how String is created.
  1. First, we created a reference variable of type String which is “string”. This object is empty for now.
  2. Then we created a new String by simple using the “new” keyword.
  3. We passed the string “Java String” to the constructor of String class.
  4. Now JVM, first will look for the existing String “Java String” in constant pool. JVM finds that there no such string created before in Constant Pool.
  5. So Java will crate a new String in normal Heap (Non pool) memory area and reference of it will be passed to reference variable of String type.
  6. And at the same time, String literal “Java String” will be placed in the String constant pool.
  7. So basically two objects will be created. First it will create a string in constant pool and then other will be created in the Heap area.
  8. After that reference of the newly created String will be passed to the String reference variable.
Now let’s modify the above example and create another String object and see what’s happens now.

String string = new String("Java String");
String string2 = "Java String";

Loot at the below diagram what’s happening internally.

String in java


What’s happening here.
  1. Now, JVM will first look for the String literal “Java String” in string constant pool.
  2. So there will no new object will be created for the “string2”.
  3. JVM will simple pass the reference of the String literal already created in the String constant pool.
  4. So there will still be only two objects in memory.

If String is immutable then what’s happening in below example.

String string = "Hello ";
string = string + "World";

System.out.println(string); // Hello World

We were saying that String in immutable in Java, once crated can not be modified. But as we can see above, we have modified the string which is giving us the concatenated string.

Remember, What you are seeing above is actually not happening internally. We are adding another string to the existing string. So JVM will take both of the String and will create a new String. And the reference of the newly crated String will be given to the existing String reference variable. So it will output the combined string and existing String literals will be removed from the memory.  

So “Hello ” will be removed from the memory and now String constant pool will contain only “Hello World”.

How to calculate the space taken by a String in java

Before we calculate the space a String takes, We need to first understand what actually String contains as below.
  • char array— A character array which contains the actual characters of a given String.
  • integer offset Offset from where String actually starts.
  • length Length of the given string.
  • hash code Some space for the calculation of the hash code.
From above it is clear that whether you create an empty String or not. String object will need some default space in memory.

That means for if we have an empty String so the memory calculation will be done as below.

Minimum String memory usage (bytes) = 8 * (int) ((((no of chars) * 2) + 45) / 8)
  1. Char array will take 4 bytes.
  2. Then, 3*4=12 bytes for the three int fields.
  3. Additionally 8 bytes for the object header.
  4. Memory taken 24 bytes (24 is a multiple of 8 so padding is not required).
  5. Again it will take up to 12 bytes of Space (Extra 4 bytes to store the length of string).
  6. Additionally 4 bytes will be added for padding to bright the memory used by the char object up to multiple of 16.
  7. So an empty string uses 40 bytes of space in memory.

String Class 

String is a class in java. So let’s discuss what do we have inside String class to manipulate String object at run time. String class internal structure.

public final class String extends Object
                          implements Serializable, Comparable<String>, CharSequence

String class is final, it can not be extends by any other class. It extends “Object” class by default, we will discuss about Object class later (But for now, Object class is the base class of all the classes in java. Whether you extend it or not, this will be always be there).

String class implements three interface such as Serializable, Comparable, CharSequence. We will discuss them later in our tutorials but for now just understand Serializable allows any object to travel over network. Comparable allows proper ordering of the contents. CharSequence used to represent the sequence of characters.

Some important Constructor provided by String Class

String()
Creates a new empty String object.
String(byte[] bytes)
You can pass byte array and a new String will be created as per default platform charset.
String(byte[] bytes, Charset charset)
You can pass byte array and a new String will be created as per given charset.
String(char[] value)
New String will be created as per the given character array.
String(char[] value, int offset, int count)
You can create a new String from an existing character array, additionally you can provide position in array from where characters should be taken and number of characters to include.
String(int[] codePoints, int offset, int count)
Allocates a new String that contains characters from a subarray of the Unicode code point array argument.
String(String original)
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder argument.

Some important methods of String class to manipulate the String object.


Modifier and Return Type Method name and it’s use
char charAt(int index)
You can get the character value from a String at specified position.
int compareTo(String anotherString)
Used to compare two strings in lexicographically.
int compareToIgnoreCase(String str)
Used to compare two strings in lexicographically but ignore case of the given string.
String concat(String str)
This method Concatenates given string at the end of the existing string and returns the new String object.
boolean contains(CharSequence s)
Returns true if and only if this string contains the specified sequence of char values.
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
boolean equals(Object anObject)
Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
static String format(String format, Object... args)
Returns a formatted string using the specified format string and arguments.
byte[] getBytes()
Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.
byte[] getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
int hashCode()
Returns a hash code for this string.
int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
String intern()
Returns a canonical representation for the string object.
boolean isEmpty()
Returns true if, and only if, length() is 0.
int lastIndexOf(String str)
Returns the index within this string of the last occurrence of the specified substring.
int length()
Returns the length of this string.
boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String[] split(String regex)
Splits this string around matches of the given regular expression.
String substring(int beginIndex)
Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
char[] toCharArray()
Converts this string to a new character array.
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
String toString()
This object (which is already a string!) is itself returned.
String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
static String valueOf(Object obj)
Returns the string representation of the Object argument.

Some examples


1. Program to get the character at given position in String.

public class StringExample {
 public static void main(String[] args) {

   String str = "Welcome to Java world.";
   System.out.println("String = " + str);

   // Get the character at positions 0 and 3.
   int index1 = str.charAt(0);
   int index2 = str.charAt(3);

   // Print out the results.
   System.out.println("The character at position 0 is " + (char)index1);
   System.out.println("The character at position 3 is " + (char)index2);
 }
}

2. Program to check whether two string ends with the same string.

public class StringExercise {

 public static void main(String[] args) {

   String str1 = "Welcome to the java programming";
   String str2 = "Welcome to the java world";

   // Enter the string whether both ends with the same string.
   String endStr = "rld";

   // Check first two Strings end with endStr
   boolean str1End= str1.endsWith(endStr);
   boolean str2End= str2.endsWith(endStr);

   // Display the results of the endsWith calls.
   System.out.println(str1 + " ends with " + end_str + " " + str1End);
   System.out.println(str2 + " ends with " + end_str + " " + str2End);
 
 }
}

It’s time to apply your learning to some practical examples

  1. Write a Java program to get the contents of a given string as a byte array.
  2. Write a Java program to get the contents of a given string as a character array.
  3. Write a Java program to get the last index of a string within a string.
  4. Write a java program to get the length of a given string.
  5. Write a Java program to replace all the characters with given character. For example replace all ‘a’ character with ‘A’ in a given string.
  6. Write a java program to replace all the Strings with given String. For example replace all “with” String with the “from” in a given string.
  7. Write a java program to get the substring from a given string from the particular position.
  8. Write a java program to convert all the character to upper case of a given String.

Related Post

Leave a Reply

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