Benefits of arraylist in java over arrays


Disadvantages of arrays:




Advantages / Benefits of arraylist in java:

  • We have some disadvantages of arrays like arrays are fixed in length. and we need to mention size of the array while creation itself.
  • So we have some advantages of arraylist when compared to arrays in java.
  • Here  the major advantages of arraylist over arrays.

1.ArrayList is variable length
  • One of the major benefit of arraylist is it is dynamic in size. we can increase as well as decrease size of the arraylist dynamically.
  • Resizable.
Program #1: Java example program to explain the advantages of ArrayList: resizable


  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.  public static void main(String[] args) {
  11.         
  12.         ArrayList<Integer> list = new ArrayList<Integer>();
  13.          
  14.         list.add(1);
  15.  
  16.         list.add(2);
  17.  
  18.         list.add(3);
  19.  
  20.         System.out.println(list.size());      
  21.         list.add(4);
  22.         list.add(5);
  23.  
  24.         System.out.println(list.size());     
  25.         list.remove(1);
  26.  
  27.         System.out.println(list.size());    
  28.     }
  29. }

Output:

  1. 3
  2. 5
  3. 4
  • In the above program by using add and remove methods of ArrayList we can change the size of the ArrayList

2.Default initial capacity is 10.
  • One of the major benefit of arraylist is by default it will assign default size as 10.
  • Whenever we create object of ArrayList constructor of ArrayList assign default capacity as 10.

3.Insert and remove elements also at particular position of  ArrayList
  • Another advantage of ArrayList is it can add and remove elements at particular position.

Program #2: Java example program to explain the advantages of ArrayList:Add and remove elements at particular position.

  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.     public static void main(String[] args) {
  11.         
  12.         ArrayList<Integer> list = new ArrayList<Integer>();
  13.          
  14.         list.add(1);
  15.  
  16.         list.add(2);
  17.  
  18.         list.add(3);
  19.  
  20.         System.out.println(list);
  21.  
  22.         list.add(0,4);
  23.         
  24.         System.out.println(list);
  25.         
  26.         list.add(2,5);
  27.  
  28.       
  29.         System.out.println(list);
  30.         list.remove(3);
  31.         
  32.         System.out.println(list);
  33.         System.out.println(list.size());    
  34.     }
  35. }

Output:

  1. [1, 2, 3]
  2. [4, 1, 2, 3]
  3. [4, 1, 5, 2, 3]
  4. [4, 1, 5, 3]
  5. 4


4.Add any type of data into ArrayList.
  • We can add different type of objects in to the ArrayList.
  • In this scenario avoid mentioning generics while declaring ArrayList.

Program #3: Java example program to explain the advantages of ArrayList: Add any type of Object.

arrayList advantages in java

5.Traverse in both directions.
  • We can traverse both direction using List Iterator.

Program #4: Java example program to explain the advantages of ArrayList: Traverse in both directions.
  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.ListIterator;
  5.  
  6. public class ArrayListExample {
  7.     /**
  8.     * Advantages of arrayList over arrays in java
  9.     * @author www.instanceofjava.com
  10.     */
  11.     public static void main(String[] args) {
  12.         
  13.         ArrayList<String> list = new ArrayList<String>();
  14.          
  15.         list.add("ArrayList Advantages");
  16.  
  17.         list.add("ArrayList benefits");
  18.         
  19.         list.add("ArrayList in java");
  20.  
  21.         ListIterator iterator = list.listIterator();
  22.         
  23.         System.out.println("**ArrayList Elements in forward direction**");
  24.          
  25.         while (iterator.hasNext())
  26.         {
  27.             System.out.println(iterator.next());
  28.         }
  29.          
  30.         System.out.println("**ArrayList Elements in backward direction**");
  31.          
  32.         while (iterator.hasPrevious())
  33.         {
  34.             System.out.println(iterator.previous());
  35.         } 
  36.     }
  37. }
 Output:

  1. **ArrayList Elements in forward direction**
  2. ArrayList Advantages
  3. ArrayList benefits
  4. ArrayList in java
  5. **ArrayList Elements in backward direction**
  6. ArrayList in java
  7. ArrayList benefits
  8. ArrayList Advantages

6.ArrayList allows Multiple null values
  • We can add multiple null elements to ArrayList

Program #5: Java example program to explain the benefits of ArrayList: Add null elements
  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.     public static void main(String[] args) {
  11.         
  12.         ArrayList<String> arraylist = new ArrayList<String>();
  13.          
  14.         arraylist.add(null);
  15.  
  16.         arraylist.add(null);
  17.         
  18.         arraylist.add(null);
  19.  
  20.         System.out.println(arraylist);
  21.     }
  22. }

Output:

  1. [null, null, null]

