0% found this document useful (0 votes)
16 views46 pages

Java Basics: A Beginner's Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views46 pages

Java Basics: A Beginner's Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA BASICS

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:

 Mobile applications (especially 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

Java Example
Java is often used in everyday programming tasks, like saying hello to a user:

Example
public class Main {

public static void main(String[] args) {

Page | 1
String name = "John";

[Link]("Hello " + name);

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!

Java Getting Started


Java Install
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 ([Link]):

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 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]

public class Main {

public static void main(String[] args) {

[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]":

C:\Users\Your Name>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:

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 [Link], and we used the following code
to print "Hello World" to the screen:

Example

Page | 3
[Link]

public class Main {

public static void main(String[] args) {

[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

The main Method


The main() method is required in every Java program. It is where the program starts running:

public static void main(String[] args)

Any code placed inside the main() method will be executed.

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

public static void main(String[] args) {

[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):

 System is a built-in Java class.


 out is a member of System, short for "output".
 println() is a method, short for "print line".

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.

In a programming language, these programming instructions are called statements.

The following statement "instructs" the compiler to print the text "Java is fun!" to the screen:

Example
[Link]("Java is fun!");

It is important that you end the statement with a semicolon ;.

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!");

[Link]("Have a good day!");

[Link]("Learning Java is fun!");

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).

Java Output / Print


Print Text
You learned from the previous chapter that you can use the println() method to output values or
print text in Java:

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]("I am learning Java.");

[Link]("It is awesome!");

Double Quotes
Text must be wrapped inside double quotations marks "".

If you forget the double quotes, an error occurs:

Example
[Link]("This sentence will work!");

[Link](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
[Link]("Hello World! ");

[Link]("I will print on the same line.");

Note that we add an extra space (after "Hello World!" in the example above) for better
readability.

Java Output Numbers


Page | 7
Print Numbers
You can also use the println() method to print numbers.

However, unlike text, we don't put numbers inside double quotes:

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).

This example uses a single-line comment before a line of code:

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:

[Link]("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 */

[Link]("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
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

Declaring (Creating) Variables


To create a variable in Java, you need to:

 Choose a type (like int or String)


 Give the variable a name (like x, age, or name)
 Optionally assign it a value using =

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:

String name = "John";

[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:

int myNum = 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:

int myNum = 15;

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;

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:

Example
String name = "John";

[Link]("Hello " + name);

Page | 11
You can also use the + character to add a variable to another variable:

Example
String firstName = "John ";

String lastName = "Doe";

String fullName = firstName + lastName;

[Link](fullName);

In Java, the + symbol has two meanings:

 For text (strings), it joins them together (called concatenation).


 For numbers, it adds values together.

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;

[Link](x + y); // Print the value of x + y

From the example above, here's what happens step by step:

 x stores the value 5


 y stores the value 6
 println() displays the result of x + y, which is 11

Mixing Text and Numbers


Be careful when combining text and numbers in the same line of code. Without parentheses, Java
will treat the numbers as text after the first string:

Example
int x = 5;

int y = 6;

Page | 12
[Link]("The sum is " + x + y); // Prints: The sum is 56

[Link]("The sum is " + (x + y)); // Prints: The sum is 11

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".

Declare Multiple Variables


To declare more than one variable of the same type, you can use a comma-separated list:

Example

Instead of writing:

int x = 5;

int y = 6;

int z = 50;

[Link](x + y + z); // 61

You can write:

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.

One Value to Multiple Variables


You can also assign the same value to multiple variables in one line:

Example

Page | 13
int x, y, z;

x = y = z = 50;

[Link](x + y + z); // 150

Identifiers
All Java variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and


maintainable code:

Example

// Good

int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is

int m = 60;

The general rules for naming variables are:

 Names can contain letters, digits, underscores, and dollar signs


 Names must begin with a letter
 Names should start with a lowercase letter, and cannot contain whitespace
 Names can also begin with $ and _
 Names are case-sensitive ("myVar" and "myvar" are different variables)
 Reserved words (like Java keywords, such as int or boolean) cannot be used as names

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

int my var = 10; // Cannot contain spaces

int int = 20; // Cannot use reserved keywords

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

final int myNum = 15;

myNum = 20; // Error: cannot assign a value to final variable 'myNum'

When to Use final?


You should declare variables as final when their values should never change. For example, the
number of minutes in an hour, or your birth year:

Example

final int MINUTES_PER_HOUR = 60;

final int BIRTHYEAR = 1980;

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.

Real-Life Variables Examples


Often in our examples, we simplify variable names to match their data type (myInt or myNum
for int types, myChar for char types, and so on). This is done to avoid confusion.

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

String studentName = "John Doe";

int studentID = 15;

int studentAge = 23;

float studentFee = 75.25f;

char studentGrade = 'B';

// Print variables

[Link]("Student name: " + studentName);

[Link]("Student id: " + studentID);

[Link]("Student age: " + studentAge);

[Link]("Student fee: " + studentFee);

[Link]("Student grade: " + studentGrade);

Calculate the Area of a Rectangle


In this real-life example, we create a program to calculate the area of a rectangle (by multiplying
the length and width):

Example

// Create integer variables

int length = 4;

int width = 6;

int area;

// Calculate the area of a rectangle

area = length * width;

// Print variables

[Link]("Length is: " + length);

[Link]("Width is: " + width);

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

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 (you will learn more about
these in a later chapter)

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

Page | 17
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

You Cannot Change the Type


Once a variable is declared with a type, it cannot change to another type later in the program:

Example

int myNum = 5; // myNum is an int

// myNum = "Hello"; // Error: cannot assign a String to an int

String myText = "Hi"; // myText is a String

// myText = 123; // Error: cannot assign a number to a String

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

byte myNum = 100;

[Link](myNum);

Short
The short data type can store whole numbers from -32768 to 32767:

Example

short myNum = 5000;

[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

int myNum = 100000;

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

long myNum = 15000000000L;

[Link](myNum);

Floating Point Types


You should use a floating point type whenever you need a number with a decimal, such as 9.99
or 3.14515.

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

float myNum = 5.75f;

[Link](myNum);

Double Example

double myNum = 19.99d;

[Link](myNum);

Use float or double?

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.

Therefore it is safer to use double for most calculations.

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);

Boolean Data Types


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 only take the values true or false:

Example

boolean isJavaFun = true;

boolean isFishTasty = false;

[Link](isJavaFun); // Outputs true

[Link](isFishTasty); // Outputs false

Boolean values are mostly used for conditional testing.

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

char myGrade = 'B';

[Link](myGrade);

Alternatively, if you are familiar with ASCII values, you can use those to display certain
characters:
Page | 21
Example

char myVar1 = 65, myVar2 = 66, myVar3 = 67;

[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

String greeting = "Hello World";

[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.

Real-Life Data Types Example


Here's a real-life example of using different data types, to calculate and output the total cost of a
number of items:

Example

// Create variables of different data types

int items = 50;

float costPerItem = 9.99f;

float totalCost = items * costPerItem;

char currency = '$';

Page | 22
// Print variables

[Link]("Number of items: " + items);

[Link]("Cost per item: " + costPerItem + currency);

[Link]("Total cost = " + totalCost + currency);

Non-Primitive Data Types


Non-primitive data types are called reference types because they refer to objects.

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


The var keyword was introduced in Java 10 (released in 2018).

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.

For example, instead of writing int x = 5;, you can write:

Example

var x = 5; // x is an int

[Link](x);

When using var, the compiler understands that 5 is an int.

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

var myNum = 5; // int

var myDouble = 9.98; // double

var myChar = 'D'; // char

var myBoolean = true; // boolean

var myString = "Hello"; // String

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:

var x = 5; // x is now an int


x = 10; // OK - still an int
x = 9.99; // Error - can't assign a double to an int

When to Use var


For simple variables, it's usually clearer to write the type directly (int, double, char, etc.).

But for more complex types, such as ArrayList or HashMap, var can make the code shorter and
easier to read:

Example

// Without var

ArrayList<String> cars = new ArrayList<String>();

Page | 24
// With var

var cars = new ArrayList<String>();

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.

In Java, there are two main types of casting:

 Widening Casting (automatic) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manual) - converting a larger type to a smaller type size


double -> float -> long -> int -> char -> short -> byte

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;

double myDouble = myInt; // Automatic casting: int to double

[Link](myInt); // Outputs 9

[Link](myDouble); // Outputs 9.0

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

double myDouble = 9.78d;

int myInt = (int) myDouble; // Manual casting: double to int

[Link](myDouble); // Outputs 9.78

[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

// Set the maximum possible score in the game to 500

int maxScore = 500;

// The actual score of the user

int userScore = 423;

/* Calculate the percentage of the user's score in relation to the maximum available score.

Convert userScore to double to make sure that the division is accurate */

double percentage = (double) userScore / maxScore * 100.0d;

[Link]("User's percentage is " + percentage);

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

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 x-y

Page | 27
another

* Multiplication Multiplies two values x*y

/ Division Divides one value by x/y


another

% Modulus Returns the division x%y


remainder

++ Increment Increases the value of a ++x


variable by 1

-- Decrement Decreases the value of a --x


variable by 1

Here is an example using different arithmetic operators in one example:

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;

[Link](a / b); // Integer division, result is 3

double c = 10.0d;

double d = 3.0d;

[Link](c / d); // Decimal division, result is 3.333...

Incrementing and Decrementing


Incrementing and decrementing are very common in programming, especially when working
with counters, loops, and arrays (which you will learn more about in later chapters).

The ++ operator increases a value by 1, while the -- operator decreases a value by 1:

Example

int x = 5;

++x; // Increment x by 1

[Link](x); // 6

--x; // Decrement x by 1

Page | 29
[Link](x); // 5

Real Life Example: Counting People


Imagine you are building a program to count how many people enter and leave a room. You can
use ++ to increase the counter when someone enters, and -- to decrease it when someone leaves:

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;

The addition assignment operator (+=) adds a value to a variable:

Example

int x = 10;

x += 5;

Page | 30
A list of all assignment operators:

Operator Example Same As

= 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

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.

Real-Life Example: Tracking Savings


Page | 31
Assignment operators can also be used in real-life scenarios. For example, you can use
the += operator to keep track of savings when you add money to an account:

Example

int savings = 100;

savings += 50; // add 50 to savings

[Link]("Total savings: " + savings);

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.

The return value of a comparison is either true or false.

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;

[Link](x > y); // returns true, because 5 is higher than 3

A list of all comparison operators:

Operato Name Example


r

== Equal to x == y

!= Not equal x != y

> Greater than x>y

Page | 32
< Less than x<y

>= Greater than or equal x >= y


to

<= Less than or equal to 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

int age = 18;

[Link](age >= 18); // true, old enough to vote

[Link](age < 18); // false, not old enough

Another common use is checking if a password is long enough:

Example

int passwordLength = 5;

[Link](passwordLength >= 8); // false, too short

[Link](passwordLength < 8); // true, needs more characters

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::

Operator Name Description Example

Page | 33
&& Logical and Returns true if x < 5 && x < 10
both statements are
true

|| Logical or Returns true if one x < 5 || x < 4


of the statements is
true

! Logical not Reverse the result, !(x < 5 && x < 10)
returns false if the
result is true

Real-Life Example: Login Check


The example below shows how logical operators can be used in a real situation, e.g. when
checking login status and access rights:

Example

boolean isLoggedIn = true;

boolean isAdmin = false;

[Link]("Regular user: " + (isLoggedIn && !isAdmin));

[Link]("Has access: " + (isLoggedIn || isAdmin));

[Link]("Not logged in: " + (!isLoggedIn));

Result:

Is regular user: true


Has any access: true
Not logged in: false

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);

Why Does This Happen?


In 2 + 3 * 4, the multiplication is done first, so the answer is 14.

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

int result1 = 10 - 2 + 5; // (10 - 2) + 5 = 13

int result2 = 10 - (2 + 5); // 10 - 7 = 3

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.

A String variable contains a collection of characters surrounded by double quotes:

Example

Create a variable of type String and assign it a value:

String greeting = "Hello";

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

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

[Link]("The length of the txt string is: " + [Link]());

More String Methods


There are many string methods available in Java.

For example:

 The toUpperCase() method converts a string to upper case letters.


 The toLowerCase() method converts a string to lower case letters.

Example

String txt = "Hello World";


Page | 36
[Link]([Link]()); // Outputs "HELLO WORLD"

[Link]([Link]()); // Outputs "hello world"

Finding a Character in a String


The indexOf() method returns the index (the position) of the first occurrence of a specified text
in a string (including whitespace):

Example

String txt = "Please locate where 'locate' occurs!";

[Link]([Link]("locate")); // Outputs 7

Java counts positions from zero.


0 is the first position in a string, 1 is the second, 2 is the third ...

You can use the charAt() method to access a character at a specific position in a string:

Example

String txt = "Hello";

[Link]([Link](0)); // H

[Link]([Link](4)); // o

Comparing Strings
To compare two strings, you can use the equals() method:

Example

String txt1 = "Hello";

String txt2 = "Hello";

String txt3 = "Greetings";

String txt4 = "Great things";

[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

String txt = " Hello World ";

[Link]("Before: [" + txt + "]");

[Link]("After: [" + [Link]() + "]");

Result:

Before: [ Hello World ]


After: [Hello World]

String Concatenation
The + operator can be used between strings to combine them. This is called concatenation:

Example

String firstName = "John";

String lastName = "Doe";

[Link](firstName + " " + lastName);

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

String name = "John";

int age = 25;

[Link]("My name is " + name + " and I am " + age + " years old.");

Page | 38
Result:

My name is John and I am 25 years old.

The concat() Method


You can also use the concat() method to concatenate strings:

Example

String firstName = "John ";

String lastName = "Doe";

[Link]([Link](lastName));

You can also join more than two strings by chaining concat() calls:

Example

String a = "Java ";

String b = "is ";

String c = "fun!";

String result = [Link](b).concat(c);

[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.

Numbers and Strings


WARNING!

Java uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example

Page | 39
int x = 10;

int y = 20;

int z = x + y; // z will be 30 (an integer/number)

If you add two strings, the result will be a string concatenation:

Example

String x = "10";

String y = "20";

String z = x + y; // z will be 1020 (a String)

If you add a number and a string, the result will be a string concatenation:

Example

String x = "10";

int y = 20;

String z = x + y; // z will be 1020 (a String)

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:

Escape Result Description


character

\' ' Single


quote

Page | 40
\" " Double
quote

\\ \ Backslash

The sequence \" inserts a double quote in a string:

Example

String txt = "We are the so-called \"Vikings\" from the north.";

The sequence \' inserts a single quote in a string:

Example

String txt = "It\'s alright.";

The sequence \\ inserts a single backslash in a string:

Example

String txt = "The character \\ is called backslash.";

Other common escape sequences that are valid in Java are:

Code Result Try it

\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

[Link](2, 8); // 256.0

Note: [Link](2, 8) means 2 multiplied by itself 8 times:


2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 = 256

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:

 [Link](x) - rounds to the nearest integer


 [Link](x) - rounds up (returns the smallest integer greater than or equal to x)
 [Link](x) - rounds down (returns the largest integer less than or equal to x)

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

int randomNum = (int)([Link]() * 101); // 0 to 100

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

boolean isJavaFun = true;

boolean isFishTasty = false;

[Link](isJavaFun); // Outputs true

[Link](isFishTasty); // Outputs false

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;

[Link](x > y); // returns true, because 10 is greater than 9

Or even easier:

Example

[Link](10 > 9); // returns true, because 10 is greater than 9

In the examples below, we use the equal to (==) operator to evaluate an expression:

Example

int x = 10;

[Link](x == 10); // returns true, because the value of x is equal to 10

Example

[Link](10 == 15); // returns false, because 10 is not equal to 15

Real Life Example


Let's think of a "real life example" where we need to find out if a person is old enough to vote.

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

int myAge = 25;

int votingAge = 18;

[Link](myAge >= votingAge);

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.":

int myAge = 25;

int votingAge = 18;

if (myAge >= votingAge) {

[Link]("Old enough to vote!");

} else {

[Link]("Not old enough to vote.");

Booleans are the basis for all Java comparisons and conditions.

You will learn more about conditions (if...else) in the next chapter.

Page | 46

You might also like