Arrays and Strings

This section discussed about the the 2 major concepts in Java programming language.

Arrays

What are arrays in Java ?

An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++.

Following are some important point about Java arrays.

Important Points

Creating / Declaring Array :

type var-name[];
or
type[] var-name;
// Array of Primitive data types
int[] intArr;
byte[] byteArr;
short[] shortArr;
long[] longArr;
float[] floatArr;
double[] doubleArr;
char[] charArr;

// Array of Boxed Types
Integer[] integerArr;

// Array of Object of unknown type
Object[] objArr;

// Array of Collection of unknown type
Collection[] collArr;

// Array of User Defined Type
MyClass[] myClassArr;

public static void main(String[] args){
  System.out.println("hello");
  System.out.println("hello");
  System.out.println("hello");
}

Instantiating / Initializing Array :

var-name = new type [size];
int intArr[];    //declaring array
intArr = new int[20];  // allocating memory to array
int[] intArr = new int[20]; // combining both statements in one
Array Literal:
 int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; // Declaring array literal
 int[] intArray = { 1,2,3,4,5,6,7,8,9,10 }; // Declaring array literal in newer Java Versions

Accessing Array :

// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++) {
  System.out.println("Element at index " + i + " : "+ arr[i]);
}

Example:

class Student { 
    public int roll_no; 
    public String name; 
    
    Student(int roll_no, String name) { 
        this.roll_no = roll_no; 
        this.name = name; 
    } 
} 
  
// Elements of array are objects of a class Student. 
public class UserDefinedDataTypeArrayExample { 
    public static void main (String[] args) { 
        // declares an Array of of type Student. 
        Student[] arr; 
  
        // allocating memory for 5 objects of type Student. 
        arr = new Student[5]; 
  
        // initialize the first elements of the array 
        arr[0] = new Student(1,"aman"); 
  
        // initialize the second elements of the array 
        arr[1] = new Student(2,"vaibhav"); 
        arr[2] = new Student(3,"shikar"); 
        arr[3] = new Student(4,"dharmesh"); 
        arr[4] = new Student(5,"mohit"); 
  
        // accessing the elements of the specified array 
        for (int i = 0; i < arr.length; i++) 
            System.out.println("Element at " + i + " : " + arr[i].roll_no + " " + arr[i].name); 
    } 
}

Output:

Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit

Multi-dimensional Arrays :

int[][] int2DArr = new int[10][20];  // 2D array or matrix
int[][][] int3DArr = new int[10][20][10];  // 3D array

Example:

class multiDimensionalArrayExample { 
    public static void main(String args[]) { 
        // declaring and initializing 2D array 
        int arr[][] = { {2,7,9},{3,6,1},{7,4,2} }; 
  
        // printing 2D array 
        for (int i=0; i< 3 ; i++) { 
            for (int j=0; j < 3 ; j++) {
                System.out.print(arr[i][j] + " "); 
            }
            System.out.println(); 
        } 
    } 
} 

Output:

2 7 9 
3 6 1 
7 4 2 

Other Array Concepts :

1. Passing Arrays to Methods
class Test {     
    public static void main(String args[])  { 
        int arr[] = {3, 1, 2, 5, 4}; 
          
        sum(arr);  // passing array to method m1 
    } 
  
    public static void sum(int[] arr) {  
        int sum = 0;  // getting sum of array values
          
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
          
        System.out.println("sum of array values : " + sum); 
    } 
} 

Output:

sum of array values : 15
2. Array Members

Arrays Class :

What is Arrays Class in Java ?
Class Hierarchy :
java.lang.Object
  java.util.Arrays
Class Declaration :
public class Arrays extends Object
Basic Syntax:
Arrays.<methodName>;
Need for Java Arrays Class
Methods in Arrays Class :
New Java 9 Methods:

