AppDividend
Latest Code Tutorials

Java String Class Example | String Class in Java Tutorial

0

Java String Class Example | String Class in Java Tutorial is today’s topic. In Java,  String is a class which deals with all that is written in double quotation marks, or other words string is a collection of characters. For example – “Java” is a String of length 4.  Every string is an instance of this class. They are immutable, and so once written, and their value cannot be changed. See the following figure.

 

Java String Class Example

The string is a sequence of characters. In Java, objects of String are immutable, which means a constant and cannot be changed once created. The java.lang.String class provides the lot of functions to work on the string. By the help of these functions, we can perform the operations on string such as trimming, concatenating, converting, comparing, replacing strings, etc.

#Why Strings are immutable or final in Java

Strings are used as parameters for many Java classes e.g.

  1. For opening a network connection. 
  2. For opening a database connection. 
  3. For File handling.

In case if strings were not immutable, this would have jeopardized the security.

#How Strings are created in Java

For creating a String, there are two approaches:

  1. Using String Literal.
  2. Using a new keyword. 

#Using String Literal

This is the simplest way to create strings in Java. The syntax is:

String stringName = “Value”;

String name = “Mike”;

String anotherName = “Harvey”;

Now, we know that String is a class in Java, so where is that fancy syntax of creating Objects?

Well, here the compiler takes that responsibility to do that implicitly so that we can save our time and keystrokes!

In this way of creating strings once an object is created(Mahesh) if another instance has the same value as the previously made object then the compiler assigns that previous object to the new instance(anotherName) created thus saving memory. 

But if you don’t want to use that, then you need to use the new operator.

#Using a new keyword

See the following syntax.

String stringName = new String(“Value”); 

See the following example.

String name = new String(“Mike”);
String anotherName = new String(“Mike”);

Now, when we use new operator, every time a new object is created even if the same Value is used. 

So in this case name and anotherName both point to different Mike objects.

See the following code example.

class StringExample
{
   public static void main(String[]args)
   {
	String name = "Mahesh";				// Using String Literal
	String anotherName = new String("Mahesh");	// Using new operator
	System.out.println(name);
	System.out.println(anotherName);
   }
}

See the following output.

 

Java String Class

Now, let’s look at all the methods and constructors provided by the String class. For this, type javap java.lang.String in your Command Prompt/ PowerShell/ Terminal. If an error is displayed, you need to configure your Environment Variables.

See the following text file.

