Java Examples – Arrays in Java Example




Java Tutorial for Beginners
Java Tutorial for Beginners
  • An array is an ordered list of values
  • An array of size N is indexed from zero to N-1
  • A particular value in an array is referenced using the array name followed by the index in brackets
  • For example, the expression
    scores[2]
  • That expression represents a place to store a single integer and can be used wherever an integer variable can be used
  • For example, an array element can be assigned a value, printed, or used in a calculation:
      scores[2] = 89;
    
      scores[first] = scores[first] + 2;
    
      mean = (scores[0] + scores[1])/2;
    
      System.out.println ("Top = " + scores[5]);
  • The values held in an array are called array elements
  • An array stores multiple values of the same type – the element type
  • The element type can be a primitive type or an object reference
  • Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc.
  • In Java, the array itself is an object that must be instantiated
  • Definitions using new
    double [] scores = new double [NUMBER_OF_STUDENTS];
    • The above statement will:
    • allocate block of memory to hold 7 doubles
    • initialize block with zeros
    • returns the address of the block
    • create a handle called scores
    • store address of the block in scores
/*************************************************************************
* Arrays in Java Example
*
*************************************************************************/
package lesson1;
public class MyClass {
public static void main(String[] args) {
int[] myintarray = {100,31,26,48,52};
/*
int[] myIntArray = new int[3];
int[] myIntArray = {1,2,3};
int[] myIntArray = new int[]{1,2,3};
*/
int index=0;
while(index < 5) {
System.out.println(myintarray[index]);
index++;
}
}
}

Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Leave a Reply

Your email address will not be published.


*