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

Java Class Attributes

Uploaded by

farhadbks3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Java Class Attributes

Uploaded by

farhadbks3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

Java Class Attributes

In the previous chapter, we used the term "variable" for x in the example (as
shown below). It is actually an attribute of the class. Or you could say that class
attributes are variables within a class:

Create a class called "Main" with two attributes: x and y:

public class Main {


int x = 5;
int y = 3;}

Another term for class attributes is fields.

Accessing Attributes
You can access attributes by creating an object of the class, and by using the
dot syntax (.):

The following example will create an object of the Main class, with the name
myObj. We use the x attribute on the object to print its value:

Create an object called "myObj" and print the value of x:

public class Main {


int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}
}

Modify Attributes
You can also modify attribute values:
Set the value of x to 40:

public class Main {


int x;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 40;
System.out.println(myObj.x);
}
}

Or override existing values:

Change the value of x to 25:

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

If you don't want the ability to override existing values, declare the attribute as
final:

public class Main {


final int x = 10;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 25; // will generate an error: cannot assign a value to
a final variable
System.out.println(myObj.x);
}
}
The final keyword is useful when you want a variable to always store the same value,
like PI (3.14159...).

The final keyword is called a "modifier". You will learn more about these in the Java
Modifiers Chapter.

Multiple Objects
If you create multiple objects of one class, you can change the attribute values
in one object, without affecting the attribute values in the other:

Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:

public class Main {


int x = 5;

public static void main(String[] args) {


Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
myObj2.x = 25;
System.out.println(myObj1.x); // Outputs 5
System.out.println(myObj2.x); // Outputs 25
}
}

Multiple Attributes
You can specify as many attributes as you want:

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

The next chapter will teach you how to create class methods and how to access them
with objects.

Java Class Methods


You learned from the Java Methods chapter that methods are declared within a class, and
that they are used to perform certain actions:

Create a method named myMethod() in Main:

public class Main {


static void myMethod() {
System.out.println("Hello World!");
}
}

myMethod() prints a text (the action), when it is called. To call a method, write the
method's name followed by two parentheses () and a semicolon;

myMethod() prints a text (the action), when it is called. To call a method, write
the method's name followed by two parentheses () and a semicolon;

Inside main, call myMethod():

public class Main {

static void myMethod() {

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

}
public static void main(String[] args) {

myMethod();

// Outputs "Hello World!"

Static vs. Public


You will often see Java programs that have either static or public attributes
and methods.

In the example above, we created a static method, which means that it can
be accessed without creating an object of the class, unlike public, which can
only be accessed by objects:

An example to demonstrate the differences between static and public


methods:

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

// myPublicMethod(); This would compile an error

Main myObj = new Main(); // Create an object of Main

myObj.myPublicMethod(); // Call the public method on the object

Note: You will learn more about these keywords (called modifiers) in the Java Modifiers
chapter.

Access Methods With an Object


Create a Car object named myCar. Call the fullThrottle() and speed()
methods on the myCarobject, and run the program:

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

// The car is going as fast as it can!

// Max speed is: 200


Example explained
1) We created a custom Main class with the class keyword.

2) We created the fullThrottle() and speed() methods in the Main class.

3) The fullThrottle() method and the speed() method will print out some
text, when they are called.

4) The speed() method accepts an int parameter called maxSpeed - we will


use this in 8).

5) In order to use the Main class and its methods, we need to create an object
of the Main Class.

6) Then, go to the main() method, which you know by now is a built-in Java
method that runs your program (any code inside main is executed).

7) By using the new keyword we created an object with the name myCar.

8) Then, we call the fullThrottle() and speed() methods on the myCar


object, and run the program using the name of the object (myCar), followed by
a dot (.), followed by the name of the method (fullThrottle(); and
speed(200);). Notice that we add an int parameter of 200 inside the speed()
method.

Remember that..

The dot (.) is used to access the object's attributes and methods.

To call a method in Java, write the method name followed by a set of parentheses (),
followed by a semicolon (;).

A class must have a matching filename (Main and Main.java).


Using Multiple Classes
Like we specified in the Classes chapter, it is a good practice to create an object
of a class and access it in another class.

Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory:

● Main.java
● Second.java

Main.java

public class Main {

public void fullThrottle() {

System.out.println("The car is going as fast as it can!");

public void speed(int maxSpeed) {

System.out.println("Max speed is: " + maxSpeed);

Second.java

class Second {

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

When both files have been compiled:

C:\Users\Your Name>javac Main.java

C:\Users\Your Name>javac Second.java

Run the Second.java file:

C:\Users\Your Name>java Second

And the output will be:

The car is going as fast as it can!

Max speed is: 200


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. It can be used to set
initial values for object attributes:

Get your own Java ServerCreate a constructor:

// Create a Main class

public class Main {

int x; // Create a class attribute

// Create a class constructor for the Main class

public Main() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

Main myObj = new Main(); // Create an object of class Main (This


will call the constructor)

System.out.println(myObj.x); // Print the value of x

// Outputs 5
Note that the constructor name must match the class name, and it cannot have a return
type (like void).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial values
for object attributes.

Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the
constructor we set x to y (x=y). When we call the constructor, we pass a
parameter to the constructor (5), which will set the value of x to 5:

Example

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

// Outputs 5

You can have as many parameters as you want:

Example

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

// Outputs 1969 Mustang

Modifiers

By now, you are quite familiar with the public keyword that appears in almost all of our
examples:

public class Main


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

For classes, you can use either public or default:

Modifier Description Try it

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.
You will learn more about packages in the Packages
chapter

For attributes, methods and constructors, you can use the one of the following:
Modifier Description Try it

public The code is accessible for all classes

private The code is only accessible within the declared class

default The code is only accessible in the same package. This is


used when you don't specify a modifier. You will learn
more about packages in the Packages chapter

protected The code is accessible in the same package and


subclasses. You will learn more about subclasses and
superclasses in the Inheritance chapter
Non-Access Modifiers

For classes, you can use either final or abstract:

Modifier Description Try it

final The class cannot be inherited by other classes (You will


learn more about inheritance in the Inheritance chapter)

abstract The class cannot be used to create objects (To access


an abstract class, it must be inherited from another class.
You will learn more about inheritance and abstraction in
the Inheritance and Abstraction chapters)
For attributes and methods, you can use the one of the following:

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).
You will learn more about inheritance and abstraction in the
Inheritance and Abstraction chapters

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"

Final

If you don't want the ability to override existing attribute values, declare attributes as
final:

public class Main {

final int x = 10;

final double PI = 3.14;


public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 50; // will generate an error: cannot assign a value to


a final variable

myObj.PI = 25; // will generate an error: cannot assign a value


to a final variable

System.out.println(myObj.x);

Static

A static method means that it can be accessed without creating an object of the class,
unlike public:

An example to demonstrate the differences between static and public methods:

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

// myPublicMethod(); This would output an error

Main myObj = new Main(); // Create an object of Main

myObj.myPublicMethod(); // Call the public method

}
Abstract

An abstract method belongs to an abstract class, and it does not have a body. The
body is provided by the subclass:

// Code from filename: Main.java

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


}

// End code from filename: Main.java

// Code from filename: Second.java

class Second {

public static void main(String[] args) {

// create an object of the Student class (which inherits


attributes and methods from Main)

Student myObj = new Student();

System.out.println("Name: " + myObj.fname);

System.out.println("Age: " + myObj.age);

System.out.println("Graduation Year: " + myObj.graduationYear);

myObj.study(); // call abstract method

}
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

Get and Set


You learned from the previous chapter that private variables can only be
accessed within the same class (an outside class has no access to it). However,
it is possible to access them if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.

Syntax for both is that they start with either get or set, followed by the name
of the variable, with the first letter in upper case:

public class Person {

private String name; // private = restricted access

// Getter
public String getName() {
return name;
}

// Setter
public void setName(String newName) {
this.name = newName;
}
}

Example explained

The get method returns the value of the variable name.


The set method takes a parameter (newName) and assigns it to the name
variable. The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it from


outside this class:

Example

public class Main {


public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John"; // error
System.out.println(myObj.name); // error
}
}

If the variable was declared as public, we would expect the following output:

John

However, as we try to access a private variable, we get an error:

MyClass.java:4: error: name has private access in Person

myObj.name = "John";

MyClass.java:5: error: name has private access in Person


System.out.println(myObj.name);

2 errors

Instead, we use the getName() and setName() methods to access and update
the variable:

Example

public class Main {


public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to
"John"
System.out.println(myObj.getName());
}
}

// Outputs "John"