7.ArrayList allows to add duplicate elements
  • We can add duplicate elements into arrayList
Program #6: Java example program to explain the advantages of ArrayList: Add any type of Object.
  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.     public static void main(String[] args) {
  11.         
  12.         ArrayList<String> arraylist = new ArrayList<String>();
  13.          
  14.        arraylist.add("ArrayList");
  15.  
  16.         arraylist.add("ArrayList");
  17.         
  18.         arraylist.add("ArrayList");
  19.  
  20.         System.out.println(arraylist);
  21.     }
  22. }

Output:

  1. [ArrayList, ArrayList, ArrayList]

8.ArrayList has many methods to manipulate stored objects.
  • ArrayList has many methods to manipulate stored objects.
  • addAll(), isEmpty(). lastIndexOf() etc.

Advantages and disadvantages of arrays in java


Disadvantages of array in java
  • Arrays are Strongly Typed.
  • Arrays does not have add or remove methods.
  • We need to mention the size of the array. Fixed length.
  • So there is a chance of memory wastage.
  • To delete an element in an array we need to traverse through out the array so this will reduce performance.
  • Arrays have a fixed size, which means that their size cannot be changed once they are created. This can be a disadvantage when working with dynamic data sets that need to grow or shrink in size.
  • Arrays are not suitable for storing large numbers of different types of elements, it is best used when the data is of a single type.
  • Insertion and deletion operations on arrays can be slow, as they require shifting elements to make room for new elements or close the gap left by deleted elements.
  • Accessing an element in an array can be slow if the array is large, and the index of the element is not known in advance.



Advantages of arrays:


  • We can access any element randomly by using indexes provided by arrays.
  • Primitive type to wrapper classes object conversion will not happen so it is fast.
  • Array can store many number of elements at a time.
  • Arrays have a fixed size, which means that their size cannot be changed once they are created. This can make it easier to manage memory usage and avoid runtime errors caused by dynamic memory allocation.
  • Arrays are relatively fast and efficient. They have a constant time complexity for basic operations such as accessing and updating elements, which makes them suitable for large data sets.
  • Arrays are easy to understand and use, and they are supported by many built-in methods in the Java API, such as Arrays.sort(), Arrays.binarySearch(), and Arrays.toString().



Arrays in java   InstanceOfJava

Java interview programs on arrays:

  • Check below for some of the interesting java interview programs on arrays.

Five different ways to print arrays in java:



Creating array of objects in java:



Java program to find missing numbers in an array:



Find second highest number in java arrays:




Convert arrayList to array:

Copy all elements of  hash set to Object array:


Java xor operator with example programs


Java Bitwise XOR operator:

In Java, you can use the ^ operator to perform a bitwise exclusive or (XOR) operation on two integers. The XOR operation compares each bit of the first number to the corresponding bit of the second number. If the bits are the same, the corresponding result bit is set to 0.  
The matching result bit is set to 1 if the bits vary.
Here's an example:

int a = 12; // binary: 1100
int b = 25; // binary: 11001
int result = a ^ b;
System.out.println("Result of XOR operation: " + result);

In this example, the XOR operation compares the bits of the integers a and b. Since the bits at positions 2 and 3 are different, the corresponding result bits are set to 1. Therefore the binary representation of result is 01101 which decimal representation is 13
This will output:

Result of XOR operation: 13

It's important to note that XOR operation is not only limited to integers. You can also perform it on bytes or even on bytes of an array, by applying the operation on each element of array.


byte[] array1 = {0, 1, 2, 3, 4, 5};
byte[] array2 = {5, 4, 3, 2, 1, 0};
byte[] result = new byte[6];

for (int i = 0; i < 6; i++) {
    result[i] = (byte) (array1[i] ^ array2[i]);
}

It's also useful for some cryptographic algorithms for example the One Time Pad encryption, where the XOR operation is used to encrypt and decrypt the data.
  • Java bit wise Xor operator operates on bits of numbers.
  • It will be represented as "^".
  • XOR will return true if  both bits are different.
  •  For example 1 XOR 0 gives 1. Ex: 1^0=1.
  • 0^1=1.




Java Bitwise Xor:

Java bitwise XOR operator


Program#1:Java Example program on two integer numbers Xor operation.


  1. package com.Xorinjava;
  2. public class XOR {
  3.     /**
  4.     * Xor in java Xor example program
  5.     * @author www.instanceofjava.com
  6.     */
  7.     public static void main(String[] args) {
  8.         int a=1;
  9.         int b=0;
  10.         int c= a^b;
  11.         
  12.         System.out.println(c);
  13.  
  14.     }
  15.  
  16. }
Output:

  1. 1

