Published 15 October 2018

How to work with strings in Java

What are strings, what are they used for

What are strings, what are they used for

String — an ordered sequence of symbols, is a carrier of textual information. The following classes are used to work with strings: String, StringBuffer, StringBuilder.

A string is an object that can be created by using the new operator or a string literal. Creating objects using a literal is only possible in the String class.

String hello = "Hello World!";

char[] ch= { 'a', 'b', 'c' };

String st = new String(ch);

Strings are used when debugging, working with text, specifying file names and URLs as parameters to methods.

Methods of working with strings

Methods of working with strings

The functionality of the String class is defined through its methods:

  • сoncat, concatenates strings by appending to the end;
  • valueOf, a string representation of the passed argument data type;
  • сompare, compares two strings;
  • charAt, returns the character by index;
  • equals, compares the string, case-sensitive;
  • regionMatches, compares whether two substrings are equal in a string;
  • indexOf, returns the index of the first occurrence of a substring in a string;
  • lastIndexOf, returns the index of the last occurrence of a substring in a string;
  • replace, returns a new string by replacing one substring with another in the string;
  • trim, returns a copy of the string removing the leading and trailing space;
  • substring, returns a new string that is a substring of this string;
  • toLowerCase, translates all the characters in the string to lower case;
  • toUpperCase, translates all the string characters to uppercase.

Main string operations

Main string operations

You can use addition "+", concat(), join() methods to join strings.

String s="Hello"; String s1="World!"; String s3=s+" "+s1;

String s=" World!"; String s1="Hello"; s1=s1.concat(s);

String s2 = String.join(" ",s1, s);

equals() (case-sensitive) and equalsIgnoreCase() (case-insensitive) methods are used to compare strings.

String s = "Hello World!";

String s1 = "hello world!";



The following methods are used to search the string: indexOf() - finds the index of the first occurrence of a substring in a string, lastIndexOf() - the index of the last occurrence.

String s="Hello credits!";

int id1 = s.indexOf("ed");

int id2 = s.lastIndexOf('e');

Use the replace() method to replace one character sequence with another in a string.  

String s = "Hello credits!";

String s1 = s.replace("Hello","Bye");

The methods to change case are: toLowerCase() - translates the string characters to lowercase, toUpperCase() - to upper case.

String s = "Hello credits!";



Votes 0, average rating 0