Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
2) By new keyword
String s=new String("Welcome");//creates two objects and one
reference variable
Java String class methods: The java.lang.String class provides many useful methods
to perform operations on sequence of char values.
No Method
.
1 char charAt(int index)
Description
returns char value for the particular
index
returns string length
returns formatted string
2
3
int length()
static String format(String format, Object... args)
boolean contains(CharSequence s)
10
11
boolean isEmpty()
12
13
14
15
String trim()
16
17
18
String intern()
19
20
21
returns
index
22
23
24
String toLowerCase()
String toLowerCase(Locale l)
25
26
String toUpperCase()
String toUpperCase(Locale l)
specified
substring
String concatenation
class Testconcat
{
public static void main(String args[])
{
String s=Vignan";
//concat() method appends the string at the end
s=s.concat(" University");
System.out.println(s);
}
class Teststringcomparison1{
public static void main(String args[]){
String s1=Vignan";
String s2=Vignan";
String s3=new String(Vignan");
String s4=Vadlamudi";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
class Teststringcomparison2{
public static void main(String args[]){
String s1=Vignan";
String s2=VIGNAN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
}
}
Substring in Java
public String substring(int startIndex): This method returns new String
object containing the substring of the given string from specified
startIndex (inclusive).
public String substring(int startIndex, int endIndex): This method
returns new String object containing the substring of the given string
from specified startIndex to endIndex.
In case of string:
startIndex: inclusive
endIndex: exclusive
The string trim() method eliminates white spaces before and after
string.
String s=Vignan";
System.out.println(s.startsWith(Vi"));//true
System.out.println(s.endsWith("n"));//true
Java String charAt() method
The string charAt() method returns a character at specified index.
String s=Vignan";
System.out.println(s.charAt(0));//V
System.out.println(s.charAt(3));//n
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
import java.io.*;
class palin
{
public static void main(String a[])
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(Enter a String);
String str=br.readLine();
String temp=str;
StringBuffer sb=new StringBuffer(str);
Sb.reverse();
str=sb.toString();
if(temp.equalsIgnoreCase(str))
System.out.println(temp+ is palindrome);
else
System.out.println(temp+ is not a palindrome);
}
}