Compiled from "String.java"
public final class java.lang.String implements java.io.Serializable, java.lang.Comparable<java.lang.String>, java.lang.CharSequence {
  static final boolean COMPACT_STRINGS;
  public static final java.util.Comparator<java.lang.String> CASE_INSENSITIVE_ORDER;
  static final byte LATIN1;
  static final byte UTF16;
  public java.lang.String();
  public java.lang.String(java.lang.String);
  public java.lang.String(char[]);
  public java.lang.String(char[], int, int);
  public java.lang.String(int[], int, int);
  public java.lang.String(byte[], int, int, int);
  public java.lang.String(byte[], int);
  public java.lang.String(byte[], int, int, java.lang.String) throws java.io.UnsupportedEncodingException;
  public java.lang.String(byte[], int, int, java.nio.charset.Charset);
  public java.lang.String(byte[], java.lang.String) throws java.io.UnsupportedEncodingException;
  public java.lang.String(byte[], java.nio.charset.Charset);
  public java.lang.String(byte[], int, int);
  public java.lang.String(byte[]);
  public java.lang.String(java.lang.StringBuffer);
  public java.lang.String(java.lang.StringBuilder);
  public int length();
  public boolean isEmpty();
  public char charAt(int);
  public int codePointAt(int);
  public int codePointBefore(int);
  public int codePointCount(int, int);
  public int offsetByCodePoints(int, int);
  public void getChars(int, int, char[], int);
  public void getBytes(int, int, byte[], int);
  public byte[] getBytes(java.lang.String) throws java.io.UnsupportedEncodingException;
  public byte[] getBytes(java.nio.charset.Charset);
  public byte[] getBytes();
  public boolean equals(java.lang.Object);
  public boolean contentEquals(java.lang.StringBuffer);
  public boolean contentEquals(java.lang.CharSequence);
  public boolean equalsIgnoreCase(java.lang.String);
  public int compareTo(java.lang.String);
  public int compareToIgnoreCase(java.lang.String);
  public boolean regionMatches(int, java.lang.String, int, int);
  public boolean regionMatches(boolean, int, java.lang.String, int, int);
  public boolean startsWith(java.lang.String, int);
  public boolean startsWith(java.lang.String);
  public boolean endsWith(java.lang.String);
  public int hashCode();
  public int indexOf(int);
  public int indexOf(int, int);
  public int lastIndexOf(int);
  public int lastIndexOf(int, int);
  public int indexOf(java.lang.String);
  public int indexOf(java.lang.String, int);
  static int indexOf(byte[], byte, int, java.lang.String, int);
  public int lastIndexOf(java.lang.String);
  public int lastIndexOf(java.lang.String, int);
  static int lastIndexOf(byte[], byte, int, java.lang.String, int);
  public java.lang.String substring(int);
  public java.lang.String substring(int, int);
  public java.lang.CharSequence subSequence(int, int);
  public java.lang.String concat(java.lang.String);
  public java.lang.String replace(char, char);
  public boolean matches(java.lang.String);
  public boolean contains(java.lang.CharSequence);
  public java.lang.String replaceFirst(java.lang.String, java.lang.String);
  public java.lang.String replaceAll(java.lang.String, java.lang.String);
  public java.lang.String replace(java.lang.CharSequence, java.lang.CharSequence);
  public java.lang.String[] split(java.lang.String, int);
  public java.lang.String[] split(java.lang.String);
  public static java.lang.String join(java.lang.CharSequence, java.lang.CharSequence...);
  public static java.lang.String join(java.lang.CharSequence, java.lang.Iterable<? extends java.lang.CharSequence>);
  public java.lang.String toLowerCase(java.util.Locale);
  public java.lang.String toLowerCase();
  public java.lang.String toUpperCase(java.util.Locale);
  public java.lang.String toUpperCase();
  public java.lang.String trim();
  public java.lang.String strip();
  public java.lang.String stripLeading();
  public java.lang.String stripTrailing();
  public boolean isBlank();
  public java.util.stream.Stream<java.lang.String> lines();
  public java.lang.String toString();
  public java.util.stream.IntStream chars();
  public java.util.stream.IntStream codePoints();
  public char[] toCharArray();
  public static java.lang.String format(java.lang.String, java.lang.Object...);
  public static java.lang.String format(java.util.Locale, java.lang.String, java.lang.Object...);
  public static java.lang.String valueOf(java.lang.Object);
  public static java.lang.String valueOf(char[]);
  public static java.lang.String valueOf(char[], int, int);
  public static java.lang.String copyValueOf(char[], int, int);
  public static java.lang.String copyValueOf(char[]);
  public static java.lang.String valueOf(boolean);
  public static java.lang.String valueOf(char);
  public static java.lang.String valueOf(int);
  public static java.lang.String valueOf(long);
  public static java.lang.String valueOf(float);
  public static java.lang.String valueOf(double);
  public native java.lang.String intern();
  public java.lang.String repeat(int);
  void getBytes(byte[], int, byte);
  java.lang.String(char[], int, int, java.lang.Void);
  java.lang.String(java.lang.AbstractStringBuilder, java.lang.Void);
  java.lang.String(byte[], byte);
  byte coder();
  byte[] value();
  static void checkIndex(int, int);
  static void checkOffset(int, int);
  static void checkBoundsOffCount(int, int, int);
  static void checkBoundsBeginEnd(int, int, int);
  static java.lang.String valueOfCodePoint(int);
  public int compareTo(java.lang.Object);
  static {};
}

In the StringClass.txt file the second line has:

public final class java.lang.String implements java.io.Serializable, java.lang.Comparable<java.lang.String>, java.lang.CharSequence

Here we can see that String class is final, which means it cannot be extended or inherited, and it implements Serializable, Comparable, and CharSequence interface. 

Serializable means that the state of String objects can be converted into byte code and vice versa. Comparable means objects can be compared. CharSequence makes it accessible to many different kinds of char sequences.