Why Encapsulation?
● Better control of class attributes and methods
● Class attributes can be made read-only (if you only use the get method),
or write-only (if you only use the set method)
● Flexible: the programmer can change one part of the code without
affecting other parts
● Increased security of data

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.

To use a class or a package from the library, you need to use the import
keyword:

Syntax

Get your own Java Server

import package.name.Class; // Import a single class

import package.name.*; // Import the whole package


Import a Class
If you find a class you want to use, for example, the Scanner class, which is
used to get user input, write the following code:

Example

import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of 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. In our example,
we will use the nextLine() method, which is used to read a complete line:

Example

Using the Scanner class to get user input:

import java.util.Scanner;

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter username");
String userName = myObj.nextLine();

System.out.println("Username is: " + userName);

Import a Package
There are many packages to choose from. In the previous example, we used the
Scanner class from the java.util package. This package also contains date
and time facilities, random-number generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign (*). The
following example will import ALL the classes in the java.util package:

Example

import java.util.*;

User-defined Packages
To create your own package, you need to understand that Java uses a file
system directory to store them. Just like folders on your computer:

Example

└── root

└── mypack
└── MyPackageClass.java

To create a package, use the package keyword:

MyPackageClass.java

package mypack;

class MyPackageClass {

public static void main(String[] args) {

System.out.println("This is my package!");

Save the file as MyPackageClass.java, and compile it:

C:\Users\Your Name>javac MyPackageClass.java

Then compile the package:

C:\Users\Your Name>javac -d . MyPackageClass.java

This forces the compiler to create the "mypack" package.


The -d keyword specifies the destination for where to save the class file. You can use
any directory name, like c:/user (windows), or, if you want to keep the package within
the same directory, you can use the dot sign ".", like in the example above.

Note: The package name should be written in lower case to avoid conflict with class
names.

When we compiled the package in the example above, a new folder was
created, called "mypack".

To run the MyPackageClass.java file, write the following:

C:\Users\Your Name>java mypack.MyPackageClass

The output will be:

This is my package!

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.

In the example below, the Car class (subclass) inherits the attributes and
methods from the Vehicleclass (superclass):
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {

// Create a myCar object


Car myCar = new Car();

// Call the honk() method (from the Vehicle class) on the myCar
object
myCar.honk();

// Display the value of the brand attribute (from the Vehicle


class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}

Did you notice the protected modifier in Vehicle?

We set the brand attribute in Vehicle to a protected access modifier. If it was set to
private, the Car class would not be able to access it.

Why And When To Use "Inheritance"?

- It is useful for code reusability: reuse attributes and methods of an existing class when
you create a new class.

Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods
to perform different tasks.
ADVERTISEMENT

The final Keyword


If you don't want other classes to inherit from a class, use the final keyword:

If you try to access a final class, Java will generate an error:

final class Vehicle {


...
}

class Car extends Vehicle {


...
}

The output will be something like this:

Main.java:9: error: cannot inherit from final Vehicle

class Main extends Vehicle {

1 error)

Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit attributes
and methods from another class. Polymorphism uses those methods to perform
different tasks. This allows us to perform a single action in different ways.

For example, think of a superclass called Animal that has a method called
animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And
they also have their own implementation of an animal sound (the pig oinks, and
the cat meows, etc.):

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

Remember from the Inheritance chapter that we use the extends keyword to inherit
from a class.

Now we can create Pig and Dog objects and call the animalSound() method on
both of them:

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(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}

Why And When To Use "Inheritance" and "Polymorphism"?

- It is useful for code reusability: reuse attributes and methods of an existing class when
you create a new class.

Java Inner Classes


In Java, 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

Get your own Java Server

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

// Outputs 15 (5 + 10)

Private Inner Class


Unlike a "regular" class, an inner class can be private or protected. If you don't want
outside objects to access the inner class, declare the class as private:

Example

class OuterClass {
int x = 10;

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

If you try to access a private inner class from an outside class, an error occurs:

Main.java:13: error: OuterClass.InnerClass has private access in


OuterClass

OuterClass.InnerClass myInner = myOuter.new InnerClass();


^

Static Inner Class


An inner class can also be static, which means that you can access it without creating an
object of the outer class:

Example

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

// Outputs 5

Note: just like static attributes and methods, a static inner class does not have access to
members of the outer class.

Access Outer Class From Inner Class


One advantage of inner classes, is that they can access attributes and methods of the outer
class:

Example
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());
}
}

// Outputs 10

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 (which you
will learn more about in the next chapter).

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).
An abstract class can have both abstract and regular methods:

abstract class Animal {


public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}

From the example above, it is not possible to create an object of the Animal
class:

Animal myObj = new Animal(); // will generate an error

To access the abstract class, it must be inherited from another class. Let's
convert the Animal class we used in the Polymorphism chapter to an abstract
class:
Remember from the Inheritance chapter that we use the extends keyword to inherit
from a class.

Example

Get your own Java Server

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

Why And When To Use Abstract Classes and Methods?

To achieve security - hide certain details and only show the important details of an
object.
Note: Abstraction can also be achieved with Interfaces, which you will learn more about
in the next chapter.

Interfaces
Another way to achieve abstraction in Java, is with interfaces.

An interface is a completely "abstract class" that is used to group related


methods with empty bodies:

Example

Get your own Java Server

// interface
interface Animal {
public void animalSound(); // interface method (does not have a
body)
public void run(); // interface method (does not have a body)
}

To access the interface methods, the interface must be "implemented" (kinda


like inherited) by another class with the implements keyword (instead of
extends). The body of the interface method is provided by the "implement"
class:
Example

// Interface
interface Animal {
public void animalSound(); // interface method (does not have a
body)
public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Notes on Interfaces:

● Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass)
● Interface methods do not have a body - the body is provided by the "implement"
class
● On implementation of an interface, you must override all of its methods
● Interface methods are by default abstract and public
● Interface attributes are by default public, static and final
● An interface cannot contain a constructor (as it cannot be used to create objects)

Why And When To Use Interfaces?

1) To achieve security - hide certain details and only show the important details of an
object (interface).

2) Java does not support "multiple inheritance" (a class can only inherit from one
superclass). However, it can be achieved with interfaces, because the class can
implement multiple interfaces. Note: To implement multiple interfaces, separate them
with a comma (see example below).

Multiple Interfaces
To implement multiple interfaces, separate them with a comma:

Example

interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}

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

To create an enum, use the enum keyword (instead of class or interface), and
separate the constants with a comma. Note that they should be in uppercase
letters:

Example

Get your own Java Server

enum Level {
LOW,
MEDIUM,
HIGH
}

You can access enum constants with the dot syntax:

Level myVar = Level.MEDIUM;

Enum is short for "enumerations", which means "specifically listed".

Enum inside a Class


You can also have an enum inside a class:

Example

public class Main {


enum Level {
LOW,
MEDIUM,
HIGH
}

public static void main(String[] args) {


Level myVar = Level.MEDIUM;
System.out.println(myVar);
}
}

The output will be:

MEDIUM
Enum in a Switch Statement
Enums are often used in switch statements to check for corresponding values:

Example

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

The output will be:

Medium level
Loop Through an Enum
The enum type has a values() method, which returns an array of all enum
constants. This method is useful when you want to loop through the constants
of an enum:

Example

for (Level myVar : Level.values()) {


System.out.println(myVar);
}

The output will be:

LOW

MEDIUM

HIGH

Difference between Enums and Classes

An enum can, just like a class, have attributes and methods. The only difference is that
enum constants are public, static and final (unchangeable - cannot be overridden).

An enum cannot be used to create objects, and it cannot extend other classes (but it can
implement interfaces).
Why And When To Use Enums?

Use enums when you have values that you know aren't going to change, like month
days, days, colors, deck of cards, etc.

Java Dates
Java does not have a built-in Date class, but we can 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)

DateTimeFormatt Formatter for displaying and parsing date-time objects


er

If you don't know what a package is, read our Java Packages Tutorial.

Display Current Date


To display the current date, import the java.time.LocalDate class, and use its now()
method:

Example
Get your own Java Server

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

The output will be:

2024-06-12

Display Current Time


To display the current time (hour, minute, second, and nanoseconds), import the
java.time.LocalTimeclass, and use its now() method:

Example

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

The output will be:


20:36:11.178692

ADVERTISEMENT

Display Current Date and Time


To display the current date and time, import the java.time.LocalDateTime class, and
use its now()method:

Example

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

The output will be:

2024-06-12T20:36:11.178932

Formatting Date and Time


The "T" in the example above is used to separate the date from the time. You can use the
DateTimeFormatter class with the ofPattern() method in the same package to
format or parse date-time objects. The following example will remove both the "T" and
nanoseconds from the date-time:

Example

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

The output will be:

Before Formatting: 2024-06-12T20:36:11.178965

After Formatting: 12-06-2024 20:36:11

The ofPattern() method accepts all sorts of values, if you want to display the date and
time in a different format. For example:

Value Example Tryit

yyyy-MM-dd "1988-09-29"
dd/MM/yyyy "29/09/1988"

dd-MMM-yyyy "29-Sep-1988"

E, MMM dd yyyy "Thu, Sep 29 1988"

Java ArrayList
The ArrayList class is a resizable array, which can be found in the java.util
package.

The difference between a built-in array and an ArrayList in Java, is that the size of an
array cannot be modified (if you want to add or remove elements to/from an array, you have
to create a new one). While elements can be added and removed from an ArrayList
whenever you want. The syntax is also slightly different:

Example

Get your own Java Server

Create an ArrayList object called cars that will store strings:

import java.util.ArrayList; // import the ArrayList class

ArrayList<String> cars = new ArrayList<String>(); // Create an


ArrayList object

If you don't know what a package is, read our Java Packages Tutorial.
Add Items
The ArrayList class has many useful methods. For example, to add elements to the list,
use the add()method:

Example

import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}

You can also add an item at a specified position by referring to the index number:

Example

import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add(0, "Mazda"); // Insert element at the beginning of the
list (0)

System.out.println(cars);
}

Remember: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Access an Item
To access an element in the ArrayList, use the get() method and refer to the index
number:

Example

cars.get(0);

ADVERTISEMENT

Change an Item
To modify an element, use the set() method and refer to the index number:

Example
cars.set(0, "Opel");

Remove an Item
To remove an element, use the remove() method and refer to the index number:

Example

cars.remove(0);

To remove all the elements in the ArrayList, use the clear() method:

Example

cars.clear();

ArrayList Size
To find out how many elements an ArrayList have, use the size method:
Example

cars.size();

Loop Through an ArrayList


Loop through the elements of an ArrayList with a for loop, and use the size()
method to specify how many times the loop should run:

Example

public class Main {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for (int i = 0; i < cars.size(); i++) {
System.out.println(cars.get(i));
}
}
}

You can also loop through an ArrayList with the for-each loop:

Example

public class Main {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for (String i : cars) {
System.out.println(i);
}
}
}

Other Types
Elements in an ArrayList are actually objects. In the examples above, we created elements
(objects) of type "String". Remember that a String in Java is an object (not a primitive type).
To use other types, such as int, you must specify an equivalent wrapper class: Integer.
For other primitive types, use: Booleanfor boolean, Character for char, Double for
double, etc:

Example

Create an ArrayList to store numbers (add elements of type Integer):

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);
}
}
}
Sort an ArrayList
Another useful class in the java.util package is the Collections class, which include
the sort()method for sorting lists alphabetically or numerically:

Example

Sort an ArrayList of Strings:

import java.util.ArrayList;
import java.util.Collections; // Import the Collections class

public class Main {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Collections.sort(cars); // Sort cars
for (String i : cars) {
System.out.println(i);
}
}
}

Example

Sort an ArrayList of Integers:

import java.util.ArrayList;
import java.util.Collections; // Import the Collections class

public class Main {


public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
myNumbers.add(12);

Collections.sort(myNumbers); // Sort myNumbers

for (int i : myNumbers) {


System.out.println(i);
}
}
}

Java LinkedList
In the previous chapter, you learned about the ArrayList class. The LinkedList class
is almost identical to the ArrayList:

Example

Get your own Java Server

// Import the LinkedList class


import java.util.LinkedList;

public class Main {


public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}

ArrayList vs. LinkedList


The LinkedList class is a collection which can contain many objects of the same type,
just like the ArrayList.

The LinkedList class has all of the same methods as the ArrayList class because
they both implement the List interface. This means that you can add items, change items,
remove items and clear the list in the same way.

However, while the ArrayList class and the LinkedList class can be used in the
same way, they are built very differently.

How the ArrayList works


The ArrayList class has a regular array inside it. When an element is added, it is placed
into the array. If the array is not big enough, a new, larger array is created to replace the old
one and the old one is removed.

How the LinkedList works


The LinkedList stores its items in "containers." The list has a link to the first container
and each container has a link to the next container in the list. To add an element to the list,
the element is placed into a new container and that container is linked to one of the other
containers in the list.
When To Use

