Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Array in Java: What You Need To Know?

Updated on 16 June, 2023

5.64K+ views
8 min read

Introduction

After going through the primitive data types of java, many of us will have a question can we store more than one entry sequentially in the disk?. Arrays in java would be the answer to our query.

An array is a data structure that stores the entries of the same data type sequentially. An array reduces the duplication of code and makes it simple. When we want to store a considerably big number of values, say 50 values then assigning each value to a variable contradicts the simplicity of a code.

An array overcomes this issue we can assign all these values to a single array but remember that an array can store only values of the same data type.

Let’s get started!

Declaration and Initialization

To use an array we need to declare it and we must specify the data type of the variables we want to store in the array. Similar to all the programming languages java also has a syntax to be followed for declaration.

int[] array;  //type1

int array[];  //type2

And the syntax of creating an array goes as follows “data_type[] array = new array[array_length]”. We need to assign the length of the array at the time of creating it and the size cannot be increased after creating. After creating an array by specifying the length, it just assigns an empty array to that variable and we can push the values into it later. Let’s walk through the code for that.

And the syntax of creating an array goes as follows “data_type[] array = new array[array_length]”. We need to assign the length of the array at the time of creating it and the size cannot be increased after creating. After creating an array by specifying the length, it just assigns an empty array to that variable and we can push the values into it later. Let’s walk through the code for that.
int[] array = new int[10]; //declaration and 

                           //creating a new array

//assigning values

array[0]=1;

array[1]=5;

array[8]=9;

//method 2

int[] array = {1, 2, 3, 4, 5};

System.out.print(int[0]);

Initially, all the positions are filled with zeroes in an integer array and we can override those values with our values by mentioning the index in the square brackets. In the above snippet, “method 2” is another way of creating an array.

Looping Over The Array

We can use a for loop or a while loop for looping over an array, where we increment the index for each iteration. Remember that accessing an element with an index greater than the length of the array will throw an exception.

int[] array={1,2,3,4,5};

for(int i=0;i<5;i++){

  System.out.print(array[i]+" ");

}

The above code snippet prints “1 2 3 4 5 ” as the output.

There’s also another interesting loop called “for-each loop” for iterating over the loop.

float[] array={1.2f,2.3f,3.4f,4.5f,5.6f};

for(float f:array){

  System.out.print(f+" ");

}

The above code snippet shows the implementation of the for-each loop, where the variable float changes the value to the next entry in the array at each iteration. This implementation doesn’t need any index variable.

 

Checkout: A Complete ArrayList in Java: What You Need to Know

Predefined Methods

The Arrays class in java comes with many predefined methods that are generalized to all primitive data types. For example, if I want to sort an array with all integers and an array with all floats then I can use the same method for both cases.

Let’s walk through a few of the predefined array methods.

  • sort()

This method sorts the given array in the ascending order and updates the sorted array, as already discussed this method is overloaded for all primitive data types in java. This public method doesn’t return anything since it’s of the void return type.

Arrays.sort(array_name) is the syntax to be followed.

float[] array={2.2f,1.3f,5.4f,3.5f,7.6f};

Arrays.sort(array);

for(float f:array){

  System.out.print(f+" ");

}

The above snippet will print “1.3 2.2 3.5 5.4 7.6 “ as expected.

  • fill()

This method fills the array with the variable we passed in the function call. This method replaces a naive implementation of looping over the array and assigning a value to that position.

Arrays.fill(array_name, value) is the syntax to be followed.

float[] array={2.2f,1.3f,5.4f,3.5f,7.6f};

Arrays.fill(array,9.8f);

for(float f:array){

  System.out.print(f+" ");

}

  The above snippet will replace all the entries in the array with 9.8.

  • equals()

This method expects two arrays as the parameter and returns true if all the elements in array 1 are equal to all the elements of array 2. Remember that this method returns false if both the arrays have different lengths, or if the order of elements is different.

Arrays.equals(array_1, array_2) is the syntax to be followed.

float[] array1={2.2f,1.3f,5.4f,3.5f,7.6f};

float[] array2={2.2f,1.3f,5.4f,3.5f,7.6f};

float[] array3={2.2f,1.3f,3.5f,5.4f,7.6f};

System.out.println(Arrays.equals(array1,array2)); //line1

System.out.println(Arrays.equals(array1,array3)); //line2

