- 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]+" ");
}
Loopy Thinking
Optional NodeA lot of programming involves using loops, so you need to be able to think about them clearly. When looking at loops, you should try to follow the loop on your own (step-by-step) to see what's happening. You want to specifically look at the values of your variables at these times:
- before the loop begins
- after each iteration of the loop
- when the loop terminates
It often helps to go through an example on your own and see how code will handle it.
Question
For example, let's say you want to add up all the numbers from 1 through n
(without any formulas). How would you do it?
Think about your solution before reading on.
Answer
Starting with 1, you could manually add each number to the total sum until you reach the nth number. In code, you would create a loop that goes through all the numbers from 1 to n
adding them to a sum
variable. To make sure this works, let's examine each stage of the loop:
- Before the loop begins
Create a variablesum
and set it to 0. This is the sum of 0 elements in the array, so everything is set up correctly. - Each iteration of the loop
Go through each element in the loop one at a time, and add its value tosum
. After each iteration through the loop,sum
will hold the value of all the number up to that point. - Loop termination
n
is the last number you add tosum
, sosum
now equals the sum of all the numbers from 1 throughn
.
Here's the Java code for this loop:
static int doStuff(int a){
int sum = 0;
for(int i=1; i<=a; i=i+1){
sum = sum + i;
}
return sum;
}
Challenge
The factorial of a number a
is the product of all the positive integers less than or equal to a
, i.e. all the integers from 1 through a
. For example, the factorial of 4 is 24 (1*2*3*4 = 24). Can you calculate the factorial of a given number?
In each case, you are given one positive integer a
as input. Find the factorial of a
by multiplying all the numbers from 1 to a
together, and then return the total product. For example, when given a
as 4, return 24.
(The factorial is used to get the number of permutations of a
items.)
Guidelines for your Loop
Before the loop begins - Create a variable product
to store the product of the numbers as you go through the loop. What should you set its initial value to?
Think of the answer, then click below.
product
should be set to 1 initially, so it can be multiplied by other numbers without changing their value. (We know that the value of a
will be at least 1.)
Each iteration of the loop - Make sure that product
now equals the product of all the numbers up to the current one.
Loop termination - Terminate when you reach the end, as in the previous loop.
OK Now, go ahead and code the solution!
Note: To get more practice with loops, see the Math With Loops tutorial.
Challenge
You are given a number a
. As explained above, return the factorial of a
(the product of all the integers from 1 through a
).
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
Mitchell
Mar 20, 9:30 PMno comments? has no one finished this yet? its not that difficult...
Learneroo
Mar 22, 10:43 PM@Mitchell, many people have solved it, just not many commented here. We don't want users to paste solutions or long code samples here, but you can link to your most recent submission instead by clicking on "Load Link" below the comment form.
paresh
Apr 21, 2:03 PMmy code
Bernard Mitchell
May 22, 12:25 PMWill the answer that was given run forever since the condition is less than or equal to a.?
shobdy
Jun 21, 7:16 PMBernard, it will stop when 'i' in the for statement increments up to the same number as the 'a'.
xatructhao123
Jul 30, 4:29 AMint kq=1;
for(int i=a;i>0;i=i-1){
kq=kq*i;
}
return kq;
Phoenix
Aug 4, 12:17 PMYou can solve this with recursion.
public static int doStuff(int a){
if (a==0 || a==1) return 1;
return doStuff(a-1)*a;
}
Mauricio Andrian
Aug 13, 8:19 AMI just gave 2 as the initial value of the variable i so I think my code will just jump the first useless iteration: 1*1.
my code
Asadujjaman Shimul
Dec 2, 5:47 AMimport java.util.Scanner;
public class Factorial {
public static void main(String[] args){
}
Franky Yeung
Dec 15, 9:13 AMint b = a;
while(a!=1)
{
b = b*(a-1);
a -= 1;
}
return b;
EleiteRanger
Nov 16, 3:29 PMwhy don't we get infinate free lessions!?!?!?this is the only good site i have found )=
)=
)=
Learneroo
Nov 16, 8:22 PMHere's a coupon that gives you membership for $2 for the first month: LEARNCODING99
Enter it at learneroo.com/get-membership before checking out.
(Membership goes to regular rate afterwards, but you can cancel if you're no longer interested.)