Use an ArrayList for storing and accessing data, and LinkedList to manipulate data.

LinkedList Methods
For many cases, the ArrayList is more efficient as it is common to need access to
random items in the list, but the LinkedList provides several methods to do certain
operations more efficiently:

Method Description Try it

addFirst() Adds an item to the beginning of the list

addLast() Add an item to the end of the list

removeFirst() Remove an item from the beginning of the list

removeLast() Remove an item from the end of the list

getFirst() Get the item at the beginning of the list

getLast() Get the item at the end of the list


Java HashMap
In the ArrayList chapter, you learned that Arrays store items as an ordered
collection, and you have to access them with an index number (int type). A
HashMap however, store items in "key/value" pairs, and you can access them by
an index of another type (e.g. a String).

One object is used as a key (index) to another object (value). It can store
different types: String keys and Integer values, or the same type, like:
String keys and String values:

Example

Get your own Java Server

Create a HashMap object called capitalCities that will store String keys and String
values:

import java.util.HashMap; // import the HashMap class

HashMap<String, String> capitalCities = new HashMap<String,


String>();

Add Items
The HashMap class has many useful methods. For example, to add items to it,
use the put() method:
Example

// Import the HashMap class


import java.util.HashMap;

public class Main {


public static void main(String[] args) {
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String,
String>();

// Add keys and values (Country, City)


capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("Norway", "Oslo");
capitalCities.put("USA", "Washington DC");
System.out.println(capitalCities);
}
}

Access an Item
To access a value in the HashMap, use the get() method and refer to its key:

Example

capitalCities.get("England");
Remove an Item
To remove an item, use the remove() method and refer to the key:

Example

capitalCities.remove("England");

To remove all items, use the clear() method:

Example

capitalCities.clear();

ADVERTISEMENT

HashMap Size
To find out how many items there are, use the size() method:

Example

capitalCities.size();
Loop Through a HashMap
Loop through the items of a HashMap with a for-each loop.

Note: Use the keySet() method if you only want the keys, and use the
values() method if you only want the values:

Example

// Print keys
for (String i : capitalCities.keySet()) {
System.out.println(i);
}

Example

// Print values
for (String i : capitalCities.values()) {
System.out.println(i);
}

Example
// Print keys and values
for (String i : capitalCities.keySet()) {
System.out.println("key: " + i + " value: " +
capitalCities.get(i));
}

Other Types
Keys and values in a HashMap are actually objects. In the examples above, we
used objects of type "String". Remember that a String in Java is an object (not
a primitive type). To use other types, such as int, you must specify an
equivalent wrapper class: Integer. For other primitive types, use: Boolean for
boolean, Character for char, Double for double, etc:

Example

Create a HashMap object called people that will store String keys and Integer
values:

// Import the HashMap class


import java.util.HashMap;

public class Main {


public static void main(String[] args) {

// Create a HashMap object called people


HashMap<String, Integer> people = new HashMap<String, Integer>();

// Add keys and values (Name, Age)


people.put("John", 32);
people.put("Steve", 30);
people.put("Angie", 33);

for (String i : people.keySet()) {


System.out.println("key: " + i + " value: " + people.get(i));
}
}
}

Java HashSet
A HashSet is a collection of items where every item is unique, and it is found in
the java.util package:

Example

Get your own Java Server

Create a HashSet object called cars that will store strings:

import java.util.HashSet; // Import the HashSet class

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

Add Items
The HashSet class has many useful methods. For example, to add items to it,
use the add() method:

Example
// Import the HashSet class
import java.util.HashSet;

public class Main {


public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("BMW");
cars.add("Mazda");
System.out.println(cars);
}
}

Note: In the example above, even though BMW is added twice it only appears
once in the set because every item in a set has to be unique.

Check If an Item Exists


To check whether an item exists in a HashSet, use the contains() method:

Example

cars.contains("Mazda");

Remove an Item
To remove an item, use the remove() method:

Example

cars.remove("Volvo");

To remove all items, use the clear() method:

Example

cars.clear();

ADVERTISEMENT

HashSet Size
To find out how many items there are, use the size method:

Example

cars.size();
Loop Through a HashSet
Loop through the items of an HashSet with a for-each loop:

Example

