What is Java?
Java is a popular programming language, created in 1995.
It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
Mobile applications (specially Android apps)
Desktop applications
Web applications
Web servers and application servers
Games
Database connection
And much, much more!
Why Use Java?
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
It is one of the most popular programming languages in the world
It has a large demand in the current job market
It is easy to learn and simple to use
It is open-source and free
It is secure, fast and powerful
It has huge community support (tens of millions of developers)
Java is an object oriented language which gives a clear structure to programs and allows code to be
reused, lowering development costs
As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa
Installing Java
However, if you want to run Java on your own computer, follow the instructions below.
Some PCs might have Java already installed.
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 (cmd.exe):
C:\Users\Your Name>java -version
If Java is installed, you will see something like this (depending on version):
java version "22.0.0" 2024-08-21 LTS
Java(TM) SE Runtime Environment 22.9 (build 22.0.0+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 22.9 (build 22.0.0+13-LTS, mixed mode)
If you do not have Java installed on your computer, you can download it at oracle.com.
Note: In this tutorial, we will write Java code in a text editor. However, 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.
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 Main.java, 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:
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus
on how to run the code above.
Save the code in Notepad as "Main.java". Open Command Prompt (cmd.exe), navigate to the directory where you
saved your file, and type "javac Main.java":
C:\Users\Your Name>javac Main.java
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:
C:\Users\Your Name>java Main
The output should read:
Hello World
Java Syntax
In the previous chapter, we created a Java file called Main.java, and we used the following code to print "Hello
World" to the screen:
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Example explained
Every line of code that runs in Java must be inside a class. And 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" has different meaning.
The name of the java file must match the class name. 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
The main Method
The main() method is required and you will see it in every Java program:
public static void main(String[] args)
Any code inside the main() method will be executed. Don't worry about the keywords before and after it. You will
get to know them bit by bit while reading this tutorial.
For now, just remember that every Java program has a class name which must match the filename, and that every
program must contain the main() method.
System.out.println()
Inside the main() method, we can use the println() method to print a line of text to the screen:
public static void main(String[] args) {
System.out.println("Hello World");
Note: The curly braces {} marks the beginning and the end of a block of code.
System is a built-in Java class that contains useful members, such as out, which is short for "output".
The println() method, short for "print line", is used to print a value to the screen (or a file).
Don't worry too much about how System, out and println() works. Just know that you need them together to print
stuff to the screen.
You should also note that each code statement must end with a semicolon (;).
Print Text
You learned from the previous chapter that you can use the println() method to output values or print text in Java:
System.out.println("Hello World!");
You can add as many println() methods as you want. Note that it will add a new line for each method:
Example
System.out.println("Hello World!");
System.out.println("I am learning Java.");
System.out.println("It is awesome!");
Double Quotes
Text must be wrapped inside double quotations marks "".
If you forget the double quotes, an error occurs:
Example
System.out.println("This sentence will work!");
System.out.println(This sentence will produce an error);
The Print() Method
There is also a print() method, which is similar to println().
The only difference is that it does not insert a new line at the end of the output:
Example
System.out.print("Hello World! ");
System.out.print("I will print on the same line.");
Note that we add an extra space (after "Hello World!" in the example above) for better readability.
In this tutorial, we will only use println() as it makes the code output easier to read.
Print Numbers
You can also use the println() method to print numbers.
However, unlike text, we don't put numbers inside double quotes:
System.out.println(3);
System.out.println(358);
System.out.println(50000);
You can also perform mathematical calculations inside the println() method:
Example
System.out.println(3 + 3);
Example
System.out.println(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).
This example uses a single-line comment before a line of code:
// This is a comment
System.out.println("Hello World");
This example uses a single-line comment at the end of a line of code:
Example
System.out.println("Hello World"); // This is a comment
Java Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by Java.
This example uses a multi-line comment (a comment block) to explain the code:
Example
/* The code below will print the words Hello World
to the screen, and it is amazing */
System.out.println("Hello World");
Single or multi-line comments?
It's up to you which one you use. Normally, we use // for short comments, and /* */ for longer.
Java Variables
Variables are containers for storing data values.
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 fals
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
type variableName = value;
Where type is one of Java's types (such as int or String), and variableName is the name of the variable (such
as x or name). The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
Example
Create a variable called name of type String and assign it the value "John".
Then we use println() to print the name variable:
String name = "John";
System.out.println(name);
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
System.out.println(myNum);
You can also declare a variable without assigning the value, and assign the value later:
Example
int myNum;
myNum = 15;
System.out.println(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:
int myNum = 15;
myNum = 20; // myNum is now 20
System.out.println(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;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
Display Variables
The println() method is often used to display variables.
To combine both text and a variable, use the + character:
ExampleGet your own Java Server
String name = "John";
System.out.println("Hello " + name);
You can also use the + character to add a variable to another variable:
Example
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
System.out.println(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;
System.out.println(x + y); // Print the value of x + y
From the example above, you can expect:
x stores the value 5
y stores the value 6
Then we use the println() method to display the value of x + y, which is 11
Java Data Types
As explained previously, a variable in Java must be a specified data type:
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
Data types are divided into two groups:
Primitive data types - includes byte, short, int, long, float, double, boolean and char
Non-primitive data types - such
as String, Arrays and Classes
Primitive Data Types
A primitive data type specifies the type of a variable and the kind of values it can hold.
There are eight primitive data types in Java:
Data Type Description
Byte Stores whole numbers from -128 to 127
Short Stores whole numbers from -32,768 to 32,767
Int Stores whole numbers from -2,147,483,648 to 2,147,483,647
Long Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Float Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
Double Stores fractional numbers. Sufficient for storing 15 to 16 decimal digits
Boolean Stores true or false values
Char Stores a single character/letter or ASCII values
Java Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
int x = 100 + 50;
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
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
Java divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator Name Description Example
+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x