GFG Day 12: Arrays and Strings

sri parthusri parthu
7 min read

Arrays in Java

  • An array is a data structure that allows storing values based on its size.

  • In arrays we can store multiple values in a single variable, instead of declaring separate variables.

  • Index is the position of the values in an array, and it always starts from "Zero (0)."

Types of arrays:

  1. One-dimensional arrays

    1. Static array

    2. Dynamic array

  2. Multi-dimensional arrays

    1. Static array

    2. Dynamic array

  1. One-dimensional arrays

Static array:

Syntax to create a static 1D array

datatype arrayName [] = new datatype [array size];

Syntax to assign value to static 1D array

arrayName [index] = value;

Syntax to read a specific value to static 1D array

arrayName [index];

Example of array (1D static array)

public class Array{
    public static void main(String[] args){
        int aa [] = new int[5];
            aa [0] = 10;
            aa [1] = 20;
            aa [2] = 30;
            aa [3] = 40;
            aa [4] = 50;
            System.out.println(aa[1] + " " + aa[3]);
    }
}

Output

20 40
  • In an array, if the size is available and the programmer doesn’t assign a value, then the JVM will assign the default value to the array depending upon the data type of the array.

    Ex:- The default value of the integer is 0, float is 0.0, etc.

  • If you provide more values than the array size, a runtime error occurs.

  • If we create an array by giving a size, it is called a static array.

Dynamic array

  • If we create an array without giving a size, it is called a dynamic array.

Syntax to create an 1D dynamic array

datatype arrayName [] = {value1, value2, value3......etc}

where value1 is 0 index, value2 is 1 index, value3 is 2 index and more.

Example of array (1D dynamic array)

public class DynamicArray{
    public static void main(String[] args){
        double aa [] = {4.5, 67.9, 12.3, 66.9};
        System.out.println(aa[1] + " " + aa[2]);
    }
}

Output

67.9 12.3
  • No default values will be assigned to the dynamic array. It will result in a runtime error.

  • If we want the size of the array, we need to use the keyword length.

Example of checking the length of the array

public class Array{
    public static void main(String[] args){
        String name [] = {"Advance Java", "Mern Stack", "Core Java"};
        System.out.println(name.length);
    }
}

Output

3

To demonstrate how to create an array of integers, a Java application inserts values into the array using iteration and outputs each value to the standard output.

public class Array{
    public static void main(String[] args){
        int abc [] = {10, 20, 30, 40, 50};
        for(int i = 0; i < abc.length; i++){
            System.out.println("The abc index " + i + " is " + abc[i]);
        }
    }
}

Output

The abc index 0 is 10
The abc index 1 is 20
The abc index 2 is 30
The abc index 3 is 40
The abc index 4 is 50
  1. Multi-dimensional array

2D static array

Syntax to declare a 2D static array

datatype arrayName [][] = new datatype [row size] [column size];

Syntax to assign 2D static array value

arrayName [row index] [column index] = value;

Syntax to read specific value of 2D static array

arrayName [row index] [column index];

Example of array (2D static array)

public class Array2DStatic{
    public static void main(String[] args){
        int aa [][] = new int [3][4];
        aa [0][0] = 10;
        aa [0][1] = 20;
        aa [1][0] = 30;
        aa [1][1] = 40;
        aa [2][0] = 50;
        System.out.println(aa[1][1] + " " + aa[2][0]);
    }
}

Output

40 50
  • In an array, if the size is available and the programmer doesn’t assign a value, then the JVM will assign the default value to the array depending upon the data type of the array.

    Ex:- The default value of the integer is 0, float is 0.0, etc.

2D Dynamic array

Syntax to create a 2D dynamic array

datatype [][] = {{col1 value, col2 value}, {col1 value, col2 value}, {col1 value, col2 value}..., etc };

Example of array (2D dynamic array)

public class Array2DDynamic{
    public static void main(String[] args){
        char aa [][] = {{'k', 'l'}, {'c', 'r'}, {'o', 'p'}};
        System.out.println(aa[0][1] + " " + aa[1][0]);
    }
}

Output

l c
  • Here default values are not applicable for dynamic arrays.

Strings

What is a String in Java?

  • A String in Java is an object that represents a sequence of characters. Strings are enclosed in double quotes and are encoded in UTF-16, meaning each character takes 16 bits of memory.
String name = "Java";
String num = "1234";
  • Strings in Java behave like an array of characters but offer much more flexibility with built-in methods for concatenation, comparison, and manipulation.

