Java String Methods : How To Create And Methods Of Java String

Updated on September 3, 2024

Article Outline

Java language has many methods for manipulating strings. The sooner you understand these methods, the more effectively you can handle strings in your Java applications. It provides a multitude of methods through which to perform operations on strings. Understanding these methods is the key to effective string handling. This article explains a variety of methods in Java String Methods and shows examples of those methods.

What is a String in Java?

A string is a sequence of characters that shows text. The class String belongs to the package “Java.lang” and is one of the most common types of data used to handle text in Java programs. This class contains many methods through which text may be manipulated and interrogated; hence, it provides the textual data process efficiency.

Using  char[] array in Java

class Main{ public static void main(String args[]){ char ch[]  = { 'N','E','E','R','A','J'} ; System.out.println(ch) ; } }

Output

NEERAJ

Using String class in Java

 

The following program demonstrates the use of String in Java: 

class Main{ public static void main(String args[]){ String name ="Neeraj Kumar " ; System.out.println(name) ; } }

Output

NEERAJ
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

How to Create a String Object?

There are two ways to make the String Object:

 

  • Using String Literal
  • Using new keyword

String Literal and String Constant Pool 

In computer science, a literal is a notation representing a value. A Java string literal can be created and represented using double quotes. All of the content/characters can be added between the double quotes.

 

The following program demonstrates the String Literal:

 

Program

 

class Main{ public static void main(String args[]){ String value =  "Neeraj Kumar" ; System.out.println(value);   } }

Output 

Neeraj Kumar

String Constant Pool

 

The String Constant Pool, also known as the String Intern Pool, is a special memory area in the Java Virtual Machine (JVM). It stores string literals and provides memory efficiency and performance optimization for strings.

 

Example

 

String str1 = “Neeraj Kumar”;

 

String str2 = “String 2 stored  here”;

 

In the above example, it is the only string object created in the string constant pool when two strings are created using the string literal method.

By New Keyword 

The ‘new’ keyword in Java creates objects dynamically at runtime when you use the ‘new’ operator. This operator allocates memory for a new object or array and returns a reference to that memory location.  Unlike string literals, these objects allocate separate memory space in the heap, regardless of whether the same value already exists in the heap or not.

 

Syntax

 

String stringName = new String(“string_value”);

 

The following program demonstrates the new keyword. 

 

Program

class Main{ public static void main(String args[]){ String ob = new String("Neeraj Kumar") ; System.out.println(ob) ; } }

Output

Neeraj Kumar

Example of Strings in Java 

The following program demonstrates the strings in Java language.

 

Program

class Main{ public static void main(String args[]){ System.out.println("Strings in Java") ;   String val1 = "Personal Value" ; System.out.println(val1);   String val2 = new String("Water Computer") ; System.out.println(val2) ;   String val3 =  val1 + val2 ;   System.out.println(val3)  ; } }

Output

Strings in Java Personal Value Water Computer Personal ValueWater Computer

Methods of Java Strings

●    int length() Method

 

The length() method of string in Java. It is used to get the string length in the Java program.

 

Syntax:

 

stringName.length() 

 

The following program demonstrates the length() method:

 

Program         

class Main{ public static void main(String args[]){ String genre = "action"  ; int genreLength = genre.length();   System.out.println(genreLength); } }

Output

6

●    char charAt(int index) Method

The charAt() method retrieves a character from a string at a specific position.It is particularly useful when accessing individual characters within a string for comparison, analysis, or processing.

 

The following program demonstrates the charAt(int index) Method:

 

Program

class Main2 { public static void main(String[] args) { String text = "Hello, World!";   char firstChar = text.charAt(0); System.out.println("Character at index 0: " + firstChar);   char eighthChar = text.charAt(7); System.out.println("Character at index 7: " + eighthChar);   try { char invalidChar = text.charAt(20);   }   catch (Exception e) { System.out.println("Invalid index! " + e.getMessage()); } } }

Output

Character at index 0: H Character at index 7: W Invalid index! String index out of range: 20

●    String concat(String string1) Method

The ‘concat()’ method joins two strings together. It is a powerful method that connects one string to the end of another, resulting in a new string.

 

Method Signature

 

public String concat(String str1)

 

The following program demonstrates the String concat() Method: 

            

Program

class Main{ public static void main(String args[]){ String str1 = "Hello" ; String str2 = "World" ;   String result = str1.concat(" "+ str2) ; System.out.println(result); } }

Output

Hello World

●    String substring(int beginIndex, int index[optional]) method

 

The substring() method extracts the string portion from the substring. This method is useful when you are working on the specific parts of a string rather than the entire string.

 

The following program demonstrates the substring() method in Java:

 

Program

class Main2 { public static void main(String[] args) { String text = "Hello, World!";   String subText1 = text.substring(7); System.out.println("Substring from index 7: " + subText1);   String subText2 = text.substring(0, 5); System.out.println("Substring from index 0 to 5: " + subText2);   try { String validText = text.substring(7, 20);   } catch (Exception e) { System.out.println("Error Problem"); } } }

Output 

Substring from index 7: World! Substring from index 0 to 5: Hello Invalid index! String index out of range: 20

●    String.equals(String anotherString) method