Program #2: java xor boolean expression : java example program


  1. package com.Xorinjava;
  2.  
  3. public class XOR {
  4.     /**
  5.     * Xor in java boolean Xor example program
  6.     * @author www.instanceofjava.com
  7.     */
  8. public static void main(String[] args) {
  9.         boolean a=true;
  10.         boolean b=false;
  11.         boolean c= a^b;
  12.         
  13.         System.out.println(c);
  14.         
  15.         System.out.println(false^false);
  16.         System.out.println(true^true);
  17.  
  18.     }
  19.  
  20. }

Output:


  1. true
  2. false
  3. false
Program #3: java xor boolean expression and integer : java example program Using Eclipse IDE.

java Xor operator

Java Xor Strings:

  • Gives compile time error.
  • The operator ^ is undefined for the argument type(s) java.lang.String, java.lang.String

Program #4: Java Xor of two strings


  1. package com.Xorinjava;
  2. public class XOR {
  3.     /**
  4.     * Xor in java boolean Xor example program
  5.     * @author www.instanceofjava.com
  6.     */
  7.     public static void main(String[] args) {
  8.         String str="a";
  9.         String str1="b";
  10.         System.out.println(str^str1);// compile time error: The operator ^ is undefined for the
  11. argument type(s) java.lang.String, java.lang.String
  12.  
  13.     }
  14.  
  15. }


 Xor of Binary Strings:

Program #5: Java xor of two binary strings.


  1. package com.Xorinjava;
  2. public class XOR {
  3.     /**
  4.     * Xor in java String bits Xor example program
  5.     * @author www.instanceofjava.com
  6.     */
  7.     public static void main(String[] args) {
  8.         String str1="1010100101";
  9.         String str2="1110000101";
  10.         StringBuffer sb=new StringBuffer();
  11.         
  12.         for (int i = 0; i < str1.length(); i++) {
  13.             
  14.             sb.append(str1.charAt(i)^str2.charAt(i));
  15.             
  16.         }
  17.        System.out.println(sb);
  18.     }
  19.  
  20. }
Output:


  1. 0100100000

How to get first two characters of a string in java

  • We can get first  two character of a string in java by using subString() method in java
  • To get first N numbers of a string s.substring(0,n);
  • Lets see an example java program on how to get first two characters or first N characters.
In Java, you can use the charAt() method to get the first character of a string. The charAt() method takes an index as a parameter and returns the character at that index. 
To get the first character of a string, you can pass in the index 0 to the charAt() method.

Here's an example:


String str = "Hello, World!";
char firstChar = str.charAt(0);
System.out.println("First character: " + firstChar);

This will output:
First character: H



Program #1: Java Program to get first two characters of a String.



  1.  package StringInterviewprograms;
  2.  
  3. public class GetFirstTwoCharacters {
  4.  
  5. /**
  6. * How to get First N characters in java 
  7. * @author www.instanceofjava.com
  8. */
  9.  
  10. public static void main(String[] args) {
  11.         
  12.         String str="Get first two characters of a String";
  13.         
  14.         System.out.println(str.substring(0,2));
  15. }
  16.     
  17.     
  18. }
     
Output:

  1.  Ge

  Program #2:


  1. package StringInterviewprograms;
  2. import java.util.Scanner;
  3.  
  4. public class GetFirstTwoCharacters {
  5. /**
  6. * How to get First N characters in java 
  7. * @author www.instanceofjava.com
  8. */
  9. public static void main(String[] args) {
  10.         
  11.          Scanner sc= new Scanner(System.in);
  12.          
  13.          System.out.println("Please Enter a String");
  14.          
  15.          String str=sc.next();         
  16.         if(str.length()>=2){
  17.  
  18.             System.out.println(str.substring(0,2));
  19.         }else{
  20.             System.out.println("please enter a string with minimum length of 2.");
  21.         }
  22.         }
  23.  
  24.   }

 Output:


  1. Please Enter a String
  2. miss you
  3. mi


Get First Two characters String Java

How to check if a character is a special character in java

  • To check if string contains special character or not or  check whether first character is special character or not we can use regex or contains method of sting class.
  • By using  java.util.regex.Matcher class and java.util.regex.Pattern class methods we can check whether string has special character or not
  • Lets see an example program on how to check a string has special character or not using java regex.



