0% found this document useful (0 votes)
54 views60 pages

Advanced Java Programming Concepts

The document provides an overview of advanced Java programming, covering fundamental concepts such as syntax, data types, variables, operators, control flow, and object-oriented programming principles. It also delves into advanced topics like server-side programming, multithreading, database connectivity, and modern Java features, emphasizing the importance of mastering these concepts for building robust applications. Additionally, it explains the distinction between classes and objects, methods, and data types in Java.

Uploaded by

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

Advanced Java Programming Concepts

The document provides an overview of advanced Java programming, covering fundamental concepts such as syntax, data types, variables, operators, control flow, and object-oriented programming principles. It also delves into advanced topics like server-side programming, multithreading, database connectivity, and modern Java features, emphasizing the importance of mastering these concepts for building robust applications. Additionally, it explains the distinction between classes and objects, methods, and data types in Java.

Uploaded by

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

Advanced Java Programming

Java fundamentals:

Java is a popular, object-oriented programming language widely used for building


various applications, from mobile apps to enterprise software.

1. Syntax

Java's syntax is similar to C and C++, making it relatively easy to learn for programmers
familiar with those languages. Key aspects include:
 Every Java program must contain a class definition.
 Lines of code end with a semicolon (;).
 Java is case-sensitive (e.g., myVariable and MyVariable are distinct).
2. Data types

Java utilizes both primitive and non-primitive data types.


 Primitive types: Store simple values and are predefined by the language.
o int: For integers (whole numbers).
o double: For decimal values (floating-point numbers).
o char: For single characters.
o boolean: For true/false values.

 Non-primitive (reference) types: Hold references to objects or data structures.


o String: For sequences of characters.
o Arrays: To store multiple values of the same type in a contiguous memory
location.
o Classes and Interfaces: Define the blueprint and behavior of objects.
3. Variables

Variables store data of a specific type. We can declare them by specifying the type and a
name.

int age = 30; // Declares an integer variable named age and assigns it a value of 30.
String name = "Alice"; // Declares a string variable named name and assigns it "Alice".

4. Operators

Operators perform operations on variables and values.


 Arithmetic: +, -, *, /, % for mathematical calculations.
 Assignment: =, +=, -=, etc. to assign values.
 Relational: ==, !=, <, >, <=, >= for comparisons.
 Logical: && (AND), || (OR), ! (NOT) to combine conditions.
5. Control flow

Control flow statements determine the order in which instructions are executed.
 Conditional statements: if-else and switch for making decisions based on conditions.
 Looping statements: for, while, do-while, and enhanced for loops for repeating code
blocks.

1
 Branching statements: break and continue to alter the flow of loops.
6. Object-oriented programming (OOP) concepts

Java is based on the OOP paradigm, and mastering its four pillars is key:
 Encapsulation: Bundling data (variables) and methods within a class, controlling
access through modifiers (public, private, protected).
 Inheritance: Creating new classes (subclasses) that inherit properties and behaviors
from existing ones (superclasses). Achieved using the extends keyword.
 Polymorphism: The ability of an object to take on many forms (e.g., method
overloading and overriding).
 Abstraction: Hiding complex implementation details and exposing only essential
features (achieved using abstract classes and interfaces).
7. Classes and objects
 Class: A blueprint or template for creating objects, defining their properties and
behaviors.
 Object: An instance of a class, representing a specific entity.
8. Methods

Methods are blocks of code within a class that perform specific tasks.
 They consist of a modifier, return type, name, parameters, and a body.
 Methods promote reusability and improve code readability.
9. Exception handling

Exceptions are abnormal events that disrupt a program's normal flow.


 Java provides mechanisms like try, catch, throw, throws, and finally to handle
exceptions gracefully.
 Exceptions can be checked (compile-time) or unchecked (runtime).
10. Java I/O (Input/Output)

Java I/O streams are used for reading and writing data.
 Byte Streams: Handle raw binary data.
 Character Streams: Handle character data (text).
 [Link] package: Contains classes for I/O operations.
11. Collections framework

The Java Collections Framework (JCF) provides a set of interfaces and classes to store
and manipulate groups of objects.
 Interfaces: Define standard behaviors (e.g., List, Set, Queue, Map).
 Classes: Provide concrete implementations (e.g., ArrayList, HashSet, HashMap).
 Algorithms: Offer utilities like sorting and searching.
12. Multithreading
Java supports multithreading, allowing multiple threads to run concurrently within a
program.
 Threads are lightweight sub processes, improving efficiency and responsiveness.
 Concurrency issues like race conditions and deadlocks need careful handling.
Advanced java fundamentals
Key concepts for robust and scalable applications

2
Advanced Java delves into concepts beyond the basics of Core Java, equipping
developers to build robust, scalable, and dynamic applications for enterprise-level projects,
web development, and backend systems.
Here are the key advanced Java fundamentals:
1. Server-side programming
 Servlets and JavaServer Pages (JSP): These are crucial technologies for building dynamic and
interactive web applications, focusing on handling HTTP requests and generating dynamic
web content.

 Java Enterprise Edition (Java EE) components: This includes EJB (Enterprise JavaBeans),
JPA (Java Persistence API), and JMS (Java Message Service), essential for building scalable,
multi-tiered enterprise applications.

