- 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 and Loops
Arrays help keep data organized, and their real power comes through when you are able to write a little code that can go through every element in an array. Instead of repeating code for each element, you just say:
for each element in array
do something
To go through an array in code, you can use an index variable to keep track of your position in the array, and increment it to get through the whole array. The For Loop works particularly well for such purposes:
//create array
int[] array1 = {1, 2, 3, 4, 5, 6, 7, 8 };
//print each element in array
for(int i = 0; i < array1.length; i = i+1){
System.out.println(array1[i]);
}
This would print:
1 2 3 4 5 6 7 8
Similarly, you can setup the initial data in an array with a for loop (Hover over code for more info.):
int[] array2 = new int[8]; for(int i = 0; i < array2.length; i = i+1){ array2[i] = i+1; }
This would create an array like above: {1, 2, 3, 4, 5, 6, 7, 8}
You can now see how a loop can find the largest number in an array:
static int getLargestNumber(int[] numbers){
int largest = 0;
for(int i=0; i < numbers.length; i = i+1){
if(numbers[i] > largest){
largest = numbers[i];
}
}
return largest;
}
The numbers are stored in an array named numbers
. i
is used to go through the array one number at a time and every numbers[i]
is compared with largest
to see which is larger. largest
will be assigned any larger value, so after going through the array, it will have the largest value.
These examples showed how for
loops can be used to setup the data in arrays, to do something to each element in an array and to search through arrays. Now you can try your own for
loops to solve the following challenge.
Challenge
You will be given an array of numbers ar
. Print each number in the array in the order it appears, unless the number is a multiple of 3. If a number is a multiple of 3, print no3
instead.
(Make sure to print everything in a given array on the same line.)
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
niveoserenity
Sep 29, 2:48 PMHint: System.out.print(...); prints the numbers on the same line.
Hint 2: remember to print the empty char for both if and else :)
Jason Nicoll
Jan 7, 3:57 PMwhy am i getting errors in the boilerplate code :\
Jason Nicoll
Jan 7, 4:04 PMforgot the curly brackets haha :P
David
Jan 10, 6:20 AMif(numbers[i] > largest){
largest = numbers[i];
}
Shouldn't be numbers[i] < largest ?
David
Jan 10, 7:13 AMHow to print on one line everything, I am having issues with that.
David
Jan 10, 7:18 AMEhh, just use System.out.print(); instead of System.out.println(""); You didn't mention it earlier :(
Andreas
Jan 21, 8:01 AM//What´s wrong with my Code??
//PLZ help I don´t get any further...
//blessed
import java.util.*;
class Main{
static void doStuff(int[] ar){
for(int i=0; i<=ar.length;i++){
}
Learneroo
Jan 21, 9:28 AM@Andreas, we will be running a membership option for people to get help with their errors. Meanwhile, here's some tips: You don't need to create a new array, just print the items in the given array. To print "no3", just type
System.out.print("no3");
Bill
Apr 13, 11:31 AMHow should I do?
when i run this code, the compiler return the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
How should i do? please help me.
import java.util.*;
public class Main{
static void doStuff(int[] ar){
//your code here
for(int j = 0; j <= ar.length; j++){
if(j % 3 != 0){
String[] ar2 = new String[j];
System.out.print(ar2[j]);
}
else{
System.out.print("no3");
}
}
}
}
Jordan
Apr 29, 9:54 AMSomeone please post the answer so I can see what I am doing wrong. :/
Learneroo
Apr 29, 10:17 AM@jordan, I would suggest starting by printing the array, and then move on to modifying it for multiples of 3. The code at the top of the page shows how to print an array, though you'll want
print
instead ofprintln
.許友誠
May 5, 11:13 AMpackage Testpac;
import java.util.Scanner;
public class Maon_Test
{
}
Michał Targiel
May 28, 2:05 PMCORRECT:
for(int i = 0; i < ar.length; i = i+1)
{
}
Prashant
Jul 10, 11:31 AMDoes anyone have any idea what boilerplate code means?
Learneroo
Jul 10, 5:14 PM@Prashant, in these challenges, it's just standard code that is included to process the input for you. I.e. it sets up the variables or arrays and passes them to the method
doStuff()
.flowra
Feb 13, 5:37 PManother simple solution using for each :
for (int element : ar)
{
if (element%3 == 0) System.out.print("no3 ");
else System.out.print(element+" ");
}
Miro
Jul 7, 4:06 AMI'm just wondering whether or not you have a guide for using streams?
Learneroo
Jul 7, 6:36 PMSorry these tutorials are focused on the basics of Java for beginners, so we don't cover that.