Program #1: Java example program to check string has special character or not using  java regex's?
 
  1. package StringInterviewprograms;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4.  
  5. public class CheckSpecialCharacterString {
  6.  
  7.     /**
  8.      * Check whether the String contains special character or not using java
  9.      * @author www.instanceofjava.com
  10.      */
  11.     
  12. public static void main(String[] args) {
  13.  
  14. String Str="Java String interview questions ";
  15. String Str1="Java String interview questions % ";
  16. Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
  17. Matcher m = p.matcher(Str);
  18. boolean check = m.find();
  19.  
  20. if (check)
  21.    System.out.println("String: "+Str+" contains special character");
  22. else
  23.    System.out.println("String: "+Str+" does not contains any special character");
  24.  
  25. Matcher m1= p.matcher(Str1);
  26.  
  27. boolean flag = m1.find();
  28.  
  29. if(flag)
  30.        System.out.println("String: "+Str1+" contains special character");
  31.     else
  32.        System.out.println("String: "+Str1+" does not contains any special character");
  33.  
  34.    }
  35. }
Output:

  1. String: Java String interview questions  does not contains any special character
  2. String: Java String interview questions %  contains special character

  • We can check each character of a string is special character or not without using java regex's.
  • By using String class contains method and for loop we can check each character of a sting is special character or not.
  • Let us see a java example program on how to check each character (including space) of a string is special character or not.
  • String validation for special characters.


Program #2: Java example program to check each character of string is special character or not without using  java regex's?

  1. package StringInterviewprograms;
  2.  
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5.  
  6. public class CheckSpecialCharacterString {
  7.  
  8.     /**
  9.      * Check whether the each character of String is special character or not using java
  10.      * @author www.instanceofjava.com
  11.      */
  12.     
  13. public static void main(String[] args) {
  14. String Str="Java String interview questions*$%";
  15.   
  16. String specialCharacters=" !#$%&'()*+,-./:;<=>?@[]^_`{|}";
  17.  
  18. for (int i = 0; i < Str.length(); i++) {
  19.     
  20.     if (specialCharacters.contains(Character.toString(Str.charAt(i))))
  21.     {
  22.        
  23.         System.out.println(Str.charAt(i)+": is a special character");
  24.     }  
  25.   }
  26.  
  27. }
  28.  
  29. }

Output:


  1.  : is a special character
  2.  : is a special character
  3.  : is a special character
  4. *: is a special character
  5. $: is a special character
  6. %: is a special character

Program #3: Java example program to check each character of string is special character or not without using  java regex's Using Eclipse IDE.


Check Special Character String java

How to check if first character of a string is a number or not in java

  • To check if first character of a string is a number or not in java we can check in multiple ways.
  • By using Character.isDigit() method by passing character of string using for loop or substring method.
  • Other way is to check str.substring(0, 1).matches("[0-9]").
  • Lets see an example program in java to check first character of a string is digit or character. 



Program #1: Java example program to check the each character of string is number or not   character is a letter or number in Java without using regexes?

  1. package StringInterviewprograms;
  2. /**
  3.  * Check whether the given character is a number /digit or not by using java character isdigit
  4.  *method
  5.  * @author www.instanceofjava.com
  6.  */
  7. public class CheckEachCharacterNumberOrNot {
  8.     public static void main(String[] args) {
  9.         String str = "instanceofjava37";
  10.  
  11.         //Check whether the given character is a number /digit or not ?
  12.  
  13.         for(int i=0; i<str.length();i++)
  14.         {
  15.             Boolean flag = Character.isDigit(str.charAt(i));
  16.  
  17.             if(flag){
  18.  
  19.                System.out.println("'"+str.charAt(i)+"' is a number");
  20.             }
  21.             else{
  22.                System.out.println("'"+str.charAt(i)+"' is not a number");
  23.             }
  24.  
  25.         }
  26.         
  27. }
  28.  
  29. }

Output:

  1. 'i' is not a number
  2. 'n' is not a number
  3. 's' is not a number
  4. 't' is not a number
  5. 'a' is not a number
  6. 'n' is not a number
  7. 'c' is not a number
  8. 'e' is not a number
  9. 'o' is not a number
  10. 'f' is not a number
  11. 'j' is not a number
  12. 'a' is not a number
  13. 'v' is not a number
  14. 'a' is not a number
  15. '3' is a number
  16. '7' is a number
     
Program #2: Java example program to check the First character of string is number or not by using regex.

  1. package StringInterviewprograms;
  2. /**
  3.  * Check whether the given character is a number /digit or not
  4.  * @author www.instanceofjava.com
  5.  */
  6. public class CheckFirstCharacterNumberOrNot {
  7.  
  8.     public static void main(String[] args) {
  9.         String str = "instanceofjava37";
  10.  
  11.           Boolean flag1 = str.substring(0, 1).matches("[0-9]");
  12.  
  13. if(flag1){
  14.  
  15.  System.out.println("First Character is a number..!");
  16.  
  17.  }
  18.  else{
  19.    System.out.println("First character is not a number..!");
  20. }
  21. }
  22.  
  23. }

Output:

  1. First character is not a number..!


Program #3: Java example program to check the First character of string is number or not using eclipse IDE.


Check first character string number digit java

Select Menu