String in Java
String in Java
String is a sequence of characters.But in Java, a string is an object that represents a sequence of characters.
There are two ways to create a String object:
1)String literal : Java String literal is created by using double quotes.
For Example: String str=“Hello String”;
2)new keyword : Java String is created by using a keyword “new”.
For example: String str=new String(“Hello String”);
It will creates two objects in String pool and in heap and one reference variable where the variable ‘str’ will refer to the object in the heap.
String's Methods.
1) String length() : The Java String length() method tells the length of the string. It returns count of total number of characters present in the String.
example :
String str=
"nirav patel on java"
;
System.out.println(str.length());
2) String concat() : The Java String concat() method combines a specific string at the end of another string and ultimately returns a combined string. It is like appending another string.
example :
String str=
"hello java"
;
str=str.concat(
"how are you"
);
System.out.println(str);
3)String compareTo() : The Java String compareTo() method compares the given string with current string. It is a method of ‘Comparable’ interface
which is implemented by String class. Don’t worry, we will be learning
about String interfaces later. It either returns positive number,
negative number or 0
|
4) String IsEmpty()
: This method checks whether the String contains anything or not. If
the java String is Empty .it returns true else false.
Comments
Post a Comment