string in java
string in java
String concatenation
Java does not allow operators with string objects , only exception is +
which concatenates two strings.
int x=10;
System.out.println(x); // 10
String age=“20”;
String y= “ He is “+ age+”years old”;
System.out.println(y);
String z=“ He is “+ x+”years old”
System.out.println(z);
Data conversion with valueOf()
static String valueOf(byte/short/int/long)
static String valueOf(float/double)
static String valueOf(char)
static String valueOf(boolean)
static String valueOf(Object) valueOf() calls toString( ) methods which
returns the description of the object.
The class Object is the super/base of all predefined and user defined
classes. The Object class has a String toString() method and that
method can be overridden by user defined class.
Use of toString() method
class Money {
int rupee;
int paisa;
Money(){
rupee=0;
paisa=0;
}
Money(int x,int y){
rupee=x;
paisa=y;
}}
class Demo{
public static void main(String t[]){
Money m=new Money(10,50);
System.out.println(m.rupee);
System.out.println(m.paisa);
System.out.println(m);
}}
Use of toString() method
class Money {
int rupee;
int paisa;
Money(){
rupee=0;
paisa=0;
}
Money(int x,int y){
rupee=x;
paisa=y;
}}
class Demo{
public static void main(String t[]){
Money m=new Money(10,50);
System.out.println(m.rupee);
System.out.println(m.paisa);
System.out.println( “Rs”+ m.rupee+”.”+m.paisa+”paisa”);
}} Rs 10.50 paisa
Use of toString() method
class Money {
int rupee;
int paisa;
Money(){
rupee=0;
paisa=0;
}
Money(int x,int y){
rupee=x;
paisa=y;
}}
String toString(){
String z= “Rs”+rupee+”.”+paisa+”paisa”;
retrun z;} }
class Demo{
public static void main(String t[]){
Money m=new Money(10,50);
System.out.println(m);}} Rs 10.50 paisa
Methods of String class
1. Character extraction
int charAt(int index);
char x=“abc”.charAt(1);
System.out.println(x);
char [ ] toCharArray();
2. String comparison
boolean equals(Object );
boolean equalsIgnoreCase(Object );
String s1=“Hello”;
String s2=new String(“Hello”);
String s3=“HELLO”;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equalsIgnoreCase(s3));
String s4=s1;
Methods of String class
equals() versus ==
System.out.println(s1==s2);
System.out.println(s1==s4);
== OPERATOR
String s1=“hello”;
String s2=“hello”;
System.out.println(s1==s2);
String s1=“hello”;
String s2= new String(“hello”);
System.out.println(s1==s2);
StringBuffer reverse()
StringBuffer delete(int start, int end);