2. Multithreading and concurrency


Advanced Java utilizes multithreading for simultaneous task execution to improve
performance. The [Link] package offers tools like ExecutorService and
synchronization mechanisms to manage shared resources and prevent issues like race
conditions and deadlocks.
3. Database connectivity (JDBC)
 Java Database Connectivity (JDBC): A standard API for connecting Java applications to
databases, allowing execution of SQL queries and management of connections.

4. Advanced frameworks
Frameworks like Spring, Hibernate, and Struts simplify development tasks such as
web development, dependency injection, and database interaction.

5. Web services
Advanced Java supports creating and using web services for communication between
applications using technologies like SOAP and RESTful services.
6. Java 8 and beyond features
Newer Java versions introduce features like Lambda Expressions, Functional
Interfaces, the Stream API, the Optional Class, and an updated Date/Time API, enhancing
code efficiency and readability.
7. Java memory management and garbage collection
Understanding the JVM memory model and how Java's automatic garbage collection
works, including different algorithms and tuning, is important for optimizing performance.
8. Reflection and annotations
 Reflection API: Allows programs to inspect and manipulate code at runtime.

 Annotations: Provide metadata to configure behaviors and reduce boilerplate code.

3
9. Java Networking and NIO
 Socket Programming: Enables communication over a network using TCP or UDP.

 Java NIO (New Input/Output): Offers a more efficient way to handle I/O operations,
particularly for network and file interactions.

Mastering these concepts helps developers build robust and scalable applications.

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform


operations on the data, while object-oriented programming is about creating objects that
contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter
development time
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:

Java Classes/Objects

Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as weight
and color, and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

4
To create a class, use the keyword class:

[Link]

Create a class named "Main" with a variable x:

public class Main {

int x = 5;

Create an Object

In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.

To create an object of Main, specify the class name, followed by the object name, and
use the keyword new:

Example

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

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

[Link](myObj.x);

Multiple Objects

You can create multiple objects of one class:

Example

Create two objects of Main:

public class Main {

int x = 5

public static void main(String[] args) {

5
Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

[Link](myObj1.x);

[Link](myObj2.x);

Using Multiple Classes

You can also create an object of a class and access it in another class. This is often
used for better organization of classes (one class has all the attributes and methods, while the
other class holds the main() method (code to be executed)).

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

 [Link]
 [Link]
[Link]
public class Main {
int x = 5;
}
[Link]
class Second {
public static void main(String[] args) {
Main myObj = new Main();
[Link](myObj.x);
}
}

When both files have been compiled:

C:\Users\Your Name>javac [Link]


C:\Users\Your Name>javac [Link]

Run the [Link] file:

C:\Users\Your Name>java Second

And the output will be:

6
5
Java Class Attributes

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

Example

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

public class Main {

int x = 5;

int y = 3;

Accessing Attributes

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

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

Example

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

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

[Link](myObj.x);

Accessing Attributes

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

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

Example

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

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

[Link](myObj.x);

Multiple Objects

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

Example

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

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

myObj2.x = 25;

[Link](myObj1.x); // Outputs 5

[Link](myObj2.x); // Outputs 25

Multiple Attributes

You can specify as many attributes as you want:

8
Example

public class Main {

String fname = "John";

String lname = "Doe";

int age = 24;

public static void main(String[] args) {

Main myObj = new Main();

[Link]("Name: " + [Link] + " " + [Link]);

[Link]("Age: " + [Link]);

Java Class Methods

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

Example

Create a method named myMethod() in Main:

public class Main {

static void myMethod() {

[Link]("Hello World!");

Example

Inside main, call myMethod():

public class Main {

static void myMethod() {

[Link]("Hello World!");

9
}

public static void main(String[] args) {

myMethod();

}// Outputs "Hello World!"

Java Data Types

As explained in the previous chapter, 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

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 type of a variable and the kind of values it can hold.

There are eight primitive data types in Java:

10
Java Numbers
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;
[Link](myNum);
Short

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

11
Example
short myNum = 5000;
[Link](myNum);
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;
[Link](myNum);
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;
[Link](myNum);
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;
[Link](myNum);

Double Example
double myNum = 19.99d;
[Link](myNum);

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,

12
while double variables have a precision of about 16 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;
[Link](f1);
[Link](d1);
Java Numbers
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;
[Link](myNum);
Short

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

13
Example
short myNum = 5000;
[Link](myNum);
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;

[Link](myNum);

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;
[Link](myNum);
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;
[Link](myNum);
Double Example
double myNum = 19.99d;
[Link](myNum);

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,

14
while double variables have a precision of about 16 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;
[Link](f1);
[Link](d1);
Java Characters
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';
[Link](myGrade);

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

Example
char myVar1 = 65, myVar2 = 66, myVar3 = 67;
[Link](myVar1);
[Link](myVar2);
[Link](myVar3);
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";
[Link](greeting);

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

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

Real-Life Example

Here's a real-life example of using different data types, to calculate and output the
total cost of a number of items:

Example
// Create variables of different data types
int items = 50;
float costPerItem = 9.99f;
float totalCost = items * costPerItem;
char currency = '$';
// Print variables
[Link]("Number of items: " + items);
[Link]("Cost per item: " + costPerItem + currency);
[Link]("Total cost = " + totalCost + currency);
Java Non-Primitive Data Types
Non-Primitive Data Types

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

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

 Primitive types in Java are predefined and built into the language, while non-primitive
types are created by the programmer (except for String).
 Non-primitive types can be used to call methods to perform certain operations,
whereas primitive types cannot.
 Primitive types start with a lowercase letter (like int), while non-primitive types
typically starts with an uppercase letter (like String).
 Primitive types always hold a value, whereas non-primitive types can be null.

Examples of non-primitive types are Strings, Arrays, Classes 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:

16
 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
[Link](myInt); // Outputs 9
[Link](myDouble); // Outputs 9.0
}
}
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
[Link](myDouble); // Outputs 9.78
[Link](myInt); // Outputs 9
}
}
Real-Life Example

Here's a real-life example of type casting where we create a program to calculate the
percentage of a user's score in relation to the maximum score in a game.

17
We use type casting to make sure that the result is a floating-point value, rather than
an integer:

Example
// Set the maximum possible score in the game to 500
int maxScore = 500;
// The actual score of the user
int userScore = 423;
/* Calculate the percentage of the user's score in relation to the maximum available
score.
Convert userScore to float to make sure that the division is accurate */
float percentage = (float) userScore / maxScore * 100.0f;
[Link]("User's percentage is " + percentage);
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;

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)

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.

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

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

19
Example
int x = 10;
x += 5;

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;
[Link](x > y); // returns true, because 5 is higher than 3

20
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:

Java Strings

Strings are used for storing text.

A String variable contains a collection of characters surrounded by double quotes:

Example

Create a variable of type String and assign it a value:

String greeting = "Hello";

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:

21
Example
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
[Link]("The length of the txt string is: " + [Link]());
More String Methods

There are many string methods available, for


example toUpperCase() and toLowerCase():

Example
String txt = "Hello World";
[Link]([Link]()); // Outputs "HELLO WORLD"
[Link]([Link]()); // Outputs "hello world"
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!";
[Link]([Link]("locate")); // Outputs 7
Java String Concatenation
String Concatenation

The + operator can be used between strings to combine them. This is


called concatenation:

Example
String firstName = "John";
String lastName = "Doe";
[Link](firstName + " " + lastName);

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

Variables in java

In Java, a variable is a container that stores a data value during program execution.
Before a variable can be used, it must be declared with a specific data type, which determines
the type of data it can hold and how much memory to allocate.
Variable declaration and initialization

22
To declare a variable, specify the data type followed by the variable name. You can
optionally assign it a value in the same statement, which is known as initialization.

Syntax:
dataType variableName = value;

Example:

java
// Declaration only
int age;

// Declaration and initialization


String name = "Alice";

// Assigning a value later


age = 30;
Types of variables

Variables are categorized based on where they are declared, which determines their scope and
lifetime.

1. Local variables

 Declared inside a method, constructor, or block of code.

 Only accessible within the block where they are defined.

 Created when the method or block is entered and destroyed when it is exited.

 Must be explicitly initialized before they are used, as they have no default value.

Example:

java
public void myMethod() {
int count = 0; // 'count' is a local variable
if (count == 0) {
String message = "Hello"; // 'message' is a local variable within
this 'if' block
[Link](message);
}
[Link](count);
}
2. Instance variables

23
 Declared within a class, but outside any method, constructor, or block.

 Created when an object (instance) of the class is created and are unique to that instance.

 Destroyed when the object is destroyed by the garbage collector.

 Have a default value if not explicitly initialized (e.g., 0 for numeric types, null for
objects, false for booleans).

Example:

java
public class Car {
String brand; // 'brand' is an instance variable
int year; // 'year' is an instance variable
}
3. Static variables (or Class variables)

 Declared within a class using the static keyword.

 Belong to the class itself, not to any specific object. Only a single copy exists, which is
shared among all instances of the class.

 Created when the program starts and destroyed when it stops.

 Have default values, similar to instance variables.

Example:

java
public class Counter {
static int count = 0; // 'count' is a static variable
public Counter() {
count++;
}
}

Example
String firstName = "John ";
String lastName = "Doe";
[Link]([Link](lastName));
Adding Numbers and Strings

WARNING!

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

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)

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)
Java Special Characters
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:

25
The sequence \" inserts a double quote in a string:

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

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

Example
String txt = "It\'s alright.";

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

Example
String txt = "The character \\ is called backslash.";

Java Math

The Java Math class has many methods that allows you to perform mathematical tasks
on numbers.

[Link](x,y)

The [Link](x,y) method can be used to find the highest value of x and y:

Example
[Link](5, 10);
[Link](x,y)

The [Link](x,y) method can be used to find the lowest value of x and y:

26
Example
[Link](5, 10);
[Link](x)

The [Link](x) method returns the square root of x:

Example
[Link](64);
[Link](x)

The [Link](x) method returns the absolute (positive) value of x:

Example
[Link](-4.7);
Random Numbers

[Link]() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):

Example
[Link]();

To get more control over the random number, for example, if you only want a random
number between 0 and 100, you can use the following formula:

Example
int randomNum = (int)([Link]() * 101); // 0 to 100
Java Booleans
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.

The name Boolean comes from George Boole, a mathematician who first defined the logic
system used in computers today.

Boolean Values

27
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;
[Link](isJavaFun); // Outputs true
[Link](isFishTasty); // Outputs false

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

Boolean Expressions

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

This is useful to build logic and make decisions in programs.

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;
[Link](x > y); // returns true, because 10 is greater than 9

Or even easier:

Example
[Link](10 > 9); // returns true, because 10 is greater than 9

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

Example
int x = 10;
[Link](x == 10); // returns true, because the value of x is equal to 10
Example
[Link](10 == 15); // returns false, because 10 is not equal to 15
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.

28
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;
[Link](myAge >= votingAge);

An even better approach 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) {

[Link]("Old enough to vote!");

} else {

[Link]("Not old enough to vote.");\

Booleans are the basis for all Java comparisons and conditions.

You will learn more about conditions (if...else) in the next chapter.

Java Modifiers
Modifiers

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

Public class Main

The public keyword is an access modifier, meaning that it is used to set the access
level for classes, attributes, methods and constructors.

We divide modifiers into two groups:

 Access Modifiers - controls the access level


 Non-Access Modifiers - do not control access level, but provides other functionality

29
Access Modifiers

For classes, you can use either public or default:

Public vs. Private Example

In the example below, the class has one public attribute and one private attribute.

Think of it like real life:

 public - a public park, everyone can enter


 private - your house key, only you can use it

Java Non-Access Modifiers


Non-Access Modifiers

30
Non-access modifiers do not control visibility (like public or private), but instead
add other features to classes, methods, and attributes.

The most commonly used non-access modifiers are final, static, and abstract.

Final

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

Example
public class Main {
final int x = 10;
final double PI = 3.14;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 50; // will generate an error: cannot assign a value to a final variable
[Link] = 25; // will generate an error: cannot assign a value to a final variable
[Link](myObj.x);
}
}
Static

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

