String methods in java

String methods in java:

Java string provides a lot of methods to perform operation on string.
java,string,java tutorial,java strings,strings in java,string class in java,java string,java string class methods,java (programming language),learn java,string methods,strings,splitting a string using split() method in java,sorting string in java,split() method of string class in java,java string methods,using strings in java,string to char array in java,strings concept in java
String methods in java


Syntax:
  • char charAt(int index)
  • int length()
  • String substring(int beginIndex)
  • String substring(int beginIndex, int endIndex)
  • boolean contains(CharSequence s)
  • boolean equals(Object other) 
  • boolean isEmpty()
  • String concat(String s)
  • String replace(CharSequence oldchar, CharSequence newchar)
  • String replaceAll(String regex, String replacement)
  • String[] split(String regex)
  • String[] split(String regex, int limit)
  • String intern()
  • int indexOf(int ch)
  • int indexOf(int ch, int fromIndex)
  • String toLowerCase()
  • String to LowerCase(Locale l)
  • String toUpperCase()
  • String toUpperCase(Locale l)
  • String[] trim()
  • static String valueOf(int value)
  • int compareTo(String s)
  • boolean equalsIgnoreCase(String s)
  • boolean endsWith(String suffix)
  • void getChars()
  • byte[] getBytes()


char charAt(int index):
This method is used to get the char from a string at specificed index. The index number starts from 0 and ends to n-1. If the index exceed the length, then we will get StringIndexOutOfBoundsException

Example:
public class Example{
    public static void main(String[] args)
       {
          String s="javaprogramming";
          char c = s.charAt(5);
          System.out.println(c);
       }
  }

Output:
r



int length():

This method is used to return total number of character in the string.

Example:

public class Example{
    public static void main(String[] args)
       {
          String s="java";
          System.out.println(s.length());
       }
  }

Output:
4



String substring():

This method is used to return part of the string. We pass the begin and end index to the string where begin index start from the 0 and end index start the string from 1.

Substring method:

String substring (int beginIndex)
String substring (int beginIndex, int endIndex)

Example:
public class Example{
    public static void main(String[] args)
       {
          String s="javaprogramming";
          System.out.println (s.substring(2));
          System.out.println (s.substring(2,4));
       }
  }

Output:
v
va



boolean contains(CharSequence s):

This method is used to search the character present in the string. If present then it will return true else it will return false.

Example:
public class Example{
    public static void main(String[] args)
       {
          String s="javaprogramming";
          System.out.println(s.contains(o));
          System.out.println(s.contains(z));
       }
  }

Output:
true
false



boolean equals(Object other):

This method is used to compare content of two different string. If content is same as other content then it will returns true else if they are unequal it will return false.

Example:
public class Example{
    public static void main(String[] args)
       {
          String s1="javaprogramming";
          String s2 = new String("javaprogramming"):
          String s3 = "Hello world";
          System.out.println(s1.equals(s2));
          System.out.println(s1.equals(s3));
       }
  }

Output:
true
false



boolean isEmpty():

This method is used to check the string is empty or not. If the length of the string is 0 then it will return true else it will return false

Example:
public class Example{
    public static void main(String[] args)
       {
          String s="javaprogramming";
          String s1 ="";
          System.out.println(s.isEmpty());
          System.out.println(s1.isEmpty());
       }
  }

Output:
false
true



String concat(String s):

This method is used to combine two specified string

Example:
public class Example{
    public static void main(String[] args)
       {
          String s="java";
          String c = s.concat(" is an object oriented programming language ");
          System.out.println(c);
       }
  }

Output:
java is an object oriented programming language


String replace():

This method is used to replace all the old char with new char and return the string.

Example:
public class Example{
    public static void main(String[] args)
       {
          String s="javaprogramming";
          String c = s.replace('a','e');
          System.out.println(c);
       }
  }

Output:
jeveprogremming



String replaceAll (String regex, String replacement):
This method is used to replace all the char sequence  matching the regex and replace with the replacement string.


Example:
public class Example{
    public static void main(String[] args)
       {
          String s="ja va prog ram min g";
          String c = s.replaceAll("\\s","");
          System.out.println(c);
       }
  }

Output:
javaprogramming



String[] split():

This method is used to split against given expression and returns a char array

Example 1:
public class Example{
    public static void main(String[] args)
       {
          String s="India,Pakistan,China,America,Russia";
          String[] c = s.split(",");
          for (String r : c)
            {
              System.out.println(r);
            }
       }
  }

Output:
India
Pakistan
China
America
Russia

Example 2:
public class Example2{
    public static void main(String[] args)
       {
          String s="World is so beautiful";
          String[] c = s.split("\\s",0);
          for (String r : c)
            {
              System.out.println(r);
            }
         String[] t = s.split("\\s",1);
          for (String y : t)
            {
              System.out.println(y);
             }
       }
  }

Output:
World
World is



String intern():
This method is used to return string from the memory. It creates exact copy of heap string object in string constant pool. The string maintains 

Example:
public class Example{
    public static void main(String[] args)
       {
          String s1 = new String("hello world");
          String s2 = "hello world"
          String s3 = s1.intern();
          System.out.println(s1 == s2);
          System.out.println(s2 == s3);
       }
  }

Output:
false
true



int indexOf():

This method is used return the index of given character or substring. This index starts from 0. If the character or substring are not found it will return -1.
It has different methods based on its signature
  • int indexOf(int ch);
  • int indexOf(int ch, int fromIndex);
  • int indexOf(String s);
  • int indexOf(String s, int fromIndex);

Example 1:
 /*
This example is for the methods
   int indexOf(int ch);
   int indexOf(String s);
*/
public class Example{
    public static void main(String[] args)
       {
          String s="This is a java program";
          System.out.println (s.indexOf('i'));
          System.out.println (s.indexOf ("av"));
          System.out.println(s.indexOf('z'));
       }
  }

Output:
2
11
-1

Example 2:
/*
This example is for the methods
int indexOf(int ch, int fromIndex);
int indexOf(String s, int fromIndex);
*/
public class Example{
    public static void main(String[] args)
       {
          String s="This is a java program";
          System.out.println("After index 5");
          System.out.println (s.indexOf('i',5));
          System.out.println (s.indexOf ("av",5));
       }
  }

Output:
After index 5
5
11



String toLowerCase():

This method is used to convert and returns the given string into lowercase.

It also has two different methods based on it's signature

  • String toLowerCase(); - it has default locale.
  • String toLowerCase(Locale l);

String toLowerCase(Locale l) method is used to convert the string to lowerCase using the given locale.

Example:

import java.util.Locale;
public class Example{
    public static void main(String[] args)
       {
          String s="THIS IS A JAVA PROGRAM";
          System.out.println (s.toLowerCase());
          System.out.println (s.toLowerCase(Locale.ENGLISH));
   System.out.println(s.toLowerCase(Locale.forLanguageTag("tr")));
       }
  }

Output:
this is a java program
this is a java program
th?s ?s a java program



String toUpperCase():

This method more similar to lowerCase method but it is used to convert and returns the given string into upper case.

It also has two different methods based on it's signature

  • String toUpperCase(); - it has default locale.
  • String toUpperCase(Locale l); - converts as given locale

Example:

import java.util.Locale;
public class Example{
    public static void main(String[] args)
       {
          String s="this is a java program";
          System.out.println (s.toUpperCase());
          System.out.println (s.toUpperCase(Locale.ENGLISH));
   System.out.println(s.toUpperCase(Locale.forLanguageTag("tr")));
       }
  }

Output:
THIS IS A JAVA PROGRAM
THIS IS A JAVA PROGRAM
TH?S ?S A JAVA PROGRAM



String[] trim():
This method is used to trim the spaces at the beginning and at the end of the string.Where the spaces are found by unicode. By omitting the spaces we can reduces the length of the string.
Example:
public class Example
{
public static void main(String[] args)
{
String s = " It is a java program ";
System.out.println("Before trimming " + s.length());
System.out.println(s);
String s1 = s.trim();
System.out.println("After trimming "+ s1.length());
System.out.println(s1);
}
}

Output:
Before trimming 22
 It is a java program
After trimming 20
It is a java program



static String valueOf(int value):
This method is used to convert any datatypes to string. It can convert int to string, char to string, boolean to string, float to string, double to string, even you can convert object to string and character array to string.

Example:
public class Example
{
public static void main(String[] args)
{
int i = 15; //integer
float f = 123.5f; //float
double d = 456.8; //double
char c = 'A'; //character
char[] ch = {'B','C','D','E','F'}; //character Array
boolean b = true; //boolean
Example obj = new Example(); //object
String s1 = String.valueOf(i);
String s2 = String.valueOf(f);
String s3 = String.valueOf(d);
String s4 = String.valueOf(c);
String s5 = String.valueOf(ch);
String s6 = String.valueOf(b);
String s7 = String.valueOf(obj);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);

}

}