for (String i : cars) {


System.out.println(i);

Other Types
Items in an HashSet are actually objects. In the examples above, we created
items (objects) of type "String". Remember that a String in Java is an object
(not a primitive type). To use other types, such as int, you must specify an
equivalent wrapper class: Integer. For other primitive types, use: Boolean for
boolean, Character for char, Double for double, etc:

Example

Use a HashSet that stores Integer objects:

import java.util.HashSet;

public class Main {


public static void main(String[] args) {

// Create a HashSet object called numbers


HashSet<Integer> numbers = new HashSet<Integer>();

// Add values to the set


numbers.add(4);
numbers.add(7);
numbers.add(8);

// Show which numbers between 1 and 10 are in the set


for(int i = 1; i <= 10; i++) {
if(numbers.contains(i)) {
System.out.println(i + " was found in the set.");
} else {
System.out.println(i + " was not found in the set.");
}
}
}
}

Java Iterator
An Iterator is an object that can be used to loop through collections, like
ArrayList and HashSet. It is called an "iterator" because "iterating" is the
technical term for looping.

To use an Iterator, you must import it from the java.util package.

Getting an Iterator
The iterator() method can be used to get an Iterator for any collection:

// Import the ArrayList class and the Iterator class


import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {

// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");

// Get the iterator


Iterator<String> it = cars.iterator();

// Print the first item


System.out.println(it.next());
}
}

Looping Through a Collection


To loop through a collection, use the hasNext() and next() methods of the
Iterator:

Example

while(it.hasNext()) {
System.out.println(it.next());

ADVERTISEMENT

Removing Items from a Collection


Iterators are designed to easily change the collections that they loop through.
The remove() method can remove items from a collection while looping.

Example

Use an iterator to remove numbers less than 10 from a collection:

import java.util.ArrayList;
import java.util.Iterator;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(12);
numbers.add(8);
numbers.add(2);
numbers.add(23);
Iterator<Integer> it = numbers.iterator();
while(it.hasNext()) {
Integer i = it.next();
if(i < 10) {
it.remove();
}
}
System.out.println(numbers);
}

Note: Trying to remove items using a for loop or a for-each loop would not work
correctly because the collection is changing size at the same time that the code is trying
to loop.
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

Sometimes you must use wrapper classes, for example when working with
Collection objects, such as ArrayList, where primitive types cannot be used
(the list can only store objects):

Example

Get your own Java Server

ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid

ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid

Creating Wrapper Objects


To create a wrapper object, use the wrapper class instead of the primitive type.
To get the value, you can just print the object:

Example

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

ADVERTISEMENT

Since you're now working with objects, you can use certain methods to get
information about the specific object.

For example, the following methods are used to get the value associated with
the corresponding wrapper object: intValue(), byteValue(), shortValue(),
longValue(), floatValue(), doubleValue(), charValue(),
booleanValue().

This example will output the same result as the example above:

Example

public class Main {


public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}
}
Another useful method is the toString() method, which is used to convert
wrapper objects to strings.

In the following example, we convert an Integer to a String, and use the


length() method of the String class to output the length of the "string":

Example

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:

Syntax

Get your own Java Server

try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

Consider the following example:

This will generate an error, because myNumbers[10] does not exist.

public class Main {


public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
The output will be something like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10

at Main.main(Main.java:4)

Note: ArrayIndexOutOfBoundsException occurs when you try to access an index


number that does not exist.

If an error occurs, we can use try...catch to catch the error and execute
some code to handle it:

Example

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.");
}
}
}
The output will be:

Something went wrong.

Finally
The finally statement lets you execute code, after try...catch, regardless
of the result:

Example

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.");
}
}
}
The output will be:

Something went wrong.

The 'try catch' is finished.

ADVERTISEMENT

The throw keyword


The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many
exception types available in Java: ArithmeticException,
FileNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc:

Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older,


print "Access granted":

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(15); // Set age to 15 (which is below 18...)
}
}

The output will be:

Exception in thread "main" java.lang.ArithmeticException: Access denied -


You must be at least 18 years old.

at Main.checkAge(Main.java:4)

at Main.main(Main.java:12)

If age was 20, you would not get an exception:

Example

checkAge(20);

The output will be:

Access granted - You are old enough!

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

Get your own Java Server

