0% found this document useful (0 votes)
8 views87 pages

Java Object-Oriented Programming Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views87 pages

Java Object-Oriented Programming Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Creating Class & Object

❖ Create a class named "MyClass" with a variable x:


public class MyClass {
int x = 5;
}

❖ Create an Object
public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj = new MyClass();
[Link](myObj.x);
}
}
Object Oriented Programming: Java
Objects
❖ Multiple Objects
public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj1 = new MyClass(); // Object 1
MyClass myObj2 = new MyClass(); // Object 2
[Link](myObj1.x);
[Link](myObj2.x);
}
}

Object Oriented Programming: Java


Attributes
❖ Class Attributes
public class MyClass {
int x = 5;
int y = 3;
}

❖ Accessing Attributes
public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj = new MyClass();
[Link](myObj.x);
}
}
Object Oriented Programming: Java
Attributes
❖ Modify Attributes: Set the value of x to 40:
public class MyClass {
int x;

public static void main(String[] args) {


MyClass myObj = new MyClass();
myObj.x = 40;
[Link](myObj.x);
}
}

Object Oriented Programming: Java


Attributes
❖ Change the value of x to 25 in myObj2, and leave x in myObj1
unchanged:
public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj1 = new MyClass(); // Object 1
MyClass myObj2 = new MyClass(); // Object 2
myObj2.x = 25;
[Link](myObj1.x); // Outputs 5
[Link](myObj2.x); // Outputs 25
}
}
Object Oriented Programming: Java
Attributes
❖ Multiple Attributes
public class Person {
String fname = "John";
String lname = "Doe";
int age = 24;

public static void main(String[] args) {


Person myObj = new Person();
[Link]("Name: " + [Link] + " " + [Link]);
[Link]("Age: " + [Link]);
}
}
Object Oriented Programming: Java
Creating method
❖ Class Methods
public class MyClass {
static void myMethod() {
[Link]("Hello World!");
}

public static void main(String[] args) {


myMethod();
}
}

// Outputs "Hello World!


Object Oriented Programming: Java
Method Types
❖ Static method
▪ it can be accessed without creating an object of the class
❖ Public method
▪ can only be accessed by objects

Object Oriented Programming: Java


