×

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two types – static arrays and dynamic arrays. In this tutorial, we will restrict ourselves to a static array only.

We will begin our discussion with an understanding of the topic, its examples, the syntax for its declaration, and its advantages and disadvantage. Further, we will sum up our discussion with a java program.

Static Array

A static array is declared with the static keyword. Its nature is hinted at in the name itself. We cannot change or alter the static array. The memory is allocated at compile-time and its size also gets fixed therein.

Limitations in altering the size of static arrays led to the rise of the dynamic array where one can easily take the size as input at run time.

Example

Let’s consider an array named arr[20] which creates an array of size 20.

It means we can insertelements up to 20 only; we cannot insert a 21st element as the size of the Array is fixed.


int arr[] = { 81, 83, 84 , 88, 89 }; // static integer array  
int arr[] = { 32, 67, 44, 77 }; // static integer array  
int arr[] = { 542, 167, 414, 707, 55 }; // static integer array  


int* arr = new int[5]; // dynamic integer array  


Declaration of a Static Array

Let us look at the way to declare a static array in java.

<data type> <name of variables> []={<data1>,<data2>,<data3>, .....<dataN>};  

Here,

Data types – the type of data of the array

Name of variables – it consists of a list of variable names to be used.

{data1, data2, …..} – it consists of the list of data.

Examples

Let us look at the following examples to understand the ways to initialize the static array in java.

Example 1: By the aid of a new keyword


String[] states = new String[] {  
  "Arunachal Pradesh",   
  "Madhya Pradesh",   
  "Uttar Pradesh",   
  "Himachal Pradesh"    
};  


Example 2:

The array can also be declared in this way


String[] states = {  
  "Arunachal Pradesh",   
  "Madhya Pradesh",   
  "Uttar Pradesh",   
  "Himachal Pradesh"    
};  

Example 3:

This is another way to declare a static array. Here, it is being declared as a list.


List states = Arrays.asList(  
"Arunachal Pradesh",   
  "Madhya Pradesh",   
  "Uttar Pradesh",   
  "Himachal Pradesh"    
);  


Advantages of Static Array

  1. Its execution time is efficient.
  2. Statically allocated arrays remain alive throughout the complete runtime of the program.
  3. Global variables are declared “in advance of time,” such as a fixed array.
  4. The size of memory allocated to “data” is static. But it is possible to alter the content of a static structure without growing the memory space allocated to it.

Disadvantages of Static Array

  1. It often leads to the wastage of space if a great number of static data has been allocated in the beginning.
  2. It is impossible to increase the space once after allocating the memory initially. So, if one fails to allocate an adequate amount of space, it becomes problematic later on.

Implementation

Let us see a program to understand the topic clearly.

Example 1

public class StaticArrayExample1
{  
private static String[] arr;  
static   
{  
arr = new String[5];  
arr[0] = "India";  
arr[1] = "is";  
arr[2] = "a";
arr[3] = "developing";
arr[4] = "country";
}  
public static void main(String args[])   
{  
for(int i = 0; i<arr.length; i++)  
{  
System.out.print(arr[i] + " ");  
}  
}  
}  

Output

Static Array in Java

Description: This image shows the output of the code written above. Here, the keyword new has been taken into account to create a static array of type strings.

Example 2


public class StaticArrayExample2
{  
// A static array of integer type will be created
static Integer[] intArray;  
static   
{  
intArray = new Integer[] { new Integer(13), new Integer(42), new Integer(83), new Integer(49), new Integer(89)};  
}  
public static void main(String args[])   
{  
//for loop to iterate over static array      
for (int j = 0; j <intArray.length; j++)   
{  
//to print array elements      
System.out.println(intArray[j]);  
}  
}  
}  


Output

Static Array in Java

Description: This image shows the output of the code written above. Here, a static array of type integershas been created.

Summary:

In this tutorial, we understood what is meant by a static array with the help of certain examples. We saw the implementation to understand the topic even better.


Related Topics

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.