Example

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

public class Main {

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

31
}

// Main method

public static void main(String[ ] args) {

myStaticMethod(); // Call the static method

// myPublicMethod(); This would output an error

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

[Link](); // Call the public method

Abstract

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

32
Example
// Code from filename: [Link]
// abstract class
abstract class Main {
public String fname = "John";
public int age = 24;
public abstract void study(); // abstract method
}
// Subclass (inherit from Main)
class Student extends Main {
public int graduationYear = 2018;
public void study() { // the body of the abstract method is provided here
[Link]("Studying all day long");
}
}
// End code from filename: [Link]
// Code from filename: [Link]
class Second {
public static void main(String[] args) {
// create an object of the Student class (which inherits attributes and methods from
Main)
Student myObj = new Student();
[Link]("Name: " + [Link]);
[Link]("Age: " + [Link]);
[Link]("Graduation Year: " + [Link]);
[Link](); // call abstract method
}
}
Non-Access Modifiers List

For classes, you can use either final or abstract:

33
Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users.
To achieve this, you must:

 declare class variables/attributes as private


 provide public get and set methods to access and update the value of
a private variable
Get and Set

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

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

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

34
Example
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
[Link] = newName;
}
}
Encapsulation
 Better control of class attributes and methods
 Class attributes can be made read-only (if you only use the get method), or write-
only (if you only use the set method)
 Flexible: the programmer can change one part of the code without affecting other
parts
 Increased security of data

Java Packages
Java Packages & API

A package in Java is used to group related classes. Think of it as a folder in a file


directory. We use packages to avoid name conflicts, and to write a better maintainable code.
Packages are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)
Built-in Packages

The Java API is a library of prewritten classes, that are free to use, included in the
Java Development Environment.

The library contains components for managing input, database programming, and
much more. The complete list can be found at Oracles.

The library is divided into packages and classes. Meaning you can either import a
single class (along with its methods and attributes), or a whole package that contain all the
classes that belong to the specified package.

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

35
Syntax

import [Link]; // Import a single class

import [Link].*; // Import the whole package

Import a Class

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

Example
import [Link];

In the example above, [Link] is a package, while Scanner is a class of 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 a complete line:

Example

Using the Scanner class to get user input

import [Link];

class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner([Link]);

[Link]("Enter username");

String userName = [Link]();

[Link]("Username is: " + userName);

Import a Package

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

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

36
Example
import [Link].*;
User-defined Packages

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

Example
└── root
└── mypack
└── [Link]

To create a package, use the package keyword:

[Link]
package mypack;
class MyPackageClass {
public static void main(String[] args) {
[Link]("This is my package!");
}
}

Save the file as [Link], and compile it:

C:\Users\Your Name>javac [Link]

Then compile the package:

C:\Users\Your Name>javac -d . [Link]


Java Inheritance
Java Inheritance (Subclass and Superclass)

In Java, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:

 subclass (child) - the class that inherits from another class


 superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):

37
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 [Link]([Link] + " " +
[Link])
}
}
Arrays

In Java, an array is a fundamental data structure that stores a fixed-size, sequential


collection of elements of the same data type. An array is a container object, and its length is
established when it is created.

Key features

 Fixed size: The size of an array cannot be changed after creation. This makes memory
management predictable but can lead to waste or errors if the required size changes.

 Homogeneous elements: An array can only store elements of the same data type. This can be