Creating Method
public class MyClass {
// Static method
static void myStaticMethod() {
[Link]("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
[Link]("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
MyClass myObj = new MyClass(); // Create an object of MyClass
[Link](); // Call the public method on the object
}
}
Object Oriented Programming: Java
Accessing Method
// Create a Car class
public class Car { // Inside main, call the methods on the myCar object
public static void main(String[] args) {
Car myCar = new Car(); // Create a myCar object
// Create a fullThrottle() method [Link](); // Call the fullThrottle() method
public void fullThrottle() { [Link](200); // Call the speed() method
}
[Link]("The car is going as fast as it can!");
}
}
// The car is going as fast as it can!
// Max speed is: 200
// Create a speed() method and add a parameter
public void speed(int maxSpeed) {
[Link]("Max speed is: " + maxSpeed);
}

Object Oriented Programming: Java


Using multiple classes
❖ [Link]
public class Car {
public void fullThrottle() {
[Link]("The car is going as fast as it
can!");
}
public void speed(int maxSpeed) {
[Link]("Max speed is: " + maxSpeed);
}
}
❖ [Link]
class OtherClass {
public static void main(String[] args) {
Car myCar = new Car(); // Create a myCar object
[Link](); // Call the fullThrottle() method
[Link](200); // Call the speed() method
}
}
Object Oriented Programming: Java
Class 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:
// Create a MyClass class
public class MyClass {
int x; // Create a class attribute

// Create a class constructor for the MyClass class


public MyClass() {
x = 5; // Set the initial value for the class attribute x
}

public static void main(String[] args) {


MyClass myObj = new MyClass(); // Create an object of class MyClass (This will call the constructor)
[Link](myObj.x); // Print the value of x
}
}
// Outputs 5
Object Oriented Programming: Java
Constructor parameter
❖ Example
public class MyClass {
int x;

public MyClass(int y) {
x = y;
}

public static void main(String[] args) {


MyClass myObj = new MyClass(5);
[Link](myObj.x);
}
}
// Outputs 5

Object Oriented Programming: Java


Constructor parameter
❖ Example
public class Car {
int modelYear;
String modelName;

public Car(int year, String name) {


modelYear = year;
modelName = name;
}

public static void main(String[] args) {


Car myCar = new Car(1969, "Mustang");
[Link]([Link] + " " + [Link]);
}
}

// Outputs 1969 Mustang

Object Oriented Programming: Java


Modifiers
❖ Modifiers are keywords that you add to those definitions to
change their meanings.
❖ Two groups of modifiers
▪ Access modifier - controls the access level
▪ Non-access modifier - do not control access level, but provides other
functionality
❖ Access modifiers for classes
▪ 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.
❖ Non-Access Modifiers for classes
▪ final - The class cannot be inherited by other classes
▪ abstract - The class cannot be used to create objects (To access an
abstract class, it must be inherited from another class.)

Object Oriented Programming: Java


Modifiers
❖ Access modifiers for attributes, methods and constructors
▪ 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.
▪ protected - The code is accessible in the same package and
subclasses.

Object Oriented Programming: Java


Modifiers
❖ Non-access modifiers for attributes and methods
▪ 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.
▪ synchronized and volatile – there are used by thread

Object Oriented Programming: Java


Modifiers
❖ Final variable
▪ If you don't want the ability to override existing attribute values,
declare attributes as final:
public class MyClass {
final int x = 10;
final double PI = 3.14;

public static void main(String[] args) {


MyClass myObj = new MyClass();
//myObj.x = 50; // will generate an error: cannot assign a value to a final variable
//[Link] = 25; // will generate an error: cannot assign a value to a final variable
[Link](myObj.x);
}
}

Object Oriented Programming: Java


❖ final modifier for method

Object Oriented Programming: Java


Modifiers
❖ static method
▪ A static method means that it can be accessed without creating an object of
the class, unlike public:
public class MyClass {
// Static method
static void myStaticMethod() {
[Link]("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
[Link]("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
MyClass myObj = new MyClass(); // Create an object of MyClass
[Link](); // Call the public method
}
}
Object Oriented Programming: Java
Modifiers
❖ static variable

Object Oriented Programming: Java


Modifiers
❖ abstract method
▪ 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: [Link] // Code from filename: [Link]
// abstract class class MyClass {
abstract class Person { public static void main(String[] args) {
public String fname = "John"; // create an object of the Student class (which inherits attributes
public int age = 24; and methods from Person)
public abstract void study(); // abstract method Student myObj = new Student();
}
[Link]("Name: " + [Link]);
// Subclass (inherit from Person) [Link]("Age: " + [Link]);
class Student extends Person { [Link]("Graduation Year: " + [Link]);
public int graduationYear = 2018; [Link](); // call abstract method
public void study() { // the body of the abstract method }
[Link]("Studying all day long"); }
}
}
// End code from filename: [Link]

Object Oriented Programming: Java


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

Object Oriented Programming: Java


Encapsulation
❖ Example
public class Person { public class MyClass {
private String name; // private = restricted public static void main(String[] args) {
access Person myObj = new Person();
[Link] = "John"; // error
// Getter [Link]([Link]); // error
public String getName() { }
return name; }
} public class MyClass {
public static void main(String[] args) {
Person myObj = new Person();
// Setter [Link]("John"); // Set the value of the name
public void setName(String newName) { variable to "John"
[Link] = newName; [Link]([Link]());
}
} }
}
// Outputs "John"
Object Oriented Programming: Java
Encapsulation
❖ 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

Object Oriented Programming: Java


Inheritance
❖ 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.

Object Oriented Programming: Java


Inheritance
❖ Example class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
[Link]("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
[Link]();

// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
[Link]([Link] + " " + [Link]);
}
} Object Oriented Programming: Java
Inheritance
❖ final class
▪ 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 {


...
}

Object Oriented Programming: Java


Polymorphism
❖ Polymorphism
▪ Polymorphism means "many forms", and it occurs when we
have many classes that are related to each other by inheritance.
▪ 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.):

Object Oriented Programming: Java


Polymorphism
❖ Example
class Animal {
public void animalSound() {
[Link]("The animal makes a sound");
}
}

class Pig extends Animal {


public void animalSound() {
[Link]("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
[Link]("The dog says: bow wow");
}
}
Object Oriented Programming: Java
Polymorphism
❖ Now we can create Pig and Dog objects and call the animalSound() method on both
of them:

class Animal { class MyMainClass {


public void animalSound() { public static void main(String[] args) {
[Link]("The animal makes a sound"); Animal myAnimal = new Animal(); // Create a Animal object
} Animal myPig = new Pig(); // Create a Pig object
} Animal myDog = new Dog(); // Create a Dog object
[Link]();
class Pig extends Animal { [Link]();
public void animalSound() { [Link]();
[Link]("The pig says: wee wee"); }
} }
}

class Dog extends Animal {


public void animalSound() {
[Link]("The dog says: bow wow");
}
}

Object Oriented Programming: 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:

Object Oriented Programming: Java


Inner Classes
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}

public class MyMainClass {


public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link](myInner.y + myOuter.x);
}
}
// Outputs 15 (5 + 10)