The above snippet will print True for line1 and False for line2 For a further read on various array methods in java, have a look at their documentation.

Accessing Arrays in Methods

Arrays would be of no use if we can’t use them in functions. But Java never lets you down, we can pass an array, return an array, and use an array in java function.

Let’s walk through them.

We need to specify the data type of the array in function declaration when we want to pass an array to the Java function. This is almost similar to passing a primitive data type to function. Similarly, when we return an array, we need to declare the array with the array as the return type.

public static float[] sorted(float[] array){

  Arrays.sort(array);

  return array;

}

public static void main(String args[]){ 

  float[] array1={2.2f,1.3f,5.4f,3.5f,7.6f};

  float[] array2=sorted(array1);

  for(float f:array2)

    System.out.print(f+" ");

}

The above snippet prints “1.3 2.2 3.5 5.4 7.6” as expected. 

Read: MATLAB Data Types: Everything You Need to Know

Initialising Arrays with Precise Values 

Syntax to initialize an array with unique values:

Datatype[] arrayname = {value1, value2, value3, …};

For example, we will create an array of integers with the following values: 

int[] numbers = {1, 2, 3, 4, 5};

Using loops to traverse and modify array elements:

We can use loops to traverse and modify array elements. The ‘for’ loop is quite common for traversing arrays. For instance, we can use a ‘for’ loop to print all values ​​in an array of numbers: 

for(int i = 0; i < numbers.length; i++){

    System.out.println(numbers[i]);

}

We can create arrays using the System.Arraycopy() technique. This technique copies the source array, the beginning index of the source array, the destination array, the beginning index of the vacation spot array, and the variety of elements to be copied. For example, we can copy the variety array to some other array referred to as numbersCopy:

int[] numbersCopy = new int[numbers.length];

System.arraycopy(numbers, 0, numbersCopy, 0, numbers.length);

Sorting Arrays the Usage of Integrated Capabilities

Java gives integrated capabilities for the array’s sorting program in Java. We can use the Arrays.Type() approach to sort arrays in ascending order. For example, we can set up the numbers in ascending order:

Arrays.Type(numbers);

Searching for Specific Elements in an Array

To search for a specific detail in an array, we can use a loop to iterate through the array and evaluate every detail to the detail we are searching for. For instance, we can search for the range 3 within the numbers array:

int searchValue = 3;

for(int i = 0; i < numbers.length; i++){

    if(numbers[i] == searchValue){

        System.out.println("Found at index " + i);

        break;

    }

}

Conclusion

Now that you are aware of arrays in java. Understood about Initialization and declaration of the array. Explored various ways of iterating over the array. Walked through a few of the predefined array methods and accessing arrays in methods. You are power-packed with a useful data structure in java, start using it now!

If you’re interested to learn more about Java, OOPs & full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

1. How is an array different from a linked list?

In an array, data elements are stored in contiguous allocation in the memory, whereas in a linked list, the data elements are stored in a non-contiguous manner. Arrays require compile-time allocation of data, whereas linked lists require dynamic data allocation, i.e., run-time allocation. Linked lists require more memory than arrays as we also need to add a reference to the next node with every element. Linked lists are helpful when we do not know how much space we require for the program, whereas in arrays, you have to declare the size of the list upfront. Arrays can be directly accessed through the index value in the list, whereas a linked list cannot be accessed directly; it requires traversing.

2. How is an array different from an Array list?

Arrays can be single-dimensional or multi-dimensional, but array lists can only be single-dimensional. For traversing elements in an array, for() loop is used, whereas an iterator is used for traversing elements in an array list. The ‘length’ keyword is used to get the size of an array, whereas size() is used to get the size of an array list. An array has a fixed size, whereas an array list has a dynamic size that can be increased and decreased based on the requirements. Arrays are relatively faster than array lists because of their fixed size. Autoboxing is required to store primitive data types in an array list.

3. What is Quicksort, and how does the worst-case time complexity occur

Quicksort is an in-place algorithm that follows the divide and conquers approach for sorting the elements in a list. In this, we need to select a pivot element, and we shift all elements smaller than it to the left side of the pivot and all elements larger than the pivot to the right side of the pivot. After each iteration, the pivot element gets placed at its correct position in the array. The worst-case time complexity is achieved by giving a sorted list as the input. By this, the time complexity gets increased from O(N logN) to O(N^2).

RELATED PROGRAMS