Output:
15
123.5
456.8
A
BCDEF
true
Example@506411



int compareTo(String s):
This method is used to compare to two string lexicographically. It returns either positive value or negative value or 0 which is based on comparison of the string character unicode that is it will compare with character to character.

Returns positive value:
If first string character unicode is greater than second string character unicode. Then it will return positive value
Example:
s1>s2 (s1 and s2 are the strings)

Returns negative value:
If first string character unicode is lesser than second string character unicode. Then it will return negative value

Example:
s1<s2 (s1 and s2 are the strings)

Returns value Zero:
If first string character unicode is equal than second string character unicode. Then it will return value 0

Example:
s1==s2 (s1 and s2 are the strings)

Program example:
public class Example
{
public static void main(String[] args)
{
String s1 = "Java";
String s2 = "java";
String s3 = "Java";
String s4 = "Hello";
System.out.println(s1.compareTo(s4));
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));

}
}

Example:
2
-32
0



boolean equalsIgnoreCase(String s):
This method is used to compare two strings irrespective to its case (ignore case). If the two string are equal then it will returns true else it will return false.

Example:

public class Example
{
public static void main(String[] args)
{
String s1 = "This is a java program";
String s2 = "This is a java program";
String s3 = new String("THIS IS A JAVA PROGRAM");
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equalsIgnoreCase(s3));
}
}

Output:
true
false
true



boolean endsWith(String suffix):
This method is used to find the string ends with specified string suffix. If the string ends with specified suffix then it will returns true else it will return false

Example:

public class Example
{
public static void main(String[] args)
{
String s1 = "This is a java program";
System.out.println(s1.endsWith("program"));
System.out.println(s1.endsWith("prog"));
}

}

Output:
true
false



void getChars():

This method is used to copies the string content into specified character array. It doesnot returns any values. We need to pass 4 argument into method to copy the context they are

  • int beginIndex - from where the index should start copying
  • int endIndex - index of a content to end copying
  • character array - copied index stored in the array
  • int arrayBeginIndex - copied from the index in array
Signature:
public void getChars(int beginIndex, int endIndex, character[], int arrayBeginIndex)

we need to enclose the code with exception handling because if we pass beginIndex is greater than the endIndex

Example:

public class Example
{
public static void main(String[] args) 
{
String s1 = "This is a java program";
char[] ch = new char[20];
try
{
s1.getChars(10,22,ch,0);
System.out.println(ch);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Output:
java program



byte[] getBytes():
This method is used to convert each and every content in the String to bytes code. It stores all character content in the string into the array and then convert that into byte code.

It has three different methods available based on its signature. They are:
public byte[] getBytes()
public byte[] getBytes(Charset ch)
public byte getBytes(String charset) throws UnsupportedEncodingException

Program Example:

Example 1:
//public byte[] getBytes()

public class Example
{
public static void main(String[] args) 
{
String s1 = "java program";
byte[] bt = s1.getBytes();
for(int i =0; i<bt.length; i++)
{
System.out.println(bt[i]);
}
String s = new String(bt);
System.out.println(s);
}
}

Output:
106
97
118
97
32
112
114
111
103
114
97
109
java program

Example 2:
//public byte[] getBytes(charset ch)
import java.nio.charset.Charset;
public class Exam 
{
public static void main(String[] args) 
{
String s1 = "java program";
byte[] bt = s1.getBytes(Charset.forName("ASCII"));
for(int i =0; i<bt.length; i++)
{
System.out.println(bt[i]);
}
String s = new String(bt);
System.out.println(s);
}
}

Output:
106
97
118
97
32
112
114
111
103
114
97
109
java program

Example 3:
//public byte[] getBytes(String charset)

public class Example 
{
public static void main(String[] args) 
{
try
{
String s1 = "java program";
byte[] bt = s1.getBytes("ASCII");
for(int i =0; i<bt.length; i++)
{
System.out.println(bt[i]);
}
String s = new String(bt);
System.out.println(s);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Output:
106
97
118
97
32
112
114
111
103
114
97
109
java program


Comments

Popular posts from this blog

Multiple image upload to database and display from it

PHP Login and Registration script