Arraylist add element at specific index

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  
  4. public class AddElementAtSpecifiedIndex {
  5.  
  6.     public static void main(String[] args) {
  7.  
  8.        //create an ArrayList object
  9.         ArrayList arrayList = new ArrayList();
  10.  
  11.         //Add elements to Arraylist
  12.         arrayList.add("a");
  13.         arrayList.add("b");
  14.         arrayList.add("c");
  15.         arrayList.add("d");
  16.         arrayList.add("f");
  17.         arrayList.add("g");
  18.  
  19.         arrayList.add(1,"Y");
  20.  
  21.         System.out.println("ArrayList values...");
  22.  
  23.         //display elements of ArrayList
  24.         for(int index=0; index < arrayList.size(); index++)
  25.           System.out.println(arrayList.get(index));
  26.        arrayList.add(2,"Z");
  27.  
  28.     System.out.println("ArrayList values...");
  29.  
  30.         //display elements of ArrayList
  31.        for(int index=0; index < arrayList.size(); index++)
  32.           System.out.println(arrayList.get(index));
  33.       }
  34.  
  35. }
  36. }
     

  1. OutPut:
  2. ArrayList values...
  3. a
  4. Y
  5. b
  6. c
  7. d
  8. f
  9. g
  10. ArrayList values...
  11. a
  12. Y
  13. Z
  14. b
  15. c
  16. d
  17. f
  18. g
     

String vs stringbuffer vs stringbuilder

1.Definition:

  • String is an immutable sequence of characters.
  • StringBuffer is mutable sequence of characters.
  • StringBuilder is also mutable sequence of characters.

The only difference between StringBuffer and StringBuilder: 

  • StringBuffer object is thread safe , it means StringBuffer object is modified by multiple concurrently, because  all its methods are declared as "synchronized".
  • StringBuilder class is given in jdk 1.5 version as non thread -safe class, means all its methods are non synchronized methods.
  • So , in single model application we must use StringBuilder, so that object locking and unlocking will not be there, hence performance is increased.
  • In single thread model application operations are executed in sequence hence there is no chance of object corruption.

When should we choose String and StringBuffer? 

  • If we do not want to store string modifications in the same memory we must choose String.
  • To do modifications in the same memory, we must choose StringBuffer or StringBuilder.

 Advantage and disadvantage in String: 

  • Advantage : Since modifications are preserving in another memory location, we will have both original and modified values.
  • Disadvantage: It consumes lot memory for every operation, as it stores it modifications in new memory. So it leads to performance issue.
  • Solution: To solve this performance issue , in projects developers store string data using StringBuilder or StringBuffer after all modifications they convert into String and pass it back to user.

Advantage and disadvantage of StringBuffer or StringBuilder:

  • Advantage: It given high performance because consumes less memory as all modifications stored in same memory.
  • Disadvantage: Original value will not be preserved.


2.Creating String , StringBuffer objects: 

String:

  • String object can be created in two ways.
  • By using string literal : String str="instance of java ";
  • By using its constructors: String str= new String("instaneofjavaforus") ;

StringBuffer:

  • By using its available constructors
  • StringBuffer str= new StringBuffer();

StringBuilder:

  • By using its available constructors
  • StringBuilder str= new StringBuilder ();

3.Special operations those we can only perform on StringBuffer and StringBuilder: 

  1. append
  2. insert
  3. delete
  4. reverse
  •  Since string is immutable we cannot perform these operations on String.

4.Concatenation:

  • Using String object we can concat new string to the current  string in two ways.
  1. Using + operator
  2. using concat() method.
  • Using StringBuffer we can perform concat operation only in one way
  1. Using append() method
  • Using StringBuilder we can perform concat operation only in one way
  1. Using append() method

  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.         String str="Java";
  7.         StringBuffer sb= new StringBuffer("Java");
  8.         StringBuilder sbr= new StringBuilder("Java");
  9.  
  10.        System.out.println(str.concat(" language"));    
  11.        System.out.println(sb.append(" language"));
  12.         System.out.println(sbr.append(" language"));
  13. }
  14. }
  15.  
  16. OutPut:
  17. Java language
  18. Java language
  19. Java language


5.Comparison:

  • Using equals() method String objects are compared with state, because it is overridden in this class. Also hashcode(0 method is overridden in order to satisfy equals() method contract.
  • But in StringBuffer and in StringBuilder equals() method is not overridden , so using equals() method their object are compared with reference. 
You might like:

StringBuffer class in java


  • StringBuffer is a thread safe, mutable sequence of characters.
  • A StringBuffer is like a String , but can be modified in the same memory location.
By using following constructors we can create StringBuffer class object.

Constructors;

1.public StringBuffer(): 

  • It  creates empty StringBuffer object with default capacity 16 characters, it means it holds 16 empty locations.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer();
  7.   System.out.println(sb.capacity());
  8. }
  9. }
  10.  
  11. OutPut:
  12. 16


