String and string method

Array

String

Introduction String

In this tutorial, we will learn about Java strings, how to create them, and various methods of the String class with the help of examples.

In Java, a string is a sequence of characters. For example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.

Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces

Array

1.String objects are stored in a special memory area known as the "string constant pool".

2. Java counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the third ...

3. The String class is immutable, so that once it is created a String object cannot be changed

4. Strings in Java are not primitive types (like int, char, etc). Instead, all strings are objects of a predefined class named String.

5. all string variables are instances of the String class.

Java String class methods :

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

Example for simple String

class example_string {

public static void main(String[] args) {


//creating string by Java string literal

String s1="java"

char ch[]={'s','t','r','i','n','g','s'};


//converting char array to string

String s2=new String(ch);


//creating Java string by new keyword

String s3=new String("example");


//diplay String

System.out.println(s1);

System.out.println(s2);

System.out.println(s3);

// To add upcomig String method

----------------------------------------------------------------

}

}

java strings example

1. int compareTo(String string):

This method compares the two strings based on the Unicode value of each character in the strings

if two strings are the equal then the return 0 and string are the differnt then the return -1

class example_string {

public static void main(String[] args) {


String str1="mane";

String str2="mane";

System.out.println("compare str1 and str2=" str1.compareTo(str2));


String str3="mane";

String str4="narayan";

System.out.println("compare str3 and str4=" str3.compareTo(str4));


}

}

compare str1 and str2 = 0
compare str3 and str4 = -1

2.String replace(char old, char new):

It replaces all occurrences of the specified char value. It replaces all occurrences of the specified CharSequenc

class example_string {

public static void main(String[] args) {


String str1="this is a cow.";


//Replace the old char to replace all new char

System.out.println(str1.replace("is","was"));


//Replace the old char to replace only one char

System.out.println(str1.replaceFirst("is","was"));

}

}

ReplaceAll = thwas was a cow.
ReplaceFirst = thwas is a cow.

3.String toLowerCase() & String toUpperCase()

It returns a string in lowercase. It returns a string in uppercase.

String str1="WELCOME";


// to convert in lowercase

System.out.println("Lowercar = "+str1.toLowerCase());


String str2 ="home";

//To convert Uppercase

System.out.println("Uppercase = "+str2.toUpperCase());

Lowercar = welcome
Uppercase = HOME

4. Length()

The length is the number of characters that a given string contains. Java has a length() method that gives the number of characters in a String.

public class example_string {

public static void main(String[] args) {


String str = "codingwolrd";

System.out.println("lenght of the string is = " +str.length());

}

}

lenght of the string is = 11

5.Concatenation()

Although Java uses a ‘+’ operator for concatenating two or more strings. A concat() is an inbuilt method for String concatenation in Java.

public class example_string {

public static void main(String[] args) {


String str1="Welcome";


String str = "codingwolrd";

// to concatenation

System.out.println(str1 + str);

System.out.println(str1.concat(str));

}

}

Welcomecodingwolrd
Welcomecodingwolrd

6.charAt()

This method is used to retrieve a single character from a given String. Given below is the program that will demonstrate how the charAt() method retrieves a particular character from the given String.

public class example_string {

public static void main(String[] args) {


String str = "codingwolrd";

// to charAt

System.out.println(str.charAt(2));

System.out.println(str.charAt(7));

}

}

d
o

7 String contains()

This method is used to determine whether a substring is a part of the main String or not. The return type is Boolean.

public class example_string {

public static void main(String[] args) {


String str = "codingwolrd";

String str1 = "welcome";

String str2 = "wolrd";

// to contains

System.out.println("wolrd is the part of codingwolrd is = "+ str.contains(str2));

System.out.println("welcome is the part of codingwolrd is = "+ str.contains(str1));

}

}

wolrd is the part of codingwolrd is = true
welcome is the part of codingwolrd is = false

8 String split()

As the name suggests, a split() method is used to split or separate the given String into multiple substrings separated by the delimiters (“”, “ ”, \\, etc). In the below example, we will split the String.

public class example_string {

public static void main(String[] args) {


String str = "codingxyzwolrdxyzThexyzwebsitexyzisxyzsoftwaretestingxyzhelp";

// to split

String[] split = str.split("xyz");

for (String obj: split) {

System.out.println(obj); }

}

}

coding wolrd The
website is softwaretesting help

9 String indexOf()

This method is used to perform a search operation for a specific character or a substring on the main String. There is one more method known as lastIndexOf() which is also commonly used.
indexOf() is used to search for the first occurrence of the character.
lastIndexOf() is used to search for the last occurrence of the character.

public class example_string {

public static void main(String[] args) {


String str = "codingwolrd";

// to indexOf

System.out.println("index of c is " + str.indexOf('c'));

System.out.println("index of first d is " + str.indexOf('d'));

System.out.println("index of last d is " + str.lastIndexOf('d'));

}

}

index of c is =0 index of first d is = 2
index of last d is =10

10 String reverse()

The StringBuffer reverse() method is used to reverse the input characters of the String.

public class example_string {

public static void main(String[] args) {


String str = "codingwolrd";

StringBuffer sb = new StringBuffer(str);

// to reverse

System.out.println( sb.reverse());

}

}

drlowgnidoc

11 Substring Method()

The Substring() method is used to return the substring of the main String by specifying the starting index and the last index of the substring.

public class example_string {

public static void main(String[] args) {


String str = "codingwolrd";

// to Substring

System.out.println(str.substring(2,10));

}

}

dingwolr

12 String IsEmpty()

This method checks whether the String contains anything or not. If the java String is Empty, it returns true else false. For example:

public class example_string {

public static void main(String[] args) {


String str = "codingwolrd";

String str1 = "";

// to IsEmpty()

System.out.println(str.isEmpty());

System.out.println(str1.isEmpty());

}

}

false
true

13 String Trim()

The java string trim() method removes the leading and trailing spaces. It checks the unicode value of space character (‘u0020’) before and after the string. If it exists, then removes the spaces and return the omitted string. For example:

public class example_string {

public static void main(String[] args) {


String str = "codingwolrd";

// to Trim()

System.out.println(str +" welcome in site");

System.out.println(str.trim() +" welcome in site");

}

}

codingwolrd welcome in site
codingwolrd welcome in site

Next Topic

No comments:

Post a Comment

How do you select data from a table in SQL?

Create Table How do you select data a table in SQL? The SELECT statement is used to se...