Find out if there are any occurrences of the word "w3schools" in a sentence:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {


public static void main(String[] args) {
Pattern pattern = Pattern.compile("w3schools",
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit W3Schools!");
boolean matchFound = matcher.find();
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
// Outputs Match found
Example Explained
In this example, The word "w3schools" is being searched for in a sentence.

First, the pattern is created using the Pattern.compile() method. The first parameter
indicates which pattern is being searched for and the second parameter has a flag to
indicates that the search should be case-insensitive. The second parameter is optional.

The matcher() method is used to search for the pattern in a string. It returns a Matcher
object which contains information about the search that was performed.

The find() method returns true if the pattern was found in the string and false if it was not
found.

ADVERTISEMENT
ADVERTISEMENT

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:


cat|dog|fish

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


end of a word like this: WORD\b

\uxxxx Find the Unicode character specified by the hexadecimal number


xxxx

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 Threads
Threads allows a program to operate more efficiently by doing multiple things at
the same time.

Threads can be used to perform complicated tasks in the background without


interrupting the main program.

Creating a Thread
There are two ways to create a thread.

It can be created by extending the Thread class and overriding its run()
method:

Extend Syntax

Get your own Java Server

public class Main extends Thread {


public void run() {
System.out.println("This code is running in a thread");
}
}

Another way to create a thread is to implement the Runnable interface:

Implement Syntax

public class Main implements Runnable {


public void run() {
System.out.println("This code is running in a thread");
}

Running Threads
If the class extends the Thread class, the thread can be run by creating an
instance of the class and call its start() method:

Extend Example

public class Main extends Thread {


public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}

}
If the class implements the Runnable interface, the thread can be run by
passing an instance of the class to a Thread object's constructor and then
calling the thread's start() method:

Implement Example

public class Main implements Runnable {


public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}

Differences between "extending" and "implementing" Threads

The major difference is that when a class extends the Thread class, you cannot extend
any other class, but by implementing the Runnable interface, it is possible to extend
from another class as well, like: class MyClass extends OtherClass implements
Runnable.

Concurrency Problems
Because threads run at the same time as other parts of the program, there is no
way to know in which order the code will run. When the threads and main
program are reading and writing the same variables, the values are
unpredictable. The problems that result from this are called concurrency
problems.
Example

A code example where the value of the variable amount is unpredictable:

public class Main extends Thread {


public static int amount = 0;

public static void main(String[] args) {


Main thread = new Main();
thread.start();
System.out.println(amount);
amount++;
System.out.println(amount);
}

public void run() {


amount++;
}

To avoid concurrency problems, it is best to share as few attributes between


threads as possible. If attributes need to be shared, one possible solution is to
use the isAlive() method of the thread to check whether the thread has
finished running before using any attributes that the thread can change.

Example

Use isAlive() to prevent concurrency problems:

public class Main extends Thread {


public static int amount = 0;

public static void main(String[] args) {


Main thread = new Main();
thread.start();
// Wait for the thread to finish
while(thread.isAlive()) {
System.out.println("Waiting...");
}
// Update amount and print its value
System.out.println("Main: " + amount);
amount++;
System.out.println("Main: " + amount);
}
public void run() {
amount++;
}

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.

Syntax
The simplest lambda expression contains a single parameter and an expression:

parameter -> expression

To use more than one parameter, wrap them in parentheses:


(parameter1, parameter2) -> expression

Expressions are limited. They have to immediately return a value, and they
cannot contain variables, assignments or statements such as if or for. In
order to do more complex operations, a code block can be used with curly
braces. If the lambda expression needs to return a value, then the code block
should have a return statement.

(parameter1, parameter2) -> { code block }

Using Lambda Expressions


Lambda expressions are usually passed as parameters to a function:

Get your own Java Server

Use a lambda expression in the ArrayList's forEach() method to print every item
in the list:

import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}

Lambda expressions can be stored in variables if the variable's type is an


interface which has only one method. The lambda expression should have the
same number of parameters and the same return type as that method. Java has
many of these kinds of interfaces built in, such as the Consumer interface
(found in the java.util package) used by lists.

Example

Use Java's Consumer interface to store a lambda expression in a variable:

import java.util.ArrayList;
import java.util.function.Consumer;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
Consumer<Integer> method = (n) -> { System.out.println(n); };
numbers.forEach( method );
}

To use a lambda expression in a method, the method should have a parameter


with a single-method interface as its type. Calling the interface's method will
run the lambda expression:

Example
Create a method which takes a lambda expression as a parameter:

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

You might also like