2.public StringBuffer(int capacity):

  • It creates StringBuffer object with given capacity.
  • Capacity value should be positive value. means >=0.
  • If we pass negative value JVM throws "java.lang.NegativeArraySizeException".

  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.  StringBuffer sb= new StringBuffer(12);
  7.  System.out.println(sb.capacity());
  8.  
  9. }
  10. }

  11. OutPut:
  12. 12

3.public StringBuffer(String s):

  • It creates StringBuffer object characters available in passed String object and with default capacity 16 (16+String length) .
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.  StringBuffer sb= new StringBuffer(new String("abc"));
  7.  System.out.println(sb.capacity());
  8.  
  9. }
  10. }

  11. OutPut:
  12. 19

4.public StringBuffer(charSequence s):

  •  It creates StringBuffer object characters available in passed charSequence object and with default capacity 16 (16+charSequence length) .
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.  CharSequence cs = "abc";
  7.  StringBuffer sb= new StringBuffer(cs);
  8.  System.out.println(sb.capacity());
  9.  
  10. }
  11. }

  12. OutPut:
  13. 19

Methods :

1.public StringBuffer append(XXX s);

  • append(String s) methods concatenates the given String and returns updated StringBuffer object. 
  • There are 8 methods with same name for accepting 8 primitive data type values.
  • And 3 more methods for accepting StringBuffer object , Object and String objects.
  1. public StringBuffer append(boolean b)
  2. public StringBuffer append(char c) 
  3. public StringBuffer append(char[] str) 
  4. public StringBuffer append(char[] str, int offset, int len) 
  5. public StringBuffer append(double d) 
  6. public StringBuffer append(float f)
  7. public StringBuffer append(int i) 
  8. public StringBuffer append(long l) 
  9. public StringBuffer append(Object obj) 
  10. public StringBuffer append(StringBuffer sb) 
  11. public StringBuffer append(String str) 

  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer();
  7.   sb.append("abc");
  8.   System.out.println(sb);
  9. }
  10. }
  11.  
  12. OutPut:
  13. abc

 

2.public StringBuffer insert(XXX s);

  • where xxx is java data types 
  • overloaded to take all possible java data type values
  1. public StringBuffer insert(int offset, boolean b)
  2. public StringBuffer insert(int offset, char c)
  3. public insert(int offset, char[] str)
  4. public StringBuffer insert(int index, char[] str, int offset, int len)
  5. public StringBuffer insert(int offset, float f)  
  6. public StringBuffer insert(int offset, int i)
  7. public StringBuffer insert(int offset, long l) 
  8. public StringBuffer insert(int offset, Object obj) 
  9. public StringBuffer insert(int offset, String str)

  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("abc");
  7.    sb.insert(1, "c");
  8.   System.out.println(sb);
  9. }
  10. }
  11.  
  12. OutPut:
  13. acbc

 

3. public StringBuffer deleteCharAt(int index):

  • This method used to delete character at specified index.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java");
  7.    sb.deleteCharAt(1);
  8.   System.out.println(sb);
  9. }
  10. }
  11.  
  12. OutPut:
  13. Jva

 

4. public StringBuffer delete(int start , int end):

  • This method used to delete characters from specified start index to end index
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.    sb.delete(1,3);
  8.   System.out.println(sb);
  9. }
  10. }
  11.  
  12. OutPut:
  13. Ja Language

 

5. public StringBuffer setCharAt(int index, char ch):

  • This method used to insert character at specified index
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.       sb.insert(0, 'S');
  8.   System.out.println(sb);
  9. }
  10. }
  11.  
  12. OutPut:
  13. SJava Language



6. public int indexOf(String str):

  • This method returns index of specified sub string. if not found returns -1.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.    System.out.println(sb.indexOf("J"));
  8. }
  9. }
  10.  
  11. OutPut:
  12. 0

7. public int indexOf(String str, int index):

  • This method returns index of specified sub string. if not found returns -1.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.  System.out.println(sb.indexOf("a",4));
  8. }
  9. }
  10.  
  11. OutPut:
  12. 6

8. public int lastIndexOf(String str):

  • This method returns last occurrence of  of specified sub string index . if not found returns -1.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.  System.out.println(sb.lastIndexOf("a"));
  8. }
  9. }
  10.  
  11. OutPut:
  12. 10

9. public int length():

  • This method returns length of StringBuffer.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.  System.out.println(sb.length());
  8. }
  9.  
  10. OutPut:
  11. 13

