GFG Day 12: Arrays and Strings

Table of contents

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:
One-dimensional arrays
Static array
Dynamic array
Multi-dimensional arrays
Static array
Dynamic array
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 is0.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
is0
index,value2
is1
index,value3
is2
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
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 is0.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:
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!
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.
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
Memory Allocation: Heap vs String Pool
String Literals
String str1 = "Hello";
String str2 = "Hello"; // Reuses the same object from the pool
New Keyword
String str1 = new String("Hello");
String str2 = new String("Hello"); // Creates new object each time
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:
CharSequence (Interface)
Methods:
length()
,charAt()
,subSequence()
,toString()
Implemented by:
String
,StringBuilder
,StringBuffer
String (Immutable Class)
String s = "Java";
String s2 = new String("Java");
StringBuffer (Mutable & Thread-safe)
StringBuffer sb = new StringBuffer("Advance Core Java");
Used in multithreaded environments
Synchronized methods — slower but safe
StringBuilder (Mutable & Not Thread-safe)
StringBuilder sb = new StringBuilder();
sb.append("AJ");
Faster than
StringBuffer
Used in single-threaded environments
StringTokenizer
import java.util.StringTokenizer;
StringTokenizer st = new StringTokenizer("Advance Core Java");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
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
ands2
point to the same object in the pools3
ands4
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
andStringTokenizer
make them a robust choice for developers.
Happy Learning
Thanks For Reading! :)
SriParthu 💝💥
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! 🌈👋