
What is Java programming language?
Java is used to develop mobile apps, web apps, desktop apps, games and much more.
Examples in Each Chapter
Our “Try it Yourself” editor makes it easy to learn Java. You can edit Java code and view the result in your browser.
Example
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Introduction to Java
What exactly is Java?
Java is a widely used computer language that was first released in 1995.
Oracle owns Java, which is used on over 3 billion devices.
It is employed for the following purposes:
Apps for mobile devices (specially Android apps)
Applications for the desktop
Applications for the web
Web servers and application servers are two types of servers.
Connection to the Games Database
And there’s a lot more!
Why Should You Use Java?
Java may be used on a variety of platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
It is one of the most widely used programming languages worldwide. It is simple to learn and use, and it is open-source and free.
It is safe, quick, and strong.
It has a considerable following in the neighborhood (tens of millions of developers)
Java is an object-oriented programming language that gives programs a logical structure and allows code to be reused.
Java Install
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 "11.0.1" 2018-10-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)
If you do not have Java installed on your computer, you can download it for free 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.
Setup for Windows
To install Java on Windows:
- Go to “System Properties” (Can be found on Control Panel > System and Security > System > Advanced System Settings)
- Click on the “Environment variables” button under the “Advanced” tab
- Then, select the “Path” variable in System variables and click on the “Edit” button
- Click on the “New” button and add the path where Java is installed, followed by \bin. By default, Java is installed in C:\Program Files\Java\jdk-11.0.1 (If nothing else was specified when you installed it). In that case, You will have to add a new path with: C:\Program Files\Java\jdk-11.0.1\bin
Then, click “OK”, and save the settings - At last, open Command Prompt (cmd.exe) and type java -version to see if Java is running on your machine
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
Congratulations! You have written and executed your first Java program.
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
. In our example, we named the class Main. A class should always start with an uppercase first letter.
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: Go to the for how to install Java. 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. You don’t have to understand the keywords before and after main. 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.
Note: Each code statement must end with a semicolon.
Test Yourself With Exercises
Exercise:
Insert the missing part of the code below to output “Hello World”.
public class MyClass { public static void main(String[] args) {
..("Hello World"); } }
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:
Example
// 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 is up to you which you want to use. Normally, we use //
for short comments, and /* */
for longer.
Test Yourself With Exercises
Exercise:
Insert the missing part to create two types of comments.
This is a single-line comment This is a multi-line comment
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 quotesint
– stores integers (whole numbers), without decimals, such as 123 or -123float
– stores floating point numbers, with decimals, such as 19.99 or -19.99char
– stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotesboolean
– stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax
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“:
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";
You will learn more about in the next section.
Test Yourself With Exercises
Exercise:
Create a variable named carName
and assign the value Volvo
to it.
= ;
Java Data Types
As explained in the previous chapter, a variable in Java must be a specified data type:
Example
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
andchar
- Non-primitive data types – such as
String
, Arrays and Classes (you will learn more about these in a later chapter)
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has no additional methods.
There are eight primitive data types in Java:
Data Type | Size | Description |
---|---|---|
byte | 1 byte | Stores whole numbers from -128 to 127 |
short | 2 bytes | Stores whole numbers from -32,768 to 32,767 |
int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
boolean | 1 bit | Stores true or false values |
char | 2 bytes | Stores a single character/letter or ASCII values |
Test Yourself With Exercises
Exercise:
Add the correct data type for the following variables:
myNum = 9; myFloatNum = 8.99f; myLetter = 'A'; myBool = false; myText = "Hello World";
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:
Example
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 | Try it |
---|---|---|---|---|
+ | 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 |
Java 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;
The addition assignment operator (+=
) adds a value to a variable:
Example
int x = 10;
x += 5;
A list of all assignment operators:
Operator | Example | Same As | Try it |
---|---|---|---|
= | 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 | |
^= | x ^= 3 | x = x ^ 3 | |
>>= | x >>= 3 | x = x >> 3 | |
<<= | x <<= 3 | x = x << 3 |
Java Comparison Operators
Comparison operators are used to compare two values:
Operator | Name | Example | Try it |
---|---|---|---|
== | Equal to | x == y | |
!= | Not equal | x != y | |
> | Greater than | x > y | |
< | Less than | x < y | |
>= | Greater than or equal to | x >= y | |
<= | Less than or equal to | x <= y |
Java Logical Operators
Logical operators are used to determine the logic between variables or values:
Operator | Name | Description | Example | Try it |
---|---|---|---|---|
&& | Logical and | Returns true if both statements are true | x < 5 && x < 10 | |
|| | Logical or | Returns true if one of the statements is true | x < 5 || x < 4 | |
! | Logical not | Reverse the result, returns false if the result is true | !(x < 5 && x < 10) |
Test Yourself With Exercises
Exercise:
Multiply 10
with 5
, and print the result.
System.out.println(10 5);