Categories: Java

Strings in Java

Strings are Objects in Java that are internally backed by a char array. They are immutable because arrays are immutable (they can’t grow). Every time you make a change to a String, a new String is created.

An array of characters functions similarly to a Java string. Consider the following scenario:

char[] ch={'c','o','d','e','r','z','p','y'};  
String s=new String(ch);  

is the same as:

String s="coderzpy";  

The Serializable, Comparable, and CharSequence interfaces are implemented by the Java String class, as shown in the diagram below.

Interface for CharSequences:


To represent a sequence of characters, the CharSequence interface is used. It is implemented by the String, StringBuffer, and StringBuilder classes. This means that these three classes can be used to create strings in Java.

Memory allotment of String

A String Object will be created in the string constant pool whenever it is created as a literal. This allows JVM to optimize String literal initialization.

The string can also be dynamically allocated by using the new operator. Strings that are dynamically allocated are given a new memory location in the heap. The string constant pool will not include this string.

For instance:

String str = new String("Coderzy");
Example to declare String :
// Java code to illustrate String
import java.io.*;
import java.lang.*;

class Test {
 public static void main(String[] args)
 {
  // Declare String without using new operator
  String s = "student at";

  // Prints the String.
  System.out.println("String s = " + s);

  // Declare String using new operator
  String s1 = new String("Coderzpy");

  // Prints the String.
  System.out.println("String s1 = " + s1);
 }
}
Output:
String s = student at
String s1 = Coderzpy

Note: also read about the Interface vs Abstract class

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago