Advanced Java Programming Concepts
Advanced Java Programming Concepts
Java fundamentals:
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
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
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
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.
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.
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.
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
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.
Create a Class
4
To create a class, use the keyword class:
[Link]
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
int x = 5;
[Link](myObj.x);
Multiple Objects
Example
int x = 5
5
Main myObj1 = new Main(); // Object 1
[Link](myObj1.x);
[Link](myObj2.x);
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);
}
}
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
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
int x = 5;
[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
int x = 5;
[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
int x = 5;
myObj2.x = 25;
[Link](myObj1.x); // Outputs 5
[Link](myObj2.x); // Outputs 25
Multiple Attributes
8
Example
You learned from the Java Methods chapter that methods are declared within a class,
and that they are used to perform certain actions:
Example
[Link]("Hello World!");
Example
[Link]("Hello World!");
9
}
myMethod();
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
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.
10
Java Numbers
Numbers
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);
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
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
[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.
Type casting is when you assign a value of one primitive data type to another type.
16
Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
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
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
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)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
18
Java Assignment Operators
In the example below, we use the assignment operator (=) to assign the value 10 to a
variable called x:
Example
int x = 10;
19
Example
int x = 10;
x += 5;
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
Example
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
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
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;
Variables are categorized based on where they are declared, which determines their scope and
lifetime.
1. Local variables
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.
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)
Belong to the class itself, not to any specific object. Only a single copy exists, which is
shared among all instances of the class.
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.
Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer/number)
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.";
Example
String txt = "It\'s alright.";
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)
Example
[Link](64);
[Link](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
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.":
} else {
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:
The public keyword is an access modifier, meaning that it is used to set the access
level for classes, attributes, methods and constructors.
29
Access Modifiers
In the example below, the class has one public attribute and one private attribute.
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
// Static method
// Public method
31
}
// Main method
Abstract
An abstract method belongs to an abstract class, and it does not have a body. The
body is provided by the subclass:
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
33
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users.
To achieve this, you must:
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
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 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
import [Link];
class Main {
[Link]("Enter 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]
[Link]
package mypack;
class MyPackageClass {
public static void main(String[] args) {
[Link]("This is my package!");
}
}
In Java, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:
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
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.
One-dimensional arrays
Declaration
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
java
int[] numbers = new int[3];
numbers[0] = 100;
numbers[1] = 200;
numbers[2] = 300;
java
int[] numbers = {100, 200, 300};
39
String[] cars = {"Volvo", "BMW", "Ford"};
Accessing elements
java
String[] cars = {"Volvo", "BMW", "Ford"};
[Link](cars[0]); // Outputs "Volvo"
java
for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}
java
for (int number : numbers) {
[Link](number);
}
Multidimensional arrays
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
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 [Link] class provides many useful static methods for manipulating arrays,
including:
Disadvantages
Fixed size: The main drawback is that the size cannot be changed after creation, making it
inefficient for adding or removing elements.
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.
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.
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.
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.
When performing an arithmetic operation with mixed data types, Java automatically
promotes the operands to the largest data type involved to ensure accuracy.
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.
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.
java
class Animal {
void speak() { [Link]("Animal speaks"); }
}
46
}
Converting between primitives and String
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
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
Assignment operators
= (Simple assignment)
47
/= (Divide and assign)
Unary operators
Relational operators
Also known as comparison operators, these compare two values and return a boolean result
(true or false).
== (Equal to)
Logical operators
Bitwise operators
48
These operators perform operations on individual bits of integers.
| (Bitwise OR)
^ (Bitwise XOR)
~ (Bitwise complement)
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
Operator precedence
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
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 continue statement skips the rest of the current iteration of a loop and moves on to the
next one.
1
3
5
return
The return statement exits from the current method and returns control to the caller. It
can optionally return a value.
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
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.
// constructor
public Bicycle(String color) {
[Link] = color;
}
// methods (behavior)
public void applyBrake() {
[Link]("Brake applied.");
}
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.
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 {} .
Methods defined within a class are used to manipulate the data (fields) of an object created
from that class.
To use the Bicycle class, you first create an object, or instance, of it using
the new keyword.
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.
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.
Subclass: The class that inherits from the superclass and can add or override features.
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)
Code Reusability: Reduces redundant code by allowing subclasses to use superclass methods
and fields.
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.
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 .
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.
try-with-resources statement
import [Link];
import [Link];
58
Creating custom exceptions
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.
60