a primitive (e.g., int, char) or an object (e.g., String).

 Zero-based indexing: The elements are accessed using a numerical index, which starts
at 0 for the first element.

 Memory allocation: Arrays are dynamically allocated objects in Java, meaning memory is
allocated on the heap at runtime. For primitive types, the values are stored in contiguous

38
memory. For objects, the contiguous memory holds references to the objects, which may be
located elsewhere on the heap.

 .length property: The number of elements in an array can be obtained by accessing


its length property.

One-dimensional arrays

Declaration

An array variable can be declared in two ways:

 dataType[] arrayName; (Preferred)

 dataType arrayName[];

Example:

java
int[] numbers; // Declares an array that will hold integers
String[] names; // Declares an array that will hold strings
Instantiation

After declaration, memory for the array must be allocated using the new keyword.

Example:

java
int[] numbers;
numbers = new int[5]; // Allocates memory for 5 integers
Initialization

An array can be initialized with values at the time of creation.

Method 1: Manual assignment

java
int[] numbers = new int[3];
numbers[0] = 100;
numbers[1] = 200;
numbers[2] = 300;

Method 2: Using an array literal

java
int[] numbers = {100, 200, 300};

39
String[] cars = {"Volvo", "BMW", "Ford"};

Accessing elements

Elements are accessed using their index, from 0 to [Link] - 1.

java
String[] cars = {"Volvo", "BMW", "Ford"};
[Link](cars[0]); // Outputs "Volvo"

Iterating through an array

A standard for loop or an enhanced for loop (for-each) can be used.

Standard for loop:

java
for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}

Enhanced for loop:

java
for (int number : numbers) {
[Link](number);
}

Multidimensional arrays

A multidimensional array is an "array of arrays" and is useful for storing data in a


tabular format, like a matrix.

Declaration and instantiation

java
// Declares and instantiates a 2D array with 3 rows and 3 columns
int[][] matrix = new int[3][3];

Initialization

java
int[][] matrix = {

40
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing and iterating

Elements are accessed using multiple indices.

java
[Link](matrix[0][1]); // Outputs 2

// Iterating a 2D array
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}

The Arrays class

The [Link] class provides many useful static methods for manipulating arrays,
including:

 [Link](array): Sorts the elements in ascending order.

 [Link](array, key): Searches for a value in a sorted array.

 [Link](original, newLength): Copies an array.

 [Link](array, value): Fills all array elements with a static value.

 [Link](array): Returns a string representation of the array.

Disadvantages

 Fixed size: The main drawback is that the size cannot be changed after creation, making it
inefficient for adding or removing elements.

 Inefficient insertion/deletion: Inserting or deleting an element requires creating a new array


and copying elements, which is a costly operation.

For scenarios requiring a resizable collection, the ArrayList class (a part of the Java
Collections Framework) is a more flexible and efficient alternative.

41
primitive types in java

In
Jav
a,
pri
mit
ive
typ
es
are
the
bas
ic
buil
din
g
blo
cks
for
stor
ing
sim
ple,
dire
ct
val
ues
like
nu
mb
ers
and
cha
ract
ers.
The
re
are
eig
ht
pre
defi
ned
pri
mit
ive
dat
a

42
typ
es,
whi
ch
are
cat
ego
rize
d
into
inte
ger
s,
floa
ting
-
poi
nt
nu
mb
ers,
cha
ract
ers,
and
boo
lea
ns.
Unlike non-primitive types (objects) such as String or Array, primitive types do not
have methods and are always stored directly in memory, making them highly efficient.
Integer types
Integer types are used for whole-number values. Java has four integer types with different
storage sizes.
 byte: An 8-bit signed integer.
o Size: 1 byte (8 bits)
o Range: -128 to 127
o Use case: Conserves memory when working with large arrays of small integer
values.
 short: A 16-bit signed integer.
o Size: 2 bytes (16 bits)
o Range: -32,768 to 32,767
o Use case: Useful for memory-sensitive applications, like embedded systems,
when an int is not necessary.
 int: A 32-bit signed integer.
o Size: 4 bytes (32 bits)
o Range: Approximately -2.14 billion to +2.14 billion (

43
-231negative 2 to the 31st power
−231
to
(231−1)open paren 2 to the 31st power minus 1 close paren
(231−1)
).
o Use case: The most common choice for general-purpose integer data.
 long: A 64-bit signed integer.
o Size: 8 bytes (64 bits)
o Range: Approximately -9.22 quintillion to +9.22 quintillion (
-263negative 2 to the 63rd power
−263
to
(263−1)open paren 2 to the 63rd power minus 1 close paren
(263−1)
).
o Use case: For situations where an int is not large enough to hold a value. A
numeric literal for a long should end with an L or l (e.g., 15000000000L).
Floating-point types
Floating-point types are used for numbers with fractional parts.
 float: A 32-bit single-precision floating-point number.
o Size: 4 bytes (32 bits)
o Precision: Up to 7 decimal digits.
o Use case: Use for single-precision decimal values. The literal for a float must
end with f or F (e.g., 9.81f).
 double: A 64-bit double-precision floating-point number.
o Size: 8 bytes (64 bits)
o Precision: Up to 15 decimal digits.
o Use case: The default data type for decimal values in Java and used when
greater precision is needed.
Character type
 char: A single 16-bit Unicode character.
