Tutorials Hut

Java String

Java String is non primitive data types, it is a class used to hold multiple characters or sequence of characters or words.

String provides different methods to manipulate value of string and perform operations.

Syntax to Create Java String

String <string variable name> = “value of string”;

Example of Java String

public class StringTest {
	public static void main(String[] args) {
//Simple String example String simpleString = "I am a string value.";
//Created a string from Integer class Integer number = 10; String numString = number.toString();
//Created string from char sequences char[] charSequence = {'h', 'e', 'l', 'l', 'o'}; String strOfChars = new String(charSequence);
System.out.println("simpleString = "+simpleString); System.out.println("numString = "+numString); System.out.println("strOfChars = "+strOfChars); } }

Output:

simpleString = I am a string value.
numString = 10
strOfChars = hello

Java String is Immutable

String class is immutable by default which means we can’t mutate or change value of it later on. This is very useful behaviour because if want to use any class as a key to certain values then String becomes our first choice because it will be safe from any change in future.

Any operation which creates another string won’t change existing string value but new will be created.

String buffer is another class similar to string which is mutable, if you need to mutate or do a lot of operation then it is better to use.

String Concatenation

We can concatenate two strings and make one single string as well, there are two ways to do it, by using concatenate() method or by simily using + operator between two strings.

Example of String Concatenation

String str1 = “World”;
String str2 = “ war”;
String finalString = str1 + str2;
String anotherFinalString = str1.concate(str2)

Java String Formatter (format)

String class has useful method format() which can format string with values and return back new update string.

Java Format Method Signature

public static String format(String format, Object… args)
public static String format(Locale locale, String format, Object… args)

Parameters:

  • locale: specifies local method to apply on formatter.
  • format: input string format.
  • args: arguments to be applied on string.

Returns:

string

Java String format Example

public class StringFormat {
public static void main(String[] args) {
     String name = "John";
     String str1 = String.format("my name is %s", name);
     String str2 = String.format("float value is %f ",12.34f);
     String str3 = String.format("integer value is %d ",14);
     System.out.println("str1 = "+str1);
     System.out.println("str2 = "+str2);
     System.out.println("str3 = "+str3);
}
}

 

Output:

str1 = my name is John
str2 = float value is 12.340000
str3 = integer value is 14

Methods of String Class

Below are some useful methods of string class to do some manipulation on any string.

  1. substring() – This is very useful method to get part of an existing string , example if you want to get some specific word or a specific part of string then can use this method to substring the actual string.
  2. charAt() – Returns char at any specific position in string.
  3. compareTo – Compares two strings lexicographically.
  4.  compareToIgnore() – Compares two string but ignores case difference.
  5. concat – Concats two strings together and returns one concatenated string.
  6.  contains() – Checks if string contains any specific string passed to method.
  7. equals- Checks if two string values are equal or not and returns boolean true or false.
  8. equalsIgnore() – Checks if two string values are equal or not but ignores case of string(upper or lower case difference)
  9. indexOf – This method returns index or position of a string (passed as argument) in a string.
  10. isEmpty() – Checks if string is empty.
  11. replace() – Replaces matching string.
  12. replaceAll – Replaces all matching string values.
  13. replaceFirst() – Replaces first matching string.
  14. toUpperCase() – Converts all letters of string to upper case.
  15. toLowerCase() – Converts all letters of string to lower case.
  16. trim() – Removes spaces from both ends of string.

Example of String Methods

public class StringMethodsExample {
public static void main(String[] args) {
String tempString = "Tom works hard";
String subString = tempString.substring(0,3);
System.out.println(subString);
char charAt = tempString.charAt(0);
System.out.println(charAt);
String concat = tempString.concat(". he finishes his work perfectly.");
System.out.println(concat);
boolean isStringEqual = "Tom".equals("Tom");
System.out.println(isStringEqual);
boolean isEmpty = tempString.isEmpty();
System.out.println(isEmpty);
String replaceString = tempString.replace("Tom", "John");
System.out.println(replaceString);
String toLower = tempString.toLowerCase();
System.out.println(toLower);
String trimString = " Tom works hard ".trim(); // see there are spaces at start and end of string
System.out.println(trimString);
boolean contains = tempString.contains("Tom");
System.out.println(contains);
}
}

Output:

Tom
T
Tom works hard. he finishes his work perfectly.
true
false
John works hard
tom works hard
Tom works hard
true

Java String Split

Java string class has split method which takes a regex and can split string into array based o regex match.

Example:

String str = "tutorias@study@only";
String[] arrOfStr = str.split("@", 2);

This will split the string into array of string {“tutorias”, study@only}

References

Reference articles from Oracle on String.

Next Article To Read

You may be interested to read next articles- 


















  • Leave a Reply

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