Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

COURSE CODE: CPT 221

COURSE TITLE: OBJECT-ORIENTED PROGRAMMING II

JAVA FUNDAMENTALS
INTRODUCTION
Java is a powerful, versatile, and widely-used programming language known for its
simplicity, robustness, and platform independence. It was developed by Sun Microsystems
(which was later acquired by Oracle Corporation) in the mid-1990s by a team led by James
Gosling. Here's an introduction to Java programming language:
1. Platform Independence: One of the key features of Java is its platform
independence. Java programs are compiled into bytecode, which can run on any
device with a Java Virtual Machine (JVM) installed. This "write once, run anywhere"
capability makes Java suitable for developing applications ranging from small applets
to large enterprise systems.
2. Object-Oriented: Java is a fully object-oriented programming language. It supports
concepts like classes, objects, inheritance, polymorphism, and encapsulation. Object-
oriented programming (OOP) enables developers to create modular, reusable, and
maintainable code.
3. Syntax: Java syntax is similar to that of C and C++, making it familiar to programmers
from those backgrounds. It has a C-like syntax with curly braces {}, semicolons ;, and
a rich set of keywords like public, private, class, static, etc.
4. Automatic Memory Management: Java employs automatic garbage collection,
which manages memory allocation and deallocation. Developers do not need to
explicitly allocate and deallocate memory as the JVM takes care of it, reducing the risk
of memory leaks and memory-related errors.
5. Rich Standard Library: Java comes with a vast standard library (Java API) that
provides ready-to-use classes and methods for various tasks such as input/output
operations, networking, database connectivity, GUI development, and more. This
extensive library simplifies development and saves time by offering pre-built
solutions to common programming challenges.
6. Security: Security is a major concern in software development, especially for web-
based and enterprise applications. Java addresses security concerns by providing
features like sandboxing for applets, cryptographic services, access control
mechanisms, and robust authentication and authorization frameworks.
7. Multithreading: Java supports multithreading, allowing concurrent execution of
multiple threads within a single program. Multithreading is essential for developing

1|Page
responsive and scalable applications, particularly in scenarios where tasks need to be
performed simultaneously or asynchronously.
8. Community Support: Java has a large and active community of developers,
enthusiasts, and organizations contributing to its growth and evolution. There are
numerous online resources, forums, tutorials, and libraries available to help
developers learn, troubleshoot, and extend Java-based solutions.
9. Cross-Platform Development: Java's platform independence makes it an ideal
choice for cross-platform development. Applications written in Java can run on
various operating systems, including Windows, macOS, Linux, Unix, and mobile
platforms like Android.
10. Enterprise Adoption: Java is widely used in enterprise software development for
building robust, scalable, and secure backend systems, web applications, middleware,
and enterprise integration solutions. Its reliability, performance, and scalability make
it a preferred choice for mission-critical business applications.
Overall, Java's combination of simplicity, portability, performance, and extensive ecosystem
makes it a versatile and popular programming language for a wide range of applications,
from small-scale projects to large-scale enterprise solutions.
GENERAL SYNTAX
The general syntax of Java follows a structured format with specific rules for defining classes,
methods, variables, control flow statements, and other constructs. Here's a breakdown of the
general syntax:
1. Package Declaration (Optional): Defines the package to which the current file
belongs.
package packageName;
2. Import Statements: Allows access to classes or packages from other packages.
import packageName.ClassName;
3. Class Declaration: Defines the blueprint for objects and contains the main method.
public class ClassName {
// Class body
}
4. Main Method: Acts as the entry point for the program, where execution begins.
public static void main(String[] args) {
// Program logic
}

2|Page
5. Variables Declaration: Declares variables to store data of specific types.
dataType variableName;
6. Methods Declaration: Defines the behavior of the class by declaring methods with
return types, names, and parameters.
returnType methodName(parameters) {
// Method body
}
7. Control Flow Statements: Includes decision-making and looping constructs like if-
else, switch, for, while, and do-while.
Code
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}

Code
for (initialization; condition; update) {
// Code to repeat
}

Code
while (condition) {
// Code to repeat
}

Code
do {
// Code to repeat
} while (condition);

8. Comments: Java supports single-line comments (//) and multi-line comments (/* */)
to add explanatory notes within the code.
9. Access Modifiers: Access modifiers (public, private, protected, default) can be
applied to classes, methods, and variables to control their visibility and accessibility.

3|Page
10. Exception Handling: Handles exceptions gracefully using try, catch, and finally
blocks.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
}