o Size: 2 bytes (16 bits)
o Range: Can represent characters from '\u0000' (0) to '\uffff' (65,535).
o Use case: Stores a single character and is enclosed in single quotes (e.g., 'A').
Boolean type
 boolean: A logical data type that represents a true or false value.
o Size: The size is not precisely defined by the language specification, but it can
be implemented to represent a single bit.
o Range: true or false
o Use case: Used for simple flags and conditional logic.
Type conversion and casting in java

In Java, type conversion involves changing a value from one data type to another

44
. The two main types of conversion are implicit (automatic) type conversion and explicit
(manual) type casting.

Implicit (widening) type conversion

Also known as widening conversion, this happens automatically when a smaller data
type is converted into a larger data type. The Java compiler performs this for you because
there is no risk of losing data.

Hierarchy (from smallest to largest):


byte → short → char → int → long → float → double

Example:
An int can be implicitly converted to a double.

java
int myInt = 9;
double myDouble = myInt; // Automatic conversion: int to double
[Link](myDouble); // Outputs 9.0
Use code with caution.

Explicit (narrowing) type casting

This type of conversion must be done manually by the programmer because it


involves converting a larger data type into a smaller one, which could lead to data loss. To
perform an explicit cast, you use the cast operator () with the target data type.

Hierarchy (from largest to smallest):


double → float → long → int → short → byte

Example:
A double can be explicitly cast to an int. The fractional part is truncated.

java
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
[Link](myInt); // Outputs 9
Use code with caution.

Type promotion in expressions

When performing an arithmetic operation with mixed data types, Java automatically
promotes the operands to the largest data type involved to ensure accuracy.

Rules of type promotion:

 All byte, short, and char values are promoted to int.

45
 If one operand is a long, float, or double, the entire expression is promoted to that type.

Example:

java
int i = 10;
long l = 20L;
float f = 15.5f;

// The result is a float because float has a higher hierarchy than int and long
float result = i + l + f;
Use code with caution.

Casting with reference types

Type casting can also be used with objects, particularly within an inheritance hierarchy.

 Upcasting: Treating a subclass object as an instance of its superclass. This is safe and
happens automatically.

 Downcasting: Casting a superclass reference back to one of its subclass types. This must be
done explicitly and can cause a ClassCastException if the object is not a valid instance of the
subclass.

Example of upcasting and downcasting:

java
class Animal {
void speak() { [Link]("Animal speaks"); }
}

class Dog extends Animal {


void bark() { [Link]("Woof!"); }
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Upcasting is implicit

// To access the Dog-specific bark() method, you must downcast


if (myAnimal instanceof Dog) {
Dog myDog = (Dog) myAnimal; // Explicit downcasting
[Link]();
}
}

46
}
Converting between primitives and String

Incompatible types, such as a primitive and a String, require using dedicated


conversion methods rather than a cast operator.

Examples:

java
// Primitive to String
int num = 123;
String str = [Link](num);

// String to Primitive
String data = "456";
int num2 = [Link](data);
OPERATORS IN JAVA

In Java, operators are special symbols that perform operations on variables and
values. They are categorized based on the type of operation they perform.

Arithmetic operators

These are used to perform basic mathematical calculations.

 + (Addition)

 - (Subtraction)

 * (Multiplication)

 / (Division)

 % (Modulus), which returns the remainder of a division.

Assignment operators

These operators are used to assign a new value to a variable.

 = (Simple assignment)

 += (Add and assign): x += 5 is equivalent to x = x + 5.

 -= (Subtract and assign)

 *= (Multiply and assign)

47
 /= (Divide and assign)

 %= (Modulus and assign)

Unary operators

These operators act on a single operand.

 + (Unary plus): Indicates a positive value.

 - (Unary minus): Negates an expression.

 ++ (Increment): Increases a value by 1. Can be used as a prefix (++x) or postfix (x++).

 -- (Decrement): Decreases a value by 1. Can be used as a prefix (--x) or postfix (x--).

 ! (Logical NOT): Inverts the value of a boolean.

Relational operators

Also known as comparison operators, these compare two values and return a boolean result
(true or false).

 == (Equal to)

 != (Not equal to)

 > (Greater than)

 < (Less than)

 >= (Greater than or equal to)

 <= (Less than or equal to)

Logical operators

Used to combine multiple conditions or reverse the logical state of a Boolean.

 && (Logical AND): Returns true if both operands are true.

 || (Logical OR): Returns true if at least one operand is true.

 ! (Logical NOT): Inverts the Boolean value of an operand.

Bitwise operators

48
These operators perform operations on individual bits of integers.

 & (Bitwise AND)

 | (Bitwise OR)

 ^ (Bitwise XOR)

 ~ (Bitwise complement)

 << (Left shift)

 >> (Right shift)

 >>> (Unsigned right shift)

Ternary operator

Also known as the conditional operator, this is a shorthand for an if-else statement. It
has the following format: condition ? value_if_true : value_if_false.

Instance of operator

This is a comparison operator used to check if an object is an instance of a particular


class or interface. It returns true or false.

Operator precedence

When multiple operators appear in a single expression, operator precedence


determines the order in which they are evaluated. For example, multiplication (*) and
division (/) have higher precedence than addition (+) and subtraction (-). Parentheses can be
used to override the default order of precedence.
CONTROL STATEMENTS IN JAVA

