TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java Int Array

Use int arrays: create them and loop over them with different syntaxes.
Int arrays. Integers are everywhere in the modern world: we use them for counting, for data representation. They can be used alone. But often ints are best kept together in an array.Array
Notes, int arrays. An array cannot be resized dynamically. For a collection that grows are you need more elements, consider an ArrayList. The Integer class is helpful.ArrayListArrayList int, Integer
Create arrays. This program creates 2 int arrays. First it uses the short, initializer syntax—we use curly brackets. Ints are specified in one line.

For: The for-loop syntax can be used on an int array in two ways—with a ":" over elements, or in the standard indexing syntax.

For

Also: We initialize an array in separate statements. This is the "alternative" array, but this style is standard and clear.

Java program that creates int arrays public class Program { public static void main(String[] args) { // Create int array with four elements. int[] values = { 10, 20, 30, 40 }; // ... Loop over the array's elements. for (int value : values) { System.out.println(value); } // Create int array with three elements in separate statements. int[] alternative = new int[3]; alternative[0] = 100; alternative[1] = 200; alternative[2] = -100; // ... Use for-loop to access all elements. for (int i = 0; i < alternative.length; i++) { System.out.println(alternative[i]); } } } Output 10 20 30 40 100 200 -100
Return int array. A method can return an array. Here we introduce a getEmployees method—it internally populates an array and then returns it.Return
Java program that returns an int array public class Program { static int[] getEmployees() { // Create an int array and return it. int[] array = new int[6]; array[0] = 9; array[1] = 11; array[2] = 15; array[3] = 19; array[4] = 29; array[5] = 55; return array; } public static void main(String[] args) { // Loop over an array returned by a method. for (int e : getEmployees()) { System.out.println(e); } } } Output 9 11 15 19 29 55
Array in class. Arrays can be used as fields in classes. This fits well with the object-based design in many Java programs. Here, we place an apartmentIds array in the Building class.Class

AddResidentAt: This method increments the apartmentIds array at a specified index. In a real program, it might check for a valid index.

RemoveResidentAt: This is the same style of method as addResidentAt but it subtracts from the element at the array index.

GetOccupancyAt: This method returns the value of the element at an index. In main, we use it and the other two methods.

Java program that uses int array in class class Building { int[] apartmentIds = new int[10]; public void addResidentAt(int id) { // Add to the array at this index. apartmentIds[id]++; } public void removeResidentAt(int id) { // Subtract from element value. apartmentIds[id]--; } public int getOccupancyAt(int id) { // Return element value. return apartmentIds[id]; } } public class Program { public static void main(String[] args) { // Create a Building. // ... Some residents move in and one leaves. Building b = new Building(); b.addResidentAt(5); b.addResidentAt(3); b.addResidentAt(9); b.removeResidentAt(5); // Display occupancy of apartments. for (int i = 0; i < 10; i++) { System.out .println(Integer.toString(i) + ": " + b.getOccupancyAt(i)); } } } Output 0: 0 1: 0 2: 0 3: 1 4: 0 5: 0 6: 0 7: 0 8: 0 9: 1
NullPointerException. An int array is a reference to a memory region—in this way it is similar to other classes. The reference can be null. We must guard for this case.Exceptions

Note: Even in a for-loop, we must first check for a null array. A NullPointerException will otherwise occur.

Java program that causes an exception public class Program { public static void main(String[] args) { int[] array = null; // We must first check for null before looping over an array. // ... This causes a runtime error. for (int value : array) { System.out.println(value); } } } Output Exception in thread "main" java.lang.NullPointerException at program.Program.main(Program.java:9)
ArrayIndexOutOfBoundsException. With an array of any type, we must be careful to avoid checking element ranges. Sometimes programs can omit these checks for performance.

However: If the array's size is uncertain, we must use an if-check to ensure an exception does not occur.

If
Java program that uses invalid element index public class Program { public static void main(String[] args) { // This array has just 5 elements. // ... So the only valid indexes are 0, 1, 2, 3 and 4. int[] array = { 40, 50, -60, -70, 80 }; // This causes an exception. array[10] = 1000; } } Output Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at program.Program.main(Program.java:7)
Clone. This method is helpful with int arrays. It copies all the elements from the original array into a new one. The arrays will occupy different memory regions.

So: When a cloned array is modified, the original does not reflect those changes.

Java program that uses clone public class Program { public static void main(String[] args) { int[] items = { 10, 20, 40 }; // Clone the int array. // ... All the elements are copied into a new array. int[] copy = items.clone(); // When the copy is modified, the original "items" is not affected. copy[0] = -100; System.out.println(items[0]); System.out.println(copy[0]); } } Output 10 -100
A summary. Ints are sometimes used alone. But often we use many elements together. In an int array we accommodate many ints into a single class—this makes ints more convenient.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf