Free trial: Java для начинающих
Complete a couple of real lessons from this course — no signup required.
Lesson 1: Variables, Data Types & Operators
Java is a simple, object-oriented, and highly efficient programming language. One of its main goals is to make learning to code easier and faster. To write a working Java program, it's enough to remember the core keywords, and your code will run correctly.
In this lesson we'll cover the basic structure of a Java program, variables, data types, reading input from the console, and the main math operators.
Your first Java program
Let's look at the first simple example of a Java program:
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println(a + b);
}
}
30When this code runs, we create two numbers: a and b. Variable a equals 10, and variable b equals 20. Then we print their sum:
a + b = 10 + 20 = 30
The line System.out.println(a + b); prints the result to the console.
Structure of a Java program
If we break down the program above, we see it starts with the keywords: public class Main.
This means we're creating a class called Main. The class name must match the source file's name exactly.
If the file is called Main.java, the class must be called Main. If the file is called Hello.java, the class must be called Hello.
For example, if you named the file Hello.java, the code would look like this:
public class Hello {
public static void main(String[] args) {
...
}
}
Next we see curly braces { }. They open and close a block of code. In Java, it's very important to make sure every opening brace is closed.
Inside the class we create the program's main method: public static void main(String[] args). This is exactly the method where a Java program starts running.
Basic structure:
public class Main {
public static void main(String[] args) {
// The program's logic goes here
}
}
We'll cover methods a bit later. For now, the main thing to remember is: every Java program starts running from the main method.
Printing text to the console
To print data to the console, we use the command System.out.println().
public class Main {
public static void main(String[] args) {
System.out.println("Hello BITLAB");
}
}
Hello BITLABNote that we end every statement with a semicolon: ;. It means the statement is complete.
Variables and the int type
A variable is a piece of memory where a value is stored. In Java, every variable has its own data type.
For example, to store whole numbers we use the int type. The word int is short for integer, meaning a whole number.
public class Main {
public static void main(String[] args) {
int age = 22;
System.out.println(age);
}
}
22In this example, we created a variable called age, stored the number 22 in it, and printed that value to the console.
The double type
To store decimal numbers in Java, we use the double type.
public class Main {
public static void main(String[] args) {
double x = 3.4;
double y = 4.5;
double sum = x + y;
System.out.println("Result is: " + sum);
}
}
Result is: 7.9This time we created decimal numbers instead of whole ones. For that, we used the double data type.
In Java, you can't create a decimal variable using the int type:
int x = 3.4;
int y = 4.5;
This code causes an error, because int only stores whole numbers. For decimal numbers you need to use double.
Also note the line: System.out.println("Result is: " + sum);. Here we combine text and a number using the + operator.
The String type
To store text in Java, we use the String type.
public class Main {
public static void main(String[] args) {
String name = "Ilyas";
String surname = "Zhuanyshev";
String city = "Almaty";
String sentence = "I am " + name + " " + surname + " from " + city;
System.out.println(sentence);
}
}
I am Ilyas Zhuanyshev from AlmatyIn this example we create three text variables: name, surname, and city.
Note that text in Java must start and end with double quotes: " ".
Correct: String name = "Ilyas";
Beginners often make this mistake:
String name = Ilyas; // Not allowed!
String surname = Zhuanyshev; // Not allowed!
String city = Almaty; // Not allowed!
This code is wrong, because Java will think that Ilyas, Zhuanyshev, and Almaty are variable names, not text.
Main data types in Java
For working with whole numbers:
byte— a very small whole numbershort— a short whole numberint— a standard whole numberlong— a large whole number
For working with decimal numbers:
float— a lower-precision decimal numberdouble— a higher-precision decimal number
For working with characters:
char— a single character
For boolean values:
boolean— true or false
For working with text:
String— text data
Reading input from the console
This raises a question: do we always have to hard-code variable values right in the code? What if we want to enter them freely?
For this, Java has a ready-made class called Scanner. It lives in the java.util library and lets you read data from the console.
Let's modify our first example, where we added two whole numbers:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert first number:");
int a = in.nextInt();
System.out.println("Insert second number:");
int b = in.nextInt();
System.out.println(a + b);
}
}
5
712When you run the program, the console will ask for two whole numbers. If we enter 5 and 7, we get 12.
The line import java.util.Scanner; means we're importing the ready-made Scanner class.
The line Scanner in = new Scanner(System.in); creates a Scanner object that will read data from the console.
The method in.nextInt() reads a whole number of type int.
Reading decimal numbers
You can also enter decimal numbers freely from the console. For that, we use the nextDouble() method.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert first number:");
double x = in.nextDouble();
System.out.println("Insert second number:");
double y = in.nextDouble();
double sum = x + y;
System.out.println("Result is: " + sum);
}
}
2.2
4.5Result is: 6.7The only difference from reading whole numbers: instead of in.nextInt() we write in.nextDouble().
Reading strings
To read strings, meaning text, we use the in.next() method.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert name:");
String name = in.next();
System.out.println("Insert surname:");
String surname = in.next();
System.out.println("Insert city:");
String city = in.next();
String sentence = "I am " + name + " " + surname + " from " + city;
System.out.println(sentence);
}
}
Aybek Serikov AktobeI am Aybek Serikov from AktobeThe next() method reads a single word up to the next space. That's why we read the name, surname, and city with three separate in.next() calls.
Math operators
Math operators let you perform operations on numbers. They're commonly used in tasks, calculations, and algorithms.
Addition (+)
int a = 10;
int b = 20;
int sum = a + b; // 30
Subtraction (-)
int a = 20;
int b = 15;
int diff = a - b; // 5
Multiplication (*)
int a = 10;
int b = 5;
int result = a * b; // 50
Division (/)
int a = 50;
int b = 5;
int div = a / b; // 10
Remainder (%)
int a = 21;
int b = 6;
int rem = a % b; // 3
These operators are enough to get started solving basic calculation tasks.
The remainder operator %
You probably have a question about the remainder operator. It returns the remainder of dividing two numbers.
For example, if we divide 30 by 7, then 7 fits into 30 four times:
7 * 4 = 28
30 - 28 = 2
30 % 7 = 2
For example, 40 % 5 is 0, because 40 divides evenly by 5.
The % operator is often used to check whether a number divides evenly by another, whether a number is even or odd, or whether an action needs to happen every few steps.
That's enough material for now. It's recommended to practice and solve a few exercises to reinforce variables, data types, Scanner, and math operators.
Company monthly earnings
String companyName, int profit, double month) and prints the company's name and its average monthly income.P&G
145900
8Company P&G earns 18237.5 dollars in a monthAirAstana
142854
5.8Company AirAstana earns 24630.0 dollars in a month-
Input:
P&G, 145900, 8 -
Input:
AirAstana, 142854, 5.8 -
Input:
TechCorp, 100000, 4 -
Input:
Kcell, 96000, 12 -
Input:
Halyk, 45000, 9
Print user info
Alibek
Maratov
19
KazakhstanName: Alibek
Surname: Maratov
Age: 19
Country: KazakhstanAigerim
Bekova
21
KazakhstanName: Aigerim
Surname: Bekova
Age: 21
Country: Kazakhstan-
Input:
Alibek, Maratov, 19, Kazakhstan -
Input:
Aigerim, Bekova, 21, Kazakhstan -
Input:
John, Smith, 30, USA -
Input:
Marat, Zhaksybekov, 17, Kazakhstan -
Input:
Elena, Petrova, 25, Russia
Square and cube
24
8636
216-
Input:
2 -
Input:
6 -
Input:
3 -
Input:
10 -
Input:
-2
Evaluate a formula
x and finds y = 3x² − 6x − 7 for that value.2-7538-
Input:
2 -
Input:
5 -
Input:
1 -
Input:
3 -
Input:
4
Evaluate a 3-variable formula
x, y, z and calculates x³ + 5xy − 6zy + z³.1 2 323 3 8440-
Input:
1 2 3 -
Input:
3 3 8 -
Input:
0 0 0 -
Input:
2 1 1 -
Input:
1 1 1
Lesson 2: Conditional Statements
We use conditions all the time in everyday life. For example, we wake up and start having breakfast. If the kettle has boiled, we turn it off. If not yet, we wait until it does. We start getting dressed and head to work. If we're running late, we order a taxi; otherwise, we walk there in about 25 minutes. If we're hungry after work, we go have dinner. If there's no food at home, we order some. You could keep writing out the algorithm of our life's conditions forever like this.
In short, we always act and make decisions depending on the situation — that is, on input data. Programming works exactly the same way: you can build conditional actions based on variables and their values.
if statements
For example, I enter a number. If that number is greater than 10, I print the text "YES":
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert number:");
int a = in.nextInt();
if (a > 10) {
System.out.println("YES");
}
System.out.println("Program ended");
}
}
20YES
Program ended5Program endedHow does this code work?
First, we create a whole number int a, whose value we read from the console. Then we set up a condition check using the regular comparison operator >, meaning "greater than".
The keyword if means "if". If a > 10, the program enters the block of code inside the curly braces. If the condition is false, the program skips that block and keeps going.
As you've noticed, checking a condition always produces one of two results: true, or false.
Conditions with multiple checks
You can also combine several comparisons using logical operators. For example, we enter a number, and if that number is between 10 and 20, the condition is true. Logically, a number between 10 and 20 must be less than 20 and, at the same time, greater than 10. If either of those conditions is false, the whole condition fails.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert number:");
int a = in.nextInt();
if (a > 10 && a < 20) {
System.out.println("YES");
}
System.out.println("Program ended");
}
}
As you can see in the example, we use the double ampersand — &&. This symbol means logical "AND".
If I enter 15, it falls between 10 and 20, since 15 is less than 20 and also greater than 10. If I enter 25 instead, the condition "greater than 10" gives true, but "less than 20" gives false, since 25 isn't less than 20. So if I enter 25, I skip the condition's block.
Here is a table of the logical operators and what they do:
| Operator | Description | Example |
|---|---|---|
&& |
Logical AND | 10 > 5 && 20 <= 40 is TRUE |
|| |
Logical OR | 5 == 3 || 30 < 20 is FALSE |
! |
Logical NOT | 5 != 5 is FALSE |
The logical AND operator
Logical AND works on this principle: every condition must be true. Here's a simple everyday example. Say I claim:
"Ilyas, Aibek, Yeldar, and Anel all passed the exam with top marks."
In that sentence, if even one of those people didn't get top marks, my statement becomes false. For my statement to be true, every single one of them has to have passed with top marks. Programming works the same way.
When I use the logical AND operator (&&), every condition has to be true.
The logical OR operator
Now let's look at the logical OR operator. In Java, logical OR is written as ||. It works like this: at least one of the conditions has to be true.
For example, I could say:
"Ilyas, or Aibek, or Yeldar, or Anel passed the exam with top marks."
In this example, if none of them passed with top marks, then I'm lying. In other words, for the statement to be true, at least one of them has to have passed.
In programming, here's an example: we enter a number, and if it equals 10 or 20, the program prints the word "YES".
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert number:");
int a = in.nextInt();
if (a == 10 || a == 20) {
System.out.println("YES");
}
System.out.println("Program ended");
}
}
In this example, if we enter 10 or 20, the expression is true, and the program prints "YES". Now we both know how AND and OR work.
The logical NOT operator
Now let's move on to the next logical operator: NOT. In programming, NOT is written as a simple exclamation mark — !. The NOT operator flips true into false or the other way around:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert number:");
int a = in.nextInt();
if (a != 10) {
System.out.println("YES");
}
System.out.println("Program ended");
}
}
In this example, if we enter any number except 10, the program prints "YES". Here we're simply checking whether the number is not 10.
if-else statements
Now let's look at what to do when a condition is false. That's done with the else keyword.
For example, I'll write a program that checks your age for entry to a club. If your age is 18 or older, the program prints "You can enter", otherwise "Sorry, you can't".
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert your age:");
int age = in.nextInt();
if (age >= 18) {
System.out.println("You can enter");
} else {
System.out.println("Sorry, you can't");
}
}
}
If the condition inside if is true, the first block runs. If it's false, the else block runs.
Running this code with 25 as input prints "You can enter", otherwise "Sorry, you can't". The else block is exactly what gives our program its alternative behavior.
else if statements
Picture this: we enter a number from 1 to 7, representing the days of the week by number. If I enter 1, the program prints "Monday". If 2, "Tuesday", if 3, "Wednesday", and so on up to 7, "Sunday".
But if we enter a number outside that range, say 15, the program should print "Error". That's a trickier task, but it's easy to solve with else if:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert day of the week:");
int day = in.nextInt();
if (day == 1) {
System.out.println("Monday");
} else if (day == 2) {
System.out.println("Tuesday");
} else if (day == 3) {
System.out.println("Wednesday");
} else if (day == 4) {
System.out.println("Thursday");
} else if (day == 5) {
System.out.println("Friday");
} else if (day == 6) {
System.out.println("Saturday");
} else if (day == 7) {
System.out.println("Sunday");
} else {
System.out.println("Error");
}
}
}
Running this code, entering numbers from 1 to 7 prints the matching day of the week. Entering a number outside 1–7 gives "Error".
else if works like this: we run a regular if check, and if that's false, we check again. The final else fires only when none of the earlier conditions matched.
It's a bit like real life: you go to an electronics store to buy a TV. You look through the options until you find the right one. If you don't find one that fits, you go to another store or head back home.
Congratulations — now you know how conditionals work in programming. From here on, you can build programs that behave differently depending on the input they receive.
Bigger by exactly 10
YES, otherwise print NO.20
10YES10
75NO-
Input:
20, 10 -
Input:
10, 75 -
Input:
15, 5 -
Input:
8, 8 -
Input:
50, 30
Sum if different
a and b. If they are not equal, print their sum, otherwise print 0.10
203010
100-
Input:
10, 20 -
Input:
10, 10 -
Input:
5, 15 -
Input:
7, 3 -
Input:
-10, 10
Which school?
Beginners School, grades 5–9 are Middle School, and grades 10–11 are High School.2Beginners School10High School-
Input:
2 -
Input:
10 -
Input:
1 -
Input:
9 -
Input:
11
All three equal?
YES, otherwise print NO.15
15
15YES12
37
20NO-
Input:
15, 15, 15 -
Input:
12, 37, 20 -
Input:
0, 0, 0 -
Input:
5, 5, 6 -
Input:
-3, -3, -3
Positive and even
YES if the entered integer is positive and even, otherwise prints NO.12YES-5NO-
Input:
12 -
Input:
-5 -
Input:
7 -
Input:
0 -
Input:
100
Lesson 3: Loops: while & for
In programming, you very often run into situations where the same action needs to happen several times. For example: printing the same text many times, processing several numbers, going through a list of students, repeating an action for as long as a condition stays true.
Java uses loops for tasks like these. A loop means you don't write the same code over and over — you describe the repetition once.
Why do we need loops?
Picture this: you want to run a process that repeats periodically up to a certain point. For example, printing "Hello BITLAB" 10 times.
Without loops, it would look like this:
public class Main {
public static void main(String[] args) {
System.out.println("Hello BITLAB");
System.out.println("Hello BITLAB");
System.out.println("Hello BITLAB");
System.out.println("Hello BITLAB");
System.out.println("Hello BITLAB");
System.out.println("Hello BITLAB");
System.out.println("Hello BITLAB");
System.out.println("Hello BITLAB");
System.out.println("Hello BITLAB");
System.out.println("Hello BITLAB");
}
}
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLABThis code works, but it's inconvenient. Now imagine we wanted to print that same text 100 times. A bit much, right?
In that case you'd have to write System.out.println("Hello BITLAB"); 100 times. And if we ever wanted to change the text, we'd have to change it in a lot of places.
The core idea behind loops: write the repeating action once, and tell Java how many times, or until when, to repeat it.
With loops, everything changes. The code becomes shorter, clearer, and easier to modify.
The while loop
We can shorten our "print Hello BITLAB 10 times" task like this:
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
System.out.println("Hello BITLAB");
i = i + 1;
}
}
}
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLABThe idea is that a while loop checks a condition just like a regular if.
If the condition is true, the block of code runs. If it's false, the block is skipped. The key difference with while is that after the block runs, it goes right back to checking the condition again.
A while loop reads as: while the condition is true — run this block of code.
So this while loop keeps running for as long as the condition i < 10 stays true.
How while works, step by step
Let's break the loop down. In our example there's a variable i. It's there to count the number of repetitions.
- Create the variable
int i = 0; - Check the condition
i < 10 - If it's true, print "Hello BITLAB"
- Increase i by 1
- Go back to checking the condition again
At each step, the value of i increases:
i = 0 → i = 1 → i = 2 → i = 3 → ... → i = 10
Once i reaches 10, the condition i < 10 becomes false, because 10 is no longer less than 10. The loop then ends.
An important note about while
With a while loop, it's crucial not to forget to update the variable used in the condition.
In our example, that line is:
i = i + 1;
If you remove that line, the value of i stays 0 forever. Then the condition i < 10 is always true, and the program will print "Hello BITLAB" forever.
An infinite loop is a situation where a loop's condition always stays true, and the loop never ends.
So when working with while, always check that something inside the loop will eventually make the condition false.
The for loop
The for loop is one of the most popular and commonly used loops in programming. A for statement controls a loop and keeps running until its controlling boolean expression becomes false.
In a for loop, initialization happens first, then the condition is checked, then the code block runs, and after that comes the iteration step.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Hello BITLAB");
}
}
}
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLABThis code does the same thing as the while example: it prints "Hello BITLAB" 10 times.
But the for loop looks more compact, because the initialization, condition, and step are all written on one line.
The structure of a for loop
The general structure of a for loop looks like this:
for (initialization; condition; iteration) {
// loop body
}
- Initialization — create the starting value, e.g.
int i = 0 - Condition — check whether the loop can continue, e.g.
i < 10 - Iteration — run a step after each repetition, e.g.
i++
In our example:
int i = 0;— we start at 0i < 10;— we keep going while i is less than 10i++— after every step, we increase i by 1
The block of code runs for as long as the condition stays true. First initialization happens, then the condition is checked, then the block runs, and then comes the iteration step.
i++ vs i = i + 1
In the while example, we increased the variable like this:
i = i + 1;
In the for loop, we wrote it shorter:
i++;
These do exactly the same thing: they increase i's value by 1. That's why i++ is so commonly used in loops.
A for loop variable's scope
When you declare a for loop's control variable inside the loop itself, keep in mind its scope is limited to the loop's body only.
For example:
for (int i = 0; i < 10; i++) {
System.out.println("Hello BITLAB");
}
Here, the variable i only exists inside the loop. Outside the loop, that variable stops existing.
If you need to use the control variable elsewhere in the program, you have to declare it beforehand, outside the for loop.
public class Main {
public static void main(String[] args) {
int i;
for (i = 0; i < 10; i++) {
System.out.println("Hello BITLAB");
}
System.out.println("Loop finished");
}
}
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Hello BITLAB
Loop finishedIf a variable is only needed for the loop, declare it inside the for. If it's needed after the loop too, declare it beforehand.
When to use while, and when to use for?
Both loops can solve similar tasks, but they're usually used in different situations.
while is convenient when it's not always clear in advance how many times the action needs to repeat.
for is convenient when the number of repetitions is known ahead of time — for example, printing "Hello BITLAB" 10 times.
Early on, it's usually more convenient to use for when you need to repeat an action a specific number of times. while fits well for tasks where the repetition depends on a condition.
It's recommended to practice now and solve a few exercises to reinforce while and for loops. After this topic, you'll be able to write programs that repeat actions many times without unnecessary copy-pasting.
Count up to n
n and prints all the numbers from 1 to n. Tip: use System.out.print() instead of System.out.println() to print numbers on one line.51 2 3 4 5101 2 3 4 5 6 7 8 9 10-
Input:
5 -
Input:
10 -
Input:
1 -
Input:
7 -
Input:
0
Count from n to m
n and m and prints all the numbers from n to m. Tip: use System.out.print() instead of System.out.println() to print numbers on one line.5 105 6 7 8 9 102 92 3 4 5 6 7 8 9-
Input:
5 10 -
Input:
2 9 -
Input:
1 3 -
Input:
7 7 -
Input:
4 1
Even numbers up to n
n and prints all the EVEN numbers from 0 to n (an even number divides by 2 with no remainder).60 2 4 6100 2 4 6 8 10-
Input:
6 -
Input:
10 -
Input:
0 -
Input:
1 -
Input:
7
Factorial with a for loop
n and prints the factorial of that number, using a for loop.512001-
Input:
5 -
Input:
0 -
Input:
1 -
Input:
3 -
Input:
6
Odd numbers from n to m
n and m and prints all the ODD numbers from n to m.3 113 5 7 9 1110 2311 13 15 17 19 21 23-
Input:
3 11 -
Input:
10 23 -
Input:
1 5 -
Input:
6 6 -
Input:
0 1
Lesson 4: Arrays
In programming, you very often need to store not one value, but several values of the same type at once. For example, at BITLAB ACADEMY we might have a group of students, and each student has an exam score.
If there are few students, you could create several separate variables. But if there are many students, that approach quickly becomes inconvenient. Java uses arrays to solve this kind of problem.
The problem without an array
Let's look at a case where you want to store the exam results for 5 students in a group and print their sum and average. Normally you could create 5 variables of type double in your program and work with them.
public class Main {
public static void main(String[] args) {
double sc1 = 100;
double sc2 = 90;
double sc3 = 95;
double sc4 = 80;
double sc5 = 75;
double total = sc1 + sc2 + sc3 + sc4 + sc5;
double average = total / 5;
System.out.println("Total score : " + total);
System.out.println("Average score : " + average);
}
}
Total score : 440.0
Average score : 88.0As you can see from the example, we created 5 double variables for each student's score, and calculated the sum and the average.
But this is very inefficient, because this kind of approach is static. If someone suddenly tells me I need to add 5 more students, it would be silly to keep creating separate variables for them.
And what if the group has not 5 students, but 100 students? Creating variables sc1, sc2, sc3, and so on by hand would be very inconvenient.
To solve this kind of problem, we need to store the students' scores in a single structure. And that's where arrays come to mind.
What is an array?
An array is a data type, or data structure, in the form of a set of components — that is, array elements — placed one right after another in memory.
Access to individual array elements happens through indexing, meaning a reference to the array along with the number, or index, of the needed element.
In Java, an array is convenient for working with a large amount of same-type data. For example, if all the values are student grades, we can store them in a single array of type double.
In short, if a variable is a one-seat motorcycle, then an array is a bus, where you can fit a bunch of variables — that is, passengers.
Going back to our example, let's imagine we created an array with our students' scores:
double scores[] = {100, 90, 95, 80, 75};
Now all 5 results live not in separate variables, but inside one array called scores.
What does an array look like inside?
Every array element has its own number, called an index. The most important rule: in Java, array indices start at 0.
- scores[0] = 100
- scores[1] = 90
- scores[2] = 95
- scores[3] = 80
- scores[4] = 75
So if the array has 5 elements, the indices aren't from 1 to 5, but from 0 to 4.
The first element of the array is scores[0]. The last element of a 5-element array is scores[4].
If you try to access scores[5], the program will throw an error, because there's no element with that index in the array.
Array illustration
Let's visualize what the scores[] array looks like in the program's memory:
| Index | Value | Element |
|---|---|---|
| 0 | 100 | scores[0] |
| 1 | 90 | scores[1] |
| 2 | 95 | scores[2] |
| 3 | 80 | scores[3] |
| 4 | 75 | scores[4] |
As the illustration shows, the scores array consists of 5 elements. Each element has its own index. The most important thing to remember: array indexing in Java always starts at 0.
This means the first element of the array is scores[0], and the last element in this example is scores[4].
Sum and average using an array
Now let's look at a program where I calculate the array's sum and average:
public class Main {
public static void main(String[] args) {
double scores[] = {100, 90, 95, 80, 75};
double total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
double average = total / scores.length;
System.out.println("Total score : " + total);
System.out.println("Average score : " + average);
}
}
Total score : 440.0
Average score : 88.0Let's break this code down. First, we create an array with 5 elements:
double scores[] = {100, 90, 95, 80, 75};
To access the first element, we write scores[0], since indexing always starts at 0. The second element is scores[1], and so on.
If you want to print the array's last element, write System.out.println(scores[4]);.
How does looping over an array work?
In the example above we use a for loop to go through every element of the array.
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
Following this logic, we build a loop starting at 0 and going up to (but not including) 5. That means our i takes the values 0, 1, 2, 3, 4 on each iteration.
- i = 0 → take scores[0] → 100
- i = 1 → take scores[1] → 90
- i = 2 → take scores[2] → 95
- i = 3 → take scores[3] → 80
- i = 4 → take scores[4] → 75
Notice that to find the array's length, we use the array's length property.
scores.length means the number of elements in the array. In our example, scores.length equals 5.
So we add each element into the total variable, which starts at 0.
The line:
total += scores[i];
means the same thing as:
total = total + scores[i];
And finally, dividing the sum by the number of elements gives us the average.
Advantages of arrays
Using arrays gives you several advantages:
- Code optimization — less repeated code
- Random access to elements via index
- Easy to look through the data
- Easy to manage a large amount of same-type data
- Easy to sort data and perform additional calculations
In our case, the array lets us conveniently store the students' results, loop over them, calculate the sum and the average, and perform other operations when needed.
Declaring an array in advance
Just like any variable, an array can be declared in advance and filled in later:
double scores[] = new double[5];
In this example we create an array scores that can hold 5 values of type double.
You can assign the elements later, by accessing each index:
double scores[] = new double[5];
scores[0] = 100;
scores[1] = 95;
scores[2] = 90;
scores[3] = 80;
scores[4] = 75;
This approach is convenient when you already know the array's size, but want to fill in the actual values later.
Filling an array from the console
You can declare the array's size and enter its elements from the console by hand — that is, type in the size yourself and create an array of that size.
Let's look at the example below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
double scores[] = new double[size];
for (int i = 0; i < scores.length; i++) {
scores[i] = in.nextDouble();
}
double total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
double average = total / size;
System.out.println("Total score : " + total);
System.out.println("Average score : " + average);
}
}
5
100 90 95 80 75Total score : 440.0
Average score : 88.0We create a number size and set its value from the console. Then we declare an array of size size.
Using a loop, we set each value in the array in order, filling it up. And finally, we also calculate the sum and average of all the elements.
This version is already a lot more flexible. Now the program can work not only with 5 students, but with any number of students we type into the console.
Key takeaways
- An array stores several values of the same type.
- Array indices start at 0.
- An array's length is available through
array.length. - A
forloop is the convenient way to go through every element of an array. - An array helps you avoid creating lots of separate variables by hand.
After this topic, you'll be able to store several values of the same type in one variable and process them with a loop.
Positive numbers only
n. Then we enter n numbers and store all the entered numbers in an array. Print only the positive elements at the end.10
6 19 26 -3 46 8 5 -65 90 256 19 26 46 8 5 90 2510
1 2 -3 4 5 -6 7 8 -9 101 2 4 5 7 8 10-
Input:
10, 6 19 26 -3 46 8 5 -65 90 25 -
Input:
10, 1 2 -3 4 5 -6 7 8 -9 10 -
Input:
5, -1 -2 -3 -4 -5 -
Input:
4, 0 5 -5 10 -
Input:
3, 100 -100 50
Even numbers in the array
n. Then we enter n numbers and store all the entered numbers in an array. Print all the even numbers contained in this array.8
3 8 2 4 6 9 12 158 2 4 6 129
6 0 -3 4 8 0 -6 9 56 0 4 8 0 -6-
Input:
8, 3 8 2 4 6 9 12 15 -
Input:
9, 6 0 -3 4 8 0 -6 9 5 -
Input:
5, 1 3 5 7 9 -
Input:
6, -2 -4 -6 1 3 5 -
Input:
1, 0
Squares of the array elements
n. Then we enter n numbers and store all the entered numbers in an array. Print the squares of all the entered numbers at the end.6
1 2 3 4 5 61 4 9 16 25 3610
1 2 3 4 5 6 7 8 9 101 4 9 16 25 36 49 64 81 100-
Input:
6, 1 2 3 4 5 6 -
Input:
10, 1 2 3 4 5 6 7 8 9 10 -
Input:
3, -1 -2 -3 -
Input:
1, 0 -
Input:
4, 10 -10 5 -5
Elements at even indices
n. Create an array of n integers entered on the second line, and use a loop to print all the elements at even indices.8
-4 9 2 -5 8 7 -11 16-4 2 8 -1110
1 2 3 4 5 6 7 8 9 101 3 5 7 9-
Input:
8, -4 9 2 -5 8 7 -11 16 -
Input:
10, 1 2 3 4 5 6 7 8 9 10 -
Input:
1, 5 -
Input:
2, 7 8 -
Input:
5, 10 20 30 40 50
Elements at odd indices
n. Create an array of n integers entered on the second line, and use a loop to print all the elements at odd indices.8
-4 9 2 -5 8 7 -11 169 -5 7 1610
1 2 3 4 5 6 7 8 9 102 4 6 8 10-
Input:
8, -4 9 2 -5 8 7 -11 16 -
Input:
10, 1 2 3 4 5 6 7 8 9 10 -
Input:
1, 5 -
Input:
2, 7 8 -
Input:
5, 10 20 30 40 50