Control statements in Java manage the flow of a program by determining which code
executes and in what order
. They are categorized into three main types: decision-making, looping, and jumping
statements.

Decision-making statements

These statements evaluate a boolean condition and execute a specific block of code
based on whether the condition is true or false.

if-else-if

49
This statement allows a program to execute different blocks of code for more than two
conditions.

java
int score = 75;
if (score >= 90) {
[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B");
} else if (score >= 70) {
[Link]("Grade: C");
} else {
[Link]("Grade: D or F");
}
switch

The switch statement is an alternative to a long if-else-if chain. It evaluates a single


expression and executes code from the matching case block.

java
char grade = 'B';
switch (grade) {
case 'A':
[Link]("Excellent!");
break;
case 'B':
[Link]("Good job!");
break;
case 'C':
[Link]("Well done.");
break;
default:
[Link]("Need improvement.");
}
Ternary operator

This is a short hand for a simple if-else statement. It evaluates a boolean condition and
returns one of two expressions.

java
int number = 10;
String result = (number % 2 == 0) ? "Even" : "Odd";
[Link]("The number is " + result);

50
Looping statements

Also known as iterative statements, these are used to execute a block of code
repeatedly as long as a certain condition remains true.

for loop

This loop is used when the number of iterations is known in advance. It combines the
initialization, condition, and update expressions into a single line.

java
for (int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}
for-each loop

java
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
[Link](fruit);
}
while loop

The while loop repeatedly executes a block of code as long as its condition is true. It
is best used when the number of iterations is not known beforehand.

java
int i = 1;
while (i <= 5) {
[Link]("Count: " + i);
i++;
}
do-while loop

This loop is similar to the while loop but guarantees that the code block is executed at
least once before the condition is checked.

java
int i = 1;
do {
[Link]("Count: " + i);
i++;
} while (i <= 5);
Jumping statements

51
These statements transfer the flow of control to another part of the program.

break

The break statement is used to immediately exit a loop or switch statement.

for (int i = 1; i <= 10; i++) {


if (i == 6) {
break; // Exits the loop when i is 6
}
[Link](i);
}
continue

The continue statement skips the rest of the current iteration of a loop and moves on to the
next one.

for (int i = 1; i <= 5; i++) {


if (i % 2 == 0) {
continue; // Skips even numbers
}
[Link](i);
}
Output:

1
3
5

return

The return statement exits from the current method and returns control to the caller. It
can optionally return a value.

public int calculateSum(int a, int b) {


return a + b; // Returns the sum and exits the method
}
classes and methods in java

A class is a blueprint for creating objects, while methods define the behaviours that an object
can perform. A class combines data (variables or "fields") with methods into a single,
cohesive unit.

Classes

A class is a user-defined data type that acts as a template for objects.

52
 It is a logical construct that outlines the attributes (state) and methods (behavior) that its
objects will have.

 Classes do not occupy memory until an object (or "instance") is created from them.

 In addition to methods and fields, a class can contain constructors, nested classes, and
interfaces.

Example: Bicycle class

A Bicycle class can serve as a blueprint for different types of bicycles.

public class Bicycle {


// fields (state)
String color;
int gear = 1;

// constructor
public Bicycle(String color) {
[Link] = color;
}

// methods (behavior)
public void applyBrake() {
[Link]("Brake applied.");
}

public void changeGear(int newGear) {


[Link] = newGear;
[Link]("Gear changed to: " + gear);
}
}
Methods

A method is a block of code within a class that performs a specific task and only runs when it
is called.

 Methods provide modularity and code reusability by allowing you to define a set of actions
once and use it multiple times.

 They can accept input data, known as parameters, and can return a value.

Method syntax

53
A method declaration typically includes the following components:

 Access modifier: Defines the visibility of the method (e.g., public , private ).

 Return type: The data type of the value the method returns. Use the void keyword if the
method does not return a value.

 Method name: The name of the method. By convention, it should be in camelCase .

 Parameter list: An optional, comma-separated list of inputs the method accepts, enclosed in
parentheses () .

 Method body: The block of code that defines the actions the method performs, enclosed in
curly braces {} .

How classes and methods work together

Methods defined within a class are used to manipulate the data (fields) of an object created
from that class.

Example: Using the Bicycle class and its methods

To use the Bicycle class, you first create an object, or instance, of it using
the new keyword.

public class BikeShop {


public static void main(String[] args) {
// Create a new Bicycle object named 'myBike'
Bicycle myBike = new Bicycle("blue");

// Access the object's properties and call its methods


[Link]("My bike's color is: " + [Link]); // Output: My bike's color is:
blue

[Link](3); // Call the changeGear() method


[Link](); // Call the applyBrake() method
}
}

 myBike is an object of the Bicycle class.

 The [Link] line accesses the color field of the myBike object.

54
 The [Link](3) and [Link]() lines call the methods on
the myBike object using the dot ( . ) operator.

Static vs. instance methods

 Instance methods, like changeGear() and applyBrake() in the example, belong to a specific
object and require an object instance to be called.

 Static methods, declared with the static keyword, belong to the class itself and can be called
directly on the class name without creating an object. The main entry point for a Java
application, public static void main(String[] args) , is a static method.

