- 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]+" ");
}
Variables, Methods and Parameters
Variables
A variable in programming is like a container which holds a value:
There are different types of containers for different types of objects. For example, you can have a container which holds an integer (like 6), or another container which holds a String of text (like "hello").
In Java, you need to declare all your variables before using them. That means you simply state its type and name:
int num;
In this case you declared a variable called num
, which can hold an int
or integer.
Once its been declared, you can assign it to a value:
num = 5;
You can also combine these steps:
int num = 5;
You can change the value of a variable at any point:
num = 72;
num
is now 72 instead of 5.
But in Java it cannot be set to the wrong type:
num = "word"; //error!
Since num
was declared as an int
, you cannot assign it the String "word".
Methods
In the previous challenge (and future ones), you coded a solution within a piece of code known as a method:
public static int doStuff(int a, int b){
//your code here - you could then type:
return a + b;
}
A method is a block of code that can be called by other code. In this example, the code at the bottom (that we said you could ignore), calls the method doStuff
and it does stuff. By putting pieces of your code into method blocks, you can keep things organized, and you can call the same code multiple times from different parts of your program.
Note that you will usually want to name your methods with a more descriptive name than "do stuff".
In many cases, methods can be used like parts of a logical flowchart seen in Algorithm ways.
Parameters
Look at the top of that method again:
doStuff(int a, int b){
The method takes in two variables, a
and b
. Variables that are taken in by a method are called parameters. They are declared in the opening parentheses of a method and are assigned a value whenever the method is called. If the method is called again, they are assigned new values.
So other code can pass two numbers to doStuff
to do stuff with. In this example, it will add two numbers, so:
doStuff(1, 3)
// will return 4
doStuff(-1, 11
) // will return 10
doStuff("hello", "world")
//will cause an error! This is because, the method declares a
and b
as integers so they cannot receive Strings!
In the challenges on this site, the code on the bottom of each challenge passes in numbers to the method doStuff
(which get assigned to the parameters a
and b
). You need to fill in doStuff
so it "does something" with a
and b
and returns the correct answer to the code that called it.
Challenge
As in the previous challenge, you will be given the method doStuff
which takes in two parameters a
and b
. (You should replace //your code here
with your own code.) For this challenge, you are to return the average of the two numbers, rounded down to the nearest integer.
Guideline: Create a new variable to store the sum of a
and b
. To get the average of the two numbers, simply divide that sum by 2 with /
, and return that result. /
will automatically round the answer down.
Challenge
Return the Average of any two integers, rounded down.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Challenge
Declare an integer variable age
and assign it a value of 22
in one line of code.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
Tinnika Tulloch
Feb 5, 4:24 AMThis one was a doozy for me. I tried to change the variable name(doStuff) and create new values within the name variable I created. Anyways I must have written 3 or 4 lines, just to find out I only needed to simple lines :( .
Rony Lussari
Mar 12, 2:01 PMI love this site. Thank you very much!
Vishwa Katulanda
Apr 1, 6:11 AMBrilliant way to teach! I have been searching through out the whole web for a sophisticated JAVA learn by doing site! Really glad to say that I have fortunate enough to experience learneroo.com! :)
Yuta
Apr 24, 6:00 AMI don't solve the problem...
Would someone help me?
import java.util.Scanner;
public class Main {
a =10;
b =20;
int sum=a+b;
return(sum)/2;
a= 14;
b = -14;
int sum=a+b;
return(sum)/2;
}
}
Shanna
May 5, 5:17 PMAwesome!
Kasian Van Heningen
May 19, 2:48 PMWow Simple
Jig
Jun 5, 4:16 AMExcellent site, I have tried codebat, codeacdemy, udemy, tutorialpoint, learnjavaonline.org, http://docs.oracle.com/javase/tutorial/ but this is the best so far
int mySum = a + b; //creates variable to hold sum of a = b
return mySum/2; //return average
Maliha
Jul 14, 2:53 AMThe quotes are definitely motivating :)
Mita Ramabulana
Jul 23, 8:12 AMIt is taking a very long time to show the results and it is really annoying.
ShadowCube
Aug 9, 4:48 AMI was more confused about the value of int a and int b then anything i couldn't work out how it had come to the results if no number have been declared. so i was trying to declare it the whole time which failed me.
ajay agabus
Aug 11, 1:18 AMi think this code will be efficient if we generalize both the numerator and denominator with a variable(s) and give a condition where denominator is >0
Richard Rosa
Aug 23, 5:37 AMIts not as complicated as it first seems. Just remember how the order of operations works when you write the code.
Mezbaur Rahman
Sep 5, 10:50 AMHi @Yuta, the code is simple
int sum = a + b;
return sum / 2;
you are putting variable sum inside parenthesis which is wrong.
Dion Matthew Levy
Sep 30, 12:33 AMahh specifying parameters is what got me as well Mezbaur
Rynofitium
Nov 27, 9:23 AMThe simplest 1line code:
return (a + b)/2;
EleiteRanger
Apr 20, 3:47 PMthe simplest answer is to put return a/2+b/2 for you idiots who can't figure it out for yourselves
givemorejasi
Jun 4, 10:06 AMHave tried several times but getting "Compilation failed" Where do I go to check the correct coding?
chima oscar
Jul 26, 8:06 AMlol..seriously? made several lines and giving values to int a and b. This is fun
Cabdi Casiis Cabdulaahi
Sep 19, 11:20 PMcan i use public static void main (string []args) instead of public static int doStuff
Learneroo
Sep 20, 6:17 PMIf you look at the code on the bottom you'll see that main method there, which calls the method doStuff. (See static and main methods for more info.)
EleiteRanger
Sep 21, 3:39 PMjust put return a/2+b/2 where it says your code here
yuta
Hamid Raza khan
Dec 4, 9:32 AMoh That was so easy.
Hamid Raza khan
Dec 4, 9:33 AMSathya
Jan 7, 2:32 AMIt takes more time to run the code
Nikan
May 14, 7:30 PMreturn (a+b)/2;
Is a better answer then storing it on a variable first
elakkiya
May 22, 3:10 AMthis site is very useful to me to learn javacoding..
chinna
Jul 24, 2:16 AMThere is no value of A & B then how it's working. tell me any one
Kiran Prasad
Mar 1, 9:32 AMwhat is use of public and static
Mark Herbert
Sep 3, 1:14 PMthis one is hard for me
actually have no idea what to do
Mark Herbert
Sep 3, 1:23 PMi had to cheat
AhrM
Oct 4, 11:53 PMjust return(a+b)/2;
the average is the sum of variables / the # of variables.