[go: up one dir, main page]

0% found this document useful (0 votes)
2 views17 pages

Csc 321 Java Programming

The document provides an overview of Object-Oriented Programming (OOP) principles, comparing them with Procedural Programming (POP) and detailing the advantages and disadvantages of both paradigms. It introduces Java as a high-level, object-oriented programming language, covering its features, history, and basic syntax. Additionally, it explains control structures in Java, including sequence, selection, and looping, with examples for each.
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)
2 views17 pages

Csc 321 Java Programming

The document provides an overview of Object-Oriented Programming (OOP) principles, comparing them with Procedural Programming (POP) and detailing the advantages and disadvantages of both paradigms. It introduces Java as a high-level, object-oriented programming language, covering its features, history, and basic syntax. Additionally, it explains control structures in Java, including sequence, selection, and looping, with examples for each.
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/ 17

ADVANCED LEVEL PROGRAMMING LANGUAGE

USING

JAVA PROGRAM

AYEPEKU FELIX

1
CHAPTER ONE

Overview of Object-Oriented Programming (OOP)

What is Object-Oriented Programming (OOP)?

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design


around objects, which represent real-world entities. These objects contain data (attributes) and
functions (methods) that operate on the data. OOP improves code modularity, reusability, and
maintainability by following principles like encapsulation, inheritance, abstraction, and
polymorphism.

Key Concepts of OOP

1. Encapsulation

o Data and methods are bundled inside a class to prevent direct access to object details.

o Example: Private variables in a class can only be accessed through getter and setter
methods.

2. Inheritance

o Allows a new class (child class) to derive properties and methods from an existing
class (parent class).

o Promotes code reuse and reduces redundancy.

3. Polymorphism

o The ability to use a single interface to represent different data types or behaviors.

o Example: Method overloading (same method name, different parameters) and method
overriding (modifying inherited methods).

4. Abstraction

o Hides complex implementation details and exposes only necessary functionalities.

o Example: A car's driver only needs to know how to start the engine, not how the
engine works internally.

2
Basic Components of OOP

1. Class – A blueprint for creating objects.

2. Object – An instance of a class with specific values assigned to its attributes.

3. Methods – Functions inside a class that define the object's behavior.

4. Attributes (Properties) – Variables inside a class that store object data.

Advantages of OOP

✔ Modularity – Code is divided into independent, reusable objects.


✔ Scalability – Suitable for large applications (e.g., enterprise software, games).

✔ Data Security – Encapsulation restricts direct access to object properties.


✔ Code Reusability – Inheritance enables code reuse and reduces redundancy.

✔ Maintainability – Easy to modify and extend without affecting existing code.

Disadvantages of OOP

✖ Higher Memory Usage – Objects and class structures consume more memory.

✖ Slower Execution – Due to additional abstraction and method calls.


✖ Steep Learning Curve – Requires understanding OOP principles.

✖ Overhead for Small Applications – Not always efficient for simple scripts.

Applications of OOP

