Friday, December 27, 2024
Google search engine
HomeLanguagesJavaDifference between Array and String in Java

Difference between Array and String in Java

An array is a collection of similar type of elements that are stored in a contiguous memory location. Arrays can contain primitives(int, char, etc) as well as object(non-primitives) references of a class depending upon the definition of the array. In the case of primitive data type, the actual values are stored in contiguous memory locations whereas in the case of objects of a class the actual objects are stored in the heap segment. In Java, all the arrays are allocated dynamically. The size of an array must be specified by an int value and not long or short. The array index starts from 0 and goes up to n-1 where n is the length of the array.

Array Declaration Syntax:

type var-name[]'
OR
type[] var-name;

An array declaration has two components: the type and the var-name. The type declares the element type of the array. The element type determines the data type of each element that comprises the array. The var-name declares the name of the array variable. Like an array of int type, we can also create an array of other primitive data types like char, float, double…etc.

Examples:

// both are valid declarations
int intArray[]
or int[] intArray

byte byteArray[]
short shortArray[]
boolean booleanArray[]
float floatArray[]
double doubleArray[]
char charArray[]

// An array of references to object of
// the class MyClass (a class created by 
// user)
MyClass myClassArray[];

// Array of object
Object[] arrayObject,

// Array of collection of unknown type
Collection[] collectionObject

Instantiating an Array in Java

When an array is declared only a reference is created. To actually create or give memory to an array, we can create an array like this: 

var-name = new type[size];

Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and var-name is the name of the array variable.

Example:

// Declaring an array
int intArray[]

// Allocating memory to array
int Array = new int[10];

OR

// Combining both statements in one
int[] intArray = new int[10];

Accessing Java Array Elements using for Loop

Each element in the array is accessed via its index. The index begins with 0 and ends at (array size) – 1. All the elements of an array can be accessed using Java for Loop.

// 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:

Java




// Java program to illustrate creating an array
// of integers, put some values in the array,
// and prints each value to standard output
class GFG {
    public static void main(String args[])
    {
        // Declaring an Array of integers
        int[] arr;
 
        // Allocating memory for 5 integers
        arr = new int[5];
 
        // Initialize the first element of the array
        arr[0] = 10;
        // Initialize the second element of the array
        arr[1] = 20;
 
        // So on...
        arr[2] = 30;
        arr[3] = 40;
        arr[4] = 50;
 
        // Accessing the elements of the specified array
        for (int i = 0; i < arr.length; i++)
            System.out.println("Element at index " + i
                               + " : " + arr[i]);
    }
}


Output

Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

String:

In Java string is basically treated as an object which represents a sequence of characters but it’s not a primitive type. In Java, String class is provided to create and manipulate strings. In String class, a number of methods are provided to perform different operations on strings. Since arrays are mutable(array elements can be changed) , Strings are immutable in Java. Whenever a change to a String is made, an entirely new String is created.

Below is the basic syntax for creating a String in Java programming language.

Syntax: 

<String_Type> <string_variable> = 
"<sequence_of_string>";

OR

<String_Type> <string_variable> = 
<new> <String_Type>("<sequence_of_string>");

Whenever a String object is created, two objects will be created- one in the Heap Area and one in the String constant pool and the String object reference always points to the heap area object.

Example:

Java




// Java program to illustrate String
class GFG {
    public static void main(String args[])
    {
        // Creating a String without using new operator
        String str = "GeeksForGeeks";
 
        // Prints the String
        System.out.println("String str = " + str);
 
        // Creating a String using new operator
        String str1 = new String("GeeksForGeeks");
 
        // Prints the String
        System.out.println("String str1 = " + str1);
    }
}


Output

String str = GeeksForGeeks
String str1 = GeeksForGeeks

Difference between Array and String :

S.NO.

Array

String

01. An array is a data structure that stores a collection of elements of the same data type. A string is basically treated as an object which represents a sequence of characters. An array
02. Array can hold any of the data types. But, the String can hold only a char data type.
03. The elements of the array are stored in a contiguous memory location. A string class contains a pointer to some part of the heap memory where the actual contents of the string are stored in memory.
04. Java array not ended with a null character, the end element of the array is the last element of the array. But by default String is ended with null (‘\0’) character in Java.
05. Arrays are mutable. Strings are immutable.
06. The length of the array is fixed. The size of the string is not fixed.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments