String in java

What is String in java

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.

How to create a string object?

There are two ways to create String object:

  1. By string literal
  2. By new keyword

String Literal

Java String literal is created by using double quotes. 

For Example: String s="welcome";  

 By new keyword

String s=new String("Welcome");//creates two objects and one reference variable



Example Program:

class StringDemo
{
public static void main(String args[])
{
String str=new String("Hello");

System.out.println(str);
System.out.println(str.length());
System.out.println(str.indexOf("H"));
System.out.println("Character at="+str.charAt(4));
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
System.out.println(str.compareTo("hello"));
System.out.println(str.trim());
 }
}





























Comments