0% found this document useful (0 votes)
2 views

Java My Note 2025

Java is a widely-used programming language created in 1995 and owned by Oracle, running on over 3 billion devices. It supports various applications, including mobile, desktop, web, and games, and is known for its cross-platform capabilities, ease of learning, and strong community support. The document also covers Java installation, syntax, output methods, variables, and comments, providing examples for beginners to understand the basics of Java programming.

Uploaded by

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

Java My Note 2025

Java is a widely-used programming language created in 1995 and owned by Oracle, running on over 3 billion devices. It supports various applications, including mobile, desktop, web, and games, and is known for its cross-platform capabilities, ease of learning, and strong community support. The document also covers Java installation, syntax, output methods, variables, and comments, providing examples for beginners to understand the basics of Java programming.

Uploaded by

Musa Jusu Alex
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

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

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

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

public class Main {

public static void main(String[] args) {

System.out.println("Hello World");

Output =Hello Word


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

Try it Yourself »

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:
Go to the Get Started Chapter 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. 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");

Example

public class Main {

public static void main(String[] args) {

System.out.println("Hello World");

Output= 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 ( ;).
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
System.out.println("Hello World!");

public class Main {

public static void main(String[] args) {


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

Try this,

public class Main {

public static void main(String[] args) {

System.out.println("Hello World!");
System.out.println("I am learning Java.");

System.out.println("It is awesome!");
}

}
Output =
Hello World!

I am learning Java.

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

Try it Yourself »
public class Main {
public static void main(String[] args) {

System.out.println(This sentence will produce an error);

Output=

Main.java:3: error: ')' expected

System.out.println(This sentence will produce an error);

Main.java:3: error: ';' expected

System.out.println(This sentence will produce an error);

Main.java:3: error: ';' expected

System.out.println(This sentence will produce an error);

^
Main.java:3: error: not a statement
System.out.println(This sentence will produce an error);

Main.java:3: error: ';' expected

System.out.println(This sentence will produce an error);

5 errors

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

Try it yourself

public class Main {


public static void main(String[] args) {

System.out.print("Hello World! ");


System.out.print("I will print on the same line.");

Output=

Hello World! 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.
Java Output Numbers

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

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

ExampleGet your own Java Server


System.out.println(3);

System.out.println(358);

System.out.println(50000);

Try it Yourself »

public class Main {

public static void main(String[] args) {

System.out.println(3);

System.out.println(358);

System.out.println(50000);

Output= 3
358
50000

You can also perform mathematical calculations inside the println() method:

Example
System.out.println(3 + 3);

Try it yourself
public class Main {

public static void main(String[] args) {

System.out.println(3 + 3);

Output= 6

Example
System.out.println(2 * 5);

public class Main {

public static void main(String[] args) {

System.out.println(2 * 5);
}

Output= 10

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:


ExampleGet your own Java Server
// This is a comment

System.out.println("Hello World");

Try it Yourself »

public class Main {

public static void main(String[] args) {

// This is a comment

System.out.println("Hello World");

Output= 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

Try it Yourself »

public class Main {

public static void main(String[] args) {

System.out.println("Hello World"); // This is a comment

Output= Hello World

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

Try it Yourself »

public class Main {


public static void main(String[] args) {
/* The code below will print the words Hello World
to the screen, and it is amazing */
System.out.println("Hello World");
}
}

Output= 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 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".
Then we use println() to print the name variable:

String name = "John";

System.out.println(name);

Try it Yourself »

public class Main {

public static void main(String[] args) {

String name = "John";

System.out.println(name);

}
}

Output= John

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

Try it Yourself »

public class Main {

public static void main(String[] args) {

int myNum = 15;

System.out.println(myNum);

Output= 15

You can also declare a variable without assigning the value, and assign the
value later:

Example
int myNum;

myNum = 15;

System.out.println(myNum);

Try it Yourself »

public class Main {


public static void main(String[] args) {

int myNum;

myNum = 15;

System.out.println(myNum);

Output= 15

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

Try it Yourself »

public class Main {

public static void main(String[] args) {

int myNum = 15;

myNum = 20; // myNum is now 20

System.out.println(myNum);

}
Output= 20
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

Try it Yourself »

public class Main {


public static void main(String[] args) {
final int myNum = 15;
myNum = 20; // will generate an error
System.out.println(myNum);
}
}
Output= Main.java:4: error: cannot assign a value to final variable myNum

myNum = 20;

1 error

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

Java Print Variables


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

System.out.println("Hello " + name);

Try it Yourself »
public class Main {
public static void main(String[] args) {
String name = "John";
System.out.println("Hello " + name);
}
}
Output= Hello John

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

Try it Yourself »
public class Main {
public static void main(String[] args) {
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
System.out.println(fullName);
}
}
Output= John Doe

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

Try it Yourself »
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 6;
System.out.println(x + y); // Print the value of x + y
}
}
Output= 11

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 Declare Multiple Variables


Declare Many Variables
To declare more than one variable of the same type, you can use a comma-
separated list:
ExampleGet your own Java Server
Instead of writing:

int x = 5;

int y = 6;

int z = 50;

System.out.println(x + y + z);

You can simply write:

int x = 5, y = 6, z = 50;

System.out.println(x + y + z);

Try it Yourself »
public class Main {
public static void main(String[] args) {
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
}
}
Output= 61
One Value to Multiple Variables

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

Example
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);

Try it Yourself »
public class Main {
public static void main(String[] args) {
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);
}
}
Output= 150
Java Identifiers

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;

Try it Yourself »
public class Main {
public static void main(String[] args) {
// Good
int minutesPerHour = 60;

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


int m = 60;

System.out.println(minutesPerHour);
System.out.println(m);
}
}
Output= 60
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

Real-Life 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
// Student data
String studentName = "John Doe";
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25f;
char studentGrade = 'B';

// Print variables
System.out.println("Student name: " + studentName);
System.out.println("Student id: " + studentID);
System.out.println("Student age: " + studentAge);
System.out.println("Student fee: " + studentFee);
System.out.println("Student grade: " + studentGrade);

Try it Yourself »
public class Main {
public static void main(String[] args) {
// Student data
String studentName = "John Doe";
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25f;
char studentGrade = 'B';

// Print variables
System.out.println("Student name: " + studentName);
System.out.println("Student id: " + studentID);
System.out.println("Student age: " + studentAge);
System.out.println("Student fee: " + studentFee);
System.out.println("Student grade: " + studentGrade);
}
}
Output=
Student name: John Doe
Student id: 15
Student age: 23
Student fee: 75.25
Student grade: B
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
System.out.println("Length is: " + length);
System.out.println("Width is: " + width);

System.out.println("Area of the rectangle is: " + area);

Try it Yourself »
public class Main {
public static void main(String[] args) {
// Create integer variables
int length = 4;
int width = 6;
int area;

// Calculate the area of a rectangle


area = length * width;

// Print variables
System.out.println("Length is: " + length);
System.out.println("Width is: " + width);
System.out.println("Area of the rectangle is: " + area);
}
}
Output=
Length is: 4
Width is: 6
Area of the rectangle is: 24

Java Data Types


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

Try it Yourself »
public class Main {
public static void main(String[] args) {
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
System.out.println(myNum);
System.out.println(myFloatNum);
System.out.println(myLetter);
System.out.println(myBool);
System.out.println(myText);
}
}
Output=
5
5.99
D
true
Hello

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

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 Numbers
Numbers
Primitive number types are divided into two groups:

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:

ExampleGet your own Java Server


byte myNum = 100;

System.out.println(myNum);

Try it Yourself »
public class Main {
public static void main(String[] args) {
byte myNum = 100;
System.out.println(myNum);
}
}
Output= 100

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

Example
short myNum = 5000;

System.out.println(myNum);

Try it Yourself »
public class Main {
public static void main(String[] args) {
short myNum = 5000;
System.out.println(myNum);
}
}
Output= 5000

Int
The int data type can store whole numbers from -2147483648 to
2147483647. In general, and in our tutorial, the int data type is the preferred
data type when we create variables with a numeric value.

Example
int myNum = 100000;
System.out.println(myNum);

Try it Yourself »
public class Main {
public static void main(String[] args) {
int myNum = 100000;
System.out.println(myNum);
}
}
Output=100000

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;

System.out.println(myNum);

Try it Yourself »

public class Main {


public static void main(String[] args) {
long myNum = 15000000000L;
System.out.println(myNum);
}
}
Output= 15000000000

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;
System.out.println(myNum);
Try it Yourself »
public class Main {
public static void main(String[] args) {
float myNum = 5.75f;
System.out.println(myNum);
}
}
Output= 5.75

Double Example
double myNum = 19.99d;
System.out.println(myNum);

Try it Yourself »
public class Main {
public static void main(String[] args) {
double myNum = 19.99d;
System.out.println(myNum);
}
}
Output= 19.99

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 six or seven 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:

Example
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);

Try it Yourself »

public class Main {

public static void main(String[] args) {

float f1 = 35e3f;

double d1 = 12E4d;

System.out.println(f1);

System.out.println(d1);

Output=

35000.0
120000.0

Java Boolean Data Types


Boolean 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;
System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs false
Try it Yourself »
public class Main {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);
}
}
Output=
true
false

Boolean values are mostly used for conditional testing.

Java Characters
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';
System.out.println(myGrade);

Try it Yourself »
public class Main {
public static void main(String[] args) {
char myGrade = 'B';
System.out.println(myGrade);
}
}
Output= B

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

Example
char myVar1 = 65, myVar2 = 66, myVar3 = 67;
System.out.println(myVar1);
System.out.println(myVar2);
System.out.println(myVar3);
Try it Yourself »
public class Main {
public static void main(String[] args) {
char myVar1 = 65, myVar2 = 66, myVar3 = 67;
System.out.println(myVar1);
System.out.println(myVar2);
System.out.println(myVar3);
}
}
Output

public class Main {


public static void main(String[] args) {
char myVar1 = 65, myVar2 = 66, myVar3 = 67;
System.out.println(myVar1);
System.out.println(myVar2);
System.out.println(myVar3);
}
}

A
B
C

Tip: A list of all ASCII values can be found in our ASCII Table Reference.

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

System.out.println(greeting);

Try it Yourself »
public class Main {
public static void main(String[] args) {
String greeting = "Hello World";
System.out.println(greeting);
}
}
Output= Hello World

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 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 = '$';

// Print variables
System.out.println("Number of items: " + items);
System.out.println("Cost per item: " + costPerItem + currency);
System.out.println("Total cost = " + totalCost + currency);

Try it Yourself »
public class Main {
public static void main(String[] args) {
// Create variables of different data types
int items = 50;
float costPerItem = 9.99f;
float totalCost = items * costPerItem;
char currency = '$';

// Print variables
System.out.println("Number of items: " + items);
System.out.println("Cost per item: " + costPerItem + currency);
System.out.println("Total cost = " + totalCost + currency);
}
}
Output=
Number of items: 50
Cost per item: 9.99$
Total cost = 499.50$

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.

Java Type Casting

Type casting is when you assign a value of one primitive data type to another
type.

In Java, there are two types of casting:

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


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

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


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

Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:

Example
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Try it Yourself »
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt);
System.out.println(myDouble);
}
}
Output=
9
9.0

Narrowing Casting

Narrowing casting must be done manually by placing the type in


parentheses () in front of the value:

Example
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}
Try it Yourself »
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Explicit casting: double to int

System.out.println(myDouble);
System.out.println(myInt);
}
}
Output=
9.78
9

Real-Life Example
Here's a real-life example of type casting where we create a program to
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 percantage of the user's score in relation to the maximum


available score.
Convert userScore to float to make sure that the division is accurate */
float percentage = (float) userScore / maxScore * 100.0f;

System.out.println("User's percentage is " + percentage);

Try it Yourself »

public class Main {

public static void main(String[] args) {

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

int maxScore = 500;

// The actual score of the user

int userScore = 423;


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

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

float percentage = (float) userScore / maxScore * 100.0f;

// Print the result

System.out.println("User's percentage is " + percentage);

Output= User's percentage is 84.6

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;

Try it Yourself »
public class Main {
public static void main(String[] args) {
int x = 100 + 50;
System.out.println(x);
}
}output =150

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)

Try it Yourself »
public class Main {
public static void main(String[] args) {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
}
}
Output =
150
400
800

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


by 1

--X Decrement Decreases the value of a variable --X


by 1

Working Example

X+Y

public class Main {

public static void main(String[] args) {

int x = 5;

int y = 3;

System.out.println(x + y);

Output= 8

Working 2.

x–y

public class Main {

public static void main(String[] args) {


int x = 5;

int y = 3;

System.out.println(x - y);

Output= 2

Working 3. x * y

public class Main {

public static void main(String[] args) {

int x = 5;

int y = 3;

System.out.println(x * y);

Output = 15

Working 4.) x / y

public class Main {

public static void main(String[] args) {

int x = 12;

int y = 3;

System.out.println(x / y);

} output= 6
Working 5.) X % y

public class Main {

public static void main(String[] args) {

int x = 5;

int y = 2;

System.out.println(x % y);

} output 1

Working 6.) ++x

public class Main {

public static void main(String[] args) {

int x = 5;

++x;

System.out.println(x);

} output = 6

Working 7.) – -X

public class Main {

public static void main(String[] args) {

int x = 5;

--x;

System.out.println(x);

}
} output = 4

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;

Try it Yourself »

public class Main {


public static void main(String[] args) {
int x = 10;
System.out.println(x);
}
}
The addition assignment operator (+=) adds a value to a variable:
Example
int x = 10;
x += 5; output= 10

Try it Yourself »

public class Main {


public static void main(String[] args) {
int x = 10;
x += 5;
System.out.println(x);
}
} output=15
A list of all assignment operators:

Operator Example Same as

= X=5 X=5

+= X+=3 X = +3
- = X-=3 X = -3

*= X *=3 X =*3

/= X/=3 X=/3

%= X%=3 X=X%3

&= X&=3 X=& 3

|= X |=3 X = |3

^= X^= 3 X= ^3

>>= X>> 3 X=X>>3

<<= X<<=3 X=X<<3

Working Example

X=5

public class Main {

public static void main(String[] args) {

int x = 5;

System.out.println(x);

} output =5

Working example
+=

public class Main {

public static void main(String[] args) {

int x = 5;

x += 3;

System.out.println(x);

} output= 8

Working example

-=

public class Main {

public static void main(String[] args) {

int x = 5;

x -= 3;

System.out.println(x);

} output =2

Working example

*=

public class Main {

public static void main(String[] args) {

int x = 5;

x *= 3;
System.out.println(x);

} output= 15

Java 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. These values are known
as Boolean values, and you will learn more about them in
the Booleans and If..Else chapter.

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;
System.out.println(x > y); // returns true, because 5 is higher than 3

Try it Yourself »

public class Main {


public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x > y); // returns true, because 5 is higher than 3
}
} output= True

Operator Name Example


== 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
Working example
==
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x == y); // returns false because 5 is not equal to 3
}
} output =false

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

You might also like