String

String:
  • It is an in-build class present in java.lang package
  • It is a final class so you cannoot extends String class
  • It has one private and final data member char array "value" since it is also called immutable class because once you create an object of String you cannot modified its value later 
  • It implements Serializable, Comparable<String> and CharSequence interfaces
  • Object of String can be created in two ways one with new keyword and another with string literal
  • Objects created using string literals are stored in different memory called string constant pool

Constructors of String class:
String()
Initializes a newly created String object so that it represents an empty character sequence.

String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's default charset.

String(byte[] bytes, Charset charset)
Constructs a new String by decoding the specified array of bytes using the specified charset.

String(byte[] bytes, int offset, int length)
Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.

String(byte[] bytes, int offset, int length, Charset charset)
Constructs a new String by decoding the specified subarray of bytes using the specified charset.

String(byte[] bytes, int offset, int length, String charsetName)
Constructs a new String by decoding the specified subarray of bytes using the specified charset.

String(byte[] bytes, String charsetName)
Constructs a new String by decoding the specified array of bytes using the specified charset.

String(char[] value)
Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.

String(char[] value, int offset, int count)
Allocates a new String that contains characters from a subarray of the character array argument.

String(int[] codePoints, int offset, int count)
Allocates a new String that contains characters from a subarray of the Unicode code point array argument.

String(String original)
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.

String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder argument.



Example 1:
package com.java.string;

import java.io.UnsupportedEncodingException;

public class StringConstructors {