• Software Development (Java, C++, Python, C#)

• Web Development (Django, Flask, ASP.NET)

• Game Development (Unity, Unreal Engine)

• Machine Learning & AI (Scikit-learn, TensorFlow)

• Database Systems (Object-Relational Mappers like Hibernate

3
CHAPTER TWO

POP vs OOP

Procedural Programming (POP)

Definition

Procedural Programming is a programming paradigm that follows a step-by-step approach to solving


problems using procedures (also called functions or subroutines). It follows a top-down approach,
where the program is divided into smaller functions that are executed sequentially.

Characteristics of Procedural Programming

1. Top-down Approach – The program is divided into functions that are executed in sequence.

2. Reusability – Functions can be reused in different parts of the program.

3. Global and Local Variables – Data can be shared across functions using global variables.

4. Control Flow – Uses loops (for, while), conditionals (if-else), and function calls to control
program execution.

5. Code Readability – Easy to understand for simple and medium-sized programs.

Examples of Procedural Programming Languages

• C

• Pascal

• Fortran

• COBOL

• BASIC

Merits of Procedural Programming

1. Simple and Easy to Implement – Best for small programs and applications.

2. Fast Execution – Direct function calls lead to better performance in simpler applications.

4
3. Efficient Memory Usage – Less memory overhead compared to OOP.

4. Reusability – Functions can be reused across different programs.

5. Easier Debugging – Since functions are independent, debugging is straightforward.

Demerits of Procedural Programming

1. Not Suitable for Large Programs – Becomes difficult to manage as program size increases.

2. Data Security Issues – No concept of encapsulation; global variables are accessible to all
functions.

3. Code Redundancy – Difficult to maintain reusable code without objects.

4. Scalability Issues – Does not support complex data structures efficiently.

5. Less Flexibility – Functions depend on data structures, making modifications harder.

Applications of Procedural Programming

• Embedded Systems – Microcontrollers and hardware programming (e.g., C language).

• Scientific Computing – FORTRAN is used in mathematical and engineering simulations.

• Operating Systems – Early operating systems were written in C (e.g., UNIX).

• Game Development – Some games use procedural programming for performance


optimization.

Example using BASIC and C programming Language to compute Area of rectangle

10 PRINT "Enter Length: "


20 INPUT L
30 PRINT "Enter Width: "
40 INPUT W
50 LET A = L * W
60 PRINT "Area of Rectangle: "; A
70 END

5
#include <stdio.h>
int main() {
float length, width, area;
// Get user input
printf("Enter Length: ");
scanf("%f", &length);
printf("Enter Width: ");
scanf("%f", &width);
// Calculate area
area = length * width;
// Display result
printf("Area of Rectangle: %.2f\n", area);
return 0;
}

Object-Oriented Programming (OOP)

Definition

Object-Oriented Programming (OOP) is a programming paradigm that focuses on objects and their
interactions. Objects are instances of classes, which contain both data (attributes) and functions
(methods). OOP follows a bottom-up approach and is designed for modularity and reusability.

Characteristics of Object-Oriented Programming

1. Encapsulation – Data and functions are wrapped inside objects to prevent direct access.

2. Abstraction – Hides implementation details from the user and only exposes essential features.

3. Inheritance – Allows a new class to acquire properties of an existing class.

4. Polymorphism – Enables the same function name to have different behaviors based on the
object.

5. Code Reusability – Encourages modular and reusable code.

6
Examples of Object-Oriented Programming Languages

• Java

• Python

• C++

• C#

• Ruby

Merits of Object-Oriented Programming

1. Modular and Reusable Code – Objects and classes promote code reuse.

2. Better Data Security – Encapsulation prevents unauthorized access to data.

3. Easier Maintenance – Programs are divided into objects, making debugging easier.

4. Scalability – Supports large, complex applications efficiently.

5. Code Flexibility – Inheritance and polymorphism make it easy to extend and modify code.

Demerits of Object-Oriented Programming

1. Slower Execution – Object creation and method calls introduce some overhead.

2. More Memory Consumption – Objects and classes require more memory.

3. Steep Learning Curve – Requires more time to learn and implement properly.

4. Overhead in Small Applications – Using OOP for small programs can be unnecessary.

5. Complexity – Requires more planning and design compared to procedural programming.

Applications of Object-Oriented Programming

• Web Development – Java, Python (Django, Flask), and PHP use OOP for web applications.

• Game Development – Unity (C#), Unreal Engine (C++).

7
• Mobile Apps – Android (Java/Kotlin), iOS (Swift).

• Enterprise Software – Large-scale applications like CRM, ERP, and financial systems.

• Machine Learning and AI – Python (TensorFlow, Scikit-learn) uses OOP for model
development.

• Example using JAVA and C++ programming Language to compute Area of rectangle

import java.util.Scanner;
public class RectangleArea {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Get user input
System.out.print("Enter Length: ");
double length = input.nextDouble();
System.out.print("Enter Width: ");
double width = input.nextDouble();
// Calculate area
double area = length * width;
// Display result
System.out.println("Area of Rectangle: " + area);
input.close();
}
}

8
Comparison: Procedural Programming vs Object-Oriented Programming

Feature Procedural Programming (POP) Object-Oriented Programming (OOP)

Approach Top-down Bottom-up

Code Structure Uses functions Uses objects and classes

Data Handling Data is global and shared Data is encapsulated within objects

Security Less secure (global variables) More secure (data hiding)

Reusability Limited to function reuse High, through classes and objects

Scalability Less scalable More scalable

Performance Faster for small applications Slightly slower due to object overhead

Best For Small, simple programs Large, complex applications

9
CHAPTER THREE

INTRODUCTION TO JAVA PROGRAMMING

Overview of Java

Java is a high-level, object-oriented, and platform-independent programming language developed by


Sun Microsystems (now owned by Oracle). It is widely used for building desktop, web, and mobile
applications.

History and Evolution of Java

• 1991: James Gosling and his team at Sun Microsystems started Java as a project called Oak.

• 1995: Java was officially released as Java 1.0.

• 2000s: Java introduced J2EE for enterprise applications.

• 2010s: Oracle acquired Java and released newer versions like Java 8 (Lambdas), Java 11
(LTS), and later versions.

Features of Java

• Platform Independence: Java uses the Java Virtual Machine (JVM) to run code on different
operating systems.

• Object-Oriented: Java follows principles like Encapsulation, Inheritance, and Polymorphism.

• Robust and Secure: Features like exception handling and memory management improve
reliability.

• Multi-threading: Supports concurrent execution of tasks.

Setting Up the Java Development Environment

1. Install JDK (Java Development Kit): Download from Oracle's website.

2. Choose an IDE: IntelliJ IDEA, Eclipse, or NetBeans.

3. Check Java installation:

java -version

10
javac -version

Writing and Running a Simple Java Program

public class HelloJava {

public static void main(String[] args) {

System.out.println("Hello, Java!");

11
CHAPTER FOUR

JAVA BASICS – VARIABLES, DATA TYPES, AND OPERATORS

Variables and Constants in Java

Variable: A memory location that stores a value.

int age = 25; // Variable declaration

Constant: A variable whose value cannot change (use final).

final double PI = 3.14159;

Data Types (Primitive and Reference Types)

• Primitive Types: int, double, char, boolean, byte, short, long, float

• Reference Types: Objects, Strings, Arrays

Type Casting and Type Conversion

• Implicit Casting: Automatically converting smaller to larger types.

int num = 10;

double d = num; // Implicit conversion

int num = 10;

double d = num; // Implicit conversion

Operators in Java

Type Operators

Arithmetic + - * / %

Relational > < >= <= == !=

Logical `&&

12
Type Operators

Bitwise `&

Input and Output in Java

• Using Scanner for Input:

import java.util.Scanner;

Scanner input = new Scanner(System.in);

int num = input.nextInt();

Printing Output:

System.out.println("Hello, World!");

Comments and Documentation in Java

• Single-line Comment: // This is a comment

• Multi-line Comment:

/*

This is a multi-line comment

*/

13
CHAPTER FIVE

CONTROL STRUCTURES AND DECISION MAKING

1. Sequence (Sequential Execution)

Definition

• The sequence structure is the simplest control structure in programming.

• It involves executing statements one after another in a linear order.

• There are no conditional statements or loops in a sequence structure.

• This is the default behavior of any program unless instructed otherwise.

Explanation

• Every program follows a sequence unless control is diverted using selection or looping.

• The program starts from the first instruction and moves to the next in the order they appear.

• No condition checks or repetitions occur.

Example: Sequence in Java

public class SequenceExample {


public static void main(String[] args) {
System.out.println("Step 1: Start the Program");
System.out.println("Step 2: Enter your name");
System.out.println("Step 3: Display the name");
System.out.println("Step 4: End the Program");
}
}
Key Points
• The program executes from top to bottom.
• No conditions are checked, and no loops are used.
• Useful for simple tasks like displaying messages or performing calculations in a fixed order.

14
2. Selection (Decision-Making)
Definition
• Selection allows a program to make decisions based on conditions.
• It enables a program to execute different statements based on a given condition.
• The most commonly used selection structures in Java are:
o if statement
o if-else statement
o switch statement
Explanation
• The program evaluates a condition.
• If the condition is true, one block of code executes.
• If the condition is false, another block of code (if specified) executes.
• This structure is essential for implementing logic where different outcomes are required based
on user input or computed values.
Example: Selection using if-else
import java.util.Scanner;
public class SelectionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
Key Points

15
• The program evaluates the condition number % 2 == 0.
• If true, it prints "Even"; otherwise, it prints "Odd".
• Selection is useful when different actions need to be taken based on conditions, such as:
o Checking login credentials.
o Validating user input.
o Implementing menu-driven applications.
3. Looping (Iteration)
Definition
• Looping allows a program to execute a block of code multiple times.
• This is useful when repetitive tasks need to be performed.
• The three main types of loops in Java are:
o for loop
o while loop
o do-while loop
Explanation
• Loops reduce redundancy by avoiding the need to write repetitive code.
• A loop runs as long as a specified condition remains true.
• Loops consist of:
1. Initialization - Setting up a loop control variable.
2. Condition - Checking whether the loop should continue.
3. Iteration - Updating the loop control variable after each cycle.
Example: Looping using for loop
public class LoopExample {
public static void main(String[] args) {
System.out.println("Counting from 1 to 5:");
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}

16
}
Key Points
• The loop starts with i = 1 (initialization).
• The condition i <= 5 is checked; if true, the loop executes.
• After execution, i++ increases i by 1, and the loop repeats until i exceeds 5.
• Loops are useful for:
o Counting and iteration tasks.
o Processing large data sets.
o Implementing repetitive tasks like calculating sums or averages.

Comparison of Control Structures

Feature Sequence Selection Looping


Executes a block based on a Repeats a block based on a
Execution One by one, in order
condition condition
Condition No conditions Uses if, if-else, or switch Uses a loop condition
Repetition No No Yes
Example Displaying text, simple Decision-making (e.g., Repeating tasks (e.g.,
Use calculations checking login credentials) counting, iterating over lists)

17

You might also like