07-Java Array
07-Java Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
Java array is an object the contains elements of similar data type. It is a data structure where we
store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
arrayRefVar=new datatype[size];
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
Example
class Testarray1{
public static void main(String args[]){
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
int a[]={33,3,4,5};
min(a);//passing array to method
}}
class Testarray4{
public static void main(String args[]){
int arr[]={4,4,5};
Class c=arr.getClass();
String name=c.getName();
System.out.println(name);
}}
public static void arraycopy( Object src, int srcPos,Object dest, int destPos, int length)
Example
class TestArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e','i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to
traverse the complete array sequentially without using an index variable.
The java.lang.String class provides a lot of methods to work on string. By the help of these
methods, we can perform operations on string such as trimming, concatenating, converting,
comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any form
in window based, web based or mobile application.
Creating Strings:
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in
this case, "Hello world!'.