    public static void main(String[] args) {
        String s1 = "abc";
        System.out.println("s1 = " + s1);
        
        String s2 = new String();
        System.out.println("s2 = " + s2);
        
        String s3 =new String("xyz");
        System.out.println("s3 = " + s3);
        
        String s4 = new String(new char[]{'a''b''c''d''e'});
        System.out.println("s4 = " + s4);
        
        String s5 = new String(new char[]{'a''b''c''d''e''f''g''h'}, 2, 4);
        System.out.println("s5 = " + s5);
        
        String s6 = new String(new byte[]{65, 66, 67, 68, 69, 70});
        System.out.println("s6 = " + s6);
        
        String s7 = new String(new byte[]{65, 66, 67, 68, 69, 70, 46, 46, 46, 90, 97, 98, 46, 46, 46, 122}, 5, 6);
        System.out.println("s7 = " + s7);
        
        String s8 = "";
        try {
            s8 = new String(new byte[]{65, 66, 67, 68, 69, 70, 46, 46, 46}, "US-ASCII");
            System.out.println("US-ASCII = " + s8);
            s8 = new String(new byte[]{65, 66, 67, 68, 69, 70, 46, 46, 46}, "UTF-8");
            System.out.println("UTF-8 = " + s8);
            s8 = new String(new byte[]{65, 66, 67, 68, 69, 70, 46, 46, 46}, "UTF-16");
            System.out.println("UTF-16 = " + s8);
            s8 = new String(new byte[]{65, 66, 67, 68, 69, 70, 46, 46, 46}, "ISO-8859-1");
            System.out.println("ISO-8859-1 = " + s8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        
        String s9 = new String(new StringBuilder("core"));
        System.out.println("s9 = " + s9);
        
        String s10 = new String(new StringBuffer("java"));
        System.out.println("s10 = " + s10);
    }
}

Output:
s1 = abc
s2 =
s3 = xyz
s4 = abcde
s5 = cdef
s6 = ABCDEF
s7 = F...Za
US-ASCII = ABCDEF...
UTF-8 = ABCDEF...
UTF-16 = 䅂䍄䕆⸮�
ISO-8859-1 = ABCDEF...
s9 = core
s10 = java


Methods of String class:
char charAt(int index)
Returns the char value at the specified index.

int codePointAt(int index)
Returns the character (Unicode code point) at the specified index.

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

int codePointCount(int beginIndex, int endIndex)
Returns the number of Unicode code points in the specified text range of this String.

int compareTo(String anotherString)
Compares two strings lexicographically.

int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.

String concat(String str)
Concatenates the specified string to the end of this string.

boolean contains(CharSequence s)
Returns true if and only if this string contains the specified sequence of char values.

boolean contentEquals(CharSequence cs)
Compares this string to the specified CharSequence.

boolean contentEquals(StringBuffer sb)
Compares this string to the specified StringBuffer.

static String copyValueOf(char[] data)
Equivalent to valueOf(char[]).

static String copyValueOf(char[] data, int offset, int count)
Equivalent to valueOf(char[], int, int).

boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.

boolean equals(Object anObject)
Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.

static String format(Locale l, String format, Object... args)
Returns a formatted string using the specified locale, format string, and arguments.

static String format(String format, Object... args)
Returns a formatted string using the specified format string and arguments.

byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

byte[] getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.

byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.

int hashCode()
Returns a hash code for this string.

int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.

int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.

int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

String intern()
Returns a canonical representation for the string object.

boolean isEmpty()
Returns true if, and only if, length() is 0.

static String join(CharSequence delimiter, CharSequence... elements)
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.

int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

int lastIndexOf(String str)
Returns the index within this string of the last occurrence of the specified substring.

int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

int length()
Returns the length of this string.

boolean matches(String regex)
Tells whether or not this string matches the given regular expression.

int offsetByCodePoints(int index, int codePointOffset)
Returns the index within this String that is offset from the given index by codePointOffset code points.

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.

boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.

String replace(char oldChar, char newChar)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.

String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.

String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.

String[] split(String regex)
Splits this string around matches of the given regular expression.

String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.

boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.

boolean startsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with the specified prefix.

CharSequence subSequence(int beginIndex, int endIndex)
Returns a character sequence that is a subsequence of this sequence.

String substring(int beginIndex)
Returns a string that is a substring of this string.

String substring(int beginIndex, int endIndex)
Returns a string that is a substring of this string.

char[] toCharArray()
Converts this string to a new character array.

String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.

String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.

String toString()
This object (which is already a string!) is itself returned.

String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.

String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.

String trim()
Returns a string whose value is this string, with any leading and trailing whitespace removed.

static String valueOf(boolean b)
Returns the string representation of the boolean argument.

static String valueOf(char c)
Returns the string representation of the char argument.

static String valueOf(char[] data)
Returns the string representation of the char array argument.

static String valueOf(char[] data, int offset, int count)
Returns the string representation of a specific subarray of the char array argument.

static String valueOf(double d)
Returns the string representation of the double argument.

static String valueOf(float f)
Returns the string representation of the float argument.

static String valueOf(int i)
Returns the string representation of the int argument.

static String valueOf(long l)
Returns the string representation of the long argument.

static String valueOf(Object obj)
Returns the string representation of the Object argument.

Example 2:
package com.java.string;

public class StringComparison {
    public static void main(String[] args) {
        String s1 = "java";
        String s2 = "java";
        String s3 = new String("learning string class in java");
        String s4 = new String("learning string class in java");
        String s5 = "JAVA";
        String s6 = "learning";
        String s7 = "aaaaaaaaaaaaaaaabbbb";
        
        System.out.println(s1 + " '==' " + s2 + " ? " + (s1 ==  s2));
        System.out.println(s3 + " '==' " + s4 + " ? " + (s3 == s4));
        
        System.out.println(s1 + " *is equals to* " + s2 + " ? "+ s1.equals(s2));
        System.out.println(s3 + " *is equals to* " + s4 + " ? "+ s3.equals(s4));
        
        System.out.println(s1 +  " + s5 + " ? " + s1.equalsIgnoreCase(s5));
        System.out.println(s3 +  " + s4 + " ? "  + s3.equalsIgnoreCase(s4));
        
        System.out.println(s3 + " (startsWith) " + s6 + " ? " + s3.startsWith(s6));
        System.out.println(s4 + " (endsWith)  " + s2 + " ? " + s4.endsWith(s2));
        
        System.out.println(s4 + " *contains* class " + s4.contains("class"));
        
        System.out.println(s7 + " ## matches with the regular expression (a+b+) ## " + s7.matches("a+b+"));
        System.out.println(s7 + " ## matches with the regular expression (a*b*) ## "  + s7.matches("a*b*"));
        
        System.out.println(s5.compareTo(s1));
        System.out.println("a".compareTo("c"));
        System.out.println("d".compareTo("a"));
        System.out.println(s1.compareTo(s2));
    }
}

Output:
java '==' java ? true
learning string class in java '==' learning string class in java ? false
java *is equals to* java ? true
learning string class in java *is equals to* learning string class in java ? true
java <equalsIgnoreCase> JAVA ? true
learning string class in java <equalsIgnoreCase> learning string class in java ? true
learning string class in java (startsWith) learning ? true
learning string class in java (endsWith)  java ? true
learning string class in java *contains* class true
aaaaaaaaaaaaaaaabbbb ## matches with the regular expression (a+b+) ## true
aaaaaaaaaaaaaaaabbbb ## matches with the regular expression (a*b*) ## true
-32
-2
3
0

Example 3:
package com.java.string;

import java.util.Arrays;

public class StringModification {
    public static void main(String[] args) {
        String mobile = "7056432345";
        String email = "abcdef@gmail.com";
        String loginDetails = "admin:test123";
        String basics = "JAVA BASICS ";
        String core = "core java";
        String str = "mississipi";
        
        System.out.println(mobile + " is valid number " + mobile.matches("[7-9][0-9]{9}"));
        System.out.println(email + " is valid mail id " + email.matches("[\\w]{6,30}@[\\w]*.[\\w]*"));
        String[] details = loginDetails.split(":");
        System.out.println("Username is " + details[0]);
        System.out.println("Password is " + details[1]);
        System.out.println(basics + "*toLowerCase()* " + basics.toLowerCase());
        System.out.println(core + " *toUpperCase()* " + core.toUpperCase());
        System.out.println(basics + " #concat(String str)# " + core + " => " + basics.concat(core));
        System.out.println(mobile + " #length()# " + mobile.length());
        System.out.println(basics + " #substring(5)# " + basics.substring(5));
        System.out.println(email + " #substring(7, 12)# " + email.substring(7, 12));
        System.out.println(email + " #charAt(6)# " + email.charAt(6));
        System.out.println(email + " $indexOf('@')$ " + email.indexOf('@'));
        System.out.println(email + " $indexOf('a', 6)$ " + email.indexOf('a', 6));
        System.out.println(email + " $indexOf(\"gmail\")$ " + email.indexOf("gmail"));
        System.out.println(str + " $indexOf(\"ss\", 4)$ " + str.indexOf("ss", 4));
        System.out.println(basics + " $lastIndexOf('A')$ " + basics.lastIndexOf('A'));
        System.out.println(basics + " $lastIndexOf('A', 4)$ " + basics.lastIndexOf('A', 4));
        System.out.println(str + " $lastIndexOf(\"ss\")$ " + str.lastIndexOf("ss"));
        System.out.println(str + " $lastIndexOf(\"ss\", 5)$ " + str.lastIndexOf("ss", 4));
        System.out.println(str + " #split(\"s\")# " + Arrays.toString(str.split("s")));
        System.out.println(str + " #split(\"s\", 3)# " + Arrays.toString(str.split("s", 3)));
        System.out.println(str + " #replace('s', 'c')# " + str.replace('s''c'));
        System.out.println(str + " #replace(\"ss\", \"c\")# " + str.replace("ss""c"));
        System.out.println(str + " #replaceAll(\"s+\", \"c\")# " + str.replaceAll("s+""c"));
        System.out.println(str + " #replaceFirst(\"s+\", \"c\")# " + str.replaceFirst("s+""c"));
        String result = String.format("Mobile No: %s \tEmail ID: %s \tUser Details: %s \tstr: %s", mobile, email, loginDetails, str);
        System.out.println(result);
        String value = String.valueOf(1234);
        System.out.println(value);
        value = String.valueOf(20.25);
        System.out.println(value);
        value = String.valueOf(10.5f);
        System.out.println(value);
        value = String.valueOf('a');
        System.out.println("Unicode value for '"+ value + "' is " + (int)value.charAt(0));
    }
}

Output:
7056432345 is valid number true
abcdef@gmail.com is valid mail id true
Username is admin
Password is test123
JAVA BASICS *toLowerCase()* java basics
core java *toUpperCase()* CORE JAVA
JAVA BASICS  #concat(String str)# core java => JAVA BASICS core java
7056432345 #length()# 10
JAVA BASICS  #substring(5)# BASICS
abcdef@gmail.com #substring(7, 12)# gmail
abcdef@gmail.com #charAt(6)# @
abcdef@gmail.com $indexOf('@')$ 6
abcdef@gmail.com $indexOf('a', 6)$ 9
abcdef@gmail.com $indexOf("gmail")$ 7
mississipi $indexOf("ss", 4)$ 5
JAVA BASICS  $lastIndexOf('A')$ 6
JAVA BASICS  $lastIndexOf('A', 4)$ 3
mississipi $lastIndexOf("ss")$ 5
mississipi $lastIndexOf("ss", 5)$ 2
mississipi #split("s")# [mi, , i, , ipi]
mississipi #split("s", 3)# [mi, , issipi]
mississipi #replace('s', 'c')# micciccipi
mississipi #replace("ss", "c")# micicipi
mississipi #replaceAll("s+", "c")# micicipi
mississipi #replaceFirst("s+", "c")# micissipi
Mobile No: 7056432345 Email ID: abcdef@gmail.com User Details: admin:test123 str: mississipi
1234
20.25
10.5
Unicode value for 'a' is 97

What is difference between String and StringBuffer or StringBuilder?
String StringBuffer and StringBuilder
String objects are immutable Object are mutable
It does not have append(), delete(), capacity(), reverse(), insert() methods They have  append(), delete(), capacity(), reverse(), insert() methods
Every time if do modification to a String object then a new String object will be created The default capacity value is 16. If you do any modification then no new object will be created
equals() method of Object class is Overridden by String class equals() method of Object class is not Overridden in these classes

What is difference between StringBuffer and StringBuilder?
StringBuffer StringBuffer and StringBuilder
All methods of this class are synchronized means it is thread safe. All methods of this class are not synchronized means it is not thread safe.
It available since JDK 1.0 It is available since JDK 1.5
It is slower than StringBuilder It is faster than StringBuffer

No comments:

Post a Comment