Ways to Create Strings in Java

  • Java offers two main ways to create Strings:
  1. String Literal (Stored in String Pool)

String str = "Advance Core Java";
  • This goes into a special area of the heap called the String Constant Pool.

  • if a string with the same value already exists, it reuses the existing one—saving memory!

Memory allocation of Java String literal in heap and stack, highlighting string constant pool and references.

  1. Using the new Keyword (Stored in Heap)

String s = new String("Welcome");
  • This creates a new object in heap memory, even if the same string already exists in the String Pool.

Heap Memory vs String Pool in Java Explanation

Code Example

public class Geeks {
    public static void main(String[] args) {
        String str = new String("Java");
        System.out.println(str); // Output: Java
    }
}

String Immutability in Java

  • Java Strings are immutable — once created, their value cannot be changed.
public class Geeks {
    public static void main(String[] args) {
        String s = "Sachin";
        s.concat(" Tendulkar");  // This creates a new object
        System.out.println(s);   // Output: Sachin
    }
}

Correct way to change it:

String s = "Sachin";
s = s.concat(" Tendulkar");
System.out.println(s);  // Output: Sachin Tendulkar

Immutable String example in Java with memory diagram

Memory Allocation: Heap vs String Pool

String Literals

String str1 = "Hello";
String str2 = "Hello";  // Reuses the same object from the pool

Same object reference from pool in Java memory

New Keyword

String str1 = new String("Hello");
String str2 = new String("Hello"); // Creates new object each time

Separate heap memory allocations in Java

String Pool Migration: PermGen to Heap

  • Before Java 8, the String Pool resided in PermGen space. But due to size limitations (~64MB), it was moved to Heap memory in later versions to avoid memory overflow and allow larger applications.
String demoString = new String("Bhubaneswar");

Use .intern() to explicitly move a string to the pool:

String interned = demoString.intern();

Interfaces and Classes with String

  • Java provides an interface and several classes for string manipulation:
  1. CharSequence (Interface)

  • Methods: length(), charAt(), subSequence(), toString()

  • Implemented by: String, StringBuilder, StringBuffer

  1. String (Immutable Class)

String s = "Java";
String s2 = new String("Java");
  1. StringBuffer (Mutable & Thread-safe)

StringBuffer sb = new StringBuffer("Advance Core Java");
  • Used in multithreaded environments

  • Synchronized methods — slower but safe

  1. StringBuilder (Mutable & Not Thread-safe)

StringBuilder sb = new StringBuilder();
sb.append("AJ");
  • Faster than StringBuffer

  • Used in single-threaded environments

  1. StringTokenizer

import java.util.StringTokenizer;

StringTokenizer st = new StringTokenizer("Advance Core Java");
while (st.hasMoreTokens()) {
    System.out.println(st.nextToken());
}
  1. StringJoiner

import java.util.StringJoiner;

StringJoiner sj = new StringJoiner(", ");
sj.add("Advance");
sj.add("Core");
sj.add("Java");
System.out.println(sj); // Output: Advance, Core, Java

Creating Strings Using Arrays

Example 1: Using Byte Array

byte ascii[] = { 71, 70, 71 }; // ASCII for A, C, J
String first = new String(ascii);
System.out.println(first); // Output: ACJ

Example 2: Using Char Array

char chars[] = { 'A', 'C', 'J' };
String first = new String(chars);
System.out.println(first); // Output: ACJ

Practical Program – Memory Visualization

public class Geeks {
    public static void main(String[] args) {
        String s1 = "TAT";
        String s2 = "TAT";

        String s3 = new String("TAT");
        String s4 = new String("TAT");

        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
    }
}

Here:

  • s1 and s2 point to the same object in the pool

  • s3 and s4 are two different objects in the heap

Conclusion

  • Java Strings offer an efficient and flexible way to handle character data. Their immutability, memory management through String Pools, and support from powerful classes like StringBuilder and StringTokenizer make them a robust choice for developers.

Happy Learning

Thanks For Reading! :)

SriParthu 💝💥

0
Subscribe to my newsletter

Read articles from sri parthu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

sri parthu
sri parthu

Hello! I'm Sri Parthu! 🌟 I'm aiming to be a DevOps & Cloud enthusiast 🚀 Currently, I'm studying for a BA at Dr. Ambedkar Open University 📚 I really love changing how IT works to make it better 💡 Let's connect and learn together! 🌈👋