Understanding and applying these syntax elements allows for the effective creation of Java
programs for various applications.
DATA TYPES: In Java, data types specify the type of data that a variable can hold. Java has
two categories of data types: primitive data types and reference data types.
Primitive Data Types:
1. byte: Used for storing small integers within a limited range, suitable for conserving
memory when memory optimization is crucial.
2. short: Similar to byte, but with a wider range and can store larger integers compared
to byte, also used for memory optimization when integers fall within its range.
3. int: Used for storing whole numbers without decimal points, like counting or
indexing.
4. long: Similar to int, but can store larger whole numbers with a wider range.
5. float: Used for storing decimal numbers with single precision, like representing
measurements or ratios.
6. double: Similar to float, but with higher precision for more accurate decimal values.
7. char: Represents a single character, such as a letter, digit, or special symbol, from the
Unicode character set.
8. boolean: Stores a value representing true or false, useful for logical operations and
decision-making.
Reference Data Types:
1. Class Types: Any class you create or one of Java's built-in classes like String.
2. Interface Types: Interfaces implemented by classes.
3. Array Types: Arrays of any data type, including arrays of other arrays (multi-
dimensional arrays).
4. Enumeration Types: Enumerations, a special data type that allows for a variable to
be a set of predefined constants.

4|Page
IDENTIFIERS: Identifiers in Java are names given to various programming elements such as
variables, methods, classes, packages, etc. They must follow certain rules:
1. Naming Rules:
• Must start with a letter, underscore (_), or dollar sign ($).
• After the first character, can include letters, digits, underscores, and dollar
signs.
• Cannot contain whitespace characters or special symbols like @, #, %, etc.
• Should not be a reserved word (e.g., int, class, public, etc.).
2. Case Sensitivity: Java identifiers are case-sensitive, meaning myVariable,
MyVariable, and myvariable are considered different.
Examples of valid identifiers: myVariable, _variable, $variable123, MyClass,
calculateInterest(), etc.
VARIABLES: Variables in Java are named memory locations used to store data during
program execution. They hold values that can be changed and manipulated throughout the
program. Here's a brief overview of variables in Java:
1. Declaration: Variables must be declared before they can be used. This involves
specifying the variable's data type and giving it a name.
Code
dataType variableName;
Example:
int age;
double salary;
2. Initialization: Optionally, variables can be assigned an initial value during
declaration or later in the program.
dataType variableName = initialValue;
Example:
int age = 30;
double salary = 2500.50;
3. Assignment: Values can be assigned or updated to variables using the assignment
operator =.
variableName = value;

5|Page
Example:
Code
age = 35;
salary = 3000.75;
4. Data Types: Variables must have a specific data type that determines what kind of
values they can hold (e.g., int, double, String, etc.).
5. Scope: Variables have a scope that defines where in the code they can be accessed.
Local variables are defined within methods and have limited scope, while instance
variables belong to objects and are accessible throughout the class.
6. Naming Convention: Follow naming conventions for variables, such as using
meaningful names that reflect their purpose and starting with a lowercase letter (e.g.,
firstName, numStudents, totalAmount, etc.).
Variables are fundamental building blocks in Java programming and are used extensively to
store and manipulate data within programs.
OPERATORS: Operators in Java are symbols used to perform operations on operands. Java
supports various types of operators, including arithmetic, relational, logical, assignment,
bitwise, and conditional operators. Operators in Java are used to perform various operations
such as arithmetic calculations, comparisons, logical operations, and more. Understanding
and correctly using operators is essential for writing effective and efficient Java code.
Examples of operators are:
1. Arithmetic Operators:
• Addition +
• Subtraction -
• Multiplication *
• Division /
• Modulus %
• Increment ++
• Decrement --
2. Relational Operators:
• Equal to ==
• Not equal to !=
• Greater than >

6|Page
• Less than <
• Greater than or equal to >=
• Less than or equal to <=
3. Logical Operators:
• Logical AND &&
• Logical OR ||
• Logical NOT !
4. Assignment Operators:
• Assignment =
• Addition assignment +=
• Subtraction assignment -=
• Multiplication assignment *=
• Division assignment /=
• Modulus assignment %=
5. Bitwise Operators:
• Bitwise AND &
• Bitwise OR |
• Bitwise XOR ^
• Bitwise NOT ~
• Left shift <<
• Right shift >>
• Unsigned right shift >>>
6. Conditional Operator (Ternary Operator):
• condition ? expression1 : expression2
7. Instanceof Operator:
• Instanceof

