top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

String In Java

String in java

In java, String is an object that represents sequence of charactactes, String is widely used object in java and you will interact with String a lot when you work on any java project, most of the object that we deal in a project are String objects, example (name, account number, email etc...).


The java.lang.String class is used to create a string object.


How to Declaring the String

1. char[] ch={‘w’,’e’,’l’,’c’,’o’,’m’,’e’};

2. String s=new String(ch);

is same as:

1.String s="welcome";


There are two ways to create String object:

1. By string literal

2. By new keyword

Before we start to understand these two ways, let's first understand the memory allocation used for String objects.

String either created in pool or heap memory.

Heap memory

“Heap” memory, also known as “dynamic” memory, is an alternative to local stack memory. Local memory is quite automatic. Local variables are allocated automatically when a function is called and they are deallocated automatically when the function exits.Java Heap Space is used throughout the application.

String Pool

String pool is a storage space in the Java heap memory where string literals are stored. It is also known as String Constant Pool or String pool.




1.String literal

java string literal is created by using double quotes.

String str1=” Apple ”;

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool.

Consider above diagram

String str1=” Apple ”;

String str3= “Apple ”;//(It check the string pool if string is already exist ,it does not create

another string, only the reference is passed)

2.New keyword

Using ‘new ‘keyword string object will be created into heap memory .


Immutable String

An immutable object is an object which cannot be changed. String is an example for an immutable object in Java. Once an object of String is created, we cannot change it or modified

String srt1=”Apple”;

String str1=”Pear ”



However, we can change the value of variable, it can create new instance in string pool and pass the reference to the new object.

String immutability helps in saving a lot of Java heap space because different String variables can refer to the same String object in the pool.

So...

How to update and modify the existing String, java provide StringBuffer and StringBuilder classes provide methods to manipulate strings. whenever we do String manipulation like concatenation, substring, etc. it generates a new String and discards the older String for garbage collection. These are heavy operations and generate a lot of garbage in heap. So Java has provided StringBuffer and StringBuilder classes that should be used for String manipulation. They provide append(), insert(), delete(), and substring() methods for String manipulation.


Lets see the difference


​String

StringBuffer

StringBuilder

Storage

String can be store in heap as well as string constant pool .

StringBuffer store in Heap area.

StringBuilder also store in Heap area.

Object

String creates immutable object.

StirngBuffer creates mutable object.

StringBuilder creates mutable object.

​Memory

Each time when we change the string, it creates new string object thus allocates new memory. More memory will be occupied.

In this case string object is mutable, whenever we are trying to change the string,it will change in the existing string so consumes less memory.

In this case string object is mutable, whenever we are trying to change the string, it will change in the existing string so consumes less memory.

Thread safe

Strings methods are not synchronized that’s why string is not thread safe.

StringBuffer methods are synchronized that’s why StringBuffer is thread safe.

StringBuilder methods are not synchronized that’s why string is not thread safe.

​Performance

As per the performance String is slow.

StringBuffer is faster than string .

StringBuilder is faster than StingBuffer.


What is thread-safe?

A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads.


Java String Class Methods

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

1.length () – Used to find length of string

eg String Str1=” Hello”

Output - 5


2.concat () – Used to join two string

eg String str1=’’Hello”;

String str2=” World”

Str1.concat(Str2)

Output - HelloWorld


3.equals() - we can make comparisons between two strings using the equals() method. Its compares values

eg String str1=’’Hello”;

String str2=” World”;

Str1.equals(Str2)

Output - false


4.contrains () – This method is used to determine whether a substring is part of the main string or not.

eg String str1=”NumpyNinja”;

String str2=”Ninja”;

Str1.contains(str2);

Output – True


5.reverse () -This method is used to reverse the string

eg String str1=”NumPyNinja”;

StringBuffer sb = new StringBuffer(str1);

sb.reverse();

Output - ajniNypmuN


6.split() - Breaks the string into an array of strings.

eg

String text = "Java is a fun programming language";

// split string from space

String[] result = text.split(" ");

System.out.print("result = ");

for (String str : result) {

System.out.print(str + ", ");

Output - result = Java, is, a, fun, programming, language


7.toLowerCase() - converts the string to lowercase.

eg String str1="HELLO";

toLowerCase(str1);

Output - hello


8.toUpperCase() - converts the string to uppercase.

eg String str1="hello";

toUpperCase(str1);

Output - HELLO


9.startsWith() - checks if the string begins with the given string.

eg String str1="Software";

str1.startsWith(Soft);

Output - True

10.endsWith() - The Java String endsWith() method checks whether the string ends with the specified string or not.

eg String str1="software";

str1.endsWith(ware);

output - True


11.toCharArray() - converts the string to a char array.


12.trim() - The trim() method removes any leading (starting) and trailing (ending) whitespaces from the specified string.

eg String str1 = " Learn Java Programming ";

str1.trim();

Output - Learn Java Programming


Conclusion -

String is widely used in java programing. string is immutable so we can’t change the string so to overcome this problem java provide StringBuilder and StringBuffer .Using StringBuilder and StringBuffer we modify the existing String .Strings support many other functionalities, and programmers can use them according to their project requirement.

I hope this blog help you .


303 views0 comments

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page