Example:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Ex3ArraysClassOperations {
    public static void main(String[] args){
        // Create an array using :=> Type[] arr = new Type[size]
        int[] arr = new int[5];

        // Filling values in array using : arr[index] = val
        arr[0] = 10; arr[1] = 20; arr[2] = 15;
        arr[3] = 22; arr[4] = 35;

        // Get the length of the arr using : length member
        System.out.println("Length of the arr : " + arr.length);

        // Get string representation of array using : toString(arr)
        String arrString = Arrays.toString(arr);
        System.out.println("String rep of arr : " + arrString);

        // List representation of array using : asList(arr)
        System.out.println("List representation of arr : " + Arrays.asList(arr));

        // Binary Search in arr using : binarySearch(arr, key)
        Arrays.sort(arr);
        System.out.println("Find key 22 in arr : " + Arrays.binarySearch(arr, 22));

        // Binary Search in range using : binarySearch(arr, fromIndex, toIndex, key)
        System.out.println("Find key 22 in arr : " + Arrays.binarySearch(arr, 1, 3, 22));

        // Fill the arr with new value using :=> fill(arr, newVal)
        Arrays.fill(arr, 55);
        System.out.println("Arrays after filling with 55 : " + arr);

        int arr1[] = { 10, 20, 15, 22, 35 };
        int arr2[] = { 10, 15, 22 };

        // Check if arrays are equal using :=> equals(arr1, arr2)
        System.out.println("Are arr1 and arr2 equal ? : " + Arrays.equals(arr1, arr2));

        // sort arr using :=> sort(arr)
        Arrays.sort(arr1);
        System.out.println("Sorted Arr : " + Arrays.toString(arr1));

        // Use stream using :=> stream(arr)
        List<Integer> arrIntegerList = Arrays.stream(arr1)   // Stream of int
                                                .boxed()    // Stream of Integer
                                                .collect(Collectors.toList());
        System.out.println("Integer List of arr : " + arrIntegerList);
    }
}

Output:

Length of the arr : 5
String rep of arr : [10, 20, 15, 22, 35]
List representation of arr : [[I@74a14482]
Find key 22 in arr : 3
Find key 22 in arr : -4
Arrays after filling with 55 : [I@74a14482
Are arr1 and arr2 equal ? : false
Sorted Arr : [10, 15, 20, 22, 35]
Integer List of arr : [10, 15, 20, 22, 35]

Strings

What are Strings in Java ?
Basic Syntax:
String stringVarName = "sequence of chars or words"

// Example:
String str = "Geeks";

Interfaces and Classes

CharSequence Interface :

1. String

Constructors :
String str = "ExampleOfString";
String str = new String (ExampleOfString);
Methods :

Example:

import java.util.Arrays;

public class StringCreationAndOperations {
    public static void main(String[] args){
        // Create string using :=> literals
        String s = "Astik Anand";

        // Get count of characters using :=> length()
        System.out.println("Length of string s : " + s.length());

        // Check if it is empty using :=> isEmpty()
        System.out.println("Is string empty ? : " + s.isEmpty());

        // Get the char at ith position using :=> charAt(i)
        System.out.println("Char at 4th index : " + s.charAt(4));

        // Get the substring from ith to end using : s.substring(i)
        System.out.println("Substring from 4th index to end : " + s.substring(4));

        // Get the substring from ith to (j-1)th using : substring(i, j)
        System.out.println("Substring from 4th to 9th : " + s.substring(4, 9));

        // Get the subsequence b/w i and j-1 using :=> subsequence(i, j)
        System.out.println("Subsequence form 6th to 9th : " + s.subSequence(6, 9));

        // Concatenate given string to end using :=> s.concat(anotherStr)
        String s1 = "Hello! ";
        String s2 = "Folks, Welcome";
        System.out.println("Concatenated String : " + s1.concat(s2));

        // Get index of first occurrence using :=> indexOf(str)
        String s3 = "Learn Share Learn";
        System.out.println("Index of \"Share\" : " + s3.indexOf("Share"));

        // Get index of first occurrence starting at ith index using :=> indexOf(str, i)
        System.out.println("Index of 'a' starting at 3 : " + s3.indexOf('a', 3));

        // Get last index using :=> lastIndexOf(str)
        System.out.println("Last index of \"Learn\" : " + s3.lastIndexOf("Learn"));

        // Check equality of Strings using :=> equals(anotherStr)
        String s4 = "WeLcOMe";
        System.out.println("Is \"WeLcOMe\" equal to \"Welcome\" ? : " + s4.equals("Welcome"));

        // Check equality of Strings ignoring case using :=> equalsIgnoreCase(anotherStr)
        System.out.println("Is \"WeLcOMe\" equal to \"Welcome\" after ignoring case ? : "
                + s4.equalsIgnoreCase("Welcome"));

        // Check if content equals if content from StringBuffer or Builder using :=> contentEquals(content)
        System.out.println("Is \"WeLcOMe\" content equal to \"Welcome\" ? : "
                + s4.contentEquals(new StringBuffer("Welcome")));

        // Compare String Lexicographically using :=> compareTo(anotherStr)
        String s5 = "abcde";
        System.out.println("Comparing \"abcde\" to \"abcdb\" : " + s5.compareTo("abcdb"));

        // Check if string contains given str using :=> contains(str)
        System.out.println("Does s5 contains \"cd\" ? : " + s5.contains("cd"));

        // Check if string starts with given str using :=> startsWith(str)
        System.out.println("Does s5 startsWith \"abc\" ? : " + s5.startsWith("abc"));

        // Check if string ends with given str usign :=> endsWith(str)
        System.out.println("Does s5 startsWith \"cde\" ? : " + s5.endsWith("cde"));

        // Split on the basis of regex using :=> split(regex)
        String s6 = "I am   a   Programmer  ";
        String[] splitted = s6.split("\\s+");
        System.out.println("Split using regex : " + Arrays.toString(splitted));

        // Convert to Lower Case using :=> toLowerCase()
        String s7 = "ProGraMMeR";
        System.out.println("Lower case of \"ProGraMMeR\" : " + s7.toLowerCase());

        // Convert to Upper Case using :=> toUpperCase()
        System.out.println("Upper case of \"ProGraMMeR\" : " + s7.toUpperCase());

        // Trim spaces using :=> trim()
        String s8 = " Learn Programming   ";
        System.out.println("After trim : " + s8.trim());

        // Replace characters using : replace(oldChar, newChar)
        String s9 = "abracadabra";
        System.out.println("Replace 'a' with 'm' in \"abracadabra\" : " + s9.replace('a', 'm'));

        // Replace using regex : replaceFirst(regex, replacement)
        String s10 = "java, read, job, practice, senior, java, write, job, senior";
        String regex = "(java|job|senior)";
        System.out.println("Replace s10 using replaceFirst(regex, \"XYZ\") : "
                + s10.replaceFirst(regex , "XYZ"));

        // Replace using regex : replaceAll(regex, replacement)
        System.out.println("Replace s10 using replaceAll(regex, \"XYZ\") : "
                + s10.replaceAll(regex, "XYZ"));
    }
}

Output:

Length of string s : 11
Is string empty ? : false
Char at 4th index : k
Substring from 4th index to end : k Anand
Substring from 4th to 9th : k Ana
Subsequence form 6th to 9th : Ana
Concatenated String : Hello! Folks, Welcome
Index of "Share" : 6
Index of 'a' starting at 3 : 8
Last index of "Learn" : 12
Is "WeLcOMe" equal to "Welcome" ? : false
Is "WeLcOMe" equal to "Welcome" after ignoring case ? : true
Is "WeLcOMe" content equal to "Welcome" ? : false
Comparing "abcde" to "abcdb" : 3
Does s5 contains "cd" ? : true
Does s5 startsWith "abc" ? : true
Does s5 startsWith "cde" ? : true
Split using regex : [I, am, a, Programmer]
Lower case of "ProGraMMeR" : programmer
Upper case of "ProGraMMeR" : PROGRAMMER
After trim : Learn Programming
Replace 'a' with 'm' in "abracadabra" : mbrmcmdmbrm
Replace s10 using replaceFirst(regex, "XYZ") : XYZ, read, job, practice, senior, java, write, job, senior
Replace s10 using replaceAll(regex, "XYZ") : XYZ, read, XYZ, practice, XYZ, XYZ, write, XYZ, XYZ

2. StringBuffer

Important Points :
Constructors :
StringBuffer s1 = new StringBuffer(); // reserves room for 16 characters without reallocation
StringBuffer s2 = new StringBuffer(20); // acceepts number to set the size of buffer explicitly
StringBuffer s3 = new StringBuffer("ExampleOfStringBuffer"); // sets the initial contents and reserves 
                                                             // room for 16 more characters without reallocation
Methods :

3. StringBuilder

Why StringBuilder after StringBuffer ?
Constructors :
StringBuilder s1 = new StringBuilder(); // Creates with initial capacity of 16 characters.
StringBuilder s1 = new StringBuilder(20); // Accepts number to set the size explicitly
StringBuilder s1 = new StringBuilder(seq); // Contains the same characters as the specified seq.
StringBuilder s1 = new StringBuilder(str); // Initialized to the contents of the specified string.
Methods :

Has all the methods same as of StringBuffer.