0% found this document useful (0 votes)
16 views

mod1-javapdf

Uploaded by

HG Akash [BCA]
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

mod1-javapdf

Uploaded by

HG Akash [BCA]
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Classes and Objects in OOP

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.

 Crea ng an object is known as instan a on.


Data Abstrac on in OOP
Data Abstrac on is the concept of hiding the complex implementa on details and exposing
only the necessary and relevant parts of an object. It allows us to focus on what an object
does rather than how it does it.
In Java, abstrac on can be achieved using:
1. Abstract Classes: These classes cannot be instan ated and are meant to be
subclasses. They can have abstract methods (methods without a body) that must be
implemented by subclasses.
2. Interfaces: These are contracts that define methods which classes must implement.
Interfaces allow mul ple classes to share a common set of methods without
enforcing how the methods should be implemented.

Example of Data Abstrac on with an Abstract Class


Consider an abstract class Shape, which provides a general idea of a shape but doesn’t
specify the exact details of each shape (like Rectangle or Circle).
Explana on:
 Shape is an abstract class. It has an abstract method area() which doesn’t have a
body. The subclasses (Rectangle and Circle) must provide implementa ons for this
method.
 The method display() in Shape is a concrete method with a specific behavior.
In this example:
 We are abstrac ng out the common property of shapes (i.e., having an area) while
le ng each subclass decide the specifics of how to calculate the area.
 The main program only needs to know that each Shape has an area() method,
without worrying about the details of calcula on.

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

public class BankAccount {

private double balance; // Balance is private to prevent direct access

// Constructor

public BankAccount(double initialBalance) {

this.balance = initialBalance;

// Getter method for balance (read-only access)

public double getBalance() {

return balance;

// Method to deposit an amount

public void deposit(double amount) {

if (amount > 0) {

balance += amount;

} else {

System.out.println("Invalid deposit amount");

// Method to withdraw an amount


public void withdraw(double amount) {

if (amount > 0 && amount <= balance) {

balance -= amount;

} else {

System.out.println("Insufficient funds or invalid withdrawal amount");

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.

Advantages Of Inheritance in Java:


1. Code Reusability: Inheritance allows for code reuse and reduces the
amount of code that needs to be wri en. The subclass can reuse the
proper es and methods of the superclass, reducing duplica on of code.
2. Abstrac on: Inheritance allows for the crea on of abstract classes that
define a common interface for a group of related classes. This promotes
abstrac on and encapsula on, making the code easier to maintain and
extend.
3. Class Hierarchy: Inheritance allows for the crea on of a class hierarchy,
which can be used to model real-world objects and their rela onships.
4. Polymorphism: Inheritance allows for polymorphism, which is the ability
of an object to take on mul ple forms. Subclasses can override the
methods of the superclass, which allows them to change their behavior
in different ways.
When to Use Inheritance
 When classes share a common set of behaviors or a ributes.
 When there’s a natural hierarchical rela onship, like Vehicle -> Car,
Animal -> Dog, or Employee -> Manager.
 To promote code reuse and organiza on in large projects.
Polymorphism
Polymorphism is a core concept in object-oriented programming (OOP) that allows objects
of different classes to be treated as objects of a common superclass. It provides a way for a
single interface to represent different underlying forms (or data types). Essen ally,
polymorphism allows the same method or opera on to behave differently based on the
object that invokes it.
There are two main types of polymorphism in Java:
1. Compile-Time Polymorphism (also known as Sta c Polymorphism)
2. Run me Polymorphism (also known as Dynamic Polymorphism)
1. Compile-Time Polymorphism (Method Overloading)
Compile- me polymorphism is achieved through method overloading, where mul ple
methods in the same class share the same name but have different parameters. The correct
method is selected at compile me based on the method signature (parameters).
2. Run me Polymorphism (Method Overriding)
Run me polymorphism is achieved through method overriding, where a subclass provides a
specific implementa on of a method that is already defined in its superclass. In this case, the
method call is resolved at run me based on the actual object type (not the reference type).

class Animal {
void sound() {
System.out.println("This animal makes a sound.");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("The dog barks.");
}
}

class Cat extends Animal {


@Override
void sound() {
System.out.println("The cat meows.");
}
}

public class TestPolymorphism {


public sta c void main(String[] args) {
Animal myDog = new Dog(); // Animal reference, but Dog object
Animal myCat = new Cat(); // Animal reference, but Cat object

myDog.sound(); // Calls Dog's version of sound()


myCat.sound(); // Calls Cat's version of sound()
}
}
Benefits of Polymorphism
1. Flexibility and Extensibility: Polymorphism allows for flexible code
where objects can be used interchangeably, and behavior can change
dynamically at run me.
2. Code Reusability: With polymorphism, you can write more generic and
reusable code that operates on references of the superclass while
providing specific behavior for subclasses.
3. Easier Maintenance: Changes to behavior are o en confined to specific
subclasses, reducing the risk of breaking code elsewhere.
4. Enhanced Code Readability and Management: Polymorphism simplifies
complex hierarchies and allows for cleaner, more modular code.
Comments in Java
Purpose of Comments:
 Comments help make the code easier to read and understand.
 They are ignored by the compiler, so they don’t affect the program's
func onality.
 Commonly used to explain code logic, provide informa on about the author,
and document important details.
Types of Comments:
1. Single-line Comment:
o Starts with // and con nues to the end of the line.
o Useful for brief notes or explana ons.
// This is a single-line comment
int x = 10; // Assign 10 to variable x
Mul -line Comment:
 Enclosed within /* */, spanning across mul ple lines.
 Helpful for longer explana ons or temporarily disabling chunks of code.
/* This is a mul -line comment
explaining the following block of code */
int y = 20;
int z = x + y;
Documenta on Comment:
 Begins with /** and is commonly used to generate documenta on with tools
like Javadoc.
 O en used for documen ng methods, classes, and complex code.
/**
* Calculates the area of a rectangle.
* @param width Width of the rectangle
* @param height Height of the rectangle
* @return The area of the rectangle
*/
public int calculateArea(int width, int height) {
return width * height;
}
DATA TYPES IN JAVA

Data Types in Java


Java data types fall into two main categories: Primi ve and Reference types.
1. Primi ve Data Types:
o These are the basic data types built into Java, and they store
simple values directly in memory.
o Types and Sizes:
 byte: 8-bit integer, range -128 to 127
 short: 16-bit integer, range -32,768 to 32,767
 int: 32-bit integer, commonly used for whole numbers,
range -2,147,483,648 to 2,147,483,647
 long: 64-bit integer, range -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 (add L at the end for long
literals, e.g., 123L)
 float: 32-bit floa ng-point for decimals, use f at the end of
literals (e.g., 5.75f)
 double: 64-bit floa ng-point, suitable for precise decimal
values (e.g., 3.14159)
 char: 16-bit character (Unicode) for single characters, like ‘A’
 boolean: Holds either true or false, useful for condi onal
logic

Non-Primi ve (Reference) Data Types


The Non-Primi ve (Reference) Data Types will contain a memory address of
variable values because the reference types won’t store the variable value
directly in memory. They are strings, objects, arrays, etc.
1. String:
 In Java, a String is a class, not a primi ve type. When you declare a
String, Java allocates memory for the string object in the heap and stores
a reference to that memory loca on in the variable.
String name = "Alice"; // `name` holds a reference to the "Alice" string object in
memory
2. Objects:
 An object is an instance of a class. When you create an object, Java
allocates memory for that object in the heap and stores the reference to
that memory loca on in the variable.
Dog myDog = new Dog(); // `myDog` holds a reference to the Dog object in the
heap
3. Arrays:
 Arrays in Java are also reference types, even for arrays of primi ve data
types like int[] or char[]. The array variable holds a reference to the
memory loca on where the actual array elements are stored.
int[] numbers = {1, 2, 3}; // `numbers` stores a reference to the array in
memory
Variables in Java
Variables are containers for storing data values in Java. Each variable must be
declared with a specific type, which determines the kind of values it can hold
and the opera ons that can be performed on it. Here’s a breakdown of Java
variables:
Types of Variables
1. Local Variables:
o Declared inside a method, constructor, or block.
o Only accessible within that method or block and are destroyed
a er the method completes.
o Must be ini alized before use.
Instance Variables (Non-sta c Fields):
 Declared in a class but outside any method or block, these variables
belong to each instance of the class.
 Each object has its own copy of instance variables.
 They get default values if not explicitly ini alized (e.g., 0 for int, null for
objects).

Sta c Variables (Class Variables):


 Declared with the sta c keyword, sta c variables are shared among all
instances of a class.
 They are stored in a sta c memory area and belong to the class itself
rather than any specific instance.
 Typically used for constants or shared data among objects.

Variable Naming Rules


 Must start with a le er, underscore (_), or dollar sign ($).
 Can contain le ers, numbers, underscores, and dollar signs.
 Cannot be a reserved keyword (e.g., int, class, void).
Constants in Java
Constants are fixed values that, once assigned, cannot be changed during the
program's execu on. Java provides ways to define constants, typically used for values
that should remain consistent throughout the program, like mathema cal constants
or configura on values.
Declaring Constants
In Java, constants are created by combining the final keyword with a variable
declara on. Here’s how:
1. Using final Keyword:
o The final keyword is used to make a variable’s value unchangeable a er
it’s assigned.
o Constants are o en named in uppercase le ers with underscores
separa ng words for clarity.

Final Keyword

2. Purpose: The final keyword makes a variable unchangeable, a method un-


overridable, or a class un-inheritable.
3. Usage: It can be applied to variables, methods, and classes.

Sta c Final Constants:


 Constants that are sta c belong to the class rather than any instance.
This is useful for constants shared across all instances.
 Sta c final constants are typically used for global values like PI or
applica on-wide se ngs.

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)

2. Rela onal Operators


Rela onal operators compare 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)

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)

5. Increment and Decrement Operators


Used to increase or decrease a variable by one:
 ++ (Increment)
 -- (Decrement)

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 )

Operator Hierarchy (Precedence)


Operator precedence determines the order in which operators are evaluated in
an expression. For example, * and / have higher precedence than + and -.
Parentheses () can be used to control precedence explicitly.

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.

Type Conversion and Cas ng


Defini on: Type conversion is the process of conver ng one data type to
another. In Java, there are two types of type conversions:
1. Implicit Conversion (Widening Conversion): Automa cally done by Java
when you’re conver ng a smaller or compa ble type into a larger type.
This occurs without any extra code because there is no risk of data loss.
o Example: Conver ng an int to a double

Explicit Conversion (Narrowing Conversion or Cas ng): Done manually when


conver ng a larger type into a smaller one or incompa ble types. This can
result in data loss if the value doesn't fit within the range of the target type.
 Example: Conver ng a double to an int
Cas ng
Cas ng is the process used in narrowing conversions and requires specifying
the target type in parentheses. When cas ng, keep in mind:
 Primi ve Cas ng: Only compa ble types can be cast.
 Object Cas ng: Used in inheritance hierarchies where a superclass
reference points to a subclass object.
Key Points
 Widening Conversion is safe, no data is lost (e.g., int to double).
 Narrowing Conversion risks data loss and requires cas ng (e.g., double
to int).
 Cas ng Objects: Required when cas ng from a parent type to a child
type.

Enumerated Types (Enums)

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.

Control Flow Statements in Java


Control flow statements in Java manage the flow of a program’s execu on
based on certain condi ons or repeated opera ons. They are essen al in
direc ng the program to execute specific blocks of code based on different
circumstances. There are three main types of control flow statements in Java:
1. Decision-Making Statements:
o Used to execute certain parts of code based on condi ons.
Examples:
o if Statement: Executes code if a condi on is true.
o if-else Statement: Executes one block if true and another if false.
o else-if Ladder: Checks mul ple condi ons in a sequence.
o switch Statement: Selects code to execute based on the value of a
variable.

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.

Simple Java Standalone Programs


A standalone Java program is an applica on that runs on its own, without
relying on a web server or app server, and o en includes a main method as the
program's entry point. Here’s the structure of a basic standalone Java program:
Explana on:
 Class Declara on (HelloWorld): Every Java program is built around a
class. Here, HelloWorld is the class name.
 main Method: This is the entry point for the program and must have the
signature public sta c void main(String[] args). The args parameter is an
array of strings that allows command-line arguments.
 System.out.println: Prints text to the console. In this example, it outputs
"Hello, World!".
The public sta c void main(String[] args) method is the entry point of any
standalone Java applica on. Here's a simple breakdown of what each part
means:
1. public: This is an access modifier that means the main method can be
accessed from anywhere. It needs to be public so that the Java run me
can find and call this method when the program starts.
2. sta c: This means that the main method belongs to the class itself,
rather than to any specific instance (object) of the class. Because main is
sta c, it can be called without crea ng an object of the class.
3. void: This specifies that the main method does not return any value. It
simply performs ac ons when executed.
4. main: This is the name of the method. The Java run me looks for this
specific method name to start execu ng the program.
5. String[] args: This is an array of strings that can be used to pass
command-line arguments to the program. If you run the program with
addi onal informa on (e.g., java MyProgram arg1 arg2), those
arguments will be accessible in the args array.

EXAMPLE
import java.u l.Scanner;

public class SimpleCalculator {


public sta c void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter first number: ");


double num1 = scanner.nextDouble();

System.out.print("Enter an operator (+, -, *, /): ");


char operator = scanner.next().charAt(0);

System.out.print("Enter second number: ");


double num2 = scanner.nextDouble();

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

System.out.println("Result: " + result);


}
}
Arrays in Java
An array is a data structure that can hold a fixed number of values of the same
data type. The length of an array is established when the array is created. Java
arrays are zero-indexed, meaning that the first element is at index 0.
Declara on and Ini aliza on
To declare an array in Java, you specify the type of elements it will hold,
followed by square brackets. You can then ini alize the array using curly braces
or specify its size.

Accessing Array Elements


You can access elements in an array using their index.
Console Input and Output
In Java, you can use the System.out class for output and the Scanner class for
input.
Output
 System.out.println(): Prints the specified message and adds a new line.
 System.out.print(): Prints the specified message without adding a new
line.

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.

You might also like