7|Page
COMMENTS:
Comments are non-executable statements used to add notes or explanations within the
source code. They are ignored by the compiler and do not affect the program's functionality.
Java supports two types of comments:
• Single-line comments: Begin with // and extend to the end of the line.
• Multi-line comments: Enclosed between /* and */ and can span multiple lines.
Example
// This is a single-line comment
/* This is a
multi-line comment */
STRINGS:
Strings in Java are sequences of characters, represented by the String class. They are used to
store and manipulate text-based data and their values can not be changed once they are
created.
Example
String str = "Hello, World!";
RESERVED WORDS:
Reserved words, also known as keywords, are predefined identifiers in Java with special
meanings. These words are reserved for specific purposes and cannot be used as identifiers
(e.g., variable names, class names, etc.) in the program.
Examples of reserved words in Java include public, class, static, void, if, else, for, while,
return, true, false, etc.
Example
public class MyClass {
public static void main(String[] args) {
int count = 0;
if (count == 0) {
System.out.println("Count is zero.");
}
}
}
8|Page
CLASSES:
In Java, a class is a blueprint for creating objects. It defines the properties (attributes) and
behaviors (methods) that objects of that type will have. Classes encapsulate data and
methods that operate on that data. Instances of classes are called objects. Classes are defined
using the class keyword.
Example:
public class Car {
// Attributes
String color;
int year;
// Methods
void drive() {
System.out.println("Car is driving.");
}
}
Explanation
1. Definition: Classes are defined using the class keyword followed by the class name.
public class MyClass { // Class body }
2. Encapsulation: Classes encapsulate data (attributes) and methods (behaviors) that
operate on that data. This helps in achieving data hiding and abstraction.
3. Attributes: Attributes, also known as fields or member variables, represent the state
of the object. They define the data that each object of the class will hold.
public class Car { // Attributes String color; int year; }
4. Methods: Methods define the behavior of the objects. They represent actions that
objects can perform.
public class Car { // Attributes String color; int year; // Method void drive() {
System.out.println("Car is driving."); } }
5. Instantiation: Once a class is defined, objects of that class can be created using the
new keyword followed by a call to the class constructor.
Car myCar = new Car();

9|Page
6. Constructor: A constructor is a special method used for initializing objects. It has the
same name as the class and is invoked when an object is created.
public class Car {
// Constructor
public Car() {
// Constructor body
}
}
7. Access Modifiers: Access modifiers like public, private, and protected control the
accessibility of class members (attributes and methods).
public class Car {
// Public attribute
public String color;
// Private attribute private int year;
// Public method
public void drive() {
// Method body
}
// Private method
private void stop() {
// Method body
}
}
Classes form the foundation of object-oriented programming in Java and are essential for
creating modular, reusable, and maintainable code.

OBJECTS:
Objects are instances of classes. They represent real-world entities and have state
(attributes) and behavior (methods). Objects are created using the new keyword followed

10 | P a g e
by a constructor call. Once created, objects can invoke methods and access attributes defined
in their class.
Example:
Car myCar = new Car();
myCar.color = "Red";
myCar.year = 2022;
myCar.drive();
Explanation
1. Definition: Objects are created based on a class blueprint. Once a class is defined, one
or more objects of that class can be instantiated.
2. Instantiation: To create an object, you use the new keyword followed by a call to the
class constructor. This allocates memory for the object and initializes its attributes.
ClassName objectName = new ClassName();
Example:
Car myCar = new Car();
3. Attributes: Objects have attributes, also known as fields or member variables, which
represent their state. These attributes define the data that each object holds.
public class Car{
// Attributes
String color;
int year;
}
4. Methods: Objects have methods, which define their behavior. Methods represent
actions that objects can perform.
public class Car {
// Method
void drive( ) {
System.out.println("Car is driving.");
}
}
11 | P a g e
5. Accessing Members: Once an object is created, its members (attributes and
methods) can be accessed using the dot ‘.’ notation.
myCar.color = "Red"; // Set attribute
myCar.drive(); // Call method
6. Reference Variables: Objects are referenced using reference variables. These
variables store the memory address of the object rather than the object itself.
Car myCar; // Reference variable declaration
myCar = new Car(); // Object instantiation
Objects play a central role in Java programming, enabling the creation of modular, reusable,
and maintainable code. They allow developers to model real-world entities and interact with
them in a structured manner.
Interface:
• An interface in Java is a reference type similar to a class but only contains
constants, method signatures, default methods, static methods, and nested
types.
• It defines a contract for classes that implement it, specifying what methods
they must provide.
• Interfaces are declared using the interface keyword.
Example:
public interface Vehicle {
void drive();
void stop();
}
Enumeration (Enum):
• An enumeration in Java is a special data type used to define a set of constants.
• It is a list of named constant values.
• Enums are declared using the enum keyword.
• Each constant is an instance of the enum type.
Example:
public enum Day {

12 | P a g e
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
CONTROL STATEMENTS
Control statements are used to control the flow of execution in a program. They allow you to
make decisions, repeat blocks of code, and control the flow based on certain conditions. Here
are the main types of control statements in Java:
1. Conditional Statements:
• if Statement: Executes a block of code if a specified condition is true.
e.g.
if (condition) {
// Code to execute if condition is true
}
• if-else Statement: Executes one block of code if the condition is true and
another block if the condition is false.
e.g.
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
• else-if Statement: Checks multiple conditions one by one and executes the
block of code associated with the first true condition.
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if all conditions are false
}

13 | P a g e
2. Switch Statement:
• Evaluates an expression and executes code blocks based on matching cases.
e.g.
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
default:
// Code to execute if expression doesn't match any case
}

