Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

IT 7 - Object Oriented Programming (NOTES)

HEHE

Uploaded by

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

IT 7 - Object Oriented Programming (NOTES)

HEHE

Uploaded by

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

CHAPTER 1 - LESSON 1: OVERVIEW ON PROGRAMMING PARADIGMS

Overview on Programming Paradigms

Programming Paradigm by Definition


A programming paradigm is the classification, style or way of programming. It is an approach to solve problems by using programming
languages. Depending on the language, the difficulty of using a paradigm differs.

There are several programming languages that use paradigms, but to do this, they need to follow a strategy or methodology. Paradigms
are not meant to be mutually exclusive; a single program can feature multiple paradigms. Below is an overview of programming
languages and their paradigm methodology.

Common Programming Paradigms

Imperative Programming
Imperative programming is a programming paradigm where you write code that describes the steps to perform a task or solve a problem
in a sequential manner. It is based on the idea of giving the computer a sequence of explicit commands to execute, one after the other. In
this paradigm, the program state is manipulated through statements that change the values of variables, control flow structures like loops
and conditionals, and function calls.

Example:

public static void main(String[] args) {


int n = 10; // We want to find the sum of the first 10 natural numbers
int sum = 0; // Initialize a variable to store the sum

// Using a loop to calculate the sum of numbers from 1 to N


for (int i = 1; i <= n; i++) {
sum += i; // Add each number to the sum
}

System.out.println("The sum of the first " + n + " natural numbers is: " + sum);
}

Explanation:

In this example, we use a for loop to iterate from 1 to N, adding each number to the variable sum. The final result is printed to the
console. This is an example of an imperative approach since we explicitly specify the sequence of commands to compute the sum.

Imperative programming is one of the fundamental programming paradigms and forms the basis of most mainstream programming
languages. It's widely used in day-to-day programming due to its simplicity and ease of understanding.

Declarative Programming
Declarative programming is a programming paradigm where you focus on describing what you want to achieve rather than how to
achieve it. Instead of giving a sequence of explicit commands like in imperative programming, you specify the desired outcome or end
result, and the underlying system takes care of the implementation details.

In declarative programming, you define the logic and rules that govern the program's behavior, and the language or framework handles
the execution. This allows for a more abstract and concise representation of the problem domain, making the code easier to read and
understand.

One of the most common examples of declarative programming is SQL (Structured Query Language) used in database querying. With
SQL, you specify the data you want to retrieve or modify from a database without specifying how the database should perform the
operations.
Example:

Suppose the table schema looks like this:

ID Name JobTitle Salary


1 Johnny Sims Astronaut 60000
2 Lexi Lorem Secretary 45000
3 Mia Khalifu Teacher 50000
4 Sasha Green Model 55000
5 Maria Ozaka Nurse 50000
Now, let's say we want to retrieve the names and job titles of all the employees whose salary is greater than or equal to 50000.

The SQL query for this would look like:

SELECT Name, JobTitle

FROM Employees

WHERE Salary >= 50000;

Explanation:

 SELECT: This keyword is used to specify the columns that we want to retrieve from the table. In this case, we want to get the
"Name" and "JobTitle" columns.

 FROM: This keyword indicates the table from which we are retrieving the data. In this example, it's the "Employees" table.

 WHERE: This keyword is used to filter the rows based on a specified condition. Here, we want to retrieve only those employees
whose "Salary" is greater than or equal to 50000.

So, the query instructs the database to select the "Name" and "JobTitle" columns from the "Employees" table but only for those rows
where the "Salary" is greater than or equal to 50000.

When you execute this SQL query, the result will be:

Name JobTitle
Johnny Sims Astronaut
Mia Khalifu Teacher
Sasha Green Model
Maria Ozaka Nurse

Structured Programming
Structured programming is a programming paradigm that emphasizes the use of well-organized, clean, and modular code. It promotes the
use of structured control flow constructs, such as loops and conditionals, to manage program flow and avoid the use of unrestricted
branching (e.g., GOTO statements).

The key principles of structured programming are:

1 Single Entry, Single Exit (SESE): Each block of code (e.g., function, loop, conditional) should have only one entry point
and one exit point. This simplifies reasoning about the code's behavior and makes it easier to maintain and debug.

2 Sequence: Code is executed in a sequential order, one statement after another, unless control flow statements alter the normal
sequence.
3 Selection (Conditionals): Using if-else and switch statements to make decisions and execute specific blocks of code based on
certain conditions.

4 Iteration (Loops): Using loops (e.g., for, while) to execute a block of code repeatedly until a specified condition is met.

5 Modularity: Breaking the program into smaller, manageable functions or procedures, allowing code reuse and making the
overall program structure clearer.

6 Abstraction: Hiding implementation details behind well-defined interfaces, enabling a focus on what a module does rather
than how it does it.

Using structured programming, code becomes more organized, easier to read, and less prone to errors. It allows for better program
understanding and maintenance.

Example:

<?php
// Define a variable
$number = 15;

// Check if the number is greater than 10


if ($number > 10) {
echo "The number is greater than 10.";
} else {
echo "The number is not greater than 10.";
}
?>

Explanation:

In this example, we have a variable $number with a value of 15. We then use the if statement to check if the value of $number is greater
than 10. If the condition is true, the code block inside the if statement will be executed, and it will display the message "The number is
greater than 10.". If the condition is false, the code block inside the else statement will be executed, and it will display the message "The
number is not greater than 10.".

When you run this PHP script, it will output:

The number is greater than 10.


Since $number is 15, which is greater than 10, the if block is executed.

Function-Level Programming
Function-level programming is not a common paradigm in C++. C++ is a multi-paradigm language that supports a combination of
procedural, object-oriented, and generic programming styles. While C++ does allow for functional programming concepts, it is not
designed to be a purely function-level programming language.

That said, we can demonstrate some functional programming concepts in C++ using functional-style constructs and features like lambdas
and standard algorithms. Keep in mind that this will be a hybrid approach, as C++ inherently involves the use of variables and mutable
state.

Example:

Let's write an example in JavaScript that uses higher-order functions and array methods to calculate the squares of numbers in an array:

// Sample array of numbers

const numbers = [1, 2, 3, 4, 5];

// Function-style programming using map method and arrow function

const squaredNumbers = numbers.map(num => num * num);

// Output the squared numbers

console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]


Explanation:

In this example, we have an array numbers containing some integers. We use the map method, which is a higher-order function in
JavaScript arrays. The map method takes a callback function as an argument and applies it to each element of the array. The callback
function calculates the square of each number using an arrow function (num => num * num).

By using map, we transform the original array into a new array squaredNumbers that contains the squares of the numbers.

This code demonstrates some key functional programming concepts in JavaScript, including the use of first-class functions (arrow
functions), higher-order functions (the map method), and data transformation without mutation.

