String Class and Built in Methods in Java


In Java, string represents sequence of char values. An array of characters works same as Java string. For example:

char[] h={'H','E','L','L','O'};
String s=new String(h);

String s=“HELLO";

Java String class provides a lot of methods to perform operations on string

How to create string object?

The java.lang.String class is used to create a string object.
There are two ways to create String object:

By string literal - Java String literal is created by using double quotes. For Example:
String s1=“Selenium";

By new keyword - String s=new String(“Selenium");

Built in Methods:

Java has a librabry of classes and methods organised in packages

In order to use built in methods we need to import packages or classes
Java.lang package is automatically imported in every java Built in methods categories
String methods
Array methods
Number methods
Character methods

Different String methods:

compareTo - The Java String compareTo() method is used for comparing two strings lexicographically.

boolean equals() - The java string equals() method compares the two given strings based on the content of the string (case sensitive)
String concat() – concat two strings
boolean equalsIgnoreCase() - The java string equals() method compares the two given strings based on the content of the string (not casesensitive)
char charAt() – index position - The java string charAt() method returns a char value at the given index number.
boolean contains()
toUpperCase() – convert to upper case
toLowerCase() – convert to lower case
trim() – remove spaces from both sides of string
substring() --  returns part of string
boolean endsWith()
boolean startWith() – ends with specified suffix or not
int length()

Java Convert String to int:

Convert String to int using Integer.parseInt(String)
      String str = “54321";
      int num = Integer.parseInt(str);
Convert String to int using Integer.valueOf(String)
      String str=“123";
      int num = Integer.valueOf(str);

Java int to String Conversion:

Convert int to String using String.valueOf() 
        String int ivar = 123;
String str = String.valueOf(ivar);
System.out.println("String is: "+str);
Convert int to String using Integer.toString()
      int ivar = 123;
      String str = Integer.toString(ivar);
      System.out.println("String is: "+str);

To get more details please watch below youtube video and Subscribe the channel.

No comments:

Post a Comment