Cookie Consent Preference

By clicking "Accept", you agree to store cookies on your device.

HudaTutorials.com

java lang String Class

Last updated on

java.lang.String Class

String Class in Java

The Java String class represents character strings. A Java string literal consists of zero or more characters enclosed in double quotes. Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings. All Java string literals in Java programs, such as "abc", are implemented as instances of Java String class. Java String class objects are immutable, Java String class objects values cannot be changed after Java String class objects are created.

Java String class includes methods

  1. for examining individual characters of the sequence
  2. for comparing strings, for searching strings
  3. for extracting substrings
  4. for creating a copy of a string with all characters translated to uppercase or to lowercase

Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values). Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

What is java.lang.String in Java ?

The java.lang.String is a class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of the java.lang.String class. Strings are constant, their values cannot be changed after they are created. The class java.lang.String is available in java.lang package.

What are Strings in Java

Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character '\0'. Below is the basic syntax for declaring a string in Java programming language.

Syntax :

String <string variable> = "<character sequence>";

How to use String Class as StringTokenizer Class in Java ?

Java String class is used like Java StringTokenizer class by using the Java String class split method.

Java StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of Java String class or the java.util.regex package instead.

How to split String in Java ?

The split method of String class breaks a given string around matches of the given regular expression. The String's split method takes two parameters. One is regular expression as String. Another is int as limit. The split method returns an array of strings computed by splitting the given string.

The following example illustrates how the String.split method can be used to break up a string into its basic tokens at each space :

java.lang.String Class split method Example

/*  Java String Class split method Example
    Save with file name StringSplitMethodExample.java */
public class StringSplitMethodExample
{
	public static void main(String args[])
	{
		String[] result = "this is a test".split("\\s");
		for (int x=0; x < result.length; x++)
		{
				System.out.println(result[x]);
		}
	}
}

Splitting a Java String by the pipe symbol using split("|") ?

String s = "111206|00:00:00|2|64104|58041";
String [] temp = s.split("\\|");

This is because the split method takes a regular expression, and | is one of the special characters. It means 'or'. That means you are splitting by '' or '', which is just ''. Therefore it will split between every character. You need two slashes because the first one is for escaping the actual \ in the string, since \ is Java's escape character in a string. Java understands the string like "\|", and the regex then understands it like "|".

How to split String with || ?

String[] arrStrColumnsInRow=strHeader.split("\\|\\|");

This is because the parameter of split is a regular expression, where | is a logical operator. Pattern.quote create the escaped version of the regex representing |

Following java.lang.String example you can learn how to create java.lang.String and how to use java.lang.String.

java.lang.String Example without Constructor

/*  java.lang.String Example without Constructor
    Save with file name StringExample1.java */
public class StringExample1
{
	public static void main(String args[])
	{
		// java.lang.String DECLARATION
		String s1;
		// ASSIGN A VALUE to java.lang.String WITHOUT CONSTRUCTOR
		s1 = "Huda Tutorials";
		// java.lang.String OUTPUT
		System.out.println("java.lang.String value : " + s1);
	}
}

java.lang.String Example with Default Constructor Example

/*  java.lang.String Example with Default Constructor
    Save with file name StringExample2.java */
public class StringExample2
{
	public static void main(String args[])
	{
		// java.lang.String DECLARATION
		String s1;
		// CREATE INSTANCE for java.lang.String USING DEFAULT CONSTRUCTOR
		// THE VALUE OF STRING IS EMPTY
		s1 = new String();
		// java.lang.String OUTPUT EMPTYSTRING
		System.out.println("String value : " + s1);
	}
}

java.lang.String Example with Parameter Constructor Example

/*  java.lang.String Example with Parameter Constructor
    Save with file name StringExample3.java */
public class StringExample3
{
	public static void main(String args[])
	{
		// java.lang.String DECLARATION
		String s1;
		// CREATE INSTANCE of java.lang.String USING PARAMETER CONSTRUCTOR
		s1 = new String("Huda Tutorials");
		// java.lang.String OUTPUT
		System.out.println("String value : " + s1);
	}
}

How do I convert String to String array in Java ?

You can convert String to String array using java.lang.String's split method. The split operation convert given String into String Array. The following Java String to String Array example shows how to convert String object to String array in Java using split method.

How to convert String to String Array in Java Example

/*  Java String to String Array Example
  This Java String to String Array example shows
  how to convert String object to String array in Java
  using split method. */
