mod1-javapdf
mod1-javapdf
1. Classes
A class is like a blueprint or template that defines the structure and behavior
of objects.-
It specifies two main things:
o A ributes (Fields/Proper es): Represent the data or characteris cs of
the object.
o Methods (Func ons): Represent the behavior or ac ons that the object
can perform.
Here, Car is a class with a ributes (color, model, speed) and methods (accelerate, brake).
2. Objects
An object is an instance of a class. It has its own unique set of a ribute values and access to
the methods defined by the class.
DATA ABSTRACTION
Defini on (2 Marks): Data abstrac on is an Object-Oriented Programming
technique that:
Hides complex implementa on details
Shows only essen al features of an object
Separates interface from implementa on
Types of Abstrac on (2 Marks):
1. Abstract Classes
o Can have both abstract and concrete methods
o Supports par al implementa on
2. Interfaces
o Define a contract for implemen ng classes
o Provide pure method signatures
Benefits (2 Marks):
1. Code Simplifica on
o Reduces system complexity
o Provides clear, simple interface
o Separates essen al details from implementa on
2. Data Security
o Protects internal data
o Controls access to object's internal state
o Prevents direct manipula on of sensi ve informa on
Key Characteris cs:
Focuses on what an object does
Hides how an object does it
Provides a clean interac on mechanism
Key Points Breakdown
Abstrac on vs. Encapsula on:
Abstrac on: Hiding complexity
Encapsula on: Protec ng data through access modifiers.
Encapsula on
Encapsula on is a fundamental concept in object-oriented programming (OOP)
that involves bundling data (a ributes) and methods (func ons) that operate
on the data within a single unit or class. It also restricts direct access to some of
the object's components, which means internal details are "hidden" from
outside interference and misuse.
Key Points of Encapsula on
1. Data Hiding: By using access modifiers (like private, protected, and
public), encapsula on controls how data and methods are accessed
outside the class. Usually, sensi ve or cri cal data is kept private, and
access is provided via public methods (ge ers and se ers).
2. Controlled Access: Encapsula on allows an object to control how its data
is accessed or modified. This makes code safer and helps maintain
integrity by preven ng invalid or inconsistent states.
3. Modularity: By grouping related data and methods within a class,
encapsula on creates modular, independent components that are easy
to maintain and reuse.
Real-World Example of Encapsulation
Let’s consider a BankAccount class, where we want to ensure that the account balance is
safely managed and only modified through specific methods (like deposit and withdraw):
// Constructor
this.balance = initialBalance;
return balance;
if (amount > 0) {
balance += amount;
} else {
balance -= amount;
} else {
Explana on
1. Private Field (balance): The balance field is private, so it cannot be
accessed directly outside the BankAccount class. This prevents
unauthorized or accidental modifica on.
2. Public Ge er Method (getBalance): The getBalance method allows
controlled read-only access to the balance.
3. Controlled Modifica on (deposit and withdraw methods): The deposit
and withdraw methods provide controlled ways to modify balance. They
include valida on to ensure that the balance remains valid (no nega ve
deposits or withdrawals greater than the current balance).
Usage Example:
Benefits of Encapsula on
Data Integrity: Encapsula on protects data from unwanted access and
modifica ons.
Flexibility: Since data is only accessible via methods, you can easily
update these methods if internal implementa on changes without
impac ng outside code.
Simplified Debugging: Encapsulated classes are modular, making it
easier to isolate and fix issues.
Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP)
that allows one class (called the subclass or child class) to inherit fields and
methods from another class (called the superclass or parent class). This
mechanism enables the subclass to use or extend the func onality defined in
the superclass without rewri ng the code, promo ng code reusability and a
hierarchical class structure.
In Java, inheritance is achieved by using the extends keyword:
How Inheritance Works in the Example
In this example:
Superclass: Animal
o It has a method eat(), which describes a behavior common to all
animals.
Subclass: Dog
o It inherits the eat() method from Animal and also has its own
specific method bark().
When we create an instance of Dog, it can call both eat() and bark() methods,
even though eat() was defined in the Animal superclass.
class Animal {
void sound() {
System.out.println("This animal makes a sound.");
}
}
Final Keyword
Example
Here’s an example class with constants in use:
In this example:
PI is a constant defined at the class level, represen ng a mathema cal
constant.
Because it’s sta c final, all instances of Circle share this value, and it’s
unmodifiable.
Scope of Variables
The scope of a variable is the part of the program where the variable can be
accessed or used. In Java, the scope of a variable depends on where it is
declared:
1. Local Variables: Declared inside methods, constructors, or blocks.
o Scope: Only within the method, constructor, or block where they are
declared.
Instance Variables: Declared within a class but outside any method, and without the
sta c keyword.
Scope: Accessible by any method within the class. Each object instance has its
own copy of the instance variable.
Class Variables (Sta c Variables): Declared with the sta c keyword inside a
class but outside any method.
Scope: Accessible from any method in the class, shared by all instances
of the class
Life me of Variables
The life me of a variable is the dura on for which the variable exists in
memory during the execu on of the program.
1. Local Variables:
o Life me: Exists only while the method or block in which they are
declared is execu ng. When the method finishes, the local
variable is removed from memory.
2. Instance Variables:
o Life me: Exists as long as the object exists. When an object is no
longer referenced and is garbage collected, the instance variables
are also removed from memory.
3. Sta c Variables:
o Life me: Exists for the dura on of the program’s execu on,
regardless of the number of instances. They are removed only
when the program stops running.
Operators in Java
Operators are special symbols in Java that perform opera ons on variables and
values. Java supports a rich set of operators grouped into several categories:
1. Arithme c Operators
These operators are used to perform basic mathema cal opera ons:
+ (Addi on)
- (Subtrac on)
* (Mul plica on)
/ (Division)
% (Modulus)
3. Logical Operators
Logical operators work with boolean values to perform logical opera ons:
&& (Logical AND)
|| (Logical OR)
! (Logical NOT)
4. Assignment Operators
Assignment operators assign values to variables:
= (Simple assignment)
+= (Add and assign)
-= (Subtract and assign)
*= (Mul ply and assign)
/= (Divide and assign)
%= (Modulus and assign)
6. Ternary Operator
The ternary operator ?: is a shorthand for an if-else condi on:
Syntax: condi on ? expression1 : expression2
Example:
7. Bitwise Operators
These operators perform opera ons at the bit level:
& (Bitwise AND)
| (Bitwise OR)
^ (Bitwise XOR)
~ (Bitwise NOT)
<< (Le shi )
>> (Right shi )
>>> (Unsigned right shi )
Expressions in Java
Defini on: An expression in Java is a combina on of variables, constants,
operators, and method calls that evaluates to a single value. Expressions can
vary from simple calcula ons to complex statements used within condi ons
and loops.
Types of Expressions
1. Arithme c Expressions: These include mathema cal opera ons such as
addi on, subtrac on, mul plica on, and division.
o Example: int result = 5 + 10; (evaluates to 15)
2. Rela onal Expressions: Used to compare values, resul ng in a boolean
(true or false).
o Example: boolean isEqual = (5 == 10); (evaluates to false)
3. Logical Expressions: These combine boolean expressions using logical
operators (&&, ||, !) to form complex condi ons.
o Example: boolean isValid = (5 < 10) && (10 > 5); (evaluates to true)
4. String Expressions: String expressions are used for concatena ng strings.
o Example: String message = "Hello" + " World!"; (evaluates to
"Hello World!")
5. Assignment Expressions: Assign values to variables, such as = or
combined operators like += and -=.
o Example: int a = 5; a += 10; (now a is 15)
Importance in Java
Expressions are fundamental in Java because they allow calcula ons, decisions,
and data manipula on within the program, forming the building blocks of
statements and control flow.
Definition: An enumerated type, or enum, is a special data type in Java that defines a fixed set
of constants. It’s useful for representing a group of predefined values, making code more
readable and helping prevent errors from using invalid values.
Creating an Enum
In Java, enums are defined using the enum keyword, and the values within are usually written
in uppercase.
Key Benefits of Enums
1. Type Safety:
o With enums, you can restrict a variable to only one of the values
defined in the enum. This avoids invalid values, such as a typo or an
out-of-scope value, which could otherwise cause bugs.
2. Code Readability:
o Enums make your code more readable because each constant has a
meaningful name, rather than using arbitrary strings or numbers. For
example, Day.MONDAY is more readable than "Monday" or 1.
3. Organized Grouping of Constants:
o Enums allow you to keep related constants together in one place,
rather than sca ering them throughout the code. This improves
organiza on and maintainability.
Looping Statements:
Used to repeat a block of code mul ple mes un l a condi on is met.
Examples:
for Loop: Executes code a specific number of mes.
while Loop: Repeats code as long as a condi on is true.
do-while Loop: Similar to while loop but guarantees execu on at least
once.
Jump Statements:
Used to transfer control within a program.
Examples:
break: Exits a loop or switch statement.
con nue: Skips the current itera on of a loop and moves to the next.
return: Exits from a method and op onally returns a value.
EXAMPLE
import java.u l.Scanner;
double result = 0;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num2 != 0 ? num1 / num2 : 0; // Avoid division by zero
break;
default:
System.out.println("Invalid operator");
return;
}
Input
To read input from the console, you can use the Scanner class, which is part of
the java.u l package.
Alright, we’ll go through each of these topics one by one. Let’s start with
Constructors.
1. Constructors
A constructor in Java is a special method that is called when an object of a class
is instan ated. The primary role of a constructor is to ini alize objects. A
constructor has the same name as the class and does not have a return type.
Types of Constructors
Default Constructor: Provided by Java if no other constructor is defined.
It takes no arguments.
Parameterized Constructor: Accepts parameters to ini alize fields with
specific values when an object is created.
Example:
2. Methods
A method in Java is a block of code that performs a specific task. It may take
parameters and may or may not return a value.
Method Declara on:
3. Parameter Passing
In Java, parameters are always passed by value. This means a copy of the
variable’s value is passed into methods. For objects, the reference to the object
is passed by value, so changes to object fields persist outside the method.