Object Oriented Programming: Java


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:
class OuterClass {
int x = 10;

private class InnerClass {


int y = 5;
}
}

public class MyMainClass {


public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();//error
[Link](myInner.y + myOuter.x);
}
}
Object Oriented Programming: Java
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:
class OuterClass {
int x = 10;

static class InnerClass {


int y = 5;
}
}

public class MyMainClass {


public static void main(String[] args) {
[Link] myInner = new [Link]();
[Link](myInner.y);
}
}

// Outputs 5
Object Oriented Programming: Java
Access Outer Class From Inner Class
❖ One advantage of inner classes, is that they can access
attributes and methods of the outer class:
class OuterClass {
int x = 10;

class InnerClass {
public int myInnerMethod() {
return x; public class MyMainClass {
} public static void main(String args[]) {
} OuterClass myOuter = new OuterClass();
} [Link] myInner = [Link] InnerClass();
[Link]([Link]());
}
}
// Outputs 10
Object Oriented Programming: Java
Abstraction
❖ Java Abstract Classes and Methods
▪ Data abstraction is the process of hiding certain details and
showing only essential information to the user.
▪ Abstraction can be achieved with either abstract classes or
interfaces
❖ The abstract keyword is a non-access modifier, used for
classes and methods:
▪ Abstract class: is a restricted class that cannot be used to create
objects (to access it, it must be inherited from another class).
▪ Abstract method: can only be used in an abstract class, and it
does not have a body. The body is provided by the subclass
(inherited from).
Object Oriented Programming: Java
Abstraction
❖ An abstract class can have both abstract and regular
methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
[Link]("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

Object Oriented Programming: Java


Abstraction
❖ To access the abstract class, it must be inherited from
another class.
// Abstract class class MyMainClass {
abstract class Animal { public static void main(String[] args) {
// Abstract method (does not have a body) Pig myPig = new Pig(); // Create a Pig object
public abstract void animalSound(); [Link]();
// Regular method [Link]();
public void sleep() { }
[Link]("Zzz"); }
}
}

// Subclass (inherit from Animal)


class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
[Link]("The pig says: wee wee");
}
}

Object Oriented Programming: Java


Abstraction
❖ Why And When To Use Abstract Classes and Methods?
▪ To achieve security - hide certain details and only show the
important details of an object.

Object Oriented Programming: Java


Interface
❖ 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:
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

Object Oriented Programming: Java


Interface
// Interface
interface Animal {
public void animalSound(); // interface method (does not
have a body)
public void sleep(); // interface method (does not have a
body)
} public void sleep() {
// The body of sleep() is provided here
// Pig "implements" the Animal interface [Link]("Zzz");
class Pig implements Animal { }
public void animalSound() { }
// The body of animalSound() is provided here
[Link]("The pig says: wee wee"); class MyMainClass {
} public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
[Link]();
[Link]();
}
}

Object Oriented Programming: Java


Interface
❖ Notes:
▪ 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)
Object Oriented Programming: Java
Interface
❖ Why And When To Use Interfaces?
▪ To achieve security - hide certain details and only show the
important details of an object (interface).
▪ 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.

Object Oriented Programming: Java


Interface
❖ Multiple Interfaces
▪ To implement multiple interfaces, separate them with a comma:
interface FirstInterface {
class MyMainClass {
public void myMethod(); // interface method
public static void main(String[] args) {
}
DemoClass myObj = new DemoClass();
[Link]();
interface SecondInterface {
[Link]();
public void myOtherMethod(); // interface method
}
}
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
[Link]("Some text..");
}
public void myOtherMethod() {
[Link]("Some other text...");
}
} Object Oriented Programming: Java
Enums
❖ An enum is a special "class" that represents a group of
constants (unchangeable variables, like final variables).
❖ 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:
enum Level {
LOW,
MEDIUM,
HIGH
}

❖ You can access enum constants with the dot syntax:


Level myVar = [Link];

Object Oriented Programming: Java


Enums
❖ Enum inside a Class
▪ You can also have an enum inside a class:
public class MyClass {
enum Level {
LOW,
MEDIUM,
HIGH
}

public static void main(String[] args) {


Level myVar = [Link];
[Link](myVar);
}
}
OUTPUT: MEDIUM
Object Oriented Programming: Java
Enums
❖ Enum in a Switch Statement
▪ Enums are often used in switch statements to check for
corresponding values:
switch(myVar) {
enum Level { case LOW:
LOW, [Link]("Low level");
MEDIUM, break;
HIGH case MEDIUM:
} [Link]("Medium level");
break;
public class MyClass { case HIGH:
public static void main(String[] args) { [Link]("High level");
Level myVar = [Link]; break;
}
}
} OUTPUT: Medium level

Object Oriented Programming: Java


Enums
❖ 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:
for (Level myVar : [Link]()) {
[Link](myVar);
}

The output will be:

LOW
MEDIUM
HIGH

Object Oriented Programming: Java


Enums
❖ 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, colors, deck of cards, etc.

Object Oriented Programming: Java


User Input (Scanner)
❖ The Scanner class is used to get user input, and it is found in the [Link]
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 Strings:
import [Link]; // Import the Scanner class

class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner([Link]); // Create a Scanner object
[Link]("Enter username");

String userName = [Link](); // Read user input


[Link]("Username is: " + userName); // Output user input
}
}

Object Oriented Programming: Java


User Input (Scanner)
❖ Input Types
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

Object Oriented Programming: Java


User Input (Scanner)
❖ Input types example
import [Link];
// Output input by user
[Link]("Name: " + name);
class MyClass {
[Link]("Age: " + age);
public static void main(String[] args) {
[Link]("Salary: " + salary);
Scanner myObj = new Scanner([Link]);
}
}
[Link]("Enter name, age and salary:");

// String input Note: If you enter wrong input (e.g. text


String name = [Link](); in a numerical input), you will get an
// Numerical input
exception/error message (like
int age = [Link](); "InputMismatchException").
double salary = [Link]();

Object Oriented Programming: Java


Date and Time
❖ Java Dates
▪ Java does not have a built-in Date class, but we can import the
[Link] 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 milliseconds
(HH-mm-ss-zzz))
LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-
[Link])
DateTimeFormatt Formatter for displaying and parsing date-time objects
er

Object Oriented Programming: Java


Date and Time
❖ Display Current Date
▪ To display the current date, import the [Link] class,
and use its now() method:

import [Link]; // import the LocalDate class

public class MyClass {


public static void main(String[] args) {
LocalDate myObj = [Link](); // Create a date object
[Link](myObj); // Display the current date
}
}
The output will be:
2020-02-23

Object Oriented Programming: Java


Date and Time
❖ Display Current Time
▪ To display the current time (hour, minute, second, and
milliseconds), import the [Link] class, and use its
now() method:
import [Link]; // import the LocalTime class

public class MyClass {


public static void main(String[] args) {
LocalTime myObj = [Link]();
[Link](myObj);
}
}
The output will be:
08:17:47.054830
Object Oriented Programming: Java
Date and Time
❖ Display Current Date and Time
▪ To display the current date and time, import the
[Link] class, and use its now() method:

import [Link]; // import the LocalDateTime class

public class MyClass {


public static void main(String[] args) {
LocalDateTime myObj = [Link]();
[Link](myObj);
}
}

The output will be:


2020-02-23T08:17:47.059001

Object Oriented Programming: Java


Date and Time
❖ 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 milliseconds from the date-time:

Object Oriented Programming: Java


Date and Time
❖ DateTimeFormatter
import [Link]; // Import the LocalDateTime class
import [Link]; // Import the DateTimeFormatter class

public class MyClass {


public static void main(String[] args) {
LocalDateTime myDateObj = [Link]();
[Link]("Before formatting: " + myDateObj);
DateTimeFormatter myFormatObj = [Link]("dd-MM-yyyy HH:mm:ss");

String formattedDate = [Link](myFormatObj);


[Link]("After formatting: " + formattedDate);
}
}
The output will be:
Before Formatting: 2020-02-23T08:17:47.059297
After Formatting: 23-02-2020 08:17:47
Object Oriented Programming: Java
Date and Time
❖ 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
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"

