In this tutorial you will learn more Java and will look at Java handling and using arrays. This will allow you to write a simple Java app that you can then use in your IDE
About this Tutorial –
Objectives –
This course is aimed at object-oriented developers (e.g. C++ or C#) who need to transition into Java. It is also aimed at those learning to program for the first time; the course covers the Java programming constructs and APIs quickly, focussing on the differences between Java and other OO languages.
Audience
This training course is aimed at OO developers who need to transition into Java.
Prerequisites
No previous experience in Java programming is required. But any experience you do have in programming will help. Also no experience in eclipse is required. But again any experience you do have with programming development environments will be a valuable.
Experience using a contemporary OO language such as C++ or C# would be useful but is not required.
Contents
The Java course cover these topics and more:
- Flow Control: Decision making: if and if-else; The switch statement; Looping: for loops; while loops; do-while loops; for-each style loops; Assertionsv
- Concurrency: Overview of multithreading; Creating new threads; Object locking; Using wait, notify, and notifyAll
- Collections: Overview of Java SE collection classes; Generics; Using List-based collection classes; Using Set-based collection classes; Using Map-based collection classes; Collection techniques
Exam Preparation
The Java course will help you prepare for these certifications:
- Oracle Certified Java Associate – Exam 1Z0-803
- Oracle Certified Java Professional – Exam 1Z0-804
Quick Access
Overview
Estimated Time – 1.5 Hours
Not what you are looking? Try the next tutorial – Additional Language Features
Lab 1: Declaring and using arrays
- Overview
- An array is an sequential collection of elements of a specified type
- Elements are accessed by index position, from [0] to [n-1]
- Once created, an array is fixed size
- You can create an array of primitives or objects
- An array of primitives holds the elements in-situ
- An array of objects holds object references
- An array is an sequential collection of elements of a specified type
- Declaring and Creating an Array
- You can declare an array variable as follows:
- Where type is a primitive type or a class type
- Note: DON’T put the size in the declaration!
type[] arrayName // Java Prefered Syntax;
type arrayName[] // C++ prefered Syntax;
- The next step is to actually create the array object
- Allocates the array object on the heap (i.e. an array is an object!)
- Elements are initialized to zero (primitives) or null (for class types)
arrayName = new type[numElems]; //numElems can be a constant or a run-time value
- See DemoCreatingUsingArrays.java code file
- demoCreatingArrays() method
- View code file.
- You can declare an array variable as follows:
- Using an Array Initializer
- You can declare, create, and populate an array all in one go, using array initializer syntax
type[] arrayName = { value0, value1, ...};
- Example:
public static void demoArrayInitializers() {
final int[] DAYS_IN_MONTH = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
File[] logFiles = {
new File("C:\\errors.log"),
new File("C:\\access.log"),
new File("C:\\audit.log")
};
...
}
- View code file.
- You can declare, create, and populate an array all in one go, using array initializer syntax
- Using an Anonymous Array
- You can use array initializer syntax to initialize an array variable that already exists
- By using an “anonymous array”, as follows:
type[] arrayName;
arrayName = new type[] { value0, value1, ...};
- By using an “anonymous array”, as follows:
- View code file.
- Example:
File[] logFiles;
...
logFiles = new File[] {
new File("C:\\errors.log"),
new File("C:\\access.log"),
new File("C:\\audit.log")
};
- View code file.
- You can use array initializer syntax to initialize an array variable that already exists
- Accessing Elements in an Array
- To access elements in an array:
- If index is out-of-range, you get an ArrayIndexOutOfBoundsException
- Don’t let this happen!
- Use manual bounds-checking instead
arrayName[index]
- You can read and write array elements
- As long as the array isn’t final, of course
public static void demoArrayInitializers() {
...
System.out.println("Days in February: " + DAYS_IN_MONTH[2]);
logFiles[0] = new File("C:\\fatalErrors.log");
System.out.println("logFile[0]: " + logFiles[0].getAbsolutePath());
}
- View code file.
- As long as the array isn’t final, of course
- To access elements in an array:
- Reassigning Array Variables
- You can reassign an array variable to another array object
- The other array must be a compatible type
- The other array object must have the same number of dimensions
- The other array object can be a different size
- Type-matching rules for primitive arrays:
- You can’t assign different primitive-type arrays
- E.g. you can’t assign a byte[] array object to an int[] variable
- Type-matching rules for reference-type arrays:
- You can assign different reference-type arrays if “IS-A” rule applies
- E.g. you can assign an Employee[] array object to a Person[] variable, if Employee inherits from Person
- You can reassign an array variable to another array object
- Using arrays of primitives
- Open ArrayOfPrimitives.java, and write an application that creates and processes an array of double values.
- Suggestions and requirements:
- Ask the user how many elements he/she would like in the array (use Scanner to get this number). Then create an array of this size.
Scanner scanner = new Scanner(System.in);
// Ask user how big they want the array to be.
System.out.print("How many elements do you want in your integer array? ");
int numElems = scanner.nextInt();
// Create an integer array of specified size.
int[] array = new int[numElems];
- View code file.
- Write a for-loop that asks the user to enter values for each array element. Display prompt messages such as “Enter value for element 0:”
// Ask user for array values.
for (int i = 0; i < array.length; i++) { System.out.print("Enter value for element " + i + ": "); array[i] = scanner.nextInt(); } - View code file.
- Write a for-each loop to display each value in the array.
System.out.println("\nArray values: ");
for (int num: array) {
System.out.println(num);
}
- View code file.
- Output the sum of all the positive values in the array, and indicate how many positive values there were.
int countPositiveValues = 0;
System.out.println("\nPositive values: ");
for (int num: array) {
if (num > 0) {
System.out.println(num);
countPositiveValues++;
}
}
System.out.println("Count of positive values: " + countPositiveValues);
scanner.close();
- View code file.
- Ask the user how many elements he/she would like in the array (use Scanner to get this number). Then create an array of this size.
Lab 2: Traversing arrays
- Determining the Length of an Array
- The length of the array is determined via the length public field
- Use this to manually check array indexes whenever the user has the chance to get it wrong!
public static void demoArrayLength() {
final String[] DAYS_OF_WEEK = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
Scanner scanner = new Scanner(System.in);
System.out.print("\nEnter a day number: ");
int dayNumber = scanner.nextInt();
if (dayNumber < 0 || dayNumber >= DAYS_OF_WEEK.length) {
System.out.println("Day is out of range.");
}
else {
System.out.println("Day " + dayNumber + " is " + DAYS_OF_WEEK[dayNumber]);
}
}
- View code file.
- Use this to manually check array indexes whenever the user has the chance to get it wrong!
- The length of the array is determined via the length public field
- Using a for Loop
- You can traverse an array using a for loop
- This is the traditional approach
- Use an integer array index that ranges from 0 to (n-1)
public static void demoArrayTraversal() {
final String[] DAYS_OF_WEEK = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
for (int i = 0; i < DAYS_OF_WEEK.length; i++) { System.out.println("Day " + i + " is " + DAYS_OF_WEEK[i]); } ... } - View code file.
- You can traverse an array using a for loop
- Using a for-each Loop
- From Java SE 1.5 onwards, you can use a for-each loop to iterate over an array (or collection)
- Example:
public static void demoArrayTraversal() {
final String[] DAYS_OF_WEEK = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
for (String dayOfWeek : DAYS_OF_WEEK) {
System.out.println("Here's a day: " + dayOfWeek);
}
...
}
- View code file.
- Using arrays of objects
- Open ArrayOfObjects.java, and write an application that creates and processes an array of Product objects (we've already written the Product class).
- Suggestions and requirements:
- In main(), ask the user how many products he/she would like in the array, and then create a Product-array of this size.
Scanner scanner = new Scanner(System.in);
// Ask user how big they want the array to be.
System.out.print("How many elements do you want in your product array? ");
int numElems = scanner.nextInt();
// Create a product array of specified size.
Product[] array = new Product[numElems];
- View code file.
- Write a for-loop that populates the array with Product objects (each time round the loop, create a new Product object with an appropriate product name from the user).
// Ask user for array values.
for (int i = 0; i < array.length; i++) { System.out.print("Enter name and unit price for product " + i + ": "); String name = scanner.next(); double unitPrice = scanner.nextDouble(); array[i] = new Product(name, unitPrice); } - View code file.
- Write a for-each loop to display each product.
System.out.println("\nProducts: ");
for (Product prod: array) {
System.out.println(prod);
}
scanner.close();
- View code file.
- In main(), ask the user how many products he/she would like in the array, and then create a Product-array of this size.
Lab 3: Using the Arrays class
- Overview
- The java.util.Arrays class provides various (static) methods that allow you to perform whole-array operations
- Here are some of the methods (params not shown here):
- Arrays.fill() Fills an array (or portion) with value
- Arrays.copyOf() Returns a copy of an array
- Arrays.copyOfRange() Returns a copy of an array range
- Arrays.equals() Compares two arrays for equality
- Arrays.sort() Sorts the elements in an array
- Arrays.binarySearch() Searches for item in sorted array
- Filling an Array
- Arrays.fill(array, value)
- Fills an array with a specified value
- Arrays.fill(array, index1, index2, value)
- Fills elements index1 to (index2-1) with a specified value
public static void demoFill() {
int[] examMarks = { 89, 56, 82, 99, 72, 79, 64 };
Arrays.fill(examMarks, 99);
displayIntArray(examMarks, "Filled array with 99s.");
Arrays.fill(examMarks, 2, 5, 100);
displayIntArray(examMarks, "Filled array elements 2,3,4 with 100.");
}
private static void displayIntArray(int[] array, String msg) {
System.out.println("\n" + msg);
for(int elem: array) {
System.out.println(elem);
}
}
- View code file.
- Fills elements index1 to (index2-1) with a specified value
- Arrays.fill(array, value)
- Copying an Array
- Arrays.copyOf(array, length)
- Returns a copy of the array, truncated or padded if necessary
- Arrays.copyofRange(array, index1, index2)
- Returns a copy of array elements index1 to (index2-1)
public static void demoCopy() {
int[] examMarks = { 89, 56, 82, 99, 72, 79, 64 };
int[] first3 = Arrays.copyOf(examMarks, 3);
displayIntArray(first3, "Copy of first 3 elements.");
int[] tenElems = Arrays.copyOf(examMarks, 10);
displayIntArray(tenElems, "Copy of 10 elements.");
int[] middle3Elems = Arrays.copyOfRange(examMarks, 2, 5);
displayIntArray(middle3Elems, "Copy of middle 3 elements.");
}
- View code file.
- Returns a copy of array elements index1 to (index2-1)
- Arrays.copyOf(array, length)
- Testing Arrays for Equality
- Arrays.equals(array1, array2)
- Returns true if arrays are of same type, and elements are equal to each other (as defined by calling equals() on element pairs)
public static void demoEquals() {
int[] arr1 = { 89, 56, 82, 99, 72, 79, 64 };
int[] arr2 = { 89, 56, 82, 99, 72, 79, 64 };
...
System.out.println("\narr1 equals arr2? " + Arrays.equals(arr1, arr2));
...
String[] nephews1 = { "Huey", "Lewey", "Dewey" };
String[] nephews2 = { "Huey", "Lewey", "Dewey" };
System.out.println("nephews1 equals nephews2? " +
Arrays.equals(nephews1, nephews2));
}
- View code file.
- Returns true if arrays are of same type, and elements are equal to each other (as defined by calling equals() on element pairs)
- Arrays.equals(array1, array2)
- Sorting an Array
- Arrays.sort(array)
- Sorts the elements into ascending order
- Arrays.sort(array, index1, index2)
- Sorts elements index1 to (index2-1)
public static void demoSort() {
int[] examMarks = { 89, 56, 82, 99, 72, 79, 64 };
Arrays.sort(examMarks, 2, 5);
displayIntArray(examMarks, "Sorted array elements 2,3,4.");
Arrays.sort(examMarks);
displayIntArray(examMarks, "Sorted all elements.");
}
- View code file.
- Sorts elements index1 to (index2-1)
- Arrays.sort(array)
- Searching an Array
- Arrays.binarySearch(array, value)
- Searches a sorted array for a value, by using a binary search
- Returns index of value if found, or -1 otherwise
public static void demoSearch() {
int[] examMarks = { 89, 56, 82, 99, 72, 79, 64 };
Arrays.sort(examMarks);
System.out.println("Index of 99: " + Arrays.binarySearch(examMarks, 99));
System.out.println("Index of 22: " + Arrays.binarySearch(examMarks, 22));
}
- View code file.
- Arrays.binarySearch(array, value)
- Using arrays within a class
- Open Employee.java, and take a look at the existing code. This is the solution code from the "Defining and Using Classes" lab.
- Enhance the Employee class so that it holds an array of skills for each employee:
- For the sake of simplicity, each skill can be a simple String.
- You can also assume a fixed limit to the number of skills an employee can have, e.g. 10
// Skills for the employee.
private String[] skills = new String[10];
private int numSkills = 0;
- View code file.
- Write methods to allow client code to add a skill and to display all the skills. Make sure you avoid array overflow!
public void addSkill(String skill) {
if (numSkills == skills.length) {
System.out.println("In addSkill(), cannot add skill " + skill);
} else {
skills[numSkills++] = skill;
System.out.println("In addSkill(), added skill " + skill);
}
}
public void displaySkills() {
System.out.println("Skills:");
for (int i = 0; i < numSkills; i++) { System.out.println(" " + skills[i]); } } - View code file.
Lab 4: Multi-dimensional arrays
- Rectangular Arrays
- To create a rectangular array (e.g. with 2 dimensions):
type[][] arrayName = new type[numRows][numCols];
- To create a rectangular array (e.g. with 2 dimensions):
- You can use initializer syntax, with multiple sets of braces:
- To create a rectangular array (e.g. with 2 dimensions):
type[][] arrayName =
{
{ ..., ..., ...},
{ ..., ..., ...},
...
};
- View code file.
- To create a rectangular array (e.g. with 2 dimensions):
- Use nested loops to process:
- To create a rectangular array (e.g. with 2 dimensions):
for (int r = 0; r < arrayName.length; r++) { for (int c = 0; c < arrayName[r].length; c++) { // Access element arrayName[r][c] } }
- View code file.
- To create a rectangular array (e.g. with 2 dimensions):
- Jagged Arrays
- To create a jagged array:
- Specify number of rows initially, but not number of columns
- Specify number of columns later, on a row-by-row basis
type[][] arrayName = new type[numRows][];
...
arrayName[0] = new type[numColsForRow0];
arrayName[1] = new type[numColsForRow1];
arrayName[2] = new type[numColsForRow2];
v
- View code file.
- You can use initializer syntax, with multiple sets of braces
- Use nested loops to process
- To create a jagged array:
- Using Multi-Dimensional Arrays
- Open MultiDimArrays.java, and write an application that performs matrix manipulation, using 2-dimensional arrays.
- Allow the user to specify the number of rows and columns and to enter data
System.out.println("Using rectangular arrays...");
System.out.print("Number of rows required? ");
int numRows = scanner.nextInt();
System.out.print("Number of columns required? ");
int numCols = scanner.nextInt();
// Create and initialize 1st matrix.
int [][] m1 = new int[numRows][numCols];
System.out.print("\nEnter data for 1st matrix:");
for (int r = 0; r < m1.length; r++) { for (int c = 0; c < m1[r].length; c++) { System.out.printf("Enter element [%d][%d]: ", r, c); m1[r][c] = scanner.nextInt(); } } // Create and initialize 2nd matrix. int [][] m2 = new int[numRows][numCols]; System.out.println("\nEnter data for 2nd matrix:"); for (int r = 0; r < m2.length; r++) { for (int c = 0; c < m2[r].length; c++) { System.out.printf("Enter element [%d][%d]: ", r, c); m2[r][c] = scanner.nextInt(); } } - View code file.
- And then output the sum and difference of the matrices.
// Output sum of matrix elements.
System.out.println("Sum of matrix elements:");
for (int r = 0; r < m1.length; r++) { for (int c = 0; c < m1[r].length; c++) { System.out.printf("%2d ", m1[r][c] + m2[r][c]); } System.out.println(); } // Output difference of matrix elements. System.out.println("Difference of matrix elements:"); for (int r = 0; r < m1.length; r++) { for (int c = 0; c < m1[r].length; c++) { System.out.printf("%2d ", m1[r][c] - m2[r][c]); } System.out.println(); } } - View code file.
- Allow the user to specify the number of rows and columns and to enter data
- Open MultiDimArrays.java, and write an application that performs matrix manipulation, using 2-dimensional arrays.
Well done. You have completed the tutorial in the Java course. The next tutorial is
6. Additional Language Features
Copyright © 2016 TalkIT®
If you would like to see more content like this in the future, please fill-in our quick survey.