- Introduction
- Super Simple Formula
- Your First Program
- Variables, Methods and Parameters
- Variables in Programming and Algebra
-
Math and Comparison Operators - If Statement
- While and For Loops
- Loopy Thinking
-
Data Types - Booleans
- Logical Operators (and Booleans)
- Output and Printing
- Printing and Loops
-
Arrays - Arrays and Loops
- Array Loop Practice
-
What's Next? - Quick Reference
Quick Reference
Quickly lookup Java basics, and load code examples directly into editor.
int
), the method name (doStuff
), and the method's parameters (such as a
and b
). The method body follows, where you usually need to write code that returns a value at the end.
//method header: methodName(parameters)
static int doStuff(int a, int b){
//your code here - erase this comment and write your code!
return 1;
}
Syntax note: Every line of code in Java needs to end with a
;
or it will be considered part of the next line. Comments are marked with 2 backslashes //
and are ignored by the computer.%
operator returns the remainder after division.
int product = 4 * (1+2) / 2; //6.
int roughDivision = 8 / 3; //2
int remainder = 3 % 2; //1, the remainder of 3/2
booleans are used to store true/false values, such as the results of comparisons:
boolean check = false; //this will store result of comparison
int five = 5;
//the following are all true
check = (five == 5); //equals
check = (five != 3); //not equals
check = (five >= 5); //greater or equals
The logical operator AND &&
will return true if multiple conditions are all true, and OR ||
will return true if at least one condition is true.
//these pointless statements will both set check to true
check = (3>2 && 2>1); //AND
check = (3>2 || 1>3); //OR
if(condition){
//doSomething
}
The else statement will execute code if the condition was false. The while statement will repeatedly execute the same code while a condition is true.
public static void controlFlow(int number) {
//this if/else block will print out 1 statement for any number
if(number > 10){
System.out.println("big number");
}
else if(number > 5){
System.out.println("medium number");
}
else{
System.out.println("small number");
}
//this loop will print the numbers from 0 to 9
int i = 0;
while(i < 10){
System.out.println(i);
i = i + 1;
}
}
System.out.println("");
The above prints text and add a newline afterwards.
System.out.print
prints without a newline, but you can add in spaces " " to separate text.
System.out.println("hello"); //prints with newline
String word1 = "hello";
String word2 = "world";
System.out.print(word1 + " " + word2); //prints "hello world"
Arrays are used to store multiple items of one data type together. They are declared with the type they will hold and with brackets []
. This code creates an empty 5-cell array:
int[] ar1 = new int[5];
This shortcut creates an array with numbers 0 to 4:
int[] nums = {0,1,2,3,4};
You can use for-loop to print values of array:
for(int i=0; i < nums.length; i=i+1){
System.out.print(nums[i]+" ");
}
Arrays
Strings let you hold characters together into words and do things with them, but what if you want to keep a collection other data? For example, let's say you have a list of numbers, such as scores from a Skeeball tournament. It wouldn't make sense to create a new variable for each number, it would be simpler to keep all the numbers in one structure. Java provides various structures for storing collections of elements, but the simplest one is an array.
An array is a structure of a fixed length for storing items of one type together. It's like a shelf for storing related items. Instead of accessing a specific piece of data by calling its variable (or "container"), you can instead specify its location in the array (or "shelf").
In Java (and other languages), the first item in an array is located at position 0. You can think of the array as a number line, with the first item located in the 0th slot.
Arrays in Java use a special [brackets] syntax. To declare an array variable, you need to state the data type the array will hold, brackets to show that it's an array, and the array name:
int[] nums;
To create the actual array, you need to use the new
keyword, state the type (again), and specify the length of the array:
nums = new int[8];
This will create an empty array that can hold up to 8 integers in index positions from 0-7.
You could have also combined the above steps into one line:
int[] nums = new int[8];
To put items in an array, you specify the position in the array with brackets and assign it to a value:
nums[0] = 7;
nums[3] = 3;
This will put a 7
in the 0th spot and a 3
in the 3-index spot:
To get an element from an array, you can reverse that process:
int num = nums[0];
This will access the 0th position and set num
to 7
.
When you create an 'empty' integer array, Java sets all the values in it to 0. To quickly create an array with specific values, you can use the following 'curly-braces' shortcut:
int[] numbers = {0, 1, 2, 3, 14, 15, 16, 17};
Let's say you're given the array numbers
but you don't know how long it is. You need to access the property of an array called length
. We'll cover Objects and their properties later, but for now, just remember this syntax: arrayName.length
For example, this code would assign the length of numbers
to a variable length
:
int length = numbers.length;
length
will be 8, since that's the number of cells in numbers
. The last cell in the array is at position numbers.length -1
, since arrays are 0-indexed:
int last = numbers[numbers.length-1];
This will access the last (or 7th) spot, and set last
to 17.
Other Array Examples
The above arrays just stored integers, but you can store other data types in Arrays also. For example, this code will create an array for Strings:
String[] words = new String[10];
words[0] = "jim";
String name = words[0]; //name is now "jim"
You can even create an array of arrays, or a 2D array:
int[][] board = new int[8][8];
This 2D array could be used to store things like game boards.
Summary
Review this example code to make sure you get how arrays work:
Task | Code | Result | Explanation |
---|---|---|---|
Declare and create an array | int[] ar = new int[5]; |
{0,0,0,0,0} | Creates an array with default 0 values |
Create an array with specific values | int[] ar2 = {5,4,3,2,1}; |
{5,4,3,2,1} | Use Curly braces to create filled-in array |
Set the value in an array | ar[0] = 3; |
{3,0,0,0,0} | Sets the 0th cell to 3 |
Get the value from an array | int num = ar2[4]; |
1 | Sets num to the value of cell 4 in ar2 |
Bonus: get and set the value in an array | ar[0] = ar2[4]; |
{1,0,0,0,0} | Sets cell 0 of ar to the value of cell 4 of ar2 |
More Practice
After solving the challenge below, get some more practice with these challenges:
Challenge
You will be given an array of numbers ar
. Create and return another array of length 2 that just contains the first and last number in the original array.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Challenge
In one line of code, declare and initialize an empty array of booleans named array
with a length of 6.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Challenge
We need to get the second-to-last number in an array. In one line of code, declare an int
variable n
and set its value to equal the second-to-last number in the array numbers
.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
niveoserenity
Sep 29, 1:42 PMI got the answer in the end, but my first attempt was:
int CC = ar[ar.length-1];
int VV = ar[0];
return CC + VV;
Brandon Hall
Dec 24, 7:15 AMint[] fl = new int[2];
fl[0] = ar[0];
fl[1] = ar[ar.length - 1];
return fl;
Robin Elliott
Feb 3, 4:06 PMThanks for the site I am really learning from it.
One thing I'd like to be able to do is practice typing things out as I'm following along with your explanations. I think it would help reinforce
the information. Could you add blank text entry fields (not compilers) here and there in the lesson to give the user scratch space?
Learneroo
Feb 3, 4:14 PM@Robin, if you just want to take notes I think it would make sense to do in your own note-taking program, though we can consider adding such a feature. Note that if you click on "split-screen
view", you can view the code editor and content side-by-side, which may work for your purpose. And if you decide you want to run different code snippets, you can try the visual debugger (launched yesterday).
David
Feb 26, 4:23 PMJust a funny quote here... On the challenge Second-to-Last i scratched my head for two days trying to think how to declare the variable in a single sentence the reason was because i was understanding: from the second (meaning starting at index 1) to the last, rather than actually thinking about penultimate! Frustrated not being able to declare the variable i decided that i was not understanding the exercise, clear enough google explained me second-to-last=penultimate... OMG LOL
Pura vida.
-David
Shadov
Mar 23, 2:09 AMWhat does "Second to last" mean?
Shadov
Mar 23, 2:16 AMHOLY MOLY. 2D ARRAYS MADE MY SUDOKU SOLVER EASIER!
Shadov
Mar 23, 2:20 AMAnd here is the answer for the challenge:
int [] ars = {ar [0], ar [ar.length -1]};
return ars;
kevintaw
Jun 10, 11:38 AMthese are very good
Gaetano
Oct 24, 8:31 PMIf you get a number from an array, and do not know what slot its in. Is there a code to retrieve the slot?
Example;
I found the largest number in the array and want to know what slot that is in.
Bernard Mitchell
May 26, 9:34 PMI don't understand why my challenges are wrong:
1. int n = numbers[6];
2. boolean [] frank= new boolean [6];
thales
Jul 7, 2:38 PMI had the write awnser but it still does not work, what is wrong in this:
int[] ar2 = new int[2];
ar2[0] = ar[0];
ar2[1] = ar[ar.lenght - 1];
return ar2;
thales
Jul 7, 2:40 PMsorry i solved it lenght mus be length pfffffffffffff :-)
Mauricio Andrian
Aug 14, 8:56 AMIs the free memebership limit forever? Doesn't it restore after certain time?
Learneroo
Aug 14, 3:45 PMIt doesn't currently restore since it's considered a free trial.
Gary
Feb 19, 12:11 PMOr declare regular variables:
int a = ar[0];
int b = ar[ar.length -1];
int[] az = {a,b};
return az;
Ghadeer Alali
Jun 25, 7:15 AMSecond-to-last means, the second element in the array starting counting from the last index.
rajni dound
Nov 18, 5:13 PMimport java.util.Scanner;
public class Main(){
public static void main(String[] args){
int n;
int[] numbers= new int[8];
int[] numbers={2,3,4,5,6,7,8,9};
for(int i=0;i<8;i=i+1){
System.out.print(numbers[i]);
if(i==6){
n=numbers[i]
System.out.print(n);
}
}
}
}
Spiro
May 9, 5:57 AMDo it easy guys ...
int[] res = {ar[0], ar[ar.length -1]};
return res;