Java
Java
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:
Java Syntax
public class Main {
System.out.println("Hello World");
}
}
Java Variables
Variables are containers for storing data values.
2,147,483,647
to 9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers.
Widening Casting
public class Main {
int myInt = 9;
System.out.println(myDouble);
Narrowing Casting
public class Main {
System.out.println(myDouble);
System.out.println(myInt);
Java Operators
Operators are used to perform operations on variables and values.
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
Example
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 {
int x = 10;
x += 5;
System.out.println(x);
Example
= 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
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;
== Equal to x == y
!= Not equal x != y
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 1
true
Example
public class Main {
int x = 5;
Java Strings
Strings are used for storing text.
Example
System.out.println(greeting);
}
}
String Length
Example
1)public class Main {
public static void main(String[] args) {
System.out.println(txt.toLowerCase());
}
}
System.out.println(txt.indexOf("locate"));
}
}
String Concatenation
The + operator can be used between strings to combine them. This is
called concatenation:
Example
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:
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:
Math.sqrt(x)
The Math.sqrt(x) method returns the square root of x:
Math.abs(x)
The Math.abs(x) method returns the absolute (positive) value of x:
System.out.println(Math.abs(-4.7));
Random Numbers
Math.random() returns a random number between 0.0 (inclusive), and 1.0
(exclusive):
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:
System.out.println(isJavaFun);
System.out.println(isFishTasty);
}
}
The if Statement
public class Main {
}
}
}
} else {
System.out.println("Good evening.");
System.out.println("Good morning.");
} else if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
String result;
}
}
Java Switch
Instead of writing many if..else statements, you can use
the switch statement.
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 {
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:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
int i = 0;
do {
System.out.println(i);
i++;
}
}
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested
loop.
// Outer loop.
// Inner loop
for (int j = 1; j <= 3; j++) {
}
}
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through
elements in an array:
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.
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.
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.
System.out.println(cars[0]);
}
}
cars[0] = "Opel";
System.out.println(cars[0]);
}
}
Array Length
public class Main {
public static void main(String[] args) {
System.out.println(cars.length);
}
}
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 {
System.out.println(myNumbers[1][2]);
myNumbers[1][2] = 9;
}
}
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.
myMethod();
myMethod();
myMethod();
}
}
myMethod("Jenny");
myMethod("Anja");
}
}
Multiple Parameters
public class Main {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
Return Values
1) public class Main {
return 5 + x;
System.out.println(myMethod(3));
}
}
System.out.println(myMethod(5, 3));
}
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:
return x + y;
}
static double plusMethodDouble(double x, double y) {
return x + y;
return x + y;
}
return x + y;
}
public static void main(String[] args) {
Java Scope
In Java, variables are only accessible inside the region they are created. This
is called scope.
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 {}.
{ // This is a block
int x = 100;
System.out.println(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.
System.out.println(result);
}
} else {
return 0;
}
}
System.out.println(result);
}
public static int sum(int start, int end) {
} else {
return end;
}
}
Java OOP
OOP stands for 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.
int x = 5;
System.out.println(myObj.x);
}
}
int x = 5;
System.out.println(myObj1.x);
System.out.println(myObj2.x);
int x = 5;
System.out.println(myObj.x);
}
}
2)public class Main {
int x = 10;
System.out.println(myObj.x);
}
int x = 5;
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
System.out.println("Hello World!");
}
public static void main(String[] args) {
myMethod();
// Static method
// Public method
// Main method
public static void main(String[] args) {
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.
int x;
public Main() {
x = 5;
}
System.out.println(myObj.x);
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
int x;
public Main(int y) {
x = y;
System.out.println(myObj.x);
2) //filename: Main.java
int modelYear;
String modelName;
modelYear = year;
modelName = name;
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.
Access Modifiers
Modifier Description
public The class is accessible by any other class
Non-Access Modifiers
Modifier Description
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
transient Attributes and methods are skipped when serializing the object
containing them
synchronized Methods can only be accessed by one thread at a time
Static
public class Main {
// Static method
// Public method
// Main method
}
Abstract
// abstract class
abstract class Main {
public String fname = "John";
public void study() { // the body of the abstract method is provided here
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is
hidden from users. To achieve this, you must:
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;
}
}
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 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:
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
Example:
class Vehicle {
System.out.println("Tuut, tuut!");
myFastCar.honk();
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many
classes that are related to each other by inheritance.
Example:
class Animal {
class Main {
public static void main(String[] args) {
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
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;
System.out.println(myInner.y + myOuter.x);
}
2) class OuterClass {
int x = 10;
int y = 5;
System.out.println(myInner.y);
3) class OuterClass {
int x = 10;
class InnerClass {
return x;
System.out.println(myInner.myInnerMethod());
}
Example:
// Abstract class
// Regular method
System.out.println("Zzz");
}
class Main {
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 {
System.out.println("Zzz");
class Main {
myPig.animalSound();
myPig.sleep();
}
2) interface FirstInterface {
interface SecondInterface {
System.out.println("Some text..");
class Main {
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
System.out.println(myVar);
2) enum Level {
LOW,
MEDIUM,
HIGH
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
System.out.println(myVar);
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
Example:
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
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
(HH-mm-ss-ns))
Example:
System.out.println(myObj);
System.out.println(myObj);
The table below shows the primitive type and the equivalent wrapper class:
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Example:
1) import java.util.ArrayList;
myNumbers.add(10);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(25);
System.out.println(i);
Integer myInt = 5;
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
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).
Example:
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
} finally {
} else {
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.
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:
Example:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
if(matchFound) {
System.out.println("Match found");
} else {
}
Flags
Flags in the compile() method change how the search is performed. Here are
a few of them:
Expression Description
[abc] Find one character from the options between the brackets
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
\d Find a digit
Quantifiers
Quantifiers define quantities:
Quantifier Description
n+ Matches any string that contains at least one n
Example:
interface StringFunction {
printFormatted("Hello", exclaim);
printFormatted("Hello", ask);
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.
Example:
Create a File
import java.io.File;
import java.io.IOException;
Read a File
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
Delete a File
import java.io.File;
Delete a Folder
import java.io.File;