Functional programming in JavaScript is commonly used for working with arrays, performing data transformations, and composing
behavior from simple functions. It promotes a declarative and more readable style of programming by avoiding explicit loops and
mutable state.

Functional Programming
Functional programming is a programming paradigm that revolves around the concept of functions as first-class citizens. In functional
programming, functions are treated as values that can be passed as arguments to other functions, returned from functions, and stored in
variables. One of the key principles of functional programming is the avoidance of shared mutable state and global variables.

Functional programming promotes the use of pure functions, which are functions that produce the same output for the same input and
have no side effects. That means pure functions do not modify any external state or variables outside their scope. They only rely on the
input provided to them to produce the output.

Key features of functional programming:

1 Pure Functions: Functions should have no side effects and avoid modifying state outside their scope. They only operate on
the input parameters and return a result.

2Immutability: Data is treated as immutable, meaning it cannot be changed after creation. Instead, new data is created through
transformations.

3 Higher-order Functions: Functions that can take other functions as arguments or return functions as results. This allows for
composition and building complex behavior from simpler functions.

4 Recursion: Functional programming encourages the use of recursion over traditional looping constructs like for and while.

5 Referential Transparency: The result of a function depends solely on its input, making it easy to reason about and test.

Example:

Let's illustrate functional programming with a simple example in JavaScript. We'll write a function that calculates the square of each
element in an array using functional programming techniques:

// Function to calculate the square of a number

const square = (number) => number * number;

// Functional approach to calculate the square of each element in an array

const numbers = [1, 2, 3, 4, 5];

const squaredNumbers = numbers.map(square);

// Output the squared numbers

console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

Explanation:
In this example, we define a square function that takes a number as input and returns its square. The map function is a higher-order
function provided by arrays in JavaScript. It takes a callback function (square in this case) and applies it to each element of the
array numbers. The result is a new array squaredNumbers containing the squares of the original numbers.

Notice that the square function is a pure function, as it does not rely on or modify any external state. It only operates on the input
provided to it.

Functional programming is well-suited for handling complex data transformations, parallel processing, and writing concise, maintainable
code. It has gained popularity in recent years and is supported by many modern programming languages like JavaScript, Python, and
Scala.

Event-Driven Programming
Event-driven programming is a programming paradigm in which the flow of the program is determined by events that occur
asynchronously. Instead of executing a sequence of commands from top to bottom, the program responds to events triggered by user
interactions, system signals, or other external sources.

In event-driven programming:

1 Event Emitters: Components of the program, known as event emitters, generate events when certain conditions are met.
These conditions could be user interactions (e.g., mouse clicks, keypresses) or system events (e.g., file ready for reading).

2 Event Listeners: Event listeners are registered to respond to specific types of events. When an event occurs, the
corresponding event listener's code is executed.

3 Non-Blocking: Event-driven programs are non-blocking, meaning the program does not wait for an event to complete before
moving on to other tasks. It can handle multiple events concurrently.

Event-driven programming is commonly used in GUI (Graphical User Interface) applications, web development (e.g., handling user
clicks), and networking (e.g., responding to incoming data).

Example:

<body>

<button id="myButton">Click Me</button>

<script>

// Event listener for the button click event

