Java Basics: A Beginner's Guide
Java Basics: A Beginner's Guide
What is Java?
Java is a popular and powerful programming language, created in 1995.
Oracle owns it, and more than 3 billion devices run Java.
It is used for:
Java Example
Java is often used in everyday programming tasks, like saying hello to a user:
Example
public class Main {
Page | 1
String name = "John";
Result:
Hello John
Get Started
By the end of this tutorial, you will know how to write basic Java programs and apply your skills
to real-life examples.
You don't need any prior programming experience - just curiosity and practice!
To check if you have Java installed on a Windows PC, search in the start bar for Java or type the
following in Command Prompt ([Link]):
If Java is installed, you will see something like this (depending on version):
If you do not have Java installed on your computer, you can download it at from [Link].
Note: Apart from using a text editor, it is possible to write Java in an Integrated Development
Environment, such as IntelliJ IDEA, Netbeans or Eclipse, which are particularly useful when
managing larger collections of Java files.
Page | 2
Java Quickstart
In Java, every application begins with a class name, and that class must match the filename.
Let's create our first Java file, called [Link], which can be done in any text editor (like
Notepad).
The file should contain a "Hello World" message, which is written with the following code:
[Link]
[Link]("Hello World");
Save the code in Notepad as "[Link]". Open Command Prompt ([Link]), navigate to the
directory where you saved your file, and type "javac [Link]":
This will compile your code. If there are no errors in the code, the command prompt will take
you to the next line. Now, type "java Main" to run the file:
Hello World
Congratulations! You have written and executed your first Java program.
Java Syntax
In the previous chapter, we created a Java file called [Link], and we used the following code
to print "Hello World" to the screen:
Example
Page | 3
[Link]
[Link]("Hello World");
Example explained
Every line of code that runs in Java must be inside a class. The class name should always start
with an uppercase first letter. In our example, we named the class Main.
Note: Java is case-sensitive. MyClass and myclass would be treated as two completely different
names.
The name of the Java file must match the class name. So if your class is called Main, the file
must be saved as [Link]. This is because Java uses the class name to find and run your code.
If the names don't match, Java will give an error and the program will not run.
When saving the file, save it using the class name and add .java to the end of the filename. To
run the example above on your computer, make sure that Java is properly installed: The output
should be:
Hello World
For now, you don't need to understand the keywords public, static, and void. You will learn
about them later in this tutorial. Just remember: main() is the starting point of every Java
program.
[Link]()
Page | 4
Inside the main() method, we can use the println() method to print a line of text to the screen:
Example
[Link]("Hello World");
Note: The curly braces {} mark the beginning and the end of a block of code.
[Link]() may look long, but you can think of it as a single command that
means: "Send this text to the screen."
Here's what each part means (you will learn the details later):
Finally, remember that each Java statement must end with a semicolon (;).
Java Statements
A computer program is a list of "instructions" to be "executed" by a computer.
The following statement "instructs" the compiler to print the text "Java is fun!" to the screen:
Example
[Link]("Java is fun!");
If you forget the semicolon (;), an error will occur and the program will not run:
Example
[Link]("Java is fun!")
Result:
Page | 5
error: ';' expected
Tip: You can think of a statement like a sentence in English. Just as sentences end with a
period ., Java statements end with a semicolon ;.
Many Statements
Most Java programs contain many statements.
The statements are executed, one by one, in the same order as they are written:
Example
[Link]("Hello World!");
Example explained
From the example above, we have three statements:
1. [Link]("Hello World!");
2. [Link]("Have a good day!");
3. [Link]("Learning Java is fun!");
The first statement is executed first (print "Hello World!" to the screen).
Then the second statement is executed (print "Have a good day!" to the screen).
And at last, the third statement is executed (print "Learning Java is fun!" to the screen).
Example
Page | 6
[Link]("Hello World!");
You can add as many println() methods as you want. Note that it will add a new line for each
method:
Example
[Link]("Hello World!");
[Link]("It is awesome!");
Double Quotes
Text must be wrapped inside double quotations marks "".
Example
[Link]("This sentence will work!");
The only difference is that it does not insert a new line at the end of the output:
Example
[Link]("Hello World! ");
Note that we add an extra space (after "Hello World!" in the example above) for better
readability.
Example
[Link](3);
[Link](358);
[Link](50000);
You can also perform mathematical calculations inside the println() method:
Example
[Link](3 + 3);
[Link](2 * 5);
Java Comments
Comments can be used to explain Java code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not be executed).
Example
// This is a comment
[Link]("Hello World");
Page | 8
This example uses a single-line comment at the end of a line of code:
This example uses a multi-line comment (a comment block) to explain the code:
Example:
[Link]("Hello World");
Java Variables
In Java, there are different types of variables, for example:
String- stores text, such as "Hello". String values are surrounded by double quotes
int- stores integers (whole numbers), without decimals, such as 123 or -123
float- stores floating point numbers, with decimals, such as 19.99 or -19.99
char- stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
boolean- stores values with two states: true or false
Page | 9
Here's the basic syntax:
Syntax
type variableName = value;
For example, if you want to store some text, you can use a String:
Example
Create a variable called name of type String and assign it the value "John".
Then we use println() to print the name variable:
[Link](name);
To create a variable that should store a number, you can use int:
Example
Create a variable called myNum of type int and assign it the value 15:
[Link](myNum);
You can also declare a variable without assigning the value, and assign the value later:
Example
int myNum;
myNum = 15;
[Link](myNum);
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example
Change the value of myNum from 15 to 20:
Page | 10
myNum = 20; // myNum is now 20
[Link](myNum);
Final Variables
If you don't want others (or yourself) to overwrite existing values, use the final keyword (this
will declare the variable as "final" or "constant", which means unchangeable and read-only):
Example
final int myNum = 15;
myNum = 20; // will generate an error: cannot assign a value to a final variable
Other Types
A demonstration of how to declare variables of other types:
Example
int myNum = 5;
Display Variables
The println() method is often used to display variables.
Example
String name = "John";
Page | 11
You can also use the + character to add a variable to another variable:
Example
String firstName = "John ";
[Link](fullName);
For numeric values, the + character works as a mathematical operator (notice that we
use int (integer) variables here):
Example
int x = 5;
int y = 6;
Example
int x = 5;
int y = 6;
Page | 12
[Link]("The sum is " + x + y); // Prints: The sum is 56
Explanation:
In the first line, Java combines "The sum is " with x, creating the string "The sum is 5". Then y is
added to that string, so it becomes "The sum is 56".
In the second line, the parentheses make sure x + y is calculated first (resulting in 11), so the
output is "The sum is 11".
Example
Instead of writing:
int x = 5;
int y = 6;
int z = 50;
[Link](x + y + z); // 61
int x = 5, y = 6, z = 50;
[Link](x + y + z); // 61
Note: Declaring many variables in one line is shorter, but writing one variable per line can
sometimes make the code easier to read.
Example
Page | 13
int x, y, z;
x = y = z = 50;
Identifiers
All Java variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Example
// Good
int m = 60;
Invalid Identifiers
Here are some examples of invalid identifiers that would cause errors:
Example
// Invalid identifiers:
Page | 14
int 2ndNumber = 5; // Cannot start with a digit
Constants (final)
When you do not want a variable's value to change, use the final keyword.
A variable declared with final becomes a constant, which means unchangeable and read-only:
Example
Example
Note: By convention, final variables in Java are usually written in upper case
(e.g. BIRTHYEAR). It is not required, but useful for code readability and common for many
programmers.
However, for a practical example of using variables, we have created a program that stores
different data about a college student:
Example
Page | 15
// Student data
// Print variables
Example
int length = 4;
int width = 6;
int area;
// Print variables
Page | 16
[Link]("Area of the rectangle is: " + area);
Data Types
As explained in the previous chapter, a variable in Java must be a specified data type:
Example
Primitive data types - includes byte, short, int, long, float, double, boolean and char
Non-primitive data types - such as String, Arrays and Classes (you will learn more about
these in a later chapter)
Page | 17
long Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
Example
Note: This rule makes Java safer, because the compiler will stop you if you try to mix up types
by mistake.
If you really need to change between types, you must use type casting or conversion methods
(for example, turning an int into a double).
Numbers
Primitive number types are divided into two groups:
Page | 18
Integer types stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are byte, short, int and long. Which type you should use, depends on the
numeric value.
Floating point types represents numbers with a fractional part, containing one or more decimals.
There are two types: float and double.
Even though there are many numeric types in Java, the most used for numbers are int (for whole
numbers) and double (for floating point numbers). However, we will describe them all as you
continue to read.
Integer Types
Byte
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or
other integer types to save memory when you are certain that the value will be within -128 and
127:
Example
[Link](myNum);
Short
The short data type can store whole numbers from -32768 to 32767:
Example
[Link](myNum);
Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in
our class, the int data type is the preferred data type when we create variables with a numeric
value.
Example
Page | 19
[Link](myNum);
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note that
you should end the value with an "L":
Example
[Link](myNum);
The float and double data types can store fractional numbers. Note that you should end the value
with an "f" for floats and "d" for doubles:
Float Example
[Link](myNum);
Double Example
[Link](myNum);
The precision of a floating point value indicates how many digits the value can have after the
decimal point. The precision of float is only 6-7 decimal digits, while double variables have a
precision of about 16 digits.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
Page | 20
Example
float f1 = 35e3f;
double d1 = 12E4d;
[Link](f1);
[Link](d1);
YES / NO
ON / OFF
TRUE / FALSE
For this, Java has a boolean data type, which can only take the values true or false:
Example
Characters
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':
Example
[Link](myGrade);
Alternatively, if you are familiar with ASCII values, you can use those to display certain
characters:
Page | 21
Example
[Link](myVar1);
[Link](myVar2);
[Link](myVar3);
Strings
The String data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:
Example
[Link](greeting);
The String type is so much used and integrated in Java, that some call it "the special ninth type".
A String in Java is actually a non-primitive data type, because it refers to an object. The String
object has methods that are used to perform certain operations on strings. Don't worry if you
don't understand the term "object" just yet. We will learn more about strings and objects in a
later chapter.
Example
Page | 22
// Print variables
The main differences between primitive and non-primitive data types are:
Primitive types in Java are predefined and built into the language, while non-primitive
types are created by the programmer (except for String).
Non-primitive types can be used to call methods to perform certain operations, whereas
primitive types cannot.
Primitive types start with a lowercase letter (like int), while non-primitive types typically
starts with an uppercase letter (like String).
Primitive types always hold a value, whereas non-primitive types can be null.
Examples of non-primitive types are Strings, Arrays, Classes etc. You will learn more about
these in a later chapter.
The var keyword lets the compiler automatically detect the type of a variable based on the value
you assign to it.
This helps you write cleaner code and avoid repeating types, especially for long or complex
types.
Example
var x = 5; // x is an int
[Link](x);
Page | 23
Example with Different Types
Here are some examples showing how var can be used to create variables of different types,
based on the values you assign:
Example
Important Notes
1. var only works when you assign a value at the same time (you can't declare var x; without
assigning a value):
var x; // Error
var x = 5; // OK
2. Once the type is chosen, it stays the same. See example below:
But for more complex types, such as ArrayList or HashMap, var can make the code shorter and
easier to read:
Example
// Without var
Page | 24
// With var
Don't worry if the example above looks a bit advanced - you will learn more about these
complex types later. For now, just remember that var was introduced in Java 10, and if you work
with others, you might see it in their code - so it's good to know what it means.
Type Casting
Type casting means converting one data type into another. For example, turning an int into
a double.
Widening Casting
Widening casting is done automatically when passing a smaller size type into a larger size type.
This works because there is no risk of losing information. For example, an int value can safely fit
inside a double:
Example
int myInt = 9;
[Link](myInt); // Outputs 9
Narrowing Casting
Page | 25
Narrowing casting must be done manually by placing the type in parentheses () in front of the
value.
This is required because narrowing may result in data loss (for example, dropping decimals when
converting a double to an int):
Example
[Link](myInt); // Outputs 9
Real-Life Example
Here is a real-life example of type casting. We calculate the percentage of a user's score in
relation to the maximum score in a game.
We use type casting to make sure that the result is a floating-point value, rather than an integer:
Example
/* Calculate the percentage of the user's score in relation to the maximum available score.
Page | 26
Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
Although the + operator is often used to add together two values, like in the example above, it
can also be used to add together a variable and a value, or a variable and another variable:
Example
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Page | 27
another
Example
int x = 10;
int y = 3;
[Link](x + y); // 13
[Link](x - y); // 7
[Link](x * y); // 30
[Link](x / y); // 3
[Link](x % y); // 1
int z = 5;
Page | 28
++z;
[Link](z); // 6
--z;
[Link](z); // 5
Note: When dividing two integers in Java, the result will also be an integer. For example, 10 /
3 gives 3. If you want a decimal result, use double values, like 10.0 / 3.
Example
int a = 10;
int b = 3;
double c = 10.0d;
double d = 3.0d;
Example
int x = 5;
++x; // Increment x by 1
[Link](x); // 6
--x; // Decrement x by 1
Page | 29
[Link](x); // 5
Example
int peopleInRoom = 0;
// 3 people enter
peopleInRoom++;
peopleInRoom++;
peopleInRoom++;
[Link](peopleInRoom); // 3
// 1 person leaves
peopleInRoom--;
[Link](peopleInRoom); // 2
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
Example
int x = 10;
Example
int x = 10;
x += 5;
Page | 30
A list of all assignment operators:
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
Note: Most assignment operators are just shorter ways of writing code. For example, x += 5 is
the same as x = x + 5, but shorter and often easier to read.
Example
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
Example
int x = 5;
int y = 3;
== Equal to x == y
!= Not equal x != y
Page | 32
< Less than x<y
Real-Life Examples
Comparison operators are often used in real-world conditions, such as checking if a person is old
enough to vote:
Example
Example
int passwordLength = 5;
Logical Operators
As with comparison operators, you can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values, by combining
multiple conditions::
Page | 33
&& Logical and Returns true if x < 5 && x < 10
both statements are
true
! Logical not Reverse the result, !(x < 5 && x < 10)
returns false if the
result is true
Example
Result:
Operator Precedence
When a calculation contains more than one operator, Java follows order of operations rules to
decide which part to calculate first.
Page | 34
For example, multiplication happens before addition:
Example
int result1 = 2 + 3 * 4; // 2 + 12 = 14
int result2 = (2 + 3) * 4; // 5 * 4 = 20
[Link](result1);
[Link](result2);
If you want the addition to happen first, you must use parentheses: (2 + 3) * 4, which gives 20.
Tip: Always use parentheses ( ) if you want to make sure the calculation is done in the order you
expect. It also makes your code easier to read.
Order of Operations
Here are some common operators, from highest to lowest priority:
() - Parentheses
*, /, % - Multiplication, Division, Modulus
+, - - Addition, Subtraction
>, <, >=, <= - Comparison
==, != - Equality
&& - Logical AND
|| - Logical OR
= - Assignment
Another Example
Subtraction and addition are done from left to right, unless you add parentheses:
Example
Page | 35
[Link](result1);
[Link](result2);
Remember: Parentheses always come first. Use them to control the order of your calculations.
Strings
Strings are used for storing text.
Example
String Length
A String in Java is actually an object, which means it contains methods that can perform certain
operations on strings.
For example, you can find the length of a string with the length() method:
Example
For example:
Example
Example
[Link]([Link]("locate")); // Outputs 7
You can use the charAt() method to access a character at a specific position in a string:
Example
[Link]([Link](0)); // H
[Link]([Link](4)); // o
Comparing Strings
To compare two strings, you can use the equals() method:
Example
[Link]([Link](txt2)); // true
[Link]([Link](txt4)); // false
Page | 37
Removing Whitespace
The trim() method removes whitespace from the beginning and the end of a string:
Example
Result:
String Concatenation
The + operator can be used between strings to combine them. This is called concatenation:
Example
Note that we have added an empty text (" ") to create a space between firstName and lastName
on print.
Concatenation in Sentences
You can use string concatenation to build sentences with both text and variables:
Example
[Link]("My name is " + name + " and I am " + age + " years old.");
Page | 38
Result:
Example
[Link]([Link](lastName));
You can also join more than two strings by chaining concat() calls:
Example
String c = "fun!";
[Link](result);
Note: While you can use concat() to join multiple strings, most developers prefer the + operator
because it is shorter and easier to read.
Example
Page | 39
int x = 10;
int y = 20;
Example
String x = "10";
String y = "20";
If you add a number and a string, the result will be a string concatenation:
Example
String x = "10";
int y = 20;
Special Characters
Because strings must be written within quotes, Java will misunderstand this string, and generate
an error:
String txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:
Page | 40
\" " Double
quote
\\ \ Backslash
Example
String txt = "We are the so-called \"Vikings\" from the north.";
Example
Example
\n New Line
\t Tab
\b Backspace
\r Carriage
Return
Page | 41
\f Form
Feed
Note: Most of these escape codes are rarely used in modern programming. The most
common ones are \n (new line), \" (double quote), and \\ (backslash).
Math
The Java Math class has many methods that allows you to perform mathematical tasks on
numbers.
[Link](x,y)
The [Link](x,y) method can be used to find the highest value of x and y:
Example
[Link](5, 10);
[Link](x,y)
The [Link](x,y) method can be used to find the lowest value of x and y:
Example
[Link](5, 10);
[Link](x)
The [Link](x) method returns the square root of x:
Example
[Link](64);
[Link](x)
The [Link](x) method returns the absolute (positive) value of x:
Page | 42
Example
[Link](-4.7);
[Link](x, y)
The [Link](x, y) method returns the value of x raised to the power of y:
Example
Note: The [Link]() method always returns a double, even if the result is a whole number. For
example, [Link](2, 8) returns 256.0 (not 256).
Rounding Methods
Java has several methods for rounding numbers:
Example
[Link](4.6); // 5
[Link](4.1); // 5.0
[Link](4.9); // 4.0
Random Numbers
[Link]() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):
Example
[Link]();
Page | 43
To get more control over the random number, for example, if you only want a random number
between 0 and 100, you can use the following formula:
Example
Note: [Link]() returns a double. To get an integer, you need to cast it with (int).
Booleans
Very often in programming, you will need a data type that can only have one of two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, Java has a boolean data type, which can store true or false values.
The name boolean comes from George Boole, a mathematician who first defined the logic
system used in computers today.
Boolean Values
A boolean type is declared with the boolean keyword and can only take the values true or false:
Example
In practice, booleans are most often the result of expressions, and are used to test conditions in
programs (see below).
Boolean Expressions
A boolean expression returns a boolean value: true or false.
Page | 44
This is useful to build logic and make decisions in programs.
For example, you can use a comparison operator, such as the greater than (>) operator, to find
out if an expression (or a variable) is true or false:
Example
int x = 10;
int y = 9;
Or even easier:
Example
In the examples below, we use the equal to (==) operator to evaluate an expression:
Example
int x = 10;
Example
In the example below, we use the >= comparison operator to find out if the age (25) is greater
than OR equal to the voting age limit, which is set to 18:
Example
Page | 45
An even better approach would be to wrap the code above in an if...else statement, so we can
perform different actions depending on the result:
Example
Output "Old enough to vote!" if myAge is greater than or equal to 18. Otherwise output "Not old
enough to vote.":
} else {
Booleans are the basis for all Java comparisons and conditions.
You will learn more about conditions (if...else) in the next chapter.
Page | 46