Although the String class will be examined in depth in Part II of this book, a short exploration
of it is warranted now, because we will be using strings in some of the example programs
shown toward the end of Part I. String is probably the most commonly used class in Java’s
class library. The obvious reason for this is that strings are a very important part of
programming.
The first thing to understand about strings is that every string you create is actually an
object of type String. Even string constants are actually String objects. For example, in the
statement
class Str{
int len;
String a;
Str(String s){
a=s;
}
int lengths(){
return a.length();
}
boolean equal(Str o){
if(o.a==a) return true;
else return false;
}
char charAt(int i){
char[] car = a.toCharArray();
return car[i];
}
}
public class string {
public static void main(String[] args) {
Str c = new Str("Pakistan");
System.out.println("length of string c "+c.lengths());
Str d = new Str("Pakistanss");
if(c.equals(d))
System.out.println("c == d");
else
System.out.println("c != d");
System.out.println("Char at index 1 in c "+d.charAt(1));
d.charAt(9);
Str e ;
e = d;
if(d.equal(e))
System.out.println("d == e");
else
System.out.println("d != e");
}
}
Program
package strings;class Str{
int len;
String a;
Str(String s){
a=s;
}
int lengths(){
return a.length();
}
boolean equal(Str o){
if(o.a==a) return true;
else return false;
}
char charAt(int i){
char[] car = a.toCharArray();
return car[i];
}
}
public class string {
public static void main(String[] args) {
Str c = new Str("Pakistan");
System.out.println("length of string c "+c.lengths());
Str d = new Str("Pakistanss");
if(c.equals(d))
System.out.println("c == d");
else
System.out.println("c != d");
System.out.println("Char at index 1 in c "+d.charAt(1));
d.charAt(9);
Str e ;
e = d;
if(d.equal(e))
System.out.println("d == e");
else
System.out.println("d != e");
}
}
Output
the output of above program
Exploring the String Class in Java
Reviewed by imran ahmed
on
5:20 AM
Rating:
No comments: