String & Array
String & Array
Array in Java is index-based, the first element of the array is stored at the
0th index, 2nd element is stored on 1st index and so on.
we can get the length of the array using the length member.
1. arrayRefVar=new datatype[size];
1
3.
4. class Testarray{
5. public static void main(String args[]){
6. int a[]=new int[5];//declaration and instantiation
7. a[0]=10;//initialization
8. a[1]=20;
9. a[2]=70;
10. a[3]=40;
11. a[4]=50;
12. //traversing array
13. for(int i=0;i<a.length;i++)//length is the property of array
14. System.out.println(a[i]);
15. }}
1. for(data_type variable:array){
2. //body of the loop
3. }
2
1. //Java Program to print the array elements using for-each loop
2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse the same logic
on any array.
3
1. //Java Program to demonstrate the way of passing an anonymous array
2. //to method.
3. public class TestAnonymousArray{
4. //creating a method which receives an array as a parameter
5. static void printArray(int arr[]){
6. for(int i=0;i<arr.length;i++)
7. System.out.println(arr[i]);
8. }
9.
10. public static void main(String args[]){
11. printArray(new int[]{10,22,44,66});//passing anonymous array to
method
12. }}
4
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if
length of the array in negative, equal to the array size or greater than the
array size while traversing the array.
5
Copying a Java Array
The two Object arguments specify the array to copy from and the array to
copy to. The three int arguments specify the starting position in the source
array, the starting position in the destination array, and the number of array
elements to copy.
7
Java String
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
8
The Java String is immutable which means it cannot be changed. Whenever we
change any string, a new instance is created. For mutable strings, you can use
StringBuffer and StringBuilder classes.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the pooled
instance is returned. If the string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
9
In the above example, only one object will be created. Firstly, JVM will not
find any string object with the value "Welcome" in string constant pool that is
why it will create a new object. After that it will find the string with the value
"Welcome" in the pool, it will not create a new object but will return the
reference to the same instance.
Note: String objects are stored in a special memory area known as the "string
constant pool".
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool.
The variable s will refer to the object in a heap (non-pool).
10
StringExample.java
N Method Descrip
o. tion
11
3. String s1="javatpoint";
4. System.out.println(s1.substring(2,4));//returns va
5. System.out.println(s1.substring(2));//returns vatpoint
6. }}
Output:
va
vatpoint
Output:
12
true
false
Output:
true
false
false
Output:
true
false
13
7 String concat(String str) It
concaten
ates the
1. public class ConcatExample{
specified
2. public static void main(String args[]){ string.
3. String s1="java string";
4. // The string s1 does not get changed, even though it is inv
oking the method
5. // concat(), as it is immutable. Therefore, the explicit assign
ment is required here.
6. s1.concat("is immutable");
7. System.out.println(s1);
8. s1=s1.concat(" is immutable so assign it explicitly");
9. System.out.println(s1);
10. }}
Output:
java string
java string is immutable so assign it explicitly
1. System.out.println(replaceString);
2. }}
Output:
jevetpoint is e very good website
jevetpoint was e very good website
14
doesn't
4. String s2="javatpoint";
check
5. String s3="JAVATPOINT"; case.
6. String s4="python";
7. System.out.println(s1.equalsIgnoreCase(s2));//true because
content and case both are same
8. System.out.println(s1.equalsIgnoreCase(s3));//true because
case is ignored
9. System.out.println(s1.equalsIgnoreCase(s4));//false becaus
e content is not same
10. }}
Output:
true
true
false
15
2. public static void main(String args[]){
3. String s1="this is index of example";
4. //passing substring
5. int index1=s1.indexOf("is");//returns the index of is substri
ng
6. int index2=s1.indexOf("index");//returns the index of index
substring
7. System.out.println(index1+" "+index2);//2 8
8.
9. //passing substring with from index
10. int index3=s1.indexOf("is",4);//returns the index of is
substring after 4th index
11. System.out.println(index3);//5 i.e. the index of anoth
er is
12.
13. //passing char value
14. int index4=s1.indexOf('s');//returns the index of s ch
ar value
15. System.out.println(index4);//3
16. }}
Output:
2 8
5
3
16
3. String s1="hello string";
4. String s1upper=s1.toUpperCase();
5. System.out.println(s1upper);
6. }}
14 String trim() It
removes
1. public class StringTrimExample{
beginnin
2. public static void main(String args[]){ g and
3. String s1=" hello string "; ending
spaces
4. System.out.println(s1+"javatpoint");//without trim()
of this
5. System.out.println(s1.trim()+"javatpoint");//with trim() string.
6. }}
Output
Output:
3010
17
Immutable String in Java
A String is an unavoidable type of variable while writing any application
program. String references are used to store various attributes like
username, password, etc. In Java, String objects are immutable.
Immutable simply means unmodifiable or unchangeable.
Once String object is created its data or state can't be changed but a new
String object is created.
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable obje
cts
6. }
7. }
Output:
Sachin
Now it can be understood by the diagram given below. Here Sachin is not
changed but a new object is created with Sachin Tendulkar. That is why
String is known as immutable.
18
As you can see in the above figure that two objects are created
but s reference variable still refers to "Sachin" not to "Sachin Tendulkar".
For example:
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
In such a case, s points to the "Sachin Tendulkar". Please notice that still
Sachin object is not modified.
19
As Java uses the concept of String literal. Suppose there are 5 reference
variables, all refer to one object "Sachin". If one reference variable changes
the value of the object, it will be affected by all the reference variables. That
is why String objects are immutable in Java.
Following are some features of String which makes String objects immutable.
1. ClassLoader:
2. Thread Safe:
3. ecurity:
As we have seen in class loading, immutable String objects avoid further errors by
loading the correct class. This leads to making the application program more
secure. Consider an example of banking software. The username and password
cannot be modified by any intruder because String objects are immutable. This can
make the application program more secure.
3. Heap Space:
The immutability of String helps to minimize the usage in the heap memory.
When we try to declare a new String object, the JVM checks whether the
value already exists in the String pool or not. If it exists, the same value is
assigned to the new object. This feature allows Java to use the heap space
efficiently.
20
Java String compare
We can compare String in Java on the basis of content and reference.
By Using == operator
The == operator compares references not values.
Teststringcomparison3.java
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpo
ol)
8. }
9. }
21
o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative value.
class Teststringcomparison4{
o public static void main(String args[]){
o String s1="Sachin";
o String s2="Sachin";
o String s3="Ratan";
o System.out.println(s1.compareTo(s2));//0
o System.out.println(s1.compareTo(s3));//1(because s1>s3)
o System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
o }
o }
o Output:
o 0
o 1
o -1
TestStringConcatenation1.java
1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
22
5. }
6. }
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
Constructor Description
23
strings.
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
Output:
Hello Java
24
The insert() method inserts the given String with this string at the given
position.
StringBufferExample2.java
1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
Output:
HJavaello
StringBufferExample3.java
1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
Output:
HJavalo
StringBufferExample4.java
25
1. class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
Output:
Hlo
StringBufferExample5.java
1. class StringBufferExample5{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
Output:
olleH
StringBufferExample6.java
1. class StringBufferExample6{
26
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10.}
Output:
16
16
34
StringBufferExample7.java
1. class StringBufferExample7{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10.System.out.println(sb.capacity());//now 34
11.sb.ensureCapacity(50);//now (34*2)+2
12.System.out.println(sb.capacity());//now 70
13.}
14.}
27
Output:
16
16
34
34
70
28
Java StringBuilder Class
Java StringBuilder class is used to create mutable (modifiable) String. The
Java StringBuilder class is same as StringBuffer class except that it is non-
synchronized. It is available since JDK 1.5.
29
Java 1.0 Java 1.5
StringBuilderExample.java
1. class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
Output:
Hello Java
StringBuilderExample2.java
1. class StringBuilderExample2{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
30
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the
specified beginIndex and endIndex.
StringBuilderExample3.java
1. class StringBuilderExample3{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
Output:
HJavalo
StringBuilderExample4.java
1. class StringBuilderExample4{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
Output:
Hlo
31
StringBuilderExample5.java
1. class StringBuilderExample5{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
Output:
olleH
StringBuilderExample6.java
1. class StringBuilderExample6{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("Java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10.}
16
16
34
32
The ensureCapacity() method of StringBuilder class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
StringBuilderExample7.java
1. class StringBuilderExample7{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("Java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }
Output:
16
16
34
34
70
33