4. Objective
• To acquire Basic understanding in Java
• To develop the skill of working in Java
•To able to understand string of Java
5. String Constructors
1.String()- it is default constructor ,used to create empty string.
Syntax:-
String x=new String();
Here x is an object.
2.String(string):- it is parameterized constructor.
Syntax:- String x= new String(“Gwalior”);
3.String(char[],int p,int n):- In this p is position from where
characters are read,n is the number of characters to be read.
5
CS 306 Reference No.: R1
SELO: 1,2
6. Program for parameterized constructor
class check
{
public static void main(String ar[])
{
char x={‘G’,’W’,’A’,’L’,’I’,’O’,’R’};
String x=new String(x,2,3);
System.out.println (x);
}
} 6
CS 306 Reference No.: R1
SELO: 1,2
7. Output
ALI
note : - if we write the string as
String s=“GWALIOR”;
Here s,indicates the base address of string.
7
CS 306 Reference No.: R1
SELO: 1,2
8. Various methods of String class
1. int length()- this method returns the number of characters on
string.
Ex. Class check
{
public static void main (String ar[])
{
String x= new String(“Gwalior”);
System.out. println(x.length());
}}
8
CS 306 Reference No.: R1
SELO: 1,2
10. 2. toUpperCase():- It converts all rhe characters in a string
from lowercase to uppercase.
3.toLowerCase():- It converts all characters from uppercase to
lowercase.
Ex. class check
{
public static void main (String ar[])
{
String z= new String (“ gwalior”);
10
CS 306 Reference No.: R1
SELO: 1,2
14. 5. boolean equalsIgnoreCase(String):this method ignores the
cases and compares the strings.
6.int compareTo(String):- It is used to compare two strings.
-If string1 is greater than String2 this method returns + ve
value
-If string1 is lesser than string2 then this method returns –ve
value.
-If string1==string2 this function returns zero.
14
CS 306 Reference No.: R1
SELO: 1,2
15. Ex. if((x.compareTo(y))>0)
{
System.out.println (“string1 is greater”);
}
else if(x.compareTo(y))<0)
System.out.println (“String2 is greater”);
else
System.out.println (“both strings are equals”);
}
15
CS 306 Reference No.: R1
SELO: 1,2