Strings
Strings
Strings
========
1)Immutable object
--------------------
After object creation if we perform any changes then for every change a new object
will be created such type of object is called immutable object.
ex:
String and Wrapper classes
2)Mutable object
---------------
After object creation if we perform any changes then all the changes will be
reflected
in a single object such type of object is called mutable object.
ex:
StringBuffer and StringBuilder
String
=======
A String is a collection of characters which is enclosed in a double quotations.
case1:
------
Once if we create String object we can't perform any changes.If we perform any
changes then
for every change a new object will be created such behaviour is called immutability
of an
object.
Diagram: 1
case2:
-------
Q)What is the difference between == and .equals() method?
==
---
It is a equality operator or comparision operator which always return boolean
value.
ex:
class Test
{
public static void main(String[] args)
{
String s1=new String("bhaskar");
String s2=new String("solution");
System.out.println(s1==s2); //false
}
}
.equals()
---------
It is a method present in String which always return boolean value.
ex:
---
class Test
{
public static void main(String[] args)
{
String s1=new String("bhaskar");
String s2=new String("bhaskar");
System.out.println(s1.equals(s2)); // true
}
}
case3:
-----
Once if we create a String object.Two objects will be created one is on heap and
another
is on SCP (String Constant Pool) area.But 's' always points to heap area only.
ex:
String s=new String("bhaskar");
Diagram:2
Object creation in SCP area is always optional.First JVM will check is there any
object
is created with same content or not.If it is created then it simply refers to that
object.
If it is not created then it will create a new object.Hence there is no chance of
having
duplicate objects in SCP area.
SCP objects do not have any reference even though garbage collector can't access
them.
SCP objects will destroy at the time when JVM shutdowns or terminated.
Diagram:3
Diagram:4
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Welcome :"+str);
}
}
approach2
--------
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Welcome :"+str);
}
}
input:
Ih@ub_Tale$nt
output:
IhubTalent
ex:
class Test
{
public static void main(String[] args)
{
String str="Ih@ub_Tale$nt12";
str=str.replaceAll("[^A-Za-z0-9]","");
System.out.println(str);
}
}
Q)Write a java program to display given character which is present in given index?
input:
str = "bhaskar";
index = 3;
output:
s
ex:
---
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
int index=3;
char ch=str.charAt(index);
System.out.println(ch);
}
}
Q)Write a java program to check given word present in a given string or not?
input:
str= "This is java class";
word= "java";
output:
It is present
ex:
class Test
{
public static void main(String[] args)
{
String str="This is java class";
String word="java";
if(str.contains(word))
System.out.println("It is present");
else
System.out.println("It is not present");
}
}
input:
bhaskar
output:
BHASKAR
ex:
---
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
str=str.toUpperCase();
System.out.println(str);
}
}
input:
BHASKAR
output:
bhaskar
ex:
class Test
{
public static void main(String[] args)
{
String str="BHASKAR";
str=str.toLowerCase();
System.out.println(str);
}
}
input:
bhaskar
output:
7
ex:
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
int len=str.length();
System.out.println(len);
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
String str1="bhaskar";
String str2="bhaskar";
if(str1.equals(str2))
System.out.println("Both are equals");
else
System.out.println("Both are not equals");
}
}
approach2
---------
class Test
{
public static void main(String[] args)
{
String str1="bhaskar";
String str2="BHASKAR";
if(str1.equalsIgnoreCase(str2))
System.out.println("Both are equals");
else
System.out.println("Both are not equals");
}
}
Q)Write a java program display the first occurance index number of a given
character?
input:
str= "bhaskar";
ch='a';
output:
2
ex:
---
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
char ch='a';
int index=str.indexOf(ch);
System.out.println(index);
}
}
Q)Write a java program display the last occurance index number of a given
character?
input:
str= "bhaskar";
ch='a';
output:
5
ex:
---
class Test
{
public static void main(String[] args)
{
String str="bhaskar";
char ch='a';
int index=str.lastIndexOf(ch);
System.out.println(index);
}
}
input:
hello
output:
olleh
ex:
---
class Test
{
public static void main(String[] args)
{
String str="hello";
char[] carr=str.toCharArray(); // h e l l o
String rev="";
for(int i=carr.length-1;i>=0;i--)
{
rev+=carr[i];
}
System.out.println(rev);
}
}
input:
racar
output:
It is a palindrome string
ex:
class Test
{
public static void main(String[] args)
{
String str="racar";
char[] carr=str.toCharArray(); // h e l l o
String rev="";
for(int i=carr.length-1;i>=0;i--)
{
rev+=carr[i];
}
if(str.equals(rev))
System.out.println("It is a palindrome string");
else
System.out.println("It is not a palindrome string");
}
}
input:
This is Java class
output:
class Java is This
ex:
---
class Test
{
public static void main(String[] args)
{
String str="This is Java class";
String rev="";
for(int i=sarr.length-1;i>=0;i--)
{
rev+=sarr[i]+" ";
}
System.out.println(rev);
}
}
input:
This Is Java Class
output:
sihT sI avaJ ssalC
ex:
---
class Test
{
public static void main(String[] args)
{
String str="This Is Java Class";
for(String s:sarr)
{
//convert the string to char array
char[] carr=s.toCharArray(); // T h i s
for(int i=carr.length-1;i>=0;i--)
{
rev+=carr[i];
}
//space
rev+=" ";
}
System.out.print(rev);
}
}
input:
This Is Java Class29
output:
uppercase letters : 4
lowecase letters : 11
digits : 2
words : 4
spaces : 3
ex:
---
class Test
{
public static void main(String[] args)
{
String str="This Is Java Class29";
char[] carr=str.toCharArray();
int upper=0,lower=0,digit=0,word=1,space=0;
for(char ch:carr)
{
if(ch>='A' && ch<='Z')
{
upper++;
}
else if(ch>='a' && ch<='z')
{
lower++;
}
else if(ch>='0' && ch<='9')
{
digit++;
}
else if(ch==' ')
{
word++;
space++;
}
}
System.out.println("Uppercase letters : "+upper);
System.out.println("Lowercase letters : "+lower);
System.out.println("Digits : "+digit);
System.out.println("Words : "+word);
System.out.println("Spaces : "+space);
}
}
input:
google
output:
og
class Test
{
public static void main(String[] args)
{
String str="google";
String duplicates="";
String characters="";
for(int i=0;i<str.length();i++)
{
String current=Character.toString(str.charAt(i));
if(characters.contains(current))
{
if(!duplicates.contains(current))
{
duplicates+=current;
continue;
}
}
characters+=current;
}
System.out.println(duplicates);
}
}
input:
google
output:
gole
ex:
---
class Test
{
public static void main(String[] args)
{
String str="google";
String duplicates="";
String characters="";
for(int i=0;i<str.length();i++)
{
String current=Character.toString(str.charAt(i));
if(characters.contains(current))
{
if(!duplicates.contains(current))
{
duplicates+=current;
continue;
}
}
characters+=current;
}
System.out.println(characters);
}
}
ex:
class Test
{
public static void main(String[] args)
{
String str="A1B2C3D4";
for(int i=0;i<str.length();i++)
{
if(Character.isAlphabetic(str.charAt(i)))
{
System.out.print(str.charAt(i));
}
else
{
int j=Character.getNumericValue(str.charAt(i));
for(int k=1;k<j;k++)
{
System.out.print(str.charAt(i-1));
}
}
}
}
}
Q)Write a java program to display most repeating character from given string?
input:
googleformat
output:
o is repeating for 3 times
ex:
---
class Test
{
public static void main(String[] args)
{
String str="googleformat";
int maxCount=0;
char character=' ';
for(int i=0;i<str.length();i++)
{
int cnt=0;
for(int j=0;j<str.length();j++)
{
if(str.charAt(i)==str.charAt(j))
{
cnt++;
}
}
if(maxCount<cnt)
{
maxCount=cnt;
character=str.charAt(i);
}
}
System.out.println(character+" is repeating for "+maxCount+" times");
}
}
input:
str = ihubtalent
cnt = 2
output:
ubtalentih
ex:
---
class Test
{
public static void main(String[] args)
{
String str ="ihubtalent";
String str1=str.substring(0,2);
String str2=str.substring(cnt,str.length());
System.out.println(str2+str1);
}
}
input:
str = ihubtalent
cnt = 2
output:
ntihubtale
ex:
---
class Test
{
public static void main(String[] args)
{
String str ="ihubtalent";
String str1=str.substring(0,str.length()-cnt);
String str2=str.substring(str.length()-cnt,str.length());
System.out.println(str2+str1);
}
}
Q)Write a java program to display the strings starts with uppercase letters?
input:
This is Java session For upcoming Students
output:
This Java For Students
ex:
---
class Test
{
public static void main(String[] args)
{
String str ="This is Java session For upcoming Students";
input:
ABC
output:
ABC
ACB
BAC
BCA
CBA
CAB
Diagram:5
ex:
---
Assignment
============
Q)Write a java program to display the string in below format?
input:
ABBCCCDDDD
output:
A1B2C3D4
input:
str1 = silent
str2 = listen
output:
It is a anagram string
ex:
---
import java.util.Arrays;
class Test
{
public static void main(String[] args)
{
String str1="silent";
String str2="listen";
char[] carr1=str1.toCharArray();
char[] carr2=str2.toCharArray();
Arrays.sort(carr1); // e i l n s t
Arrays.sort(carr2); // e i l n s t
if(carr1.length!=carr2.length)
{
System.out.println("It is not an anagram string");
System.exit(0);
}
boolean flag=true;
for(int i=0;i<carr1.length && i<carr2.length;i++)
{
if(carr1[i]!=carr2[i])
{
flag=false;
break;
}
}
if(flag==true)
System.out.println("It is anagram string");
else
System.out.println("It is not anagram string");
}
}
StringBuffer
=============
If our content is not fixed then it is never recommanded to use String because
for every change a new object will be created.
In StringBuffer all the required changes will be done in a single object only.
constructor
------------
If capacity reaches to maximum capacity then new capacity will be created with
below formulea.
ex:
new capacity = current_capacity+1*2;
ex:
---
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity()); // 16
sb.append("abcdefghijklmnop");
System.out.println(sb.capacity()); // 16
sb.append("qr");
System.out.println(sb.capacity()); // 16+1*2=34
}
}
ex:
---
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer(19);
System.out.println(sb.capacity()); // 19
}
}
capacity = str.length() + 16
ex:
---
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("bhaskar");
System.out.println(sb.capacity()); // 7 + 16 = 23
}
}
class Test
{
public static void main(String[] args)
{
String str="hello";
String rev="";
rev=sb.reverse().toString();
System.out.println(rev);
}
}
class Test
{
public static void main(String[] args)
{
String str="madam";
String rev="";
rev=sb.reverse().toString();
if(str.equals(rev))
System.out.println("It is palindrome string");
else
System.out.println("It is not palindrome string");
}
}
input:
ABBCCCDDDD
output:
A1B2C3D4
ex:
---
public class Test
{
public static void main(String[] args)
{
String str = "ABBCCCDDDD";
int count = 1;
for (int i = 0; i < str.length(); i++)
{
sb.append(str.charAt(i)).append(count);
count = 1;
}
}
System.out.println(sb.toString());
}
}
StringBuilder
==============
StringBuilder is exactly same as StringBuffer with following differences.
StringBuffer StringBuilder
------------ ---------------
All the methods present in StringBuffer No method present in StringBuilder are
synchronized.
are synchronized.
At a time only one thread is allowed Multiple threads are allowed to execute.
Hence we
to execute.Hence we can achieve thread can't achieve thread safety.
safety.
Note:
------
If our content not change frequently then we need to use String object.
If our content change frequently where thread safety is required then we need to
use StringBuffer object.
If our content change frequently where thread safety is not required then we need
to use
StringBuilder object.
StringTokenizer
================
A StringTokenizer is a class which is present in java.util package.
syntax:
ex:
---
import java.util.StringTokenizer;
public class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("This is java class");
System.out.println(st.countTokens());
}
}
Note:
----
Here default regular expression is space.
ex:2
-----
import java.util.StringTokenizer;
public class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("This is java class"," ");
System.out.println(st.countTokens());
}
}
ex:3
----
import java.util.StringTokenizer;
public class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("This is java class"," ");
while(st.hasMoreTokens())
{
String str=st.nextToken();
System.out.println(str);
}
}
}
ex:4
-----
import java.util.StringTokenizer;
public class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("This is java class"," ");
while(st.hasMoreElements())
{
String str=(String)st.nextElement();
System.out.println(str);
}
}
}
ex:5
----
import java.util.StringTokenizer;
public class Test
{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("9,99,999",",");
while(st.hasMoreElements())
{
String str=(String)st.nextElement();
System.out.println(str);
}
}
}