Important String class Methods:
class String
{
int
Length()
{
}
toUpperCase()
{
}
toLoerCase()
{
}
}
package StringBasicNew1;
public class LengthOfString {
public
static void main(String[] args) {
//
Declare String variable and store
"RaMa" val
String
s = "RaMa";
//
length of string
int
l = s.length();
// 4
// l=
4
// return / gives length of String i.e
how many characters are there in String i.e 4 // value will be stored in left side variable
i.e l
// so l contains 4 value
//
display length
System.out.println("Length
of string="+ l);
//
//
s = "Ram" ; length= 3 ?
s=
"Ram";
l
= s.length();
// 3
// l = 3
System.out.println("Length
of string="+ l);
//
HW s= "sita" , length =?
// HW s=
"Rama rao";// 8 count space char also
//String toUppercase():
// convert the given String to
Upper case and return String value
// "RaMa" -->
"RAMA"
// "RAMA" -->
"RAMA"
s=
"RaMa";
String
ucaseString = s.toUpperCase();
// "RaMa". --> "RAMA"
// "RAMA"
// ucaseString
= "RAMA"
System.out.println("ucaseString="+ucaseString);
// RAMA
//
HW s = "sita" convert into upper case?
//
s.toLowerCase() "RaMa" //
covert the given String to lower case
s=
"RaMa";
String
lcaseString = s.toLowerCase();
// RaMa
// rama
// lcaseString = rama
//
System.out.println("lcaseString
="+ lcaseString);
//HW
s = "SitA" --> convert
string to lower case -->
// sita
//
HW s=
Rama rao , convert string to lower
case -->
// rama rao
}
}
HW:
//
Declare String var
String
s ;
s= "RaMa rao";
// 1234
//HW
length of string
//
HW convert to upper case and lower case?
o/p:
charAt(int indexno) :
char charAt(int indexno)
{
}
·
The charAt
method is a predefined method in the Java language
·
It can be used to get the character value at a
given index (0, 1, 2, etc.).
·
It returns the character value at the specified
index.
·
The return type is char.
package StringBasicNew1;
public class CharAtBasics {
public
static void main(String[] args) {
String
s = "RAM"; // length = 3
// 012
34567 index numbers
//
get char at index no =0 i.e 'R'
char
ch0 = s.charAt(0);
// 'R'
// ch0
= 'R'
System.out.println("ch0="+
ch0);
// 'R'
//
get char at index no =1 i.e 'A'
char
ch1 = s.charAt(1);
// 'A'
//
ch1= 'A'
System.out.println("ch1="+
ch1);
// 'A'
//
HW get char at index no =2 i.e 'M'
// get char at index no
=4 ????
// char ch4 =s.charAt(4);// Error// Exception
in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 3
// as we are using invalid index no i.e index no
=4 is not valid
//
display char
// System.out.println("ch4="+ ch4);
//
get each Char from String and display
using for loop
//
RAM
//
012
System.out.println("***************");
s = "RAMA rao";
// 01234567
-- l = 8
// for(int i=0;i<=2;i++)
for(int
i=0;i<=s.length()-1;i++)
{
// i<=7
char
ch =s.charAt(i);
// s.charAt(1);
//.....
//.....
System.out.println("ch="+ch);
}
System.out.println("after
for loop");
// ch=R
// ch=A
// ch=M
}
}
Note1:
· Nested if statements - possible
· Nested for loops - possible
· Nested methods - not possible
Example demonstrating that nested methods are not allowed:
package StringBasicNew1;
public class TestNestedMethod {
//
Define M2 inside M1()
public
static void M1()
{
public
static void M2() // Nested Method is not possible
{
// We cannot define method inside another method
}
}
public
static void main(String[] args) {
}
}
2. Duplicate
methods with the same data type arguments are not allowed in Java.
· The same method signature is not allowed.
Duplicate method with same data
type args not allowed in java
Same method signature is not allowed .
Method signature --> Method name + parameter list
public static void main(String[]
arr) { // always execution start from main () which has signature public static
void and Main() we have to pass String
array...
}
package StringBasicNew1;
public class TestNestedMethod {
// public static void main(String[] args) { // error
//
//
// }
public
static void main(int[] args) {
}
public
static void main(int a) {
}
// public static void main(int x) // erro e
// {
//
//
// }
public
static void main(String[] args) {
}
}
int
indexOf(String s):
The indexOf method returns the index within this string of the
first occurrence of the specified substring.
If the substring is not found, it returns -1.
String s = "RAMA";
// 0123
get index no of given String i.e R
--> 0
if given string is not there in main String ,
it returns -1.
return type - int
package StringBasicNew1;
public class indexOfBasics1 {
public
static void main(String[] args) {
String
s = "RAMA";
// 0123
//get
index no of given String i.e R
int
indexOfR = s.indexOf("R");
// 0
//
can be used to get index no of given String val i.e "R" - 0
// indexNoOfR
= 0
System.out.println("indexOfR="+indexOfR);
// 0
// index no of given value "A"
int
indexOfA = s.indexOf("A");
//
//
can be used to get index no of given String val 'A' i.e 1
// indexOfA = 1
System.out.println("indexOfA="+indexOfA);
// 1
//HW get index no of given String val
"M" i.e 2
// -ve
if given String val is not there i.e "P" in main string, this method return -1
int
indexOfP = s.indexOf("P");
// -1
//
//
indexOfP = -1
System.out.println("indexOfP="+indexOfP);
// -1
//
Note : if duplicates characters are
there in String i.e "A ", it
always gets the first matched index no
int
indexOfA1 = s.indexOf("A");
// 1
// indexOfA1
== 1 but not 3
System.out.println("indexOfA1
="+indexOfA1);
// 1
}
}
// String substr(int indexno)
:
The substring
method can be used to get a subpart or some part of the string from the given
index to the last index.
String
s = "RAMA";
// 0123
String s0 = s.substring(0);
// // Get string values
from index 0 to the end
package StringBasicNew1;
public class SubStringWith1Arg {
public
static void main(String[] args) {
// substr() :
can be used to get sub part or some part of string from given index no
to till last index no
String
s = "RAMA";
// 0123
// substr(int index) : can be used to get sub part or some part of
string from given index no to till last index no
//
get string values from index no 0 to all
String
substring0 = s.substring(0);
// get string values from
index no 0 to all
// RAMA
// substring0
= RAMA
System.out.println("substring0="+substring0);
// // get string values from index no = 1 to all
String
substring1 =s.substring(1);
// substring1= AMA
System.out.println("substring1="+substring1);
//
//HW get
string values from index no = 2 to all
// HW get string values from index no = 3 to all
// get string values from index no = 4 to all
String
s4= s.substring(4);
System.out.println("s4="+
s4);
// Note :
it does not throw error, even if we use invaid idex no
// it displays empty value subStr4=
}
}
Substring with 1 arg:
substring(int startIndexNo)
substring(int startIndexNo , int endingindexNo)
The substring
method can be used to get a part of the string from the given start index to
the end index (excluding the end index).
String
s = "RAMA";
// 0123
// substring(0,n) -->
get values from o to n-1 indexno
// substring(0,1) -->
get values from o to 0 indexno i.e “R”
// substring(0,2) -->
get values from o to 1 indexno
i.e “RA”
// substring(0,3) -->
get values from o to 2 indexno
i.e “RAM”
package StringBasicNew1;
public class SubStringWith2Args {
public
static void main(String[] args) {
String
s = "RAMA";
// 0123
//get
string values from index no =0 to 0
indexno i.e R
String
s01 = s.substring(0, 1); //0,0
// s01= R
get string values from index no =0
to n-1 indexno
//
System.out.println("s01="+
s01);
// get string values from index no =0 to 1 =
String
s02=s.substring(0, 2);// get string values
from index no =0 to 2-1 = 1
// RA
// s02 =
RA
System.out.println("s02="+
s02);
//
//HW get all string values from 0 to 2 o/p: RAM
//
HW get all String values from 0 to 3
o/p: RAMA
}
}
package StringBasicNew1;
public class SubStringWith2Args2
{
public
static void main(String[] args) {
String
s = "RAMA";
// 0123
// subString( beginindex, end index)
// 1,n -
values from 1 to n-1 indexno
String
s12=s.substring(1, 2);// get string
values from indexno =1 to 2-1 i.e 1,1
// A
//
System.out.println("s12
="+ s12);
String
s13= s.substring(1, 3);
// get string values from index no =1
to 3-1 =2 1,2
// AM
System.out.println("s13="+s13);
//
String
s11= s.substring(1, 1);// get string values
from indexno =1 to 1-1 = 0
// empty val ***
System.out.println("s11
= "+ s11);
}
}
o/p:
HW Write o/p for below program
String s = "RAMA Rao"; display ?
s.substring(2, 3);
s.substring(2, 4);
s.substring(2, 5);
HW Write o/p for below program
String s = "RAMA Rao"; display ?
s.substring(3, 6);
s.substring(3, 5);
s.substring(3, 4);
LastIndexOf():
The lastIndexOf
method returns the index within this string of the last occurrence of the
specified substring.
If the substring is not found, it
returns -1.
gets last index no of given
string
String
s = "rama";
// 0123
//
s.indexOf("a");
s.lastIndexOf("a");
package StringBasicNew1;
public class LastIndexOf {
public
static void main(String[] args) {
String
s = "rama";
// 0123
//
s.indexOf("a"); //
//
returns /gives index no go given String
"a" -- first matched index no = 1
//
get last index no of given String 'a'
int
lastIndexOfa = s.lastIndexOf("a");
// 3
//
lastIndexOfa = 3
//
Last index no of given String value 'a' =3
System.out.println("lastIndexOfa="+lastIndexOfa);
// 3
}
}
s= "CNo: '123' is created
succcesfully"
Get number from 123 which is
enclosed in ''
package StringBasicNew1;
public class
GetNumberFromStringinSingleQuotes {
public
static void main(String[] args) {
//// s= "CNo: '123' is created succcesfully"
// s=
"CNo: '25065' is created
succcesfully"
// get
numbers in single quotes ''
// o/p: 123
// 25065
String
s="CNo:'123' is created
succcesfully";
// 0123456789
// String s="CNo:'25065' is created succcesfully";
// 012345678910
//
get numbers from single quotes
// String number = s.substring(5, 8);
// get values from index
no =5
to 7
// "123"
// System.out.println("number="+number);
// get indexno of first single quotes
int
firstIndexOfQuotes = s.indexOf("'");
// 4
//
get index no of last single quotes '
int
lastIndexofQuotes = s.lastIndexOf("'");
// 8
String
number = s.substring(firstIndexOfQuotes + 1, lastIndexofQuotes);
// 5,8 -- valeus from index no =5 to 7
System.out.println("number="+number);
// number=123
}
}
HW get 182 from string s=
"Inbox (182)";
s= "Inbox (2000)";
o/p :
182
Hw get 123 from String "order: 123 created"
o/p: 123
Note:
// ==
Relational operator ==,<,><=, >=, !=
//
== operator can be used to compare the
numbers but not string values
// ex:
10 == 10 -->
10 == 30
-->
// If We want to compare 2 String values- we
have to use Equals().
Don't
use == to compare string values or
content
//
Equals() method - can be used to check 2
given String Values are equal or not
// if 2 string values are equal - this method returns true
// else false
package StringBasicNew1;
public class Equals {
public
static void main(String[] args) {
String
s1 = "Ram";
String
s2= "Ram";
String
s3 ="sita";
//
check s1 equals s2
boolean s1s2Result = s1.equals(s2);
// "Ram".equals("Ram");
// true
//s1s2Result = true
System.out.println("s1s2Result="+s1s2Result);
//
true
//
check s1 equals s3
boolean
s1s3result = s1.equals(s3);
//
"Ram".equals("sita")
// false
//s1s3result =
false
System.out.println("s1s3result="+s1s3result);
//
false
}
}
concat():
+
--> addition operator
+
--> concatenation operator --
join values if any one value is String
It can be used to join 2 string
values, concatenation operations
package StringBasicNew1;
public class ConcatenationBasics
{
public
static void main(String[] args) {
String
s1 = "Ram";
String
s2= "Ram";
String
s3 ="sita";
// join s1 and s3 "Ram" "Sita" --> "RamSita"
String s1s3Concat = s1.concat(s3);
// "Ram" "Sita"
// "RamSita"
System.out.println("s1s3Concat="+s1s3Concat);
//
//
HW join s1 and s2
//
//
// res
}
}
Note:
System.out.println("s5="+s5);//
s5=ramsitaLakshman
// s3.concat(10);// error :
//The
method concat(String) in the type String is not applicable for the arguments
(int)
We must pass String value in
concat(Sting) but not int no
s1.contains(String s2):
The contains method can be used to check if a string (s1) contains another string (s2).
- If s1 contains s2, this method returns true.
- Otherwise, it returns false.
package StringBasicNew1;
public class containsBasics {
public static void main(String[]
args) {
String
s1 = "ramsitaLakshman";
String
s2 = "ram";
//
check s1 contain s2 value -- true else
false
boolean
s1containss2 = s1.contains(s2);
// ramsitaLakshman ram
// true
//
s1containss2= true
System.out.println("s1containss2="+s1containss2);
// true
// check s1 contains "Hanuman"
boolean
res2 =s1.contains("Hanuman");
// ramsitaLakshman Hanuman
// false
///
res2 = false
System.out.println("res2="+
res2);
// false
}
}
String
trim():
The trim method can be used to remove leading and trailing
spaces from a string.
or
It can be used to remove spaces
in String from both sides
"
Ram sita "
package StringBasicNew1;
public class TrimBasics {
public
static void main(String[] args) {
//
Trim() - used to remove spaces in String from both sides
String
s1 = " ram sita Lakshman ";
System.out.println("before
Trim -s1="+ s1);// ram sita
Lakshman
//
remove spaces in String from both sides
s1
= s1.trim();
// "ram sita Lakshman" -- no spaces
System.out.println("after
trim s1="+s1);
}
}
o/p:
before Trim -s1= ram sita Lakshman
after trim s1=ram sita Lakshman
char[]
toCharArray():
The toCharArray method converts a string to a character array.
- Return type: char[]
package StringBasicNew1;
public class TocharArrayBasics {
public
static void main(String[] args) {
//
ToCharArray
String
s = "ram";
//
convert string to char array
char
[] charr = s.toCharArray();
// ram
// 012
// char chArr = s.toCharArray();
//
Type mismatch: cannot convert from char[] to char
// left side, we must declare char array using
[] but not char variable
//
get values from char array by index no =0,1
System.out.println("charr[0]="+
charr[0]);
//
r
System.out.println("charr[1]="+
charr[1]);
//
a
//HW get all values from char array using for loop
with int indexno
//
Hw get all values from char array using 'foreach' loop
}
}
boolean
startsWith(String s2):
The startsWith method can be used to check if a string (s1) starts with a given value.
- If s1 starts with the specified s2
value, this method returns true.
- Otherwise, it returns false.
s1.startswith(s2):
String s1 = "Ram sita
lakshman";
// check S1 startswith
"Ram"
>
true
can be used to check String s1
starts with given value- it returns true else false
check s1.startswith '';
boolean s1startsWithRam=
s1.startsWith("Sita");
//
--> false
package StringBasicNew1;
public class StratsWithEndsWith {
public
static void main(String[] args) {
String
s1 = "Ram sita lakshman";
//
check s1 starts with "Ram"
boolean
res =s1.startsWith("Ram");
// "Ram sita lakshman" "Ram"
// true
// res = true
System.out.println("res="+
res);
// true
//
check s1 starts with "Sita"
res
=s1.startsWith("Sita");
// //
"Ram sita lakshman"
"Sita"
// false
System.out.println("res="+
res);
//
check s1 starts with "ram"
res
=s1.startsWith("ram");
// "Ram sita lakshman" "ram"
// false
//
//
System.out.println("res="+
res);
}
}
//HW WAP to check String s1 =
"Ram sita lakshman" endswith
"laskhman"
check s1 ends with sita
check s1 ends with "Lakshman"
String Replace("old val", "new val"):
The replace
method can be used to replace an old value with a new value in a string.
String s =
"ram-sita-laskhman";
// replace
- eifen --> by comma ,
--> String replacedString =
s.replace("-", ","); //
replacedString = "ram,sita,lakshman"
package StringBasicNew1;
public class ReplaceBasics {
public
static void main(String[] args) {
//Replace
String
s = "ram-sita-laskhman";
// replace
- eifen --> by comma ,
String
s1 = s.replace("-", ",");
// "ram-sita-laskhman"
//
s1 ="ram,sita,laskhman";
System.out.println("s1="+
s1);
// in s1, replace comma ,
by spaces
// --> "ram sita laskhman";
s1=
s1.replace(",", " ");
//
System.out.println("s1="+
s1);
// s1=ram sita laskhman
//HW . in String S , replace
"ram" by "Amar"
// "ram-sita-laskhman";-->
"Amar-sita-laskhman"
}
}
String[] Split("String val" or reg exp) :
The split
method can be used to split a string into an array of substrings based on the
given regular expression (regex). It stores all the values in a string
array.
(or)
to split the values based on
given String value i.e - , and it stores
all values in String array
-return type is string array
String
s = "10-20-30";
package StringBasicNew1;
public class SplitBasics {
public
static void main(String[] args) {
String
s = "10-20-30";
// split the values based on given String value
i.e - , and it stores all values in
String array
//
return type - string [] array
//
split by "-"
String
[] sarr = s.split("-");
// "10-20-30"
//
sarr[0] = 10
//
sarr[1] = 20
//
sarr[2] = 30
//
display values
System.out.println("sarr[0]="+
sarr[0]);
//sArr[0]= 10
// sArr[1]=
System.out.println("sarr[1]="+
sarr[1]);
// 20
// HW
display all values from sArr using for
loop with index no
// HW
display all values from sArr using 'for
each' loop
}
}
HW Split the String with comma (,) and display
array values
//
String s1 = "11,22,33,44"
HW Split String by space and display
array values
// String
s3 = "Ram sita lakhman";
//HW get only
100.00 from "$ 100.00"
String
s4 = "$ 100.00";
// 100.00
Hint
: use replace or substring()?
// HW get 100.00 from "100.00 $" use Substring and index no
IP FAQ Swap 2 variables using 3rd variable ?
// a= 10
b=20
//
o/p: a=20 , b=10
package
StringBasicNew1;
public
class Swap2NumbersUsing3rdVariable {
public static void main(String[]
args)
{
int a =10;
int b=20;
System.out.println("Before
swapping a="+ a + " b="+b);
int tmp;
tmp = a;
a = b;
b = tmp;
System.out.println("After
swapping a="+ a + " b="+b);
}
}
IP: FAQ Swap 2 variables without 3rd variable ?
package
StringBasicNew1;
public
class Swap2NumberswihOutUsing3rdVariable {
public static void main(String[]
args) {
int a = 3;
int b = 2;
System.out.println("Before
swapping a="+ a + " b="+b);//
3 , 2
// not using any
3rd variable, use substraction
and addition and
a = a - b;
// 3 -2
// 1
// a = 1 latest value
b = a + b;
// 1 + 2
// 3
// b = 3 Latst
value
a = -(a - b);
// -(1 - 3)
// -(-2)
// a= +2
// a = 2
// note: we can
write this stmt a = -a + b; (or)
a = b-a;
// a = -a + b;
// (or)
// a = b-a;
System.out.println("After
swapping a="+ a + " b="+b);
//
}
}
o/p:
Before
swapping a=3 b=2
After
swapping a=2 b=3
IP: FAQ "Ram is good boy"; Count of words in String ?
String
s = "Ram is good boy";
o/p: 4
package StringBasicNew1;
public class CountofWordsFromString
{
public
static void main(String[] args) {
//
FAQ "Ram is good boy";
// Count of words in String ? 4
String
s= "Ram is good boy";
//String
s= "Ram is good boy. Sita is from Srilanka.";
//
split by space
String[]
sarr = s.split(" ");
// sarr[0] = ram
// sarr[1] = is...etc
//
count of array
int
wordsCnt = sarr.length;
// 4
//
count of words= 4
System.out.println("wordsCnt="+wordsCnt);
//
display 1st,2nd word
System.out.println("1st
word ="+ sarr[0]);
System.out.println("2nd
word ="+ sarr[1]);
// display all values from array using with for loop with index no
for(int
i=0;i<=sarr.length-1;i++)
{
System.out.println("all
values fron string array =" + sarr[i]);
}
// display all values from array using 'for
each' loop
for(String x :
sarr)
{
System.out.println("all
values from array using for each loop ="+ x);
}
}
}
o/p:
wordsCnt=4
1st word =Ram
2nd word =is
all values fron string array =Ram
all values fron string array =is
all values fron string array
=good
all values fron string array =boy
all values from array using for
each loop =Ram
all values from array using for
each loop =is
all values from array using for
each loop =good
all values from array using for
each loop =boy
IP : FAQ VImp *** : Reverse of String ?
i/p: RAM
o/p: MAR
Sita
atiS
way1-: using charAt():
package StringBasicNew1;
public class
ReverseOFStringUsingCharAt {
public
static void main(String[] args) {
String
s = "RAM"; // sl.length() ; //5
// 012
//
o/p: MAR
//way1-:
using charAt()
//--------------------------------
for(int
i=2;i>=0;i--) // i varies 2 = to 0 // i
=2, 2-1 =1, 1-1=0, 0-1 = -1
{
// 2>=0 true, enters for loop
// 1>=0 , true, enters for loop
// 0>=0
true , for
// -a>=0
false, ctrl goes after for loop
char
ch = s.charAt(i);
// 2 - 'M'
// 1 - 'A'
// 0 -- 'R'
// ch = 'R'
System.out.print(ch);//
MAR
}
// AMAR
}
}
Way2 using to chararay():
package StringBasicNew1;
public class
ReverseOFStringUsingCharARRay {
public
static void main(String[] args) {
String
s = "RAM"; // sl.length() ; //5
// 01234
//
o/p: MAR
char
[] charr = s.toCharArray();
// "RAM" --->
R A M
// 0 1 2
for(int
i=2;i>=0;i--)
{
System.out.print(charr[i]);
}
}
}
Way 3: always prefer this one
package StringBasicNew1;
public class
ReverseOFStringUsingCharAt2 {
//
Define method - reverseOfString and pass
String var
public
static String reverseOfString(String s)
{ // RAM s= RAM
// 012 len= 3
//
String
rev = ""; // rev = ""-->
"M" -->
"MA" --> "MAR"
for(int
i=s.length()-1;i>=0;i--)// i=2, 2-1=1, 1-1=0, 0-1 = -1
{
// i=3-1 =2;2>=0, true, for loop
// 1>=0 true , for loop
// 0>=0 , for loop
// -1>=0 false, after for loop
char
ch = s.charAt(i);
// s.charat(0) -'R'
// ch = 'R'
// System.out.println(ch);
rev
= rev + ch;
// "MA" + R
//
//
rev = "MAR"
// System.out.println("revers
of string ="+ rev);
}
System.out.println("revers
of string ="+ rev);
// MAR
return
rev;
// "MAR"
}
public
static void main(String[] args) {
System.out.println("hi");
String
s = "RAMA"; // sl.length() ; //5
// 01234
//
o/p: MAR
//
call reverseOfString() and display the o/p
String
result= reverseOfString("RAM");
// "MAR"
// result
= "MAR"
System.out.println("result="+result);
// MAR
}
}
No comments:
Post a Comment