inheritance in java

Inheritance in Java is an OOP concept where one class inherits properties from another,
creating a parent-child relationship for code reuse.

Key terms include:

 Superclass: The class whose features are inherited.

 Subclass: The class that inherits from the superclass and can add or override features.

 extends : Keyword used by a subclass to inherit from a superclass.

 super : Keyword used in a subclass to access superclass members.

55
Java supports several types of inheritance, but handles multiple inheritance specifically:

 Single inheritance: A subclass inherits from one superclass. (See example in referenced
document)

 Multilevel inheritance: A chain of inheritance where a subclass inherits from a class which is
itself a subclass. (See example in referenced document)

 Hierarchical inheritance: Multiple subclasses inherit from a single superclass. (See example
in referenced document)

 Multiple inheritance: Not supported directly for classes to avoid the "Diamond Problem," but
achievable by implementing multiple interfaces. (See example in referenced document)

 Hybrid inheritance: A combination of inheritance types, typically involving class inheritance


and interface implementation in Java.

Inheritance offers several benefits:

 Code Reusability: Reduces redundant code by allowing subclasses to use superclass methods
and fields.

 Method Overriding: Allows subclasses to provide specific implementations of superclass


methods.

 Polymorphism: Enables parent class references to refer to child class objects.

 Hierarchical Structure: Organizes code logically for better understanding and maintenance.

The final keyword can prevent inheritance: a final class cannot be extended, and
a final method cannot be overridden.

Exception Handling in java

56
Exception handling in Java is a robust mechanism for managing runtime errors and ensuring
that the normal flow of an application continues smoothly. An exception is an object that
represents an unexpected event that disrupts the program's normal execution.

Exception hierarchy

All exceptions and errors in Java are subclasses of the Throwable class.

 Errors: These represent serious, irrecoverable problems that are generally beyond the control
of the application. Examples include OutOfMemoryError and StackOverflowError .

 Exceptions: These represent conditions that a well-designed application might want to catch
and handle. They are further divided into two main types.

o Checked Exceptions: These are checked at compile-time and the compiler forces you to
either handle them (using try-catch ) or declare them (using throws ). Examples
include IOException and SQLException .

o Unchecked Exceptions: These are not checked at compile-time but occur at runtime, often
due to programming errors. They are subclasses of RuntimeException . Examples
include ArithmeticException , NullPointerException ,
and ArrayIndexOutOfBoundsException .

Keywords for exception handling

Java provides five keywords to handle exceptions:

 try : Encloses a block of code that might throw an exception. A try block must be followed
by a catch or finally block.

 catch : A block of code used to handle the exception thrown from the try block. A try block
can have multiple catch blocks to handle different types of exceptions.

 finally : A block of code that is always executed, regardless of whether an exception occurs
or is handled. It is commonly used for resource cleanup.

 throw : Used to explicitly throw an instance of an exception. This is useful for signaling a
specific error condition.

 throws : Used in a method's signature to declare the types of checked exceptions that the
method can potentially throw. It delegates the responsibility of handling the exception to the
calling method.

57
try-catch-finally block

This is the standard and most common method for handling exceptions.

public class ExceptionExample {


public static void main(String[] args) {
try {
// Code that may throw an exception
int result = 10 / 0;
} catch (ArithmeticException e) {
// This catch block handles the ArithmeticException
[Link]("Error: " + [Link]());
} finally {
// This code always executes
[Link]("Finally block executed.");
}
}
}
// Output:
// Error: / by zero
// Finally block executed.

try-with-resources statement

Introduced in Java 7, this statement simplifies resource management by automatically closing


any resource that implements the AutoCloseable interface.

import [Link];
import [Link];

public class ResourceExample {


public static void main(String[] args) {
try (FileReader reader = new FileReader("[Link]")) {
// Code that uses the resource
int character;
while ((character = [Link]()) != -1) {
[Link]((char) character);
}
} catch (IOException e) {
[Link]("An I/O error occurred: " + [Link]());
}
}
}

58
Creating custom exceptions

// Custom exception class


public class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
// Example class that uses the custom exception
public class UserValidation {
public static void validateAge(int age) throws InvalidAgeException {
if (age < 0 || age > 120) {
throw new InvalidAgeException("Age is not valid");
}
[Link]("Age is valid.");
}
public static void main(String[] args) {
try {
validateAge(150);
} catch (InvalidAgeException e) {
[Link]("Caught custom exception: " + [Link]());
}
}
}
// Output:
// Caught custom exception: Age is not valid
Best practices

 Catch specific exceptions: Avoid catching generic exceptions like Exception . Handle
specific exceptions to provide more precise error handling and avoid masking underlying
issues.

 Avoid empty catch blocks: Never ignore exceptions. At the very least, log the exception and
its stack trace to aid debugging.

 Use finally for cleanup: Place critical cleanup code, such as closing file streams or database
connections, in a finally block to ensure it runs.

59
 Throw early, catch late: Throw an exception as soon as an error condition is detected. Catch
the exception at a higher level in the call stack where it can be handled appropriately, or
where the user can be notified.

 Provide meaningful exception messages: Include descriptive messages in your exceptions to


provide context about what went wrong, which is crucial for debugging.

60

You might also like