public class JavaStringToStringArrayExample
{
	public static void main(String args[])
	{
		//String which we want to convert to String array
		String str = "Java String to String Array Example";
		String stringArray[] = str.split(" ");
		System.out.println("String converted to String array");
		//print elements of String array
		for(int i=0; i < stringArray.length; i++)
		{
			System.out.println(stringArray[i]);
		}
	}
}

Output of Java String to String Array Example would be
String converted to String array
Java
String
to
String
Array
Example

How do I convert String to String array in Java without using built-in methods ?

The following program shows how to covert String into String array, or Split a String without using built-in methods in java.

How to convert String to String Array in Java without using built-in methods Example

public class JavaStringToStringArrayExample
{
	public static void main(String[] args)
	{
		// String which we want to convert to String array
		String string1 = "Java String to String Array Example";
		String[] stringArray = customSplit(string1);
		for (int i = 0; i < stringArray.length; i++)
		{
			System.out.println(stringArray[i]);
		}
	}
	
	static String[] customSplit(String st)
	{
		// converts string into character array
		char ch[] = st.toCharArray();
		int count=0;
		// to count number of words
		for (int i = 0; i < ch.length; i++)
		{
			if (ch[i]==' ')
			{
				count++;
			}
		}
		String str[] = new String[count+1];
		int k = 0;
		str[k] = "";
		for (int i = 0; i < ch.length; i++)
		{
			if (ch[i] != ' ')
			{
				// concatenate each character of a word
				str[k] = str[k] + ch[i];
			}
			else
			{
				k++;
				str[k] = "";
			}
		}
		return str;
	}
}

Output of Java String to String Array Example would be
String converted to String array
Java
String
to
String
Array
Example

How to Concatenate String in Java ?

You can concatenate strings using + operator and concat method of java.lang.String class. The java.lang.String.concat() method concatenates the specified string to the end of this string.

java.lang.String Example with Concatenation Example

/*  java.lang.String Example with Concatenation
    Save with file name StringExample4.java */
public class StringExample4
{
	public static void main(String args[])
	{
		// java.lang.String DECLARATION
		String s1;
		// ASSIGN A VALUE WITH CONCATINATION
		s1 = "Huda" + "Tutorials";
		// java.lang.String OUTPUT
		System.out.println("String value : " + s1);
		String str1 = "Huda";
		String str2 = str1.concat("Tutorials");
		// CONCATENATED STRING
		System.out.println("Concatenated String value : " + str1);
	}
}

java.lang.String Class Using Parameter Constructor Example

/*  java.lang.String Example
    Save with file name StringExample.java  */
public class StringExample
{
	public static void main(String args[])
	{
		// java.lang.String DECLARATION
		String s1;
		// CREATE java.lang.String INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new String("Huda Tutorials");
		// java.lang.String OUTPUT
		System.out.println("String Value : " + s1);
		System.out.println("String Length : " + s1.length());
		System.out.println("charAt 3 : " + s1.charAt(3));
		System.out.println("indexOf a : " + s1.indexOf("a"));
		System.out.println("lastIndexOf a : " + s1.lastIndexOf("a"));
		System.out.println("isEmpty : " + s1.isEmpty());
		System.out.println("startsWith Huda : " + s1.startsWith("Huda"));
		System.out.println("substring : " + s1.substring(5));
		System.out.println("toLowerCase : " + s1.toLowerCase());
		System.out.println("toUpperCase : " + s1.toUpperCase());
	}
}

How to Compare two Strings in Java ?

Strings can be compare following ways

  1. == : Tests for reference equality (whether they are the same String objects).
  2. String.equals() : In Java, string equals() method compares the two given strings based on the data or content of the string. If all the contents of both the strings are same then it returns true. If all characters do not match, then it returns false.
  3. String.equalsIgnoreCase() : The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and the contents of both the Strings are same ignoring case, else false.
  4. String.compareTo (String anotherString) : Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the String.equals(Object) method would return true.
  5. String.compareToIgnoreCase (String str) : Compares two strings lexicographically, ignoring case differences. This method returns an integer whose sign is that of calling compareTo with normalized versions of the strings where case differences have been eliminated by calling Character.toLowerCase (Character.toUpperCase (character) ) on each character. Note that this method does not take locale into account, and will result in an unsatisfactory ordering for certain locales. The java.text package provides collators to allow locale-sensitive ordering.
  6. String.contentEquals() : Compares the content of the String with the content of any CharSequence (available since Java 1.5).
  7. Objects.equals() : Objects.equals() checks for null before calling .equals() so you don't have to (available as of JDK7, also available in Guava).

Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().