Object Oriented Programming: Java


ArrayList
❖ The ArrayList class is a resizable array, which can be found
in the [Link] 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:

Object Oriented Programming: Java


ArrayList
❖ Create an ArrayList object called cars that will store strings:
import [Link]; // import the ArrayList class

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

Object Oriented Programming: Java


ArrayList
❖ Add Items
▪ The ArrayList class has many useful methods. For example, to
add elements to the ArrayList, use the add() method:
import [Link];

public class MyClass {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
[Link]("Volvo");
[Link]("BMW");
[Link]("Ford");
[Link]("Mazda");
[Link](cars);
}
}
Object Oriented Programming: Java
ArrayList
❖ Access an Item
▪ To access an element in the ArrayList, use the get() method and
refer to the index number:
[Link](0);

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

Object Oriented Programming: Java


ArrayList
❖ Change an Item
▪ To modify an element, use the set() method and refer to the
index number:
[Link](0, "Opel");
❖ Remove an Item
▪ To remove an element, use the remove() method and refer to
the index number:
[Link](0);
▪ To remove all the elements in the ArrayList, use the clear()
method:
[Link]();

Object Oriented Programming: Java


ArrayList
❖ ArrayList Size
▪ To find out how many elements an ArrayList have, use the size() method:
[Link](); public class MyClass {
public static void main(String[] args) {
❖ Loop Through an ArrayList ArrayList<String> cars = new ArrayList<String>();
▪ Loop through the elements of [Link]("Volvo");
an ArrayList with a for loop, [Link]("BMW");
[Link]("Ford");
and use the size() method to [Link]("Mazda");
specify how many times the for (int i = 0; i < [Link](); i++) {
loop should run: [Link]([Link](i));
}
}
OUTPUT:
} Volvo
BMW
Ford
Mazda
Object Oriented Programming: Java
ArrayList
❖ You can also loop through an ArrayList with the for-each
loop:
public class MyClass {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
[Link]("Volvo");
[Link]("BMW");
[Link]("Ford");
[Link]("Mazda");
for (String i : cars) {
[Link](i); OUTPUT:
Volvo
} BMW
} Ford
} Mazda

Object Oriented Programming: Java


ArrayList
❖ 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: Boolean for boolean, Character
for char, Double for double, etc.

Object Oriented Programming: Java


ArrayList
❖ Create an ArrayList to store numbers (add elements of type
Integer):
import [Link];

public class MyClass {


public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
[Link](10);
[Link](15);
[Link](20);
[Link](25);
for (int i : myNumbers) {
[Link](i); OUTPUT:
} 10
} 15
20
}
25

Object Oriented Programming: Java


ArrayList
❖ Sort an ArrayList
▪ Another useful class in the [Link] package is the Collections class, which
include the sort() method for sorting lists alphabetically or numerically:
import [Link];
import [Link]; // Import the Collections class

public class MyClass {


public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
[Link]("Volvo");
[Link]("BMW");
[Link]("Ford");
[Link]("Mazda");
[Link](cars); // Sort cars
for (String i : cars) { OUTPUT:
[Link](i); BMW
} Ford
} Mazda
} Volvo

Object Oriented Programming: Java


ArrayList
❖ Sort an ArrayList of Integers:
import [Link];
import [Link]; // Import the Collections class

public class MyClass {


public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
[Link](33);
[Link](15); [Link](myNumbers); // Sort myNumbers
[Link](20); for (int i : myNumbers) {
[Link](34); [Link](i);
OUTPUT:
[Link](8); }
8
[Link](12); } 12
} 15
20
33
34

Object Oriented Programming: Java


HashMap
❖ 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:

Object Oriented Programming: Java


HashMap
❖ Create a HashMap object called capitalCities that will store
String keys and String values:
import [Link]; // import the HashMap class

HashMap<String, String> capitalCities = new HashMap<String, String>();

Object Oriented Programming: Java


HashMap
❖ Add Items
▪ to add items to it, use the put() method:
// Import the HashMap class
import [Link];

public class MyClass {


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)