#Constructors

The following are the String Constructors.

#public java.lang.String();

This creates a String object with an empty character sequence.

#public java.lang.String(byte[], int, int);

Creates string using the specified subarray of bytes.

#public java.lang.String(byte[], java.lang.String);

Creates string by decoding the specified array of bytes using the second parameter as charset.

#public java.lang.String(java.lang.StringBuffer);

Creates a string that contains the sequence of characters contained in the string buffer argument.

#public java.lang.String(java.lang.StringBuilder);

Creates a string that contains the sequence of characters contained in the string builder argument.

#Methods

#public char charAt(int);

 Returns the char value at the specified index.

#public int codePointAt(int);

 This method returns a character (Unicode code point) at the specified index.

#public int codePointBefore(int);

Returns a character (Unicode code point) before the specified index.

#public int codePointCount(int, int);   

This method returns a number of Unicode code points in the specified text range of this String. The first parameter is started index and the second is stop index.

#public int compareTo(java.lang.String);

Compares two strings.

#public int compareToIgnoreCase(java.lang.String);

Compares two strings ignoring case. 

#public java.lang.String concat(java.lang.String);

Concatenates the specified string to the end of this string.

#public boolean contains(java.lang.CharSequence);

Returns true if this string contains the specified sequence of char values.

#public boolean isEmpty();

Returns true if the length of the string is zero.

#public int length();

Returns length of the string.

#public int hashCode();

Returns a hash code for this string.

#public int indexOf(java.lang.String);

Returns an index within this string of the first occurrence of the specified substring.

#public int indexOf(java.lang.String, int);

Returns an index within this string of the first occurrence of the specified substring starting at the index supplied in the second parameter.

#public java.lang.String replace(char, char);

Returns the new string resulting from replacing all occurrences of the first parameter with the second parameter.

#public java.lang.String replaceFirst(java.lang.String, java.lang.String);

Replaces the first substring of this string that matches the given replacement.

#public java.lang.String replaceAll(java.lang.String, java.lang.String);

Replaces every substring that matches the given replacement.

#public boolean startsWith(java.lang.String);

Return true if the string starts with the supplied string. 

#public boolean startsWith(java.lang.String, int);

Return true if the string starts with the supplied string starting from the offset supplied at the second parameter.

#public boolean endsWith(java.lang.String);

Return true if a string ends with the supplied string. 

#public boolean equalsIgnoreCase(java.lang.String);

Compares this String to another String, ignoring case.

#public java.lang.String toLowerCase();

Converts the String to lower case using the rules of the default locale.

#public java.lang.String toLowerCase(java.util.Locale);

Converts the String to lower case using the rules of the given locale.

#public java.lang.String toUpperCase();

Converts this String to upper case using the rules of the default locale.

#public java.lang.String toUpperCase(java.util.Locale); 

Converts this String to upper case using the rules of the supplied locale.

See the following code example.

class UpperLowerExample
{
   public static void main(String[]args)
   {
	String food = new String("Pizza");
	System.out.println(food.toLowerCase());		//Prints lower case String
	System.out.println(food.toUpperCase());		//Prints upper case String	
   }
}

See the following output.

 

String Class in Java

#public java.lang.String trim();

Returns a copy of the string, with leading and trailing whitespace omitted.

#public java.lang.String toString();

Returns the String itself.

class FinalExample
{
	public static void main(String[]args)
	{
		String food = " Pizza";
		String person = "John";
		String verb = " loves";
		String concatenate = person.concat(verb);	//Concatenates verb at the end of person 
		System.out.println(concatenate.concat(food));	//Concatenates food at the end of concatenate
		System.out.println(concatenate.charAt(5));	//Prints Sixth character of concatenate
		System.out.println(concatenate.length());	//Prints length of concatenate 
		System.out.println(concatenate.hashCode());	//Prints hash code of concatenate 
		System.out.println(concatenate.isEmpty());	//Checks if concatenate is empty or not
		System.out.println(concatenate.contains("loves")); //Checks if concatenate contains loves
	}	
}

See the following output.

 

Why Strings are immutable or final in Java

Finally, Java String Class Example | String Class in Java Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.