The equals() method compares two strings for equality. It returns true if the strings are identical; otherwise, it returns false. If the specified string is ‘null’ , the method will return ‘false’, as a non-null string cannot be equal to ‘null’.

 

Method Signature

 

public boolean equals(Object anotherString)

The following program demonstrates the String.equals() method:

 

Program

class Main{ public static void main(String []args){ String str1 = "Hello" ; String str2 = "Hello" ; String str3 = "Hello" ; System.out.println(str1.equals(str2)); System.out.println(str1.equals(str3)); System.out.println(str1.equals(null)); } }

Output

true true false

●    String contains (String substring) Method

The contains() method in Java checks if a string contains a specified substring. If the string contains the specific string, It will return true. Otherwise, it will return false.

The following program demonstrates the String contains method:

 

Program

class Main{ public static void main(String args[]){ String str1 = "Welcome to the Java language" ; String substring = "Java language" ; String substring2 = "Python language" ;   if(str1.contains(substring)){ System.out.println("The string contains the substring "+substring) ;   }else{ System.out.println("This string does not contain the substring "+substring);   }   if(str1.contains(substring2)){ System.out.println("The string contains the substring "+substring2);   }else{ System.out.println("The string does not contain the substring "+substring2); } } }

Output

This string does not contain the substring Java language The string does not contain the substring Python language

●    String join() method

The ‘join()’ method in Java concatenates the elements of a sequence(like an array or an iterable) into a single string, with each element separated by a specified delimiter. This method was introduced in Java 8.

 

The following program demonstrates the String join() method:

 

Program 

import java.util.Arrays; import java.util.List; public class StringJoinExample { public static void main(String[] args) { String[] words = {"Hello", "World", "Java"}; String joinedWords = String.join(" ", words); System.out.println("Joined String Array: " + joinedWords);   String[] languages = {"Java", "Python", "C++"}; String joinedLanguages = String.join(", ", languages); System.out.println("Joined Languages with Comma: " + joinedLanguages);   List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); String joinedNames = String.join(" | ", names); System.out.println("Joined Names with Pipe: " + joinedNames);   String[] emptyArray = {}; String joinedEmptyArray = String.join(", ", emptyArray); System.out.println("Joined Empty Array: '" + joinedEmptyArray + "'"); } }

Output

Joined String Array: Hello World Java Joined Languages with Comma: Java, Python, C++ Joined Names with Pipe: Alice | Bob | Charlie Joined Empty Array: ''

●    String toUpperCase() Method

 

The toUpperCase() method is a string method in Java. It converts the string’s lowercase characters to uppercase (or capital) characters.

 

The following program demonstrates the toUpperCase() Method:

 

Program

class Main{ public static void main(String args[]){ String name = "holidaycomputer" ; System.out.println(name.toUpperCase()); } }

Output

HOLIDAYCOMPUTER

●    String toLowerCase() Method

The ‘toLowerCase()” method converts all the characters into their lowercase equivalents. It is part of the ‘String’ class and It is very useful for case-insensitive comparison or standardizing text.

 

The following program demonstrates the “toLowerString()” method:

 

Program

class Main{ public static void main(String args[]){ String name = "NEERAJKUMAR" ; System.out.println(name.toLowerCase()); } }

Output

neerajkumar

●    String trim() Method

The string trim() method in Java trims or removes the extra white space from the specified string at both ends.

The following program demonstrates the trim() method:

 

Program

public class Main { public static void main(String[] args) { String str = "   Hello World!   "; String trimmedStr = str.trim(); System.out.println("Original: '" + str + "'"); System.out.println("Trimmed: '" + trimmedStr + "'"); } }

Output

Original: '   Hello World!   ' Trimmed: 'Hello World!'

●    String replace(char oldChar, char newChar)

The replace() method in Java is a string manipulation tool that allows you to replace occurrences of a specific character or sequences of characters in a string with another character or sequence. This method is particularly useful when modifying dynamic strings during runtime.

 

The following program demonstrates the replace() method:

 

Progra 

class Main{ public static void main(String args[]){ String str= "Neeraj Kumar Voldemort" ; String newStr = str.replace('I', 'p') ; System.out.println(newStr) ; } }

Output

Neeraj Kumar Voldemort

Conclusion

To handle strings and process data efficiently, like string manipulation, we must know Java’s methods. These methods (e.g., charAt(), concat, etc.) allow developers to carry out tasks on strings, such as accessing a character, concatenating multiple strings together, extracting part of the string, or replacing one letter or sequence in another. Some of these techniques are the backbone for many text-based applications. Knowing how they are used can lead to the writing of cleaner and more concise Java source code.

FAQs
The concat() method in string adds the specified string to the end of the current string in the Java program. It is essential to combine two strings into one.
The ‘trim()’ method removes spaces from a string. It can remove spaces, tabs, and other whitespace characters.
The split(String regex)’ method splits the string into an array of substrings based on the specified regular expression delimiter.
The “contains()” method checks if the given string of characters is present within a string or a collection. If it is, then return true; otherwise, return false.
The replace(char oldChar, char newChar) for example “hello”.replace(‘1’, ‘x’) returns ‘hexxo’.

Updated on September 3, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved