Introduction To Strings In Java

Posted By : Hany Yadav | 31-Dec-2020

Java

Loading...

STRINGS :- In Java, string is a sequence of characters and there is a special support of string and strings cannot be changed once it is declared.

SYNTAX:-

String name;

name = new String("Rahul");

Another method to declared string

String name = "Rahul";

where name is a reference and Rahul is object.

  • Strings are immutable and cannot be changed. It means if we want to change string ‘Rahul’ to ‘Harish’ then it is not possible to update in the same string. Alternatively, we can create a copy of the string name and then update it.

  • Method to take input string from keyboard and then print

Scanner sc = new scanner(system.in)

String st = sc.next();

Here, st is a variable of type string which stores the input string entered by the user through the keyboard.

System.out.println(st);

The above command prints the string on the console entered by the user through the keyboard.

Input data:- Harish

Output data:-Harish

STRING METHODS:-

There are various string methods that operate on java strings.

1-name.length():-

It is the method that is used to find the length of string.

Example:-

String name = "Harish";

int length = name.length;

System.out.println(length);

Output:-5

Explanation of above example:-

In the first line a string is created and in the second line length of string is stored in integer value and in third line value is printed.

2-name.toLowerCase():-

It is the method that returns a new string that has all lower case characters.

Example:-

String name = "Harish";

String lString = name.toLowerCase;

System.out.println(lString);

Output:-harish

3-name.toUowerCase():-

It is the method that returns a new string that has all uppercase characters.

Example:-

String name = "Harish";

String uString = name.toUowerCase;

System.out.println(uString);

Output:-HARISH

4-name.trim():-

It is the method that returns a string after removing all the spaces in string.

Example:-

String name = " Harish ";

System.out.println(uString);

Output:-Harish

5-name.substring(int Start):-

It is the method that returns a substring from start to end and it works only on index.

Example:-

String name = " Harish ";

System.out.println(name.substring(1));

Output:-arry


We provide full-scale ERP development services to overcome complex enterprise challenges and enhance business productivity. Our custom ERP application development services streamline inbound/outbound operations with advanced problem solving capabilities. For more information, contact us at [email protected]