Java Introduction
What is Java?
Java was originally developed by James Gosling at Sun
Microsystems. It was released in May 1995 as a core component of
Sun's Java platform.
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
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 Syntax
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
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
Java Data Types
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
to 9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers.
Sufficient for storing 6 to 7 decimal digits
Double 8 bytes Stores fractional numbers.
Sufficient for storing 15 decimal digits
Boolean 1 bit Stores true or false values
Char 2 bytes Stores a single character/letter or ASCII values
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
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);
Narrowing Casting
public class Main {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Explicit casting: double to int
System.out.println(myDouble);
System.out.println(myInt);
Java Operators
Operators are used to perform operations on variables and values.
Java divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator Name Description Example
+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x
Example
public class Main {
public static void main(String[] args) {
int x = 100 + 50;
System.out.println(x);
}
Java Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
Example
public class Main {
public static void main(String[] args) {
int x = 10;
x += 5;
System.out.println(x);
The addition assignment operator (+=) adds a value to a value.
Example
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
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
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
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
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
&& Logical and Returns true if both statements are true x < 5 && x < 10
|| Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 1
true
Example
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(!(x > 3 && x < 10)); // returns false because !
(not) is used to reverse the result
Java Strings
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double
quotes
Example
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
System.out.println(greeting);
}
}
String Length
Example
1)public class Main {
public static void main(String[] args) {
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " +
txt.length());
2) public class Main {
public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}
}
3) public class Main {
public static void main(String[] args) {
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate"));
}
}
String Concatenation
The + operator can be used between strings to combine them. This is
called concatenation:
Example
1)public class Main {
public static void main(String args[]) {
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
2) public class Main {
public static void main(String[] args) {
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));
Java Math
The Java Math class has many methods that allows you to perform
mathematical tasks on numbers.
Math.max(x,y)
The Math.max(x,y) method can be used to find the highest value of x and y:
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(5, 10));
}
}
Math.min(x,y)
The Math.min(x,y) method can be used to find the lowest value of x and y:
public class Main {
public static void main(String[] args) {
System.out.println(Math.min(5, 10));
}
Math.sqrt(x)
The Math.sqrt(x) method returns the square root of x:
public class Main {
public static void main(String[] args) {
System.out.println(Math.sqrt(64));
Math.abs(x)
The Math.abs(x) method returns the absolute (positive) value of x:
public class Main {
public static void main(String[] args) {
System.out.println(Math.abs(-4.7));
Random Numbers
Math.random() returns a random number between 0.0 (inclusive), and 1.0
(exclusive):
public class Main {
public static void main(String[] args) {
System.out.println(Math.random());
}
}
Java Booleans
Boolean Values
A boolean type is declared with the boolean keyword and can only take the
values true or false:
1)public class Main {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);
}
}
Java If ... Else
Java Conditions and If Statements
You already know that Java supports the usual logical conditions from
mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
The if Statement
public class Main {
public static void main(String[] args) {
if (20 > 18) {
System.out.println("20 is greater than 18"); // obviously
}
}
}
The else Statement
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
The else if Statement
public class Main {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
Short Hand If...Else
There is also a short-hand if else, which is known as the ternary
operator because it consists of three operands.
public class Main {
public static void main(String[] args) {
int time = 20;
String result;
result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);
}
}
Java Switch
Instead of writing many if..else statements, you can use
the switch statement.
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break and default keywords are optional, a
1)public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
}
2) public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
Java While Loop
The while loop loops through a block of code as long as a specified condition
is true:
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the
loop as long as the condition is true.
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
while (i < 5);
}
}
Java For Loop
When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested
loop.
public class Main {
public static void main(String[] args) {
// Outer loop.
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
}
}
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through
elements in an array:
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Java Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
}
}
Java Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
Java Arrays
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
To declare an array, define the variable type with square brackets:
Access the Elements of an Array
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
}
}
Change an Array Element
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
}
}
Array Length
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
Loop Through an Array
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
}
Loop Through an Array with For-Each
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Multidimensional Arrays
A multidimensional array is an array of arrays.
Multidimensional arrays are useful when you want to store data as a tabular
form, like a table with rows and columns.
To create a two-dimensional array, add each array within its own set of curly
braces:
Access Elements
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]);
Change Element Values
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7
}
}
Loop Through a Multi-Dimensional
Array
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
Java Methods
A method is a block of code which only runs when it is called.
Methods are used to perform certain actions, and they are also known
as functions.
1)public class Main {
static void myMethod() {
System.out.println("I just got executed!");
public static void main(String[] args) {
myMethod();
}
}
2) public class Main {
static void myMethod() {
System.out.println("I just got executed!");
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}
}
Java Method Parameters
Information can be passed to methods as parameter. Parameters act as
variables inside the method.
public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
Multiple Parameters
public class Main {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
Return Values
1) public class Main {
static int myMethod(int x) {
return 5 + x;
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}
2) public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
System.out.println(myMethod(5, 3));
A Method with If...Else
public class Main {
// Create a checkAge() method with an integer parameter called age
static void checkAge(int age) {
// If age is less than 18, print "access denied"
if (age < 18) {
System.out.println("Access denied - You are not old enough!");
// If age is greater than, or equal to, 18, print "access granted"
} else {
System.out.println("Access granted - You are old enough!");
}
public static void main(String[] args) {
checkAge(20); // Call the checkAge method and pass along an age of 20
}
}
Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:
1)public class Main {
static int plusMethodInt(int x, int y) {
return x + y;
}
static double plusMethodDouble(double x, double y) {
return x + y;
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
2) public class Main {
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
Java Scope
In Java, variables are only accessible inside the region they are created. This
is called scope.
public class Main {
public static void main(String[] args) {
// Code here cannot use x
int x = 100;
// Code here can use x
System.out.println(x);
Block Scope
A block of code refers to all of the code between curly braces {}.
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
{ // This is a block
// Code here CANNOT use x
int x = 100;
// Code here CAN use x
System.out.println(x);
} // The block ends here
// Code here CANNOT use x
}
}
Java Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems
which are easier to solve.
1)public class Main {
public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
2) public class Main {
public static void main(String[] args) {
int result = sum(5, 10);
System.out.println(result);
}
public static int sum(int start, int end) {
if (end > start) {
return end + sum(start, end - 1);
} else {
return end;
}
}
Java OOP
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that
perform operations on the data, while object-oriented programming is about
creating objects that contain both data and methods.
Object-oriented programming has several advantages over procedural
programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the Java code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug
OOP makes it possible to create full reusable applications with less
code and shorter development time
What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented
programming.
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its
attributes and methods.
1) public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
2) public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main();
Main myObj2 = new Main();
System.out.println(myObj1.x);
System.out.println(myObj2.x);
Java Class Attributes
1)public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
2)public class Main {
int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 25; // x is now 25
System.out.println(myObj.x);
}
3) public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main();
Main myObj2 = new Main();
myObj2.x = 25;
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
4) public class Main {
String fname = "John";
String lname = "Doe";
int age = 24;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Age: " + myObj.age);
}
}
Java Class Methods
public class Main {
static void myMethod() {
System.out.println("Hello World!");
}
public static void main(String[] args) {
myMethod();
Static vs. Public
static method, which means that it can be accessed without creating an
object of the class.
1)public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating
objects");
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
Main myObj = new Main(); // Create an object of MyClass
myObj.myPublicMethod(); // Call the public method
}
}
2) // Create a Main class
public class Main {
// Create a fullThrottle() method
public void fullThrottle() {
System.out.println("The car is going as fast as it can!");
// Create a speed() method and add a parameter
public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed);
// Inside main, call the methods on the myCar object
public static void main(String[] args) {
Main myCar = new Main(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
myCar.speed(200); // Call the speed() method
Java Constructors
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created.
// Create a Main class
public class Main {
int x;
// Create a class constructor for the Main class
public Main() {
x = 5;
}
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
1) public class Main {
int x;
public Main(int y) {
x = y;
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println(myObj.x);
2) //filename: Main.java
public class Main {
int modelYear;
String modelName;
public Main(int year, String name) {
modelYear = year;
modelName = name;
public static void main(String[] args) {
Main myCar = new Main(1969, "Mustang");
System.out.println(myCar.modelYear + " " + myCar.modelName);
Java Modifiers
The public keyword is an access modifier, meaning that it is used to set the
access level for classes, attributes, methods and constructors.
We divide modifiers into two groups:
Access Modifiers - controls the access level
Non-Access Modifiers - do not control access level, but provides
other functionality
Access Modifiers
Modifier Description
public The class is accessible by any other class
default The class is only accessible by classes in the same package.
This is used when you don't specify a modifier.
protected The code is accessible in the same package and subclasses.
Non-Access Modifiers
Modifier Description
final Attributes and methods cannot be overridden/modified
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on
methods. The method does not have a body,
for example abstract void run();.
The body is provided by the subclass (inherited from
transient Attributes and methods are skipped when serializing the object
containing them
synchronized Methods can only be accessed by one thread at a time
volatile The value of an attribute is not cached thread-locally,
and is always read from the "main memory"
Static
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating
objects");
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
Main myObj = new Main(); // Create an object of MyClass
myObj.myPublicMethod(); // Call the public method
}
Abstract
// abstract class
abstract class Main {
public String fname = "John";
public int age = 24;
public abstract void study(); // abstract method
}
// Subclass (inherit from Main)
class Student extends Main {
public int graduationYear = 2018;
public void study() { // the body of the abstract method is provided here
System.out.println("Studying all day long");
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is
hidden from users. To achieve this, you must:
declare class variables/attributes as private
provide public get and set methods to access and update the value of
a private variable
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John");
System.out.println(myObj.getName());
}
public class Person {
private String name;
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Java Packages & API
A package in Java is used to group related classes. Think of it as a folder in
a file directory. We use packages to avoid name conflicts, and to write a
better maintainable code. Packages are divided into two categories:
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included
in the Java Development Environment.
The library contains components for managing input, database programming,
and much much more. The complete list can be found at Oracles
website: https://docs.oracle.com/javase/8/docs/api/.
The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.
Example:
1)import java.util.Scanner; // import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
// Enter username and press Enter
System.out.println("Enter username");
userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
}
2) import java.util.*; // import the java.util package
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
// Enter username and press Enter
System.out.println("Enter username");
userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
}
Java Inheritance (Subclass and
Superclass)
In Java, it is possible to inherit attributes and methods from one class to
another. We group the "inheritance concept" into two categories:
subclass (child) - the class that inherits from another class
superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.
Example:
class Vehicle {
protected String brand = "Ford";
public void honk() {
System.out.println("Tuut, tuut!");
class Car extends Vehicle {
private String modelName = "Mustang";
public static void main(String[] args) {
Car myFastCar = new Car();
myFastCar.honk();
System.out.println(myFastCar.brand + " " + myFastCar.modelName);
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many
classes that are related to each other by inheritance.
Polymorphism uses those methods to perform different tasks. This allows
us to perform a single action in different ways.
Example:
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myPig = new Pig();
Animal myDog = new Dog();
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
Java Inner Classes
It is also possible to nest classes (a class within a class). The purpose of
nested classes is to group classes that belong together, which makes your
code more readable and maintainable.
To access the inner class, create an object of the outer class, and then create
an object of the inner class.
Example:
1)class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.y + myOuter.x);
}
2) class OuterClass {
int x = 10;
static class InnerClass {
int y = 5;
public class Main {
public static void main(String[] args) {
OuterClass.InnerClass myInner = new OuterClass.InnerClass();
System.out.println(myInner.y);
3) class OuterClass {
int x = 10;
class InnerClass {
public int myInnerMethod() {
return x;
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.myInnerMethod());
}
Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces.
The abstract keyword is a non-access modifier, used for classes and
methods:
Abstract class: is a restricted class that cannot be used to create
objects (to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does
not have a body. The body is provided by the subclass (inherited
from).
Example:
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
Interfaces
An interface is a completely "abstract class" that is used to group related
methods with empty bodies:
Example:
1)interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
class Pig implements Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
public void sleep() {
System.out.println("Zzz");
class Main {
public static void main(String[] args) {
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
2) interface FirstInterface {
public void myMethod(); // interface method
interface SecondInterface {
public void myOtherMethod(); // interface method
// DemoClass "implements" FirstInterface and SecondInterface
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
public void myOtherMethod() {
System.out.println("Some other text...");
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
Enums
An enum is a special "class" that represents a group
of constants (unchangeable variables, like final variables).
Example:
1) enum Level {
LOW,
MEDIUM,
HIGH
public class Main {
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(myVar);
2) enum Level {
LOW,
MEDIUM,
HIGH
public class Main {
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
switch(myVar) {
case LOW:
System.out.println("Low level");
break;
case MEDIUM:
System.out.println("Medium level");
break;
case HIGH:
System.out.println("High level");
break;
3) enum Level {
LOW,
MEDIUM,
HIGH
public class Main {
public static void main(String[] args) {
for (Level myVar : Level.values()) {
System.out.println(myVar);
Java User Input
The Scanner class is used to get user input, and it is found in
the java.util package.
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation.
Input Types
In the example above, we used the nextLine() method, which is used to read
Strings. To read other types, look at the table below:
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Example:
1)import java.util.Scanner; // import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
// Enter username and press Enter
System.out.println("Enter username");
userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
}
2) import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Java Dates
import the java.time package to work with the date and time API. The
package includes many date and time classes. For example:
Class Description
LocalDate Represents a date (year, month, day (yyyy-MM-dd))
LocalTime Represents a time (hour, minute, second and nanoseconds
(HH-mm-ss-ns))
LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)
DateTimeFormatter Formatter for displaying and parsing date-time objects
Example:
1) import java.time.LocalDate; // import the LocalDate class
public class Main {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // Create a date object
System.out.println(myObj); // Display the current date
2) import java.time.LocalTime; // import the LocalTime class
public class Main {
public static void main(String[] args) {
LocalTime myObj = LocalTime.now();
System.out.println(myObj);
3) import java.time.LocalDateTime; // import the LocalDateTime class
public class Main {
public static void main(String[] args) {
LocalDateTime myObj = LocalDateTime.now();
System.out.println(myObj);
4) import java.time.LocalDateTime; // Import the LocalDateTime class
import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class
public class Main {
public static void main(String[] args) {
LocalDateTime myDateObj = LocalDateTime.now();
System.out.println("Before formatting: " + myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDate = myDateObj.format(myFormatObj);
System.out.println("After formatting: " + formattedDate);
Java Wrapper Classes
Wrapper classes provide a way to use primitive data types ( int, boolean, etc..)
as objects.
The table below shows the primitive type and the equivalent wrapper class:
Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Example:
1) import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(10);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(25);
for (int i : myNumbers) {
System.out.println(i);
2) public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
3) public class Main {
public static void main(String[] args) {
Integer myInt = 100;
String myString = myInt.toString();
System.out.println(myString.length());
Java Exceptions
When executing Java code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error
message. The technical term for this is: Java will throw an exception (throw
an error).
Java try and catch
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
The catch statement allows you to define a block of code to be executed, if an
error occurs in the try block.
The try and catch keywords come in pairs:
Example:
1) public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
2) public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
3) public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old enough!");
public static void main(String[] args) {
checkAge(20);
}
What is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to
describe what you are searching for.
A regular expression can be a single character, or a more complicated
pattern.
Regular expressions can be used to perform all types of text
search and text replace operations.
Java does not have a built-in Regular Expression class, but we can import
the java.util.regex package to work with regular expressions. The package
includes the following classes:
Pattern Class - Defines a pattern (to be used in a search)
Matcher Class - Used to search for the pattern
PatternSyntaxException Class - Indicates syntax error in a regular
expression pattern
Example:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("Youtube", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit youtube!");
boolean matchFound = matcher.find();
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
Flags
Flags in the compile() method change how the search is performed. Here are
a few of them:
Pattern.CASE_INSENSITIVE - The case of letters will be ignored when
performing a search.
Pattern.LITERAL - Special characters in the pattern will not have any
special meaning and will be treated as ordinary characters when
performing a search.
Pattern.UNICODE_CASE - Use it together with
the CASE_INSENSITIVE flag to also ignore the case of letters outside of
the English alphabet
Regular Expression Patterns
The first parameter of the Pattern.compile() method is the pattern. It
describes what is being searched for.
Brackets are used to find a range of characters:
Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find one character NOT between the brackets
[0-9] Find one character from the range 0 to 9
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
| Find a match for any one of the patterns separated by | as in: ca
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \bWORD, or at
like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number
Quantifiers
Quantifiers define quantities:
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{x} Matches any string that contains a sequence of X n's
n{x,y} Matches any string that contains a sequence of X to Y n's
n{x,} Matches any string that contains a sequence of at least X n's
Java Lambda Expressions
Lambda Expressions were added in Java 8.
A lambda expression is a short block of code which takes in parameters and
returns a value. Lambda expressions are similar to methods, but they do not
need a name and they can be implemented right in the body of a method.
Example:
interface StringFunction {
String run(String str);
public class Main {
public static void main(String[] args) {
StringFunction exclaim = (s) -> s + "!";
StringFunction ask = (s) -> s + "?";
printFormatted("Hello", exclaim);
printFormatted("Hello", ask);
public static void printFormatted(String str, StringFunction format) {
String result = format.run(str);
System.out.println(result);
}
}
Java File
File handling is an important part of any application.
Java has several methods for creating, reading, updating, and deleting
files.
Java File Handling
The File class from the java.io package, allows us to work with files.
Method Type Description
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory
Example:
Create a File
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Write To a File
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun
enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Read a File
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Get File Information
import java.io.File;
public class GetFileInfo {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable: " + myObj.canRead());
System.out.println("File size in bytes: " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
Delete a File
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
Delete a Folder
import java.io.File;
public class DeleteFolder {
public static void main(String[] args) {
File myObj = new File("C:\\Users\\MyName\\Test");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}
}