[Link]("England", "London");
[Link]("Germany", "Berlin"); OUTPUT:
[Link]("Norway", "Oslo"); {USA=Washington DC,
[Link]("USA", "Washington DC"); Norway=Oslo, England=London,
[Link](capitalCities); Germany=Berlin}
}
} Object Oriented Programming: Java
HashMap
❖ Access an Item
▪ To access a value in the HashMap, use the get() method and
refer to its key:
import [Link];

public class MyClass {


public static void main(String[] args) {
HashMap<String, String> capitalCities = new HashMap<String, String>();
[Link]("England", "London");
[Link]("Germany", "Berlin");
[Link]("Norway", "Oslo");
[Link]("USA", "Washington DC");
[Link]([Link]("England"));
OUTPUT:
} London
}
Object Oriented Programming: Java
HashMap
❖ Remove an Item
▪ To remove an item, use the remove() method and refer to the
key:
import [Link];

public class MyClass {


public static void main(String[] args) {
HashMap<String, String> capitalCities = new HashMap<String, String>();
[Link]("England", "London");
[Link]("Germany", "Berlin");
[Link]("Norway", "Oslo");
[Link]("USA", "Washington DC"); OUTPUT:
[Link]("England"); {USA=Washington DC,
[Link](capitalCities); Norway=Oslo,
} Germany=Berlin}
}

Object Oriented Programming: Java


HashMap
❖ Remove all items
▪ To remove all items, use the clear() method:
import [Link];

public class MyClass {


public static void main(String[] args) {
HashMap<String, String> capitalCities = new HashMap<String, String>();
[Link]("England", "London");
[Link]("Germany", "Berlin");
[Link]("Norway", "Oslo");
[Link]("USA", "Washington DC");
[Link](); OUTPUT:
[Link](capitalCities); {}
}
} Object Oriented Programming: Java
HashMap
❖ HashMap Size
▪ To find out how many items there are, use the size() method:
import [Link];

public class MyClass {


public static void main(String[] args) {
HashMap<String, String> capitalCities = new HashMap<String, String>();
[Link]("England", "London");
[Link]("Germany", "Berlin");
[Link]("Norway", "Oslo");
[Link]("USA", "Washington DC");
[Link]([Link]());
} OUTPUT:
} 4

Object Oriented Programming: Java


HashMap
❖ 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:

Object Oriented Programming: Java


HashMap
import [Link];

public class MyClass {


public static void main(String[] args) {
HashMap<String, String> capitalCities = new HashMap<String, String>();
[Link]("England", "London");
[Link]("Germany", "Berlin"); OUTPUT:
key: USA value: Washington DC
[Link]("Norway", "Oslo"); key: Norway value: Oslo
[Link]("USA", "Washington DC"); key: England value: London
key: Germany value: Berlin
for (String i : [Link]()) {
[Link]("key: " + i + " value: " + [Link](i));
}
}
}
Object Oriented Programming: Java
HashMap
❖ 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.

Object Oriented Programming: Java


HashMap
❖ Create a HashMap object called people that will store
String keys and Integer values:
// Import the HashMap class
import [Link];
public class MyClass {
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)
[Link]("John", 32);
[Link]("Steve", 30);
[Link]("Angie", 33);
for (String i : [Link]()) {
[Link]("key: " + i + " value: " + [Link](i)); OUTPUT:
} Name: Angie Age: 33
} Name: Steve Age: 30
} Name: John Age: 32

Object Oriented Programming: Java


Wrapper Classes
❖ 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
Object Oriented Programming: Java
Wrapper Classes
▪ 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):
import [Link];

public class MyClass {


public static void main(String[] args) {
//ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
[Link](10);
[Link](15);
[Link](20);
[Link](25); OUTPUT:
for (int i : myNumbers) { 10
[Link](i); 15
} 20
25
}
} Object Oriented Programming: Java
Wrapper Classes
❖ 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:
public class MyClass {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
[Link](myInt);
[Link](myDouble);
[Link](myChar); OUTPUT:
} 5
5.99
} A

Object Oriented Programming: Java


Wrapper Classes
▪ Since we are now working with objects, we 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().
public class MyClass {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
[Link]([Link]()); OUTPUT:
[Link]([Link]()); 5
[Link]([Link]()); 5.99
} A
}

Object Oriented Programming: Java


Wrapper Classes
▪ 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":
public class MyClass {
public static void main(String[] args) {
Integer myInt = 100;
String myString = [Link]();
[Link]([Link]());
} OUTPUT:
} 3

Object Oriented Programming: Java

You might also like