java.lang.String Comparison Example

/*  java.lang.String Comparison Example
    Save with file name StringComparison.java */
public class StringComparison
{
	public static void main(String args[])
	{
		// java.lang.String DECLARATION
		String s1, s2;
		// CREATE java.lang.String INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new String("Huda Tutorials");
		s2 = "huda tutorials";
		// java.lang.String OUTPUT
		System.out.println("equals : " + s1.equals(s2));
		System.out.println("equalsIgnoreCase : " + s1.equalsIgnoreCase(s2));
		System.out.println("compareTo : " + s1.compareTo(s2));
		System.out.println("compareToIgnoreCase : " + s1.compareToIgnoreCase(s2));
		System.out.println("contentEquals : " + s1.contentEquals(s2));
	}
}

java.lang.String String Find

/*  java.lang.String String Find Example
    Save with file name StringFind.java */
public class StringFind
{
	public static void main(String args[])
	{
		// java.lang.String DECLARATION
		String s1, s2;
		// CREATE java.lang.String INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new String("Huda Tutorials");
		s2 = "Tutorials";
		// java.lang.String OUTPUT
		System.out.println("contains : " + s1.contains(s2));
		System.out.println("endsWith : " + s1.endsWith(s2));
		System.out.println("indexOf : " + s1.indexOf("a"));
		System.out.println("indexOf from 5th Character : " + s1.indexOf("a",5));
		System.out.println("lastIndexOf : " + s1.lastIndexOf("t"));
		System.out.println("lastIndexOf from 8th Character : " + s1.lastIndexOf("t",8));
	}
}

How to Format String in Java ?

The most common way of formatting a string in java is using String.format() method. If there were a Java sprintf then this would be it.
String output = String.format("%s", "Format String");
For formatted console output, you can use printf() or the format() method of System.out and System.err PrintStreams.
System.out.printf("My name is: %s%n", "Format String using printf");

String Format Specifiers

Following are all the conversion specifiers supported in Java String format.

Specifier Applies to Output
%a floating point Hex output of floating point number
%b Any type true if non-null, false if null
%c character Unicode character
%d integer (incl. byte, short, int, long, bigint) Decimal Integer
%e floating point decimal number in scientific notation
%f floating point decimal number
%g floating point decimal number, possibly in scientific notation depending on the precision and value.
%h any type Hex String of value from hashCode() method.
%n none Platform-specific line separator.
%o integer (incl. byte, short, int, long, bigint) Octal number
%s any type String value
%t Date/Time (incl. long, Calendar, Date and TemporalAccessor) %t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%x integer (incl. byte, short, int, long, bigint)

Hex string.

java.lang.String Manipulation

/*  java.lang.String Manipulation Example
    Save with file name StringManipulation.java */
public class StringManipulation
{
	public static void main(String args[])
	{
		// java.lang.String DECLARATION
		String s1, s2;
		// CREATE java.lang.String INSTANCE USING PARAMETER CONSTRUCTOR
		s1 = new String("HudaTutorials");
		s2 = ".com";
		// CONCATINATING S1 AND S2 BUT S1 VALUE WON'T CHANGE
		s1.concat(s2);
		System.out.println("concat : " +s1);
		// IF YOU WANT TO CHANGE S1 VALUE YOU SHOULD USE LIKE THIS
		s1 = s1.concat(s2);
		System.out.println("concat : " +s1);
		// REPLACE PART OF A STRING
		System.out.println("I am a Programmer".replace("I am","You are"));
		// PART OF A STRING
		System.out.println("A1234".substring(1));
		// PART OF A STRING
		System.out.println("A1234".substring(1,3));
		// TRIM
		System.out.println("   ABC   ".trim());
		// FORMATTED INT OUTPUT LIKE C
		System.out.println(String.format("%d", 77));
		// FORMATTED INT OUTPUT 5 DIGITS LIKE C
		System.out.println(String.format("%5d", 77));
		// FORMATTED INT OUTPUT 5 DIGITS WITH LEADING ZEROS LIKE C
		System.out.println(String.format("%05d", 77));
		// FORMATTED FLOAT OUTPUT LIKE C
		System.out.println(String.format("%10.2f", 77.55));
	}
}