- 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]+" ");
}
Data Types
Basic Types
As mentioned in a previous node, when you declare a variable in Java, you need to also state what type it is, i.e. what kind of data it can hold. There are 8 primitive data types in Java, but these are the main 4:
type | definition | example operation //result |
---|---|---|
int |
This holds integers with values from about -2 billion to +2 billion. This is what we've been dealing with until now. | int sum = 999 + 1; //1000 |
double |
This holds decimal numbers (real numbers) with a wide range, like -2.1 or 123.456789 . |
double sum = 1+0.23 //1.23 |
- boolean |
This can only hold two values: true or false . |
boolean greater = (7 > 10) //false |
char |
This holds single characters, like 'c' or 'ß' or '1' in character form. To create a character you need to use single quotes. |
char letter = 'z'; |
String
In addition, there's the important String
type, which is a little different than the above types, but is also built-into the language. A String
holds any number of characters together, so it is used to store any text, like words and sentences. You can create a String by using double-quotes: String str ="hello";
. Note that it is written as String (with a capital "S") unlike the simple types above. This is some sample code with String:
String name = "Jim";
Simply store the string"Jim"
in the variablename
.String num = 23;
ERROR! You cannot store a number in a String!String num = "23"
...But you can store a String representation of a number.
In addition, you can concatenate characters with Strings or String with each other to make larger Strings.* For example:
String alpha = "ab" + 'c';
combines the character with a String to make a larger String,"abc"
.- String sentence =
"Pack " + "my " + "box."
; will setsentence
to"Pack my box."
You can even concatenate numbers with Strings, and they will automatically be turned into Strings:
int n = 5;
String message = "Pick a number from 1 to " + n;
//message is now: "Pick a number from 1 to 5"
Soon you'll see how to print Strings. Meanwhile, see if you can handle different types in the following problem:
Challenge
You will be given an int a
and a double b
as input. You need to calculate their sum and then return a String message which says:
"The sum is [sum here]"
(Place the correct sum in the string instead of the brackets.)
* However, don't use + to combine characters together with each other, since they'll 'turn into' numbers. This will be covered in a later node.
Challenge
Return an exact sentence with the sum, as specified.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
William Kennedy
Oct 12, 8:35 AMIt doesn't seem to compile my answer but it runs on Eclipse just fine.
Here is my code
public class DataTypes {
}
Learneroo
Oct 13, 4:14 PM@William the only class that can be public is Main. So either remove 'public' or rename the class to 'Main'.
Honzis
Dec 7, 12:26 PMFirst getting an error while compiling about return statement missing, wheb added about incompatible types - required String, found double
Here the code:
public static String doStuff(int a, double b){
double sum = a+b;
return sum;
String message = "The sum is "+ sum;
}
Hint and cheat missing, what's wrong in my code? Thx
Learneroo
Dec 7, 10:24 PM@Honzis, you need to return a String that contains the correct message. So remove
return sum
and returnmessage
instead.Honzis
Dec 8, 4:49 AMThanks for the quick answer, got it now. :)
pat
May 19, 9:43 AMWhat is the code to solve this
Learneroo
May 21, 9:41 AM@pat, I added an explanation, which you can 'cheat' to view.
Cameron Bee
Mar 12, 5:21 PMDon't system.out.print, return.
sanka
Jun 12, 6:37 AM@William, in this question You should implement code in doStuff() method and return the message. my code
sanka
Jun 12, 6:39 AM@Honzis , You should return only a string type in doStuff() method. because return type of doStuff method is string, check my code :) my code
Alexander
Aug 20, 11:38 AMOr you could cast a double on the sum my code
Tatyana Royer
Oct 7, 2:50 PMJust FYI, I had originally put my string as "The sum is: " + sum. It said it was incorrect because I put the : in. So, even though it ran fine, gave the correct answer, etc., it showed incorrect
due to that. Just for any others who may have missed it for something that tiny and couldn't figure out why what they were doing was wrong.
Asadujjaman Shimul
Dec 3, 1:44 AMimport java.util.Scanner;
public class DataTypes
{
public static void main(String[] args)
{
int a;
double b;
Scanner input = new Scanner(System.in);
}
Mike Grote
Mar 15, 11:29 AMThe exercise is to get you to understand how to attach a variable into a string, over complicating the output or process only clouds the issue. keep it simple like this...
String answer = "The sum is " + (a+b);
return answer;