Java Strings: Learn string functions from scratch

Java String is a sequence of characters. In Java String are immutable or final, in other words, they are constant, once created they can not be changed, there is one and only java.lang. Java String class has no subclasses, it implements three interfaces:  Serializable, Comparable and CharSequence.

Immutability of String provides some interesting possibilities :

  • Immutability makes String thread- safe, which means it can be safely shared between multiple threads, allowing to  avoid synchronization issue in multithreaded programming.
  • Use of String Pool (this is a collection of links to String objects, used to optimize memory)
  • Using strings as keys in a HashMap (We recommend keeping the key immutable)

The java.lang package contains a class that encapsulates the data structure that matches the string. In this class, there are methods that allow you to compare strings, search for them, and extract certain characters and substrings. Due to the reason that Java manipulations is a  resource consuming process, Java provides two utility classes: StringBuffer and StringBuilder.

The StringBuffer class is used when the string needs to be changed after creation. The fact that objects of type String in Java are unchanged allows the translator to apply various optimization methods to operations with them. StringBuffer operations are thread-safe and synchronized. It is a mutable class.

StringBuilder is a mutable class as well, its’ operations are not thread-safe, so it is working in a single threaded environment. StringBuilder is faster compared to StringBuffer because of no overhead of synchronized.

There are few ways of creating String object :

1.String literal a sequence of characters enclosed in double quotes, the compiler creates an object with the value of this literal:

String s = “this is string”;

          or

You can create objects of type String as any other class objects, using the new keyword

String st = new String (“this is a string as well”);
2.Using constructor

Constructors can create String object using an array of characters.The array is copied; the static methods copyOf and copyOfRange (copying the entire array and its part (if the 2nd and 3rd parameter of the constructor are specified), respectively) of the Arrays class, which in turn use the platform-dependent implementation of System.arraycopy, are used for this.

To create an empty string, you can use the default constructor without parameters:

For example:

String s = new String ();

char chars [] = {‘h’, ‘e’, ‘y’};

String s = new String (chars);

The code snippet creates a String object s, initializing it with a string of three characters passed to the constructor as a parameter in the character array.

This piece of code prints the string “abc”. So, this constructor has 3 parameters:

System.out.println (s)://output “abc”

Or:

String (char chars [], int startingIndex, int number of Characters);

char chars [] = {‘h’, ‘o’, ‘w’, ‘d’, ‘y’, ‘p’, ‘a’,’l’}:

String s = new String (chars, 1,3);

System.out.println (s);//output “owd”.

You can also create String object using a byte array. Additionally, you can pass a Charset class parameter that will be responsible for the encoding. The array is decoded using the specified encoding like  – Charset.defaultCharset () and, further, the resulting character array is copied into the value of the object.

Constructors can use StringBuffer and StringBuilder objects, their values (getValue ()) and length () () to create a string object

There some really fun methods which you can try on String

1.int length():

Returns the number of characters in the String.

String s = “this is string”; create new String object

s.length();//output 14

2.Char charAt(int i):

Returns the character at ith index.

String s = “this is string”;

str.charAt(5)//output  is i;

3.String substring (int i):

Return the substring from the ith  index character to end.

“abcdefghijk”.substring(3);//output is defghijk

4.String substring (int i, int j):

Returns the substring from i to j-1 index.

“abcdefghijk”.substring(3,5);//output is de

5.String concat( String str):

Concatenates specified string to the end of this string.

String s1=”code”;

String s2=” everyday”;

String output = s1.concat(s2);//output codeeveryday

6.int indexOf (String s):

Returns the index within the string of the first occurrence of the specified string.

String str = “Learn to code”;

int output2 = str.indexOf(“code”);//output-9

7.int indexOf (String s, int i):

Returns the index within the string of the first occurrence of the specified string, starting at the specified index.

String str =”Learn to code”;

int output3 =str.indexOf(‘a’,3);output -3

8.Int lastindexOf( int ch):

Returns the index within the string of the last occurrence of the specified string.

String str =”Learn to code”;

int output4 = str.lastIndexOf(‘a’);//output is 2

9.boolean equals( Object other Obj):

Compares this string to the specified object.

Boolean out = “Freaks”.equals(“Greeks”); // returns false

Boolean out1 = “Greeks”.equals(“greeks”); // returns false

10.boolean  equalsIgnoreCase (String anotherString):

Compares string to another string, ignoring case considerations.

Boolean out2= “Freaks”.equalsIgnoreCase(“Greeks”); // returns false

Boolean out3 = “Greeks”.equalsIgnoreCase(“greeks”); // returns true

11.int compareTo( String anotherString):

Compares two string lexicographically.

String s1 =”code”;

String s2 = “everyday”;

int output = s1.compareTo(s2);output -2. But if you try to change “everyday” to “Everyday”, the output will change.

12.int compareToIgnoreCase( String anotherString):

Compares two string lexicographically, ignoring case considerations.

String s1 =”code”;

String s2 = “everyday”;

int output = s1.compareToIgnoreCase(s2);  the output will be <0; -2 to be exact, because s1 comes before s2.in other words “c” comes before “e”.

13.String toLowerCase():

Converts all the characters in the String to lower case.

String str = “Learn to code”;

str.toLowerCase()//output learn to code

14.String toUpperCase():

Converts all the characters in the String to upper case.

String str = “Learn to code”;

str.toUpperCase()//output LEARN TO CODE

15.String trim():

Returns the copy of the String, by removing white spaces at both ends. It does not affect whitespaces in the middle.

String str = ” Learn to code “;

String newstr =str.trim();//output “Learn to code”

16.String replace (char oldChar, char newChar):

Returns new string by replacing all occurrences of oldChar with newChar.

String s3 =”code”;

String s4 =s3.replace(‘c’,’m’);//output-mode

17.String merge

Using the + operator, the lines are combined into one, for example:

String s = “Not is” + age + “years old.” in which String s = new StringBuffer (“He is”) .append (age);

s.append (“years old.”). toString ();

By definition, every object of the String class cannot be changed. You can neither insert new characters into an existing string, nor change one character for another in it. And to add one line to the end of the other is also impossible. Therefore, the Java translator transforms operations that look like modification of String objects into operations with the related class StringBuffer.

Almost any aspect of Java programming at any stage implies the use of the String and StringBuffer classes. They will be needed when debugging, and when working with text, and when specifying file names and URLs as parameters to methods. Every second byte of most strings in Java is zero (Unicode is rarely used so far). The fact that strings in Java require twice as much memory as ordinary ASCIIs is not very scary, as long as you do not have to work directly with a huge char array to work effectively with text in editors and other similar applications.

Don't miss out!
Subscribe To Our Newsletter

Learn new things. Get an article everyday.

Invalid email address
Give it a try. You can unsubscribe at any time.

Comments

comments