How to initialize an array in JShell in Java 9?


JShell is a command-line tool used to evaluate simple statements, expressions, classes, methods, variables, etc.. and prints the output immediately to the user.

An array in Java is also an object. We need to declare an array and then created. In order to declare a variable that holds an array of integers, we can mention like int[] array. In an array, the index starts from 0 to (length of array - 1).

In the below code snippet, we can use an index to find the specific element from the array. It will be done by using an indexing operator: []. The expression marks[0] maps to the first array element stored at index 0 of the array marks.

Snippet-1

jshell> int[] marks = {80, 75, 95};
marks ==> int[3] { 80, 75, 95 }

jshell> marks[0]
$2 ==> 80

jshell> marks[1]
$3 ==> 75

jshell> marks[2]
$4 ==> 95

jshell> int sum = 0;
sum ==> 0

jshell> for(int mark:marks) {
   ...>    sum = sum + mark;
   ...> }

jshell> sum
sum ==> 250


In the below code snippet, we can create an array of marks to store 8 int values and iterate through marks using for- loop, printing out its values.

Snippet-2

jshell> int[] marks = {1, 2, 3, 4, 5, 6, 7, 8};
marks ==> int[8] { 1, 2, 3, 4, 5, 6, 7, 8 }

jshell> marks.length
$1 ==> 8

jshell> for(int i=0; i < marks.length; i++) {
   ...>    System.out.println(marks[i]);
   ...> }
1
2
3
4
5
6
7
8


In the below code snippet, we can print how arrays with different types are initialized: int - 0, double - 0.0, boolean - false, object - null.

Snippet-3

jshell> int[] marks = new int[5];
marks ==> int[5] { 0, 0, 0, 0, 0 }

jshell> double[] values = new double[5];
values ==> double[5] { 0.0, 0.0, 0.0, 0.0, 0.0 }

jshell> boolean[] tests = new boolean[5];
tests ==> boolean[5] { false, false, false, false, false }

jshell> class Person {
   ...> }
| created class Person

jshell> Person[] persons = new Person[5];
persons ==> Person[5] { null, null, null, null, null }

Updated on: 24-Apr-2020

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements