- 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]+" ");
}
While and For Loops
As mentioned in How Computers Calculate, computers ultimately just do a few very simple operations. They have so much power because they can do the same operation any number of times. A programmer can get a computer to do repeated tasks by using loops.
While Loop
The While Loop is the only loop you really need, the other loops just make things more convenient. A while loop will repeatedly execute a block of code while a condition is true. The syntax is like an If-Statement, but with a while
instead of an if
:
while(condition){
//then do stuff
}
For example, you might want to run a game as long as a player still has lives:
while(lives > 0){
runGame();
}
Let's say you wanted to doSomething
10 times. You could use a While Loop to keep track:
int index = 1;
while(index <= 10){
doSomething();
index = index + 1;
}
The above loop will increase index
and call doSomething()
10 times, but then stop once index
is greater than 10.
The algorithm to get the largest number in a list (seen in Ways to show Algorithm) can also be coded with a while loop:
int getLargestNumber(int[] numbers){
int largest = 0;
int index = 0;
int number;
int length = numbers.length;
while(index < length){
number = numbers[index];
if(number > largest){
largest = number;
}
index = index + 1;
}
return largest;
}
You don't need to understand every detail of this code, but notice how the while loop uses an index
to go through a list of numbers. At the end of each loop index
is increased by 1, so once it has gone through all the numbers index
will equal length
and the loop will stop.
For Loop
Many while loops involve setting up a variable and updating its value until a certain condition is reached, when the loop will terminate. Such loops can be replaced with For Loops, which is more compact and helps prevent eternal looping errors. It does this by combining the index, condition and updater in the header of the loop.
This is the general form of the for
loop:
for(initial setup; condition; update after each loop iteration){
//do stuff
}
The for
loop header consists of 3 parts:
- setup - it usually declares and assigns a variable here (to use as an index).
- condition - the for loop will continue looping until this condition is false.
- update - usually, this is where the index variable is incremented.
For example, let's say you wanted to improve the above while loop to doSomething
10 times. Its used an index variable that it incremented each loop until it reached a certain value, so it could be replaced with a for
loop:
doSomething();
}
(hover above for more info)
This will call the method doSomething 10 times.
The while loop to find the Largest Number can be shortened by using a for loop instead:
static int getLargestNumber(int[] numbers){
int largest = 0;
int number;
int length = numbers.length;
for(int index=0; index<length; index=index+1){
number = numbers[index];
if(number > largest){
largest = number;
}
}
return largest;
}
It is the same as the previous code, except the lines to set up and increment the index have been combined into the for
loop header:
for(int index=0; index < length; index=index+1){
...
}
Note that the action in the for
loop can increase or decrease the index by any amount. Although you never need a for
loop, you should use it instead of a while
loop when possible, since it helps avoid errors.
Challenge
When the following loop terminates, what will num
equal?
int num = 0;
while(num < 10){ // loop condition
num = num + 3; //loop body
}
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Challenge
You will be given two numbers a
and b
. Print out every number from a
to b
(inclusive). a
will always be less than b
.
Since we haven't covered printing yet, you can use the included printNum()
method to print a number. Just pass it whatever number or variable you want to print. For example,this code will print 5:
printNum(5);
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
john marino
Nov 27, 2:44 PMthis is crazy hard to me..
Jason Nicoll
Jan 2, 11:59 AMhow do i remove the cheat mark my submission was the exact answer :/
Learneroo
Jan 2, 12:03 PM@Jason, sorry there's no way (currently) to remove the cheat once the cheat button has been clicked.
Valdow Valdowb
Jan 4, 6:44 AMyes this course is very good idea but is should be motivated by java tutorials like beginner ,intermediate,advanced
Jason Nicoll
Jan 4, 5:41 PMhey im sorry but im still stuck in this on challenge everything looks perfect but i'm still getting errors please help..
Learneroo
Jan 4, 6:08 PM@Jason, you want to increase the iterator each time. For example, to print the numbers from 1 through 10, you could create a loop like this:
You need to do that to go from a to b instead.
Shadov
Mar 22, 12:47 PMI love the random quotes ♥
Robert
May 12, 4:28 PMwhy is mine not working!!!
Learneroo
May 12, 4:32 PM@Robert, make sure to declare any variable you use, even if it's just used as a loop index.
Adhurim Esati
Jul 2, 3:58 PMI do understand the While Loop and the example about wanting to repeat something 10 times, but I have a question ( quite stupid really but I just wanna make sure even though I know what is correct xD )
So If we have
{ int index = 1;
while(index <= 10){
doSmth();
index = index + 1
}
}
so now after executing this program the index will at sometime be 2 3 4 5 6 7 8 9 and in the end 10.
Does this mean that after every time the code is executed the { int index = 1 } changes to 2 3 4 5 6 7 8 9 or 10 from the "index = index + 1" ?
I know it does but does that appear in the "int index = ?"
Kun Kaewken
Nov 12, 1:16 AM@Adhurim, "int index=1" is outside the while loop, so it is executed only 1 time.
Somil
Dec 18, 12:14 AMI really was tempted to click the hint for this one but I sat there and thought about the ways to make it work. I still have trouble with the for loop but by just setting int i = a would have been so simple. Oh well I'm glad I got it to work with the while loop but I should avoid it because of the possibility of errors.
my code
flowra
Feb 12, 6:28 PMI did that and although it is correct but I should think of simpler way as the model answer :D :
public static void doStuff(int a, int b){
int tmp = a;
for (int i = 0 ; i< b-a+1;i++)
{
zack
Mar 30, 3:16 PMmy code
Bernard Mitchell
May 16, 6:44 PMYeah this one is tough. There should be an explanation of how to include multiple indexes in the first part of the for condition. Do you just use the & and also there is no explanation on how to printout inclusive information i.e. 1-5
Bernard Mitchell
May 17, 7:20 PMAre we supposed to solve with the while loop or the "for" loop?
Abhinav Ramana
Jun 22, 1:31 AMit says error:for(int i=a;i<=b;i+1){
not a statement ^
Abhinav Ramana
Jun 22, 1:32 AMit says error:for(int i=a;i<=b;i+1){
not a statement ^
Diana Pereira
Jul 1, 10:28 AMyou have to put: i = i+1; or you can do an abreviation, like i++;
Mita Ramabulana
Jul 23, 9:16 AMThis is a great course. I am more comfortable with Java now, and it has only been 30 minutes.
xatructhao123
Jul 30, 4:10 AMBrant K
Sep 2, 5:21 PMHere's the easiest solution:
for (a=a, b=b; a <= b; a++){
printNum(a);
}
TBC1
Sep 12, 6:34 PMyeah i have the same thing but different variables ( i used n) and it's not working.
Riy
Nov 12, 4:59 AMwhile (a <= b) {
printNum(a++);
}
Asadujjaman Shimul
Dec 2, 2:33 AMimport java.util.Scanner;
public class Main {
public static void main(String[] args){
}
carla
Apr 22, 3:19 PMfor the for loop challenge:
for (int i=a; i<=b;i++) {
printNum (i);
}
this basically assigns i as being a for the first time since a is less than b; the condition is to display including
b, so i must be less or equal than b and then increment it. the body of the for loop prints i by calling the printNum method.
chima oscar
Aug 10, 11:55 AMfor (int i = a; i <= b; i++){
System.out.println(i);
}
EleiteRanger
Oct 19, 3:34 PMjust replace all the code with:
import java.util.Scanner;
public class Main {
long x= a;
while(x<b+1){
System.out.print(x+" ");
x = x + 1;
}
}
A.J.
Apr 18, 9:01 AMCan I use While loop for the problem code above?
Mike Grote
Mar 15, 11:09 AMThe only issue I had was thinking that he wanted actual numbers, then I realized that this is a module that gets called rather than core code. Oops.
Alexis Coker
May 17, 10:13 AMi did the right code but the part that was already done further in the code was wrong. help me?
public static void printNum(int x){
system.out.print (x+"");
}
it says illegal start of expression.
Learneroo
May 17, 9:59 PMI think you need to be careful not to add extra curly braces or remove existing ones.
Alexis Coker
May 19, 3:28 AMi did. i even reset the page and re wrote the code
Ian
Oct 4, 6:19 PMi am confusion
The Outsider
Jul 11, 4:17 PMI like this site :DD
yazan
Dec 24, 10:36 AMhuthtiuhithruhriurutrrihrwuerwuuherwhuewuhrwwwhutwhuwtwthuwuhwwetuewhewherihuerwihuweiuhwetuhiuhweiuhweuheuhweuhweuweiuuhiguwuuwgewuewgugewuwgueugwuhewuhwfuhuewuwguhhuueguwuhgwgwuegueghuegwupoohuguhgrughurwuhghuruhrwurhwhrhowhguhwoprugruowhwiphrwuogugrwurhrguwgwghughurwhuuorwhuhuwhgurgwugugrwuuwuphrwpuruhuwrhugrhgwhugrghughgurh7guhe7rguyher7h7uteiyhtyeu5yitgyhrueyhuheuighiuerhgiurhu