Switch to full style
General Java code examples
Post a reply

creating arrays in java

Thu Jan 29, 2009 1:19 am

Creating arrays in java :
Arrays are objects in java ,and for that we create them using new operator .

For primitive data types :
java code
int[] myarr=new int[3];


For not primitive data types :

java code
car[] mycars=new car[3];


Once you specify the size of arrays , you can't change it later .

Assign values to arrays :
java code
myarr[0]=32;
myarr[1]=12;
myarr[2]=50;


for non primitive types :

java code
mycars[0]=new car("BMW");
mycars[1]=new car("VOLVO");
mycars[2]=new car("FIAT");


Create objects in the heap and assign it to the the array elements .

To copy one array to another one :
java code
String[] myStrings = {"one", "two", "three", "four", "five"};
String[] copiedStrings = new String[4];
// 1 is the start position in the orginal position
// 0 is the start position in the copyTo position
System.arraycopy(myStrings, 1, copiedStrings, 0, 4);
for (int i = 0; i < copiedStrings.length; i++) {
System.out.print(copiedStrings[i] + " , ");
}


The output is :
java code
two , three , four , five ,




Re: creating arrays in java

Wed Jan 16, 2013 12:44 am

copy array part added.

Post a reply
  Related Posts  to : creating arrays in java
 Arrays in java     -  
 Multidimensional arrays in Java     -  
 How to compare two arrays in java     -  
 Comparing Arrays in java     -  
 Creating a JAR file in Java     -  
 Creating your own Exceptions in Java     -  
 Passing arrays as function parameter in java     -  
 creating application for Samsung using java     -  
 Creating a Java Application Build using RAD 7     -  
 Multidimensional Arrays in JSP     -  

Topic Tags

Java Arrays