Java Theory
String
String is a sequence of characters, which are widely used in java programming. In java strings are treated as objects.
String Declaration
String_type String_variable = 'Sequence of string';Ex: String str = "Skillpudit";
Index | 0 | 1 | 2 | 3 | 4 | 5 |
---|---|---|---|---|---|---|
Variable | H | e | l | l | 0 | \0 |
Address | 0x23451 | 0x23452 | 0x23453 | 0x23454 | 0x23455 | 0x23456 |
String Declaration
There are two ways to create string.
- String Literal
String str="Skill pundit" - Using New Keyword
String str=new String ("Skill Pundit")
Size and Range of Data Types
String a = new String("now is");
String b = new String("the time");
String c = new String("the");
Instance method call | Return Type | Return Value |
---|---|---|
a.lenght() | int | 6 |
a.charAt(4) | char | 'i' |
a.substring(2,5) | string | 'w i' |
b.stringwith('the') | boolean | true |
a.indexOf('is') | int | 4 |
a.contact(c) | string | 'now is the' |
b.replace('r'.'T') | String | 'The Tim' |
a.split('') | String[] | {'now', 'is'} |
b.equls() | boolean | false |
String length()
The Java String length() method is used to find the length of the string. It returns count of total number of characters present in the String.
Example |
---|
public class findlength { public static void main (String args[]); { String s1= "Skillpundit"; System.out.println(”String length is:” +s1.length()); //Output: 11 } } |
String compareTo()
The Java String compareTo() method is used to compares the given string with current string.
Example |
---|
public class CompareToExample { public static void main (String args[]); { String s1= "Skill"; String s2= "Pundit"; String s3= "Skill"; System.out.println(s1.compareTo(s3)); //0 because both are equal System.out.println(s1.compareTo(s2)); //greater than 0 } } |
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 |
---|
public class CompareToExample { public static void main (String args[]); { String s1= "Skill"; String s2= "Pundit"; s1 = s1 .concat(s2); System.out.println(s1); //Skillpundit } } |