Java Class Attributes
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:
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:
Modify Attributes
You can also modify attribute values:
Set the value of x to 40:
If you don't want the ability to override existing values, declare the attribute as
final:
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:
Multiple Attributes
You can specify as many attributes as you want:
The next chapter will teach you how to create class methods and how to access them
with objects.
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;
System.out.println("Hello World!");
}
public static void main(String[] args) {
myMethod();
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:
// Static method
// Public method
// Main method
Note: You will learn more about these keywords (called modifiers) in the Java Modifiers
chapter.
3) The fullThrottle() method and the speed() method will print out some
text, when they are called.
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.
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 (;).
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
Second.java
class Second {
public Main() {
// 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
int x;
public Main(int y) {
x = y;
System.out.println(myObj.x);
// Outputs 5
Example
int modelYear;
String modelName;
modelYear = year;
modelName = name;
}
Modifiers
By now, you are quite familiar with the public keyword that appears in almost all of our
examples:
For attributes, methods and constructors, you can use the one of the following:
Modifier Description Try it
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
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
Final
If you don't want the ability to override existing attribute values, declare attributes as
final:
System.out.println(myObj.x);
Static
A static method means that it can be accessed without creating an object of the class,
unlike public:
// Static method
// Public method
// Main method
}
Abstract
An abstract method belongs to an abstract class, and it does not have a body. The
body is provided by the subclass:
// abstract class
class Second {
}
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden
from users. To achieve this, you must:
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:
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Example explained
Example
If the variable was declared as public, we would expect the following output:
John
myObj.name = "John";
2 errors
Instead, we use the getName() and setName() methods to access and update
the variable:
Example
// 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
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.
To use a class or a package from the library, you need to use the import
keyword:
Syntax
Example
import java.util.Scanner;
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
import java.util.Scanner;
class MyClass {
System.out.println("Enter username");
String userName = myObj.nextLine();
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
MyPackageClass.java
package mypack;
class MyPackageClass {
System.out.println("This is my package!");
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".
This is my package!
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!");
}
}
// Call the honk() method (from the Vehicle class) on the myCar
object
myCar.honk();
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.
- 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
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");
}
}
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 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();
}
}
- It is useful for code reusability: reuse attributes and methods of an existing class when
you create a new class.
Example
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
// Outputs 15 (5 + 10)
Example
class OuterClass {
int x = 10;
If you try to access a private inner class from an outside class, an error occurs:
Example
class OuterClass {
int x = 10;
// Outputs 5
Note: just like static attributes and methods, a static inner class does not have access to
members of the outer class.
Example
class OuterClass {
int x = 10;
class InnerClass {
public int myInnerMethod() {
return x;
}
}
}
// Outputs 10
The abstract keyword is a non-access modifier, used for classes and methods:
From the example above, it is not possible to create an object of the Animal
class:
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
// 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");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
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.
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a
body)
public void run(); // interface method (does not have a body)
}
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a
body)
public void sleep(); // interface method (does not have a body)
}
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)
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 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
enum Level {
LOW,
MEDIUM,
HIGH
}
Example
MEDIUM
Enum in a Switch Statement
Enums are often used in switch statements to check for corresponding values:
Example
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;
}
}
}
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
LOW
MEDIUM
HIGH
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
If you don't know what a package is, read our Java Packages Tutorial.
Example
Get your own Java Server
2024-06-12
Example
ADVERTISEMENT
Example
2024-06-12T20:36:11.178932
Example
The ofPattern() method accepts all sorts of values, if you want to display the date and
time in a different format. For example:
yyyy-MM-dd "1988-09-29"
dd/MM/yyyy "29/09/1988"
dd-MMM-yyyy "29-Sep-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
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;
You can also add an item at a specified position by referring to the index number:
Example
import java.util.ArrayList;
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();
Example
You can also loop through an ArrayList with the for-each loop:
Example
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
import java.util.ArrayList;
Example
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
Example
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
Java LinkedList
In the previous chapter, you learned about the ArrayList class. The LinkedList class
is almost identical to the ArrayList:
Example
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.
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:
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
Create a HashMap object called capitalCities that will store String keys and String
values:
Add Items
The HashMap class has many useful methods. For example, to add items to it,
use the put() method:
Example
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");
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:
Java HashSet
A HashSet is a collection of items where every item is unique, and it is found in
the java.util package:
Example
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;
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.
Example
cars.contains("Mazda");
Remove an Item
To remove an item, use the remove() method:
Example
cars.remove("Volvo");
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
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
import java.util.HashSet;
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.
Getting an Iterator
The iterator() method can be used to get an Iterator for any collection:
// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Example
while(it.hasNext()) {
System.out.println(it.next());
ADVERTISEMENT
Example
import java.util.ArrayList;
import java.util.Iterator;
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:
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
Example
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
Example
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).
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
at Main.main(Main.java:4)
If an error occurs, we can use try...catch to catch the error and execute
some code to handle it:
Example
Finally
The finally statement lets you execute code, after try...catch, regardless
of the result:
Example
ADVERTISEMENT
The throw statement is used together with an exception type. There are many
exception types available in Java: ArithmeticException,
FileNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc:
Example
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
Example
checkAge(20);
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:
Find out if there are any occurrences of the word "w3schools" in a sentence:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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:
Expression Description
[abc] Find one character from the options between the brackets
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
Quantifiers
Quantifiers define quantities:
Quantifier Description
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at
the same time.
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
Implement Syntax
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
}
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
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
Example
Syntax
The simplest lambda expression contains a single parameter and an 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.
Use a lambda expression in the ArrayList's forEach() method to print every item
in the list:
import java.util.ArrayList;
Example
import java.util.ArrayList;
import java.util.function.Consumer;
Example
Create a method which takes a lambda expression as a parameter:
interface StringFunction {
String run(String str);
}