10. public StringBuffer replace(int start, int end, String s):

  • This method replaces the characters from start index to end index with specified string.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.      System.out.println(sb.replace(0,4,"Instance of java"));
  8. }
  9.  
  10. OutPut:
  11. Instance of java Language

11. public StringBuffer reverse():

  • This method returns reverse of sequence of characters.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.        System.out.println(sb.reverse());
  8. }
  9.  
  10. OutPut:
  11. egaugnaL avaJ


12. public String subString(int start, int end):

  • This method returns sub string from start index to end index as a string.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.     System.out.println(sb.substring(1,3));
  8.  
  9. }
  10.  
  11. OutPut:
  12. av

Print 1 to 10 without using loop in java?

  •  Basically to display numbers from 1 to 10 or a series we will use for , while or do while loop
  • So here is the programs to do same thing without using loop.
  • This is possible in two ways
  • First one is to display by printing all those things using system.out.println.
  • second one is by using recursive method call lets see these two programs

Solution #1:


  1. package com.instanceofjavaTutorial;
  2.  
  3. class Demo{  
  4.  
  5. public static void main(String args[]) { 

  6.    System.out.println(1);
  7.    System.out.println(2);
  8.    System.out.println(3);
  9.    System.out.println(4);
  10.    System.out.println(5);
  11.    System.out.println(6);
  12.    System.out.println(7);
  13.    System.out.println(8);
  14.    System.out.println(9);
  15.    System.out.println(10);
  16.  
  17. }

  18. }

Output:

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10



Solution #2


  1. package com.instanceofjavaTutorial; 
  2. public class Main {
  3.     public static void main(String[] args) {
  4.         printNumbers(1, 10);
  5.     }

  6.     public static void printNumbers(int start, int end) {
  7.         if (start > end) {
  8.             return;
  9.         }
  10.         System.out.println(start);
  11.         printNumbers(start + 1, end);
  12.     }
  13. }
  • This uses recursion to achieve the same result. In this example, the method printNumbers is called with the start and end numbers as arguments. Inside the method, it checks if the start number is greater than the end number and if so, it returns (ends the recursion). 
  • If not, it prints the current start number and then calls the printNumbers method again with the start number incremented by 1. 
  • This continues until the start number is greater than the end number and the recursion ends.
  1. package com.instanceofjavaTutorial; 
  2. class PrintDemo{
  3.  
  4. public static void recursivefun(int n) 
  5.  
  6.   if(n <= 10) {
  7.  
  8.        System.out.println(n); 
  9.          recursivefun(n+1);   }
  10. }
  11.  
  12. public static void main(String args[]) 
  13. {
  14.  
  15. recursivefun(1); 
  16.  
  17.  }
  18.  
  19. }




Output:

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Programming Questions on Static

1. what is the output of following program:

  1. package com.instanceofjavaforus;
  2.  
  3. public class StaticDemo{
  4.  
  5.  
  6.    static {
  7.           i=10;
  8.     }
  9.  
  10.     static   int i;  
  11.  
  12.       public static void main(String[] args) {
  13.  
  14.        System.out.println("i= "+i);
  15. }
  16. }





2. what is the output of following program:

  1. package com.instanceofjavaforus;
  2.  
  3. public class StaticDemo{
  4.  
  5.    static {
  6.           i=10;
  7.     }
  8.  
  9.     static   int i;  
  10.  
  11.       public static void main(String[] args) {
  12.         StaticDemo obj= new StaticDemo();
  13.           obj.i=20;
  14.  
  15.        System.out.println("i= "+StaticDemo.i);
  16. }
  17. }






Type Casting in java?

Type Casting:

Type casting means to explicitly convert one type of data to another type of data. 

Type casting has 2 types:
  • Upcasting
  • Downcasting

Upcasting:

Converting lower type value to upper type value is known as Upcasting.
http://instanceofjavaforus.blogspot.in/

Program:

package com.instanceofjavaforus;
public class Upcastingtest {
public static void main(String[] args) {
int a=100;
long b=a;
float c=b;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}

}

Output:

100
100
100.0

Downcasting:

Converting upper type value to lower type value is known as Downcasting.
http://instanceofjavaforus.blogspot.in/

Program:

package com.instanceofjavaforus;
public class Downcastingtest {
public static void main(String[] args) {
double a=10.4;
long b=(long)a;
int c=(int)b;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}

}

Output:

10.4
10
10

Program :

package com.instanceofjavaforus;
class Simple{
public static void main(String args[]){

char ch = 'A';
long a = ch;
System.out.println(a);
}

}

Output:
65

Program:

package com.instanceofjavaforus;
class Simple{
public static void main(String args[]) {
double d = 10.5;
int i = (int) d;
System.out.println(i);
}
}

Output:
10
Select Menu