3. Looping Statements:
• for Loop: Executes a block of code a specified number of times.
e.g.
for (initialization; condition; update) {
// Code to repeat
}
• while Loop: Executes a block of code as long as a specified condition is true.
e.g.
while (condition) {
// Code to repeat
}
• do-while Loop: Executes a block of code at least once, then repeats it as long
as a specified condition is true.
e.g.
do {
// Code to repeat
} while (condition);

14 | P a g e
4. Break and Continue Statements:
• break: Terminates the loop or switch statement and transfers control to the
statement immediately following the loop or switch.
• continue: Skips the current iteration of a loop and continues with the next
iteration.
Control statements are essential for implementing decision-making and repetition in Java
programs, allowing for flexible and dynamic execution flow.
EXCEPTION HANDLING
Exception handling in Java allows you to gracefully handle unexpected or exceptional
situations that may occur during the execution of a program. This ensures that your program
can recover from errors and continue functioning without crashing. Here's an overview of
exception handling in Java:
1. Exception Types:
• Checked Exceptions: These are exceptions that must be either caught or
declared in the method signature using the throws keyword. Examples
include IOException, FileNotFoundException, etc.
• Unchecked Exceptions (Runtime Exceptions): These exceptions do not
need to be explicitly caught or declared. They include NullPointerException,
ArrayIndexOutOfBoundsException, ArithmeticException, etc.
2. try-catch Block:
• The try block is used to enclose the code that may throw an exception.
• The catch block is used to handle the exception. It specifies the type of
exception it can catch and contains the code to handle the exception.
• You can have multiple catch blocks to handle different types of exceptions.
e.g.
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Exception handling code for ExceptionType1
} catch (ExceptionType2 e2) {
// Exception handling code for ExceptionType2
} finally {

15 | P a g e
// Optional finally block for cleanup code that will be executed regardless of whether an
exception occurred or not
}
3. throw Statement:
• The throw statement is used to explicitly throw an exception from within your
code.
• It is typically used to handle custom exceptions or to rethrow caught
exceptions with additional information.
e.g.
if (condition) {
throw new ExceptionType("Error message");
}
4. finally Block:
• The finally block is optional and is used to execute cleanup code that should
be run regardless of whether an exception occurred or not.
• It's commonly used for closing resources like files, database connections, etc.
e.g.
try {
// Code that may throw an exception
} catch (Exception e) {
// Exception handling code
} finally {
// Cleanup code
}
5. try-with-resources Statement:
• Introduced in Java 7, the try-with-resources statement ensures that resources
are closed automatically after the try block execution.
• It simplifies the code for closing resources and helps prevent resource leaks.

16 | P a g e
e.g.
try (ResourceType resource = new ResourceType()) {
// Code that uses the resource
} catch (Exception e) {
// Exception handling code
}
Exception handling is crucial for writing robust and reliable Java programs, ensuring that
your code can handle unexpected situations gracefully without crashing.

17 | P a g e

You might also like