Java p6
Java p6
Introduction
Array in java:
An array is a collection of similar types of data. It is a group of like-typed variables
referred to by a common name. Arrays in Java work differently than they do in C/C++.
For example, if we want to store the names of 100 people then we can create an array of
the string type that can store 100 names.
String[] array = new String[100];
Here, the above array cannot store more than 100 names. The number of values in a Java
array is always fixed.
For example,
Double[] data;
Here, data is an array that can hold values of type double.
Here are Some of key features of array in Java:-
• In Java, all arrays are dynamically allocated.
• Arrays are stored in contiguous memory [consecutive memory locations].
• Since arrays are objects in Java, we can find their length using the object property
length. This is different from C/C++, where we find length using sizeof.
• A Java array variable can also be declared like other variables with [] after the data
type.
• The variables in the array are ordered, and each has an index beginning with 0.
• Java array can also be used as a static field, a local variable, or a method parameter.
• The size of an array must be specified by int or short value and not long.
//Java program to implement array.
class ImplementArray{
int a;
int b;
ImplementArray(int a, int b){
this.a=a;
this.b=b;
}
}
public class Array{ //main class~.java file
public static void main(String[] args){
int i,j;
int[] b =new int[5];
b[0]=1;
b[1]=2;
int[] ar={2,3,5,7,8};
short[] ars={7,6,4,8};
float[] arf={1.3f,0.3f,3.14f,1.6f};
char[] arc={'J','A','V','A'};
String[] arst={"Programming","in","Java","is Fun."};
int[][] ar2d={{1,2,3},{4,5,6},{7,8,9}};