function handleClick() {

console.log('Button clicked!');

// Get a reference to the button element by its id

const buttonElement = document.getElementById('myButton');

// Attach the event listener to the button's click event

buttonElement.addEventListener('click', handleClick);

</script>

</body>

Explanation:

In this example, we have an HTML file with a single button element. The button has an id attribute with the value "myButton".
In the <script> section, we define a function named handleClick, which will be our event listener for the button's click event. When the
button is clicked, the handleClick function will be executed, and it will log a message to the console.

We use document.getElementById to get a reference to the button element by its id "myButton". Then, we use the addEventListener method to
attach the handleClick function as an event listener to the button's click event. Now, whenever the button is clicked,
the handleClick function will be called, and it will log "Button clicked!" to the console.

Procedural Programming
Procedural programming is a programming paradigm that focuses on organizing code into procedures or functions that perform specific
tasks. It is closely related to imperative programming, as it also uses explicit sequences of commands, but it places a strong emphasis on
dividing the code into reusable and modular procedures.

In procedural programming, a program is structured as a collection of procedures, where each procedure is a self-contained unit that
performs a specific task. Procedures can take input parameters and return results, allowing for data abstraction and encapsulation.

Key features of procedural programming:

1 Procedures/Functions: The primary building blocks of procedural programs are procedures or functions. These procedures
are like subroutines that can be called from different parts of the program to perform specific tasks.

2 Modularity: The program is divided into smaller, manageable units, making it easier to understand, maintain, and debug.
Each procedure is responsible for a specific task, promoting code reuse and making the codebase more organized.

3 Top-down Design: The program is typically designed from a top-level perspective, breaking down the problem into smaller
sub-problems that are then solved by individual procedures.

4 Data and Control Coupling: Procedures can share data by passing parameters and returning results. Control coupling is
achieved by calling one procedure from another.

5 Global Variables: Procedural programs may use global variables to share data across multiple procedures, but excessive use
of global variables can lead to issues with maintainability and debugging.

Example:

Let's see a simple example of procedural programming in PHP. We'll create two functions to find the sum and average of an array of
numbers:

<?php
// Function to calculate the sum of an array
function calculateSum($numbers) {
$sum = 0;
foreach ($numbers as $number) {
$sum += $number;
}
return $sum;
}

// Function to calculate the average of an array


function calculateAverage($numbers) {
$count = count($numbers);
if ($count === 0) {
return 0;
}
$sum = calculateSum($numbers);
return $sum / $count;
}

// Sample array
$numbers = [10, 20, 30, 40, 50];

// Calculate the sum and average


$sum = calculateSum($numbers);
$average = calculateAverage($numbers);

echo "Sum: $sum ";


echo "Average: $average";
?>
Explanation:

In this example, we have defined two functions calculateSum and calculateAverage, each responsible for a specific task.
The calculateSum function takes an array of numbers and returns their sum, while the calculateAverage function takes the same array and
returns their average.

By breaking down the problem into these modular functions, we achieve a more structured and organized codebase. The functions can be
reused in other parts of the program if needed.

Procedural programming was dominant in early programming languages and is still widely used in many scenarios today. However, with
the rise of object-oriented and functional programming paradigms, procedural programming is often mixed with these paradigms to
create more flexible and scalable software systems.

Object-Oriented Programming
Object-oriented programming (OOP) is a programming paradigm that focuses on modeling the program as a collection of objects that
interact with each other through messages (method calls). In OOP, objects encapsulate data and behavior, and communication between
objects occurs through method invocations or message passing.

Key characteristics of object-oriented programming:

1 Objects: Objects are instances of classes and represent entities with state (attributes) and behavior (methods).

2 Encapsulation: Objects encapsulate their internal state, and external interactions are typically performed through public
methods, maintaining data integrity.

3 Inheritance: Inheritance allows the creation of subclasses that inherit properties and behaviors from parent classes,
promoting code reuse and hierarchy.

4 Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common base class, providing
flexibility and extensibility.

5 Message Passing: Objects communicate by sending messages to each other through method calls, allowing interactions
between different objects.

Object-oriented programming is widely used and supported by many programming languages, including Java, C++, Python, and C#.

Example:

Let's demonstrate a simple object-oriented programming example in Java. We'll create two classes, Person and Car, where a person
interacts with a car by sending messages (method calls).

// Person class representing a person with a name

class Person {

private String name;

public Person(String name) {

this.name = name;

// Method to interact with a car

public void drive(Car car) {

System.out.println(name + " is driving " + car.getBrand() + ".");

car.start();
car.accelerate();

// Car class representing a car with a brand

class Car {

private String brand;

public Car(String brand) {

this.brand = brand;

// Method to start the car

public void start() {

System.out.println("The " + brand + " is starting.");

// Method to accelerate the car

public void accelerate() {

System.out.println("The " + brand + " is accelerating.");

// Method to get the brand of the car

public String getBrand() {

return brand;

public class OOPExample {

public static void main(String[] args) {

// Create a person and a car

Person person = new Person("John");

Car car = new Car("Toyota");

// Person interacts with the car

person.drive(car);

Explanation:
In this example, we have two classes, Person and Car, representing a person and a car, respectively. The Person class has a
method drive that allows a person to interact with a car. The Car class has methods start and accelerate, representing car behaviors.

In the main method, we create an instance of a person named "John" and a car with the brand "Toyota". The person interacts with the car
by calling the drive method, which sends a message to the car object to start and accelerate.

When you run this Java program, it will output:

John is driving Toyota.

The Toyota is starting.

The Toyota is accelerating.

This demonstrates object-oriented programming where a person and a car interact by sending messages to each other through method
calls.

Other Common Programming Paradigms also include:


 Flow-Driven: Programming processes communicating with each other over predefined channels.
 Logic: Programming by specifying a set of facts and rules.
 Constraint: Programming by specifying a set of constraints.
 Aspect-Oriented: Programming cross-cutting concerns applied transparently.
 Reflective: Programming by manipulating the program elements.
 Array: Programming with powerful array operators.

CHAPTER 1 - LESSON 2: INTRODUCTION TO OBJECT-ORIENTED


PROGRAMMING

Introduction to Object-Oriented Programming


Understanding Object-Oriented Programming Concepts
Object-oriented programming (OOP) is a programming structure that enables developers to create and manipulate objects within a program. It is commonly used
for developing applications and systems that are both maintainable and extensible, making it a popular choice for large-scale software development.

As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to
implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that
operate on them so that no other part of the code can access this data except that function.

OOP Concepts:

 Class
 Objects
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism

What is a Class?
In Object-Oriented Programming (OOP), a class is a fundamental concept used to create objects with similar characteristics and behaviors. It serves as a blueprint
or template that defines the common attributes (properties) and actions (methods) that objects of that class will have.

Analogy:
Imagine a class as a blueprint for a house. The blueprint describes the structure, layout, and design of the house. It defines how many rooms the house will have,
where the kitchen will be located, how the doors and windows will be placed, etc.

Similarly, a class defines the structure and design of objects. It specifies what properties the objects will have (e.g., name, age, color) and what actions the objects
can perform (e.g., walk, eat, sleep).

Defining Attributes and Methods:

Attributes in a class are like characteristics or properties of the objects. For example, in a "Person" class, attributes could be name, age, and gender.

Methods in a class are like behaviors or actions that objects can perform. For instance, in a "Car" class, methods could be start(), accelerate(), and brake().

Benefits:

Using classes helps in organizing code and promoting code reusability. It allows developers to model real-world entities, systems, or concepts in their programs.
By creating classes and objects, OOP facilitates a more intuitive and modular way of thinking about and structuring complex programs.

Note:

A class is a blueprint or template that defines the structure and behavior of objects in Object-Oriented Programming. It represents a reusable code template for
creating objects with similar attributes and methods.

What is an Object?
In Object-Oriented Programming (OOP), an object is a fundamental concept that represents a real-world entity, system, or concept. It is a concrete instance created
from a class blueprint, possessing the attributes and behaviors defined in that class.

Analogy:

Think of an object as a concrete manifestation of a house based on the blueprint we discussed earlier. While the blueprint defines the structure and design of the
house, the actual house itself is the object. It has specific property values, such as the address, number of rooms, and paint color.

Similarly, an object is a specific instance of a class, representing a unique entity with its own set of attributes and behaviors.

Attributes (Properties):

An object has attributes that represent its characteristics or properties. For example, if we have a "Person" class, the attributes of a person object could be the
person's name, age, and gender. These attributes define the state of the object and hold specific values for each instance.

Methods (Behaviors):

In addition to attributes, an object has methods that define its actions or behaviors. Methods are functions associated with the object that perform certain actions.
For example, if we have a "Car" class, the methods of a car object could be start(), accelerate(), and brake().

Creating an Object:

To create an object, you use the class blueprint as a template. When you create an object from a class, it becomes an instance of that class, and it inherits all the
attributes and methods defined in the class.

For instance, if you have a "Student" class, you can create different student objects, each representing a unique student with specific attributes and behaviors.

Note:

An object in OOP is a concrete instance created from a class blueprint. It represents a real-world entity with specific attributes (properties) and behaviors
(methods). Objects allow us to model and interact with entities and systems in our programs, making it easier to understand and manipulate complex systems.
Objects are the building blocks of Object-Oriented Programming and play a central role in creating well-organized and reusable code.

Visualizing Classes and Objects


Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and objects:
Another Example:

Note:

A class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

The Four Pillars of OOP


Abstraction: Simplifying complex things by breaking them down into smaller, more manageable parts and focusing only on the essential characteristics.

Encapsulation: It's like putting code and data inside a box, hiding the internal details, and only allowing specific ways to interact with them from the outside.

Inheritance: The ability of a class (child) to inherit properties and behaviors from another class (parent), promoting code reuse and creating a hierarchical
relationship.

Polymorphism: The capacity of objects of different classes to respond to the same method name, allowing flexibility and interchangeability while maintaining a
consistent interface.

CHAPTER 1 - LESSON 3: FOUR PILLARS OF OBJECT-ORIENTED


PROGRAMMING

Four Pillars of Object-Oriented Programming


Object Oriented Programming in Java
Let's consider an example in Java to understand abstraction, encapsulation, inheritance, and polymorphism:

// Abstract class
abstract class Media {
protected String title;

public Media(String title) {


this.title = title;
}

abstract public String play();


}

// Concrete classes
class Song extends Media {
public Song(String title) {
super(title);
}

public String play() {


return "Playing song: " + title;
}
}

class Video extends Media {


public Video(String title) {
super(title);
}

public String play() {


return "Playing video: " + title;
}
}

public class Main {


public static void main(String[] args) {
Song song = new Song("Happy Song");
Video video = new Video("Funny Cat Video");

System.out.println(song.play());
System.out.println(video.play());
}
}

What is Abstraction in OOP?


Abstraction is one of the four fundamental principles of Object-Oriented Programming (OOP), along with Encapsulation, Inheritance, and Polymorphism.
Abstraction is the process of simplifying complex real-world entities or systems into their essential characteristics, ignoring unnecessary details. In OOP,
abstraction allows us to create abstract classes and interfaces that define the structure and behavior of objects without providing the implementation details.

Explanation:

Abstraction in the sample Java Code:

Abstraction is like simplifying something complex by showing only the necessary parts while hiding the details. In the context of OOP, abstraction helps us create
a clear and understandable representation of real-world entities, focusing on what they do rather than how they do it. The Java code you provided showcases
abstraction through several key points:

1. Abstract Class Media:

 The abstract class Media serves as a blueprint for different types of media, like songs and videos.
 It defines a method called play() without providing any implementation details. This method abstractly represents the action of playing a media item.
 The abstract class doesn't worry about how each type of media plays; it only ensures that all media types have a play() method.

2. Concrete Classes Song and Video:

 The concrete classes, such as Song and Video, extend the Media abstract class.
 They are required to provide a concrete implementation of the play() method defined in the Media class.
 Each concrete class defines how the specific type of media (song or video) should be played.
3. Usage in the Main Class:

 In the main method of the Main class, you create instances of both Song and Video classes.
 You use the common play() method to play the media items, treating them uniformly despite their different types.
 The actual behavior of the play() method depends on the specific implementation in each concrete class.

Why Abstraction Matters:

 Focus on Essentials: Abstraction allows you to focus on what's essential for understanding and using different types of media. You don't need to worry
about the technical details of playing each media type.

 Simplify Complexity: The complex details of playing media (like rendering audio or video) are hidden within the concrete classes. You interact with media
through a simple and common interface.

 Easy Extensibility: If you want to add a new type of media in the future, you can create a new class that extends Media and implements its own version of
the play() method. This extension doesn't disrupt the existing codebase.

 Readability and Maintainability: Abstraction leads to more readable and maintainable code. You can understand how to interact with media without
diving into intricate implementation details.

In Summation:

Abstraction in the provided Java code allows you to represent different media types in a simplified manner, focusing on what they do (playing media) rather than
how they do it. This abstraction creates a clean separation between the common interface and the specific implementations, making your code more organized,
adaptable, and comprehensible.

Note:

Abstraction in OOP allows us to model complex systems by focusing on essential features, hiding unnecessary details, and promoting code reusability and
maintainability. By using abstract classes and interfaces, we create a clear separation between what a class does and how it does it, making our code more
adaptable and flexible.

What is Encapsulation in OOP?


Encapsulation is one of the four fundamental principles of Object-Oriented Programming (OOP), along with Abstraction, Inheritance, and Polymorphism. It is a
concept that focuses on bundling the data (attributes) and the methods (behaviors) that operate on that data within a single unit called an object. In other words, it
is the practice of hiding the internal details of an object's state and behavior from the outside world.

Encapsulation in the sample Java Code:

Encapsulation is like enclosing something in a protective capsule. In OOP, encapsulation helps in hiding the internal details of an object and providing controlled
access to its attributes and behaviors. The Java code you provided demonstrates encapsulation through the following aspects:

1 Access Modifiers:

o In the Media abstract class, the title variable is declared with the protected access modifier. This means that it can only be directly accessed
within the class itself and its subclasses.
o The use of protected encapsulates the title variable, preventing direct external access and modification.

2 Getters and Setters:

o Although not explicitly shown in the provided code, getters and setters can be used to control access to the title variable.
o A getter method could allow external code to retrieve the title value, and a setter method could set the title value after performing any
necessary validation or logic.

Why Encapsulation Matters:

 Data Protection: Encapsulation safeguards the internal state of an object from unauthorized or unintended modification by external code.

 Controlled Access: By providing getters and setters, you control how external code interacts with the encapsulated data. You can impose rules and
validation when setting or getting values.

 Flexibility: You can change the internal implementation of the class (e.g., change the variable name or data type) without affecting the external code that
uses it, as long as the getter and setter methods remain consistent

 Improved Maintenance: Encapsulation makes it easier to debug and maintain your code. If there's an issue, you know where to look, as access to attributes
is limited to a well-defined set of methods.
In Summation:

Encapsulation in the Java code ensures that the title attribute's internal details are protected and controlled. External code interacts with the title through methods
that you define, allowing you to manage how the attribute is accessed and modified. Encapsulation enhances the security, reliability, and maintainability of your
code by isolating the implementation details from external users.

Note:

Encapsulation is a key concept in OOP that promotes data protection, code organization, and the creation of well-defined interfaces for interacting with objects. By
encapsulating data and methods within objects, we can create more robust, secure, and maintainable code in our programs.

What is Inheritance in OOP?


Inheritance is one of the four fundamental principles of Object-Oriented Programming (OOP), along with Encapsulation, Abstraction, and Polymorphism.
Inheritance is a mechanism that allows a class (called the subclass or derived class) to inherit properties and behaviors from another class (called the superclass or
base class). It is a way of creating a new class based on an existing class, reusing its attributes and methods, and extending its functionality.

Inheritance in the sample Java Code:

Inheritance is like inheriting traits or characteristics from your parents. In OOP, inheritance enables a class to inherit attributes and behaviors from another class.
The Java code you provided highlights inheritance through these aspects:

Base Class Media:

o The abstract class Media serves as the base class or parent class.
o It defines a common structure and behavior that all media types share, such as the title attribute and the play() method.

Derived Classes Song and Video:

o The concrete classes Song and Video are derived classes or subclasses.
o They extend the functionality of the base class by inheriting its attributes and methods.
o They can add their own specific attributes (breed for Song and Video) and override inherited methods.

Constructor Chaining:

o In the constructor of the derived classes, you use the super(title) statement to call the constructor of the base class. This is constructor
chaining.
o This ensures that the common attribute title is initialized properly in both the base and derived classes.

Why Inheritance Matters:

 Code Reusability: Inheritance promotes code reuse by allowing you to create new classes based on existing classes. You inherit the attributes and methods
of the base class, reducing duplication.

 Hierarchy and Organization: Inheritance helps organize your code into a hierarchical structure. Derived classes are specialized versions of the base class,
forming a hierarchy of related classes.

 Extensibility: When you want to add new features to a specific type of object (like a Song or Video), you can do so by extending the corresponding class
without modifying the base class.

 Consistency and Standardization: Inherited methods provide consistent behavior across related classes. A method that works for the base class also works
for all derived classes.

In Summation:

Inheritance in the Java code demonstrates how you can build a hierarchy of related classes by inheriting attributes and behaviors from a base class. It promotes
code reusability, organizational structure, and the ability to extend or specialize classes without affecting the original base class. Inheritance helps create a clear
relationship between classes that share common traits and behaviors while allowing for specific modifications and extensions where needed.

What is Polymorphism in OOP?


Polymorphism is one of the four fundamental principles of Object-Oriented Programming (OOP), along with Encapsulation, Abstraction, and Inheritance.
Polymorphism allows an object to take on multiple forms or exhibit different behaviors based on the context in which it is used. In OOP, polymorphism can be
achieved through method overloading and method overriding.
Polymorphism in the sample Java Code:

Polymorphism is like using a single interface to represent different forms. In OOP, polymorphism enables objects of different classes to be treated as objects of a
common superclass, simplifying interactions and providing flexibility. The Java code you provided illustrates polymorphism through the following points:

Common Method Signature:

o The Media abstract class defines the play() method with the same signature in both the Song and Video classes.
o This common method signature creates a uniform way to interact with different types of media.
Method Overriding:

o In both the Song and Video classes, the play() method is overridden to provide specific implementations for each type of media.
o The overridden methods have the same name and parameters as the method in the superclass, but they exhibit different behaviors.

Usage in Main Class:

o In the Main class, you create instances of both Song and Video classes.
o You call the play() method on these instances without knowing their specific types.
o The appropriate version of the play() method (from Song or Video) is invoked based on the actual instance type.

Why Polymorphism Matters:

Unified Interface: Polymorphism allows you to use a consistent interface (play()) to interact with various objects, regardless of their specific
implementations.

Flexibility: You can treat different objects in a unified manner. This is particularly useful when you have a collection of objects of different types that
share a common base class.

Extensibility: If you add more media types in the future, you can easily extend the code by creating new subclasses and overriding the common
methods.

Readability and Maintainability: Polymorphism makes your code more readable and maintainable by simplifying interactions and reducing the need
for conditionals based on object types.

In Summation:

Polymorphism in the provided Java code allows you to treat different media types uniformly through a common interface. By overriding the common method in
subclasses, you can tailor behaviors to each specific media type. Polymorphism enhances code readability, flexibility, and extensibility by allowing different
objects to be treated the same way, making your codebase more organized and adaptable.

CHAPTER 1 - LESSON 4: ADVANTAGES AND BENEFITS OF OOP

Advantages and Benefits of OOP


Advantages of OOP
Object-Oriented Programming (OOP) offers several benefits and advantages that make it a popular and widely used programming paradigm. Here are some of the
key benefits of OOP:

Modularity and Code Reusability: OOP promotes code modularity, allowing developers to divide a complex problem into smaller, manageable
modules (classes). These modules can be reused in different parts of the program or in entirely different programs, leading to significant code
reusability and saving development time.

Encapsulation and Data Hiding: OOP provides encapsulation, hiding the internal details of an object's state and behavior from the outside world. This
protects the data from being modified unintentionally and allows access to data only through well-defined interfaces, enhancing security and
maintainability.

Abstraction and Simplification: OOP allows abstraction, which simplifies complex systems by focusing on essential features and ignoring
unnecessary details. Abstraction provides a clear and simple interface for interacting with objects, making the code more readable and understandable.
Inheritance and Code Organization: Inheritance allows the creation of class hierarchies, where subclasses inherit properties and behaviors from their
superclass. This promotes code organization and extensibility, as new functionality can be added by creating new subclasses without modifying
existing code.

Polymorphism and Flexibility: Polymorphism allows objects of different classes to be treated uniformly through a common interface. This enhances
flexibility and adaptability, as objects can take on multiple forms and exhibit different behaviors based on context.

Easy Maintenance and Debugging: OOP's modular structure, encapsulation, and code reusability make maintenance and debugging easier. Changes
can be made in one part of the code without affecting other parts, reducing the likelihood of introducing errors.

Real-World Modeling: OOP enables developers to model real-world entities, systems, and interactions more intuitively. The design of OOP programs
closely resembles the objects and interactions found in the real world, making it easier to understand and implement complex systems.

Collaborative Development: OOP supports collaborative development, as different team members can work on different classes independently. This
parallel development improves productivity and teamwork.

Enhanced Software Development Life Cycle: OOP aligns well with the software development life cycle (SDLC) stages, such as requirement
gathering, analysis, design, implementation, testing, and maintenance. This ensures a systematic and organized approach to software development.

Reuse of Libraries and Frameworks: OOP encourages the creation of libraries and frameworks that can be reused across multiple projects, saving
development effort and improving the quality of software.

In summary, Object-Oriented Programming offers numerous advantages, including code reusability, maintainability, flexibility, and real-world modeling. The
principles of OOP help developers build robust, scalable, and organized software systems, making it a widely adopted programming paradigm in the software
industry.

Benefits of OOP
Benefits of OOP include:

 Modularity. Encapsulation enables objects to be self-contained, making troubleshooting and collaborative development easier.
 Reusability. Code can be reused through inheritance, meaning a team does not have to write the same code multiple times.
 Productivity. Programmers can construct new programs quicker through the use of multiple libraries and reusable code.
 Easily upgradable and scalable. Programmers can implement system functionalities independently.
 Interface descriptions. Descriptions of external systems are simple, due to message passing techniques that are used for objects communication.
 Security. Using encapsulation and abstraction, complex code is hidden, software maintenance is easier and internet protocols are protected.
 Flexibility. Polymorphism enables a single function to adapt to the class it is placed in. Different objects can also pass through the same interface.

Examples of Object-Oriented Programming Languages


While Simula is credited as being the first object-oriented programming language, many other programming languages are used with OOP today. But some
programming languages pair with OOP better than others. For example, programming languages considered pure OOP languages treat everything as objects. Other
programming languages are designed primarily for OOP, but with some procedural processes included.

Pure Object-Oriented Programming Languages:

These languages are designed with OOP as a core principle, where almost everything is treated as an object.

 Ruby: A dynamic, open-source programming language with a focus on simplicity and productivity. Everything in Ruby is an object, including
primitive data types.
 Scala: A language that integrates object-oriented and functional programming concepts, making it highly versatile and expressive.
 Smalltalk: One of the earliest and most influential pure OOP languages, where everything, including control structures, is an object.
 JADE: A programming language developed to be completely object-oriented and designed for distributed systems.
 Emerald: A language focused on distributed object-oriented programming with an emphasis on location transparency and mobility.

Programming Languages Designed Primarily for OOP:

These languages were created with strong support for OOP, though they may support other paradigms as well.

 Java: A widely-used programming language designed from the ground up to support OOP, featuring a strong type system and comprehensive standard
libraries.
 Python: Although multi-paradigm, Python has robust support for OOP and is often used for this style of programming due to its simplicity and
readability.
 C++: An extension of C that adds OOP features like classes and inheritance, allowing for both procedural and object-oriented programming.
Programming Languages that Pair with OOP:

These languages support OOP but may not be designed primarily for it, often integrating OOP features with other paradigms.

 Visual Basic .NET: A language in the .NET framework that supports OOP, providing features like inheritance, interfaces, and polymorphism while
being rooted in a more procedural background.
 PHP: A server-side scripting language that initially focused on procedural programming but has incorporated strong OOP capabilities in later versions.
 JavaScript: A versatile language commonly used for web development, supporting OOP through prototype-based inheritance and classes, especially in
its modern ES6+ versions.

CHAPTER 2 - LESSON 1: THE JAVA PROGRAMMING LANGUAGE

Introduction to Java Programming Language


What is Java?
Java is a programming language and computing platform first released by Sun Microsystems in 1995. It has evolved from humble beginnings to power a large share of
today’s digital world, by providing the reliable platform upon which many services and applications are built. New, innovative products and digital services designed for the
future continue to rely on Java, as well.

While most modern Java applications combine the Java runtime and application together, there are still many applications and even some websites that will not function
unless you have a desktop Java installed. Java.com, this website, is intended for consumers who may still require Java for their desktop applications – specifically
applications targeting Java 8. Developers as well as users that would like to learn Java programming should visit the dev.java website instead and business users should
visit oracle.com/java for more information.

More than 3 billion devices run Java.

It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!

Why Use Java?

 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
 It is one of the most popular programming language in the world
 It has a large demand in the current job market
 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast and powerful
 It has a huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa

Setting up the Java Development Environment


Java is free to download for personal use.
Java is also free for development: developers can find all the development kits and other useful tools at https://www.oracle.com/javadownload/.

Basic Syntax and Structure of Java Programs


In Java, every application begins with a class name, and that class must match the filename.

Let's create our first Java file, called Main.java, which can be done in any text editor (like Notepad).

The file should contain a "Hello World" message, which is written with the following code:

Main.java

public class Main {


public static void main(String[] args) {
System.out.println("Hello World");
}}
Try it Yourself »

Example explained
Every line of code that runs in Java must be inside a class. In our example, we named the class Main. A class should always start with an uppercase first letter.

Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.

The name of the java file must match the class name. When saving the file, save it using the class name and add ".java" to the end of the filename. To run the example above
on your computer, make sure that Java is properly installed.

Hello World

The main Method


The main() method is required and you will see it in every Java program:

public static void main(String[] args)


Any code inside the main() method will be executed. Don't worry about the keywords before and after main. You will get to know them bit by bit while reading this tutorial.

For now, just remember that every Java program has a class name which must match the filename, and that every program must contain the main() method.

System.out.println()
Inside the main() method, we can use the println() method to print a line of text to the screen:

public static void main(String[] args) {


System.out.println("Hello World");}
Try it Yourself »

Note: The curly braces {} marks the beginning and the end of a block of code.

System is a built-in Java class that contains useful members, such as out, which is short for "output". The println() method, short for "print line", is used to print a value to the
screen (or a file).

Don't worry too much about System, out and println(). Just know that you need them together to print stuff to the screen.

You should also note that each code statement must end with a semicolon (;).

You can add as many println() methods as you want. Note that it will add a new line for each method.

Double Quotes
When you are working with text, it must be wrapped inside double quotations marks "".

If you forget the double quotes, an error occurs:

Example
System.out.println("This sentence will work!");
System.out.println(This sentence will produce an error);
Try it Yourself »

The Print() Method


There is also a print() method, which is similar to println().

The only difference is that it does not insert a new line at the end of the output:

Example
System.out.print("Hello World! ");System.out.print("I will print on the same line.");
Try it Yourself »

Note that we add an extra space (after "Hello World!" in the example above), for better readability.

In this tutorial, we will only use println() as it makes it easier to read the output of code.

Java Output Numbers


You can also use the println() method to print numbers.

However, unlike text, we don't put numbers inside double quotes:

Example
System.out.println(3);System.out.println(358);System.out.println(50000);
Try it Yourself »

You can also perform mathematical calculations inside the println() method:

Example
System.out.println(3 + 3);
Try it Yourself »

Example
System.out.println(2 * 5);
Try it Yourself »

Java Comments
Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code.

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed).

This example uses a single-line comment before a line of code:

Example
// This is a commentSystem.out.println("Hello World");
Try it Yourself »

This example uses a single-line comment at the end of a line of code:

Example
System.out.println("Hello World"); // This is a comment
Try it Yourself »

Java Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the code:

Example
/* The code below will print the words Hello World
to the screen, and it is amazing */System.out.println("Hello World");
Try it Yourself »

Single or multi-line comments?

It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer.

Java Variables
Variables are containers for storing data values.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
 boolean - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable, you must specify the type and assign it a value:

Syntax

type variableName = value;


Where type is one of Java's types (such as int or String), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the
variable.

To create a variable that should store text, look at the following example:

Example
Create a variable called name of type String and assign it the value "John":

String name = "John";


System.out.println(name);
Try it Yourself »

To create a variable that should store a number, look at the following example:

Example
Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;


System.out.println(myNum);
Try it Yourself »

You can also declare a variable without assigning the value, and assign the value later:

Example
int myNum;
myNum = 15;
System.out.println(myNum);
Try it Yourself »

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Example
Change the value of myNum from 15 to 20:

int myNum = 15;


myNum = 20; // myNum is now 20
System.out.println(myNum);
Try it Yourself »

Final Variables
If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as "final" or "constant", which means unchangeable and
read-only):

Example
final int myNum = 15;
myNum = 20; // will generate an error: cannot assign a value to a final variable
Try it Yourself »

Other Types
A demonstration of how to declare variables of other types:

Example
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";

Java Print Variables


The println() method is often used to display variables.

To combine both text and a variable, use the + character:

Example
String name = "John";
System.out.println("Hello " + name);
Try it Yourself »

You can also use the + character to add a variable to another variable:

Example
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
System.out.println(fullName);
Try it Yourself »

For numeric values, the + character works as a mathematical operator (notice that we use int (integer) variables here):

Example
int x = 5;int y = 6;
System.out.println(x + y); // Print the value of x + y
Try it Yourself »

From the example above, you can expect:

 x stores the value 5


 y stores the value 6
 Then we use the println() method to display the value of x + y, which is 11

Declare Many Variables


To declare more than one variable of the same type, you can use a comma-separated list:

Example
Instead of writing:

int x = 5;int y = 6;int z = 50;


System.out.println(x + y + z);
You can simply write:

int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
Try it Yourself »
One Value to Multiple Variables
You can also assign the same value to multiple variables in one line:

Example
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);
Try it Yourself »

Java Identifiers
All Java variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and maintainable code:

Example
// Goodint minutesPerHour = 60;
// OK, but not so easy to understand what m actually isint m = 60;
Try it Yourself »

The general rules for naming variables are:

 Names can contain letters, digits, underscores, and dollar signs


 Names must begin with a letter
 Names should start with a lowercase letter and it cannot contain whitespace
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive ("myVar" and "myvar" are different variables)
 Reserved words (like Java keywords, such as int or boolean) cannot be used as names

Java Data Types


As explained earlier, a variable in Java must be a specified data type:

Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
Try it Yourself »

Data types are divided into two groups:

 Primitive data types - includes byte, short, int, long, float, double, boolean and char
 Non-primitive data types - such as String, Arrays and Classes (you will learn more about these in a later chapter)

Primitive Data Types


A primitive data type specifies the size and type of variable values, and it has no additional methods.

There are eight primitive data types in Java:

Data
Size Description
Type
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values

Java Numbers
Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are byte, short, int and long. Which type you should use, depends
on the numeric value.

Floating point types represents numbers with a fractional part, containing one or more decimals. There are two types: float and double.

Even though there are many numeric types in Java, the most used for numbers are int (for whole numbers) and double (for floating point numbers). However, we will describe
them all as you continue to read.

Integer Types

Byte

The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other integer types to save memory when you are certain that the
value will be within -128 and 127:

Example
byte myNum = 100;
System.out.println(myNum);
Try it Yourself »

Short

The short data type can store whole numbers from -32768 to 32767:

Example
short myNum = 5000;
System.out.println(myNum);
Try it Yourself »

Int

The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial, the int data type is the preferred data type when we
create variables with a numeric value.

Example
int myNum = 100000;
System.out.println(myNum);
Try it Yourself »

Long

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value.
Note that you should end the value with an "L":

Example
long myNum = 15000000000L;
System.out.println(myNum);
Try it Yourself »

Floating Point Types


You should use a floating point type whenever you need a number with a decimal, such as 9.99 or 3.14515.
The float and double data types can store fractional numbers. Note that you should end the value with an "f" for floats and "d" for doubles:

Float Example

float myNum = 5.75f;


System.out.println(myNum);
Try it Yourself »

Double Example

double myNum = 19.99d;


System.out.println(myNum);
Try it Yourself »

Use float or double?

The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits,
while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations.

Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate the power of 10:

Example
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
Try it Yourself »

Boolean Types
Very often in programming, you will need a data type that can only have one of two values, like:

 YES / NO
 ON / OFF
 TRUE / FALSE
For this, Java has a boolean data type, which can only take the values true or false:

Example
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs false
Try it Yourself »

Boolean values are mostly used for conditional testing.

You will learn much more about booleans and conditions later in this tutorial.

Characters
The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c':

Example
char myGrade = 'B'
;System.out.println(myGrade);
Try it Yourself »

Alternatively, if you are familiar with ASCII values, you can use those to display certain characters:

Example
char myVar1 = 65, myVar2 = 66, myVar3 = 67;
System.out.println(myVar1);
System.out.println(myVar2);
System.out.println(myVar3);
Try it Yourself »

Tip: A list of all ASCII values can be found in our ASCII Table Reference.

Strings
The String data type is used to store a sequence of characters (text). String values must be surrounded by double quotes:

Example
String greeting = "Hello World";
System.out.println(greeting);
Try it Yourself »

The String type is so much used and integrated in Java, that some call it "the special ninth type".

A String in Java is actually a non-primitive data type, because it refers to an object. The String object has methods that are used to perform certain operations on
strings. Don't worry if you don't understand the term "object" just yet. We will learn more about strings and objects in a later chapter.

Non-Primitive Data Types


Non-primitive data types are called reference types because they refer to objects.

The main difference between primitive and non-primitive data types are:

 Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for String).
 Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
 A primitive type has always a value, while non-primitive types can be null.
 A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. You will learn more about these in a later chapter.

Java Type Casting


Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double
 Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte

Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:

Example
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}}
Try it Yourself »

Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:

Example
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}}
Try it Yourself »
Java Operators
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
int x = 100 + 50;
Try it Yourself »

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and
another variable:

Example
int sum1 = 100 + 50; // 150 (100 + 50)int sum2 = sum1 + 250; // 400 (150 + 250)int sum3 = sum2 + sum2; // 800 (400 + 400)
Try it Yourself »

Java divides the operators into the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operato Exampl
Name Description Try it
r e
+ Addition Adds together two values x+y Try it »
- Subtraction Subtracts one value from another x-y Try it »
* Multiplication Multiplies two values x*y Try it »
/ Division Divides one value by another x/y Try it »
% Modulus Returns the division remainder x%y Try it »
++ Increment Increases the value of a variable by 1 ++x Try it »
Decreases the value of a variable by
-- Decrement --x Try it »
1

Java Assignment Operators


Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

Example
int x = 10;
Try it Yourself »

The addition assignment operator (+=) adds a value to a variable:

Example
int x = 10;
x += 5;
Try it Yourself »

A list of all assignment operators:

Operator Example Same As Try it


= x=5 x=5 Try it »
+= x += 3 x = x + 3 Try it »
-= x -= 3 x=x-3 Try it »
*= x *= 3 x = x * 3 Try it »
/= x /= 3 x = x / 3 Try it »
%= x %= 3 x = x % 3 Try it »
&= x &= 3 x = x & 3 Try it »
|= x |= 3 x = x | 3 Try it »
^= x ^= 3 x = x ^ 3 Try it »
>>= x >>= 3 x = x >> 3 Try it »
<<= x <<= 3 x = x << 3 Try it »

Java Comparison Operators


Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either true or false. These values are known as Boolean values, and you will learn more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:

Example

int x = 5;
int y = 3;
System.out.println(x > y); // returns true, because 5 is higher than 3
Try it Yourself »

Operator Name Example Try it


== Equal to x == y Try it »
!= Not equal x != y Try it »
> Greater than x>y Try it »
< Less than x<y Try it »
Greater than or equal
>= x >= y Try it »
to
<= Less than or equal to x <= y Try it »

Java Logical Operators


You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values:

Operato
Name Description Example Try it
r
&& Logical and Returns true if both statements are true x < 5 && x < 10 Try it »
|| Logical or Returns true if one of the statements is true x < 5 || x < 4 Try it »
!(x < 5 && x <
! Logical not Reverse the result, returns false if the result is true Try it »
10)

String Length
A String in Java is actually an object, which contain methods that can perform certain operations on strings. For example, the length of
a string can be found with the length() method:

Example
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";System.out.println("The length of the txt string is: " + txt.length());
Try it Yourself »
More String Methods
There are many string methods available, for example toUpperCase() and toLowerCase():

Example
String txt = "Hello World";System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"System.out.println(txt.toLowerCase()); // Outputs "hello world"
Try it Yourself »

Finding a Character in a String


The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including whitespace):

Example
String txt = "Please locate where 'locate' occurs!";System.out.println(txt.indexOf("locate")); // Outputs 7
Try it Yourself »

Note:

Java counts positions from zero.


0 is the first position in a string, 1 is the second, 2 is the third ...

String Concatenation
The + operator can be used between strings to combine them. This is called concatenation:

Example
String firstName = "John";String lastName = "Doe";System.out.println(firstName + " " + lastName);
Try it Yourself »

Note that we have added an empty text (" ") to create a space between firstName and lastName on print.

You can also use the concat() method to concatenate two strings:

Example
String firstName = "John ";String lastName = "Doe";System.out.println(firstName.concat(lastName));
Try it Yourself »

Adding Numbers and Strings


WARNING!

Java uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example
int x = 10;int y = 20;int z = x + y; // z will be 30 (an integer/number)
Try it Yourself »

If you add two strings, the result will be a string concatenation:

Example
String x = "10";String y = "20";String z = x + y; // z will be 1020 (a String)
Try it Yourself »

If you add a number and a string, the result will be a string concatenation:

Example
String x = "10";int y = 20;String z = x + y; // z will be 1020 (a String)
Try it Yourself »

Strings - Special Characters


Because strings must be written within quotes, Java will misunderstand this string, and generate an error:

String txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

Escape
Result Description
character
\' ' Single quote
\" " Double quote
\\ \ Backslash
The sequence \" inserts a double quote in a string:

Example
String txt = "We are the so-called \"Vikings\" from the north.";
Try it Yourself »

The sequence \' inserts a single quote in a string:

Example
String txt = "It\'s alright.";
Try it Yourself »

The sequence \\ inserts a single backslash in a string:

Example
String txt = "The character \\ is called backslash.";
Try it Yourself »

Other common escape sequences that are valid in Java are:

Code Result Try it


\n New Line Try it »
Carriage
\r Try it »
Return
\t Tab Try it »
\b Backspace Try it »
\f Form Feed

Java Booleans
Very often, in programming, you will need a data type that can only have one of two values, like:

 YES / NO
 ON / OFF
 TRUE / FALSE
For this, Java has a boolean data type, which can store true or false values.

Boolean Values
A boolean type is declared with the boolean keyword and can only take the values true or false:

Example
boolean isJavaFun = true;boolean isFishTasty = false;System.out.println(isJavaFun); // Outputs trueSystem.out.println(isFishTasty); // Outputs false
Try it Yourself »

However, it is more common to return boolean values from boolean expressions, for conditional testing (see below).

Boolean Expression
A Boolean expression returns a boolean value: true or false.

This is useful to build logic, and find answers.

For example, you can use a comparison operator, such as the greater than (>) operator, to find out if an expression (or a variable) is
true or false:

Example
int x = 10;int y = 9;System.out.println(x > y); // returns true, because 10 is higher than 9
Try it Yourself »

Or even easier:

Example
System.out.println(10 > 9); // returns true, because 10 is higher than 9
Try it Yourself »

In the examples below, we use the equal to (==) operator to evaluate an expression:

Example
int x = 10;System.out.println(x == 10); // returns true, because the value of x is equal to 10
Try it Yourself »

Example
System.out.println(10 == 15); // returns false, because 10 is not equal to 15
Try it Yourself »

Real Life Example


Let's think of a "real life example" where we need to find out if a person is old enough to vote.
In the example below, we use the >= comparison operator to find out if the age (25) is greater than OR equal to the voting age limit,
which is set to 18:

Example
int myAge = 25;int votingAge = 18;System.out.println(myAge >= votingAge);
Try it Yourself »

An even better approach (since we are on a roll now), would be to wrap the code above in an if...else statement, so we can perform
different actions depending on the result:

Example
Output "Old enough to vote!" if myAge is greater than or equal to 18. Otherwise output "Not old enough to vote.":

int myAge = 25;int votingAge = 18;


if (myAge >= votingAge) {
System.out.println("Old enough to vote!");} else {
System.out.println("Not old enough to vote.");}
Try it Yourself »

Booleans are the basis for all Java comparisons and conditions.

-- End of Lesson --

CHAPTER 2 - LESSON 3: JAVA CONDITIONALS, AND USER INPUT


(SCANNER)

Basic Syntax and Structure of Java Programs

Java Conditions and If Statements


You already know that Java supports the usual logical conditions from mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is true.

Syntax
if (condition) {
// block of code to be executed if the condition is true}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:

Example
if (20 > 18) {
System.out.println("20 is greater than 18");}
Try it Yourself »

We can also test variables:

Example
int x = 20;int y = 18;if (x > y) {
System.out.println("x is greater than y");}
Try it Yourself »

Example explained

In the example above we use two variables, x and y, to test whether x is greater than y (using the > operator). As x is 20, and y is 18,
and we know that 20 is greater than 18, we print to the screen that "x is greater than y".

The else Statement


Use the else statement to specify a block of code to be executed if the condition is false.

Syntax
if (condition) {
// block of code to be executed if the condition is true} else {
// block of code to be executed if the condition is false}
Example
int time = 20;if (time < 18) {
System.out.println("Good day.");} else {
System.out.println("Good evening.");}// Outputs "Good evening."
Try it Yourself »

Example explained

In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on to the else condition and print
to the screen "Good evening". If the time was less than 18, the program would print "Good day".

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true} else {
// block of code to be executed if the condition1 is false and condition2 is false}
Example
int time = 22;if (time < 10) {
System.out.println("Good morning.");} else if (time < 18) {
System.out.println("Good day.");} else {
System.out.println("Good evening.");}// Outputs "Good evening."
Try it Yourself »

Example explained

In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else if statement, is also false,
so we move on to the else condition since condition1 and condition2 is both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

Short Hand If...Else


There is also a short-hand if else, which is known as the ternary operator because it consists of three operands.

It can be used to replace multiple lines of code with a single line, and is most often used to replace simple if else statements:

Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:

Example
int time = 20;if (time < 18) {
System.out.println("Good day.");} else {
System.out.println("Good evening.");}
Try it Yourself »

You can simply write:

Example
int time = 20;String result = (time < 18) ? "Good day." : "Good evening.";System.out.println(result);
Try it Yourself »

Java Switch Statements


Instead of writing many if..else statements, you can use the switch statement.

The switch statement selects one of many code blocks to be executed:

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block}
This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;}// Outputs "Thursday" (day 4)
Try it Yourself »

The break Keyword


When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more testing.

A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

Example
int day = 4;switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");}// Outputs "Looking forward to the Weekend"
Try it Yourself »

Note that if the default statement is used as the last statement in a switch block, it does not need a break.

Java User Input


The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In
our example, we will use the nextLine() method, which is used to read Strings:

Example
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input


System.out.println("Username is: " + userName); // Output user input
}}
Run Example »

Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:

Method Description
nextBoolean(
) Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
In the example below, we use different methods to read data of various types:

Example
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");

// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();

// Output input by user


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}}
Run Example »

Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like
"InputMismatchException").

-- End of Lesson --

You might also like