Java notes 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 42

Java Notes Explained

Java is a widely-used programming language that has undergone significant evolution since its
inception. Here’s a brief history:

1. Origins (1991)
- Java was developed at Sun Microsystems by James Gosling and his team.
- Initially, it was called Oak, designed for interactive television. However, it was not adopted due
to the limitations of the technology at that time.

2. Renaming and Release (1995)


- The language was renamed Java after Java coffee, a type of coffee from Indonesia.
- Java 1.0 was officially released in May 1995, emphasizing portability across platforms through
the slogan "Write Once, Run Anywhere" (WORA).

3. The Rise of Java (Late 1990s)


- Java gained popularity for its use in web applications, especially with the introduction of Java
Applets.
- It became a standard for server-side applications with the development of Java 2 (released in
1998), which included the Java Foundation Classes (JFC).

4. Enterprise and Mobile Development (2000s)


- The early 2000s saw the emergence of Java EE (Enterprise Edition), which provided
specifications for enterprise-level applications.
- In 2004, Java 5 introduced major language enhancements like generics, annotations, and the
enhanced for-loop.

5. Open Source and Community (2006)


- Sun Microsystems released Java under an open-source license, leading to broader community
involvement.
- In 2010, Oracle Corporation acquired Sun Microsystems and took over the development of
Java.

6. Continuous Evolution (2010s-Present)


- Java has continued to evolve with regular updates. Notable versions include:
- Java 8 (2014): Introduced lambda expressions and the Stream API.
- Java 9 (2017): Modular system with the introduction of the Java Platform Module System
(JPMS).
- Java 11 (2018): Long-Term Support (LTS) version, with features like the HTTP Client API.
- Java 17 (2021): Another LTS version with new language features and performance
improvements.

7. Current State (2023)


- Java remains one of the most popular programming languages, used in various domains such
as web development, mobile applications (Android), enterprise applications, and large systems.
- The Java community continues to thrive, with an active ecosystem of libraries, frameworks
(like Spring and Hibernate), and tools (like Maven and Gradle).

Conclusion
Java's history reflects its adaptability and resilience, maintaining relevance in a rapidly changing
technology landscape. Its emphasis on portability, performance, and community support has
solidified its status as a cornerstone in modern software development.

Java Introduction
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 Getting Started
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");

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.

W3Schools' Java Editor


When learning Java at W3Schools.com, you can use our "Try it Yourself" tool,
which shows both the code and the result. It is used to write, run, and test code
right in your browser:

Main.java
public class Main {

public static void main(String[] args) {

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

Java Syntax
Java Syntax
In the previous chapter, we created a Java file called Main.java, and we used
the following code to print "Hello World" to the screen:

Main.java

public class Main {

public static void main(String[] args) {

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

Example explained
Every line of code that runs in Java must be inside a class. And the class name
should always start with an uppercase first letter. In our example, we named the
class Main.

Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.

The name of the java file must match the class name. When saving the file, save
it using the class name and add ".java" to the end of the filename. To run the
example above on your computer, make sure that Java is properly installed: 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");

Java Output / Print


❮ Previous
Next ❯

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

Get your own Java Server

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

Try it Yourself »

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 it Yourself »

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 »

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

Java Output Numbers


❮ Previous
Next ❯

Print Numbers
You can also use the println() method to print numbers.
However, unlike text, we don't put numbers inside double quotes:

Example

Get your own Java Server

System.out.println(3);

System.out.println(358);

System.out.println(50000);

Try it Yourself »

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

Example

System.out.println(3 + 3);

Example

System.out.println(2 * 5);

Java Comments
❮ Previous
Next ❯
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

Get your own Java Server

// This is a comment

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

Try it Yourself »

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 »

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

Java Variables
❮ Previous
Next ❯

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

Get your own Java Server

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 »

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 »

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 »

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 »

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 »

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


❮ Previous
Next ❯

Display Variables
The println() method is often used to display variables.
To combine both text and a variable, use the + character:

Example

Get your own Java Server

String name = "John";

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

Try it Yourself »

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 »

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 »

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


❮ Previous
Next ❯

Declare Many Variables


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

Example

Get 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 »

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);
Java Identifiers
❮ Previous
Next ❯

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

Get your own Java Server

// Good

int minutesPerHour = 60;

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

int m = 60;

Try it Yourself »
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

Java Variables - Examples


❮ Previous
Next ❯

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

Get your own Java Server

// 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 »

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

Java Data Types


❮ Previous
Next ❯

Java Data Types


As explained in the previous chapter, a variable in Java must be a specified data
type:

Example

Get your own Java Server

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 »

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 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 to 16 decimal digits

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values

Java Numbers
❮ Previous
Next ❯

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:

Example

Get your own Java Server

byte myNum = 100;

System.out.println(myNum);

Try it Yourself »

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

Example

short myNum = 5000;

System.out.println(myNum);
Try it Yourself »

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 »

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

Double Example

double myNum = 19.99d;

System.out.println(myNum);

Try it Yourself »

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

Java Boolean Data Types


❮ Previous
Next ❯

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

Get your own Java Server

boolean isJavaFun = true;

boolean isFishTasty = false;

System.out.println(isJavaFun); // Outputs true

System.out.println(isFishTasty); // Outputs false

Java Characters
❮ Previous
Next ❯

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

Get your own Java Server

char myGrade = 'B';

System.out.println(myGrade);
Try it Yourself »

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 »

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 »

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.

Java Data Types Example


❮ Previous
Next ❯

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

Get your own Java Server

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

Java Non-Primitive Data Types


❮ Previous
Next ❯

Non-Primitive Data Types


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

The main difference 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, wheras 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, wheras 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


❮ Previous
Next ❯
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

Get your own Java Server

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 »

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

Java Operators
❮ Previous
Next ❯
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

Get your own Java Server

int x = 100 + 50;

Try it Yourself »

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 »
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 x+y Try it »


values

- Subtraction Subtracts one value x-y Try it »


from another

* Multiplication Multiplies two values x*y Try it »

/ Division Divides one value by x/y Try it »


another

% Modulus Returns the division x%y Try it »


remainder
++ Increment Increases the value of a ++x Try it »
variable by 1

-- Decrement Decreases the value of --x Try it »


a variable by 1

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 »

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

Example

int x = 10;

x += 5;
Try it Yourself »

A list of all assignment operators:

Operator Example Same As Try it

= x=5 x=5 Try it »

+= x += 3 x=x+3 Try it »

-= x -= 3 x=x-3 Try it »

*= x *= 3 x=x*3 Try it »

/= x /= 3 x=x/3 Try it »

%= x %= 3 x=x%3 Try it »

&= x &= 3 x=x&3 Try it »

|= x |= 3 x=x|3 Try it »
^= x ^= 3 x=x^3 Try it »

>>= x >>= 3 x = x >> 3 Try it »

<<= x <<= 3 x = x << 3 Try it »

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 »
Operator Name Example Try it

== Equal to x == y Try it »

!= Not equal x != y Try it »

> Greater than x>y Try it »

< Less than x<y Try it »

>= Greater than or equal x >= y Try it »


to

<= Less than or equal to x <= y Try it »

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:

Operator Name Description Example Try it

&& Logical and Returns true if both x < 5 && x Try it »


statements are true < 10

|| Logical or Returns true if one of x < 5 || x < 4 Try it »


the statements is true

! Logical not Reverse the result, !(x < 5 && x


returns false if the < 10)
result is true

You might also like