Skip to content

Chapter 7 Arrays and Strings in Java

Arrays and strings are fundamental data structures in Java, used to store multiple values and text, respectively.

Array Initialization and Manipulation

An array in Java is a static data structure that holds a fixed number of values of the same type.

Initializing an Array

Arrays in Java can be initialized in various ways:

// Declare an array
int[] arr1;

// Allocate memory for 5 integers
arr1 = new int[5];

// Shortcut syntax for declaration and memory allocation
int[] arr2 = new int[5];

// Declaration, memory allocation, and assignment of values
int[] arr3 = {1, 2, 3, 4, 5};

Manipulating an Array

After you have initialized an array, you can manipulate it. For example, you can assign values to array elements and retrieve them:

// Assign value to an array element
arr2[0] = 10;

// Retrieve value from an array element
int firstElement = arr2[0];  // firstElement is now 10

String Manipulation

A string is an object in Java that represents a sequence of characters. Java provides the String class in the java.lang package, which has several methods to manipulate strings.

String Initialization

You can initialize a string directly using a string literal:

String str = "Hello, World!";

Or you can use the new keyword:

String str = new String("Hello, World!");

String Methods

Java provides several methods for string manipulation. Here are a few examples:

  • length(): Returns the length of the string.
  • charAt(int index): Returns the character at the specified index.
  • substring(int beginIndex, int endIndex): Returns a substring from the specified beginIndex to endIndex.
  • indexOf(String str): Returns the index within this string of the first occurrence of the specified substring.
  • replace(char oldChar, char newChar): Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

Here's an example that uses some of these methods:

String str = "Hello, World!";
int len = str.length();  // len is now 13
char ch = str.charAt(0);  // ch is now 'H'
String subStr = str.substring(0, 5);  // subStr is now "Hello"
int index = str.indexOf("World");  // index is now 7
String newStr = str.replace('!', '.');  // newStr is now "Hello, World."

Arrays and strings form the basis for handling groups of values and text data in Java. By understanding these concepts, you can make your Java programming journey smoother and more efficient.