Advanced Programming Ch1
Advanced Programming Ch1
FUNDAMENTALS
1
GENERAL ■ Object-Oriented Programming (OOP) is a
EXPLANATION programming paradigm that organizes
software design around objects rather
OF OBJECT- than functions and logic. Objects are
instances of classes,
ORIENTED
PROGRAMMIN ■ Class serve as blueprint to create object .
G (OOP) IN
An object is an instance of a class. Once a
JAVA
■
class is defined, you can create objects
based on that class.
2
• Code is organized into classes,
Benefits of Object-Oriented
Programming in Java: 3
IN JAVA, OOP
FOCUSES ON FOUR
MAIN PRINCIPLES:
Encapsulation
• It allows you to focus on what an object does, rather than how it does it. In
Java, abstraction is achieved through abstract classes and interfaces.
Inheritance
• Promotes code reuse by enabling one class (child) to inherit the attributes
and behaviors (methods) of another class (parent).
Polymorphism:
4
5
■ Variables in Java are containers for storing
data values.
VARIABLES IN
JAVA: ■ Each variable has a data type (e.g., int,
DEFINITION String, boolean, etc.) that determines the
kind of data it can hold.
7
CONDITIONAL STATEMENTS IN
JAVA
8
OBJECT
CREATION IN
JAVA
DEFINITION
Objects in Java are created using the
■
new keyword followed by the class
constructor.
■ Syntax
ClassName objectName = new
ClassName();
9
EXCEPTION
HANDLING IN
JAVA ■ Exception handling in Java is a
mechanism to handle runtime errors,
ensuring that the program doesn’t crash
unexpectedly.
■ Java uses the try, catch, and finally
blocks to handle exceptions
– Try Block: Contains code that may
throw an exception.
– Catch Block: Catches and handles
the exception.
– Finally Block: Always executes,
regardless of whether an exception
was thrown or not (useful for closing
resources).
10
COMPLETE APPLICATION
■ Database
■ Networking
■ Synchronization
■ And more . . .
11
ADVANCED
PROGRAMMING
For AASTU 3RD YEAR STUDENTS
BY
GETNET A. & RAKEB D.
CHAPTER 1
FUNCTIONAL PROGRAMMING
13
BEFORE THAT
WHAT IS PROGRAMMING
PARADIGM
Key Concepts
■ A programming paradigm is a Imperative Programming: Focuses on
how to perform tasks through a series of
fundamental style or approach to
instructions.
programming that dictates how you
structure and write code.
Object-Oriented Programming (OOP):
■ Each paradigm provides a different Organizes code into objects that
way of thinking about and solving combine data and behavior.
problems,
Functional Programming:
■ Includes a set of concepts, Emphasizes the use of pure
techniques, and principles that functions and immutable data.
guide the design and
implementation of software.
Declarative Programming: Focuses
on what the outcome should be
without explicitly listing the steps to
achieve it. 14
FUNCTIONAL
PROGRAMMING
■ Functional programming is a paradigm where the basic unit of computation is a function.
■ A style of programming that treats computation as the evaluation of mathematical
functions( try to bind everything in pure mathematical functions.)
■ Here functions are not the methods we write in programming.
■ Methods are procedures where we write a sequence of instructions to tell the computer what
to do.
■ In functional programming, functions are treated like mathematical functions where we map
inputs to outputs to produce a result. Eg. f(x)=3x.
■ It primarily work with functions and immutable data, focusing on
the evaluation of expressions rather than executing commands.
■ In FP, functions are first-class citizens, which means you can
assign them to variables, pass them as arguments, or return them
from other functions.
15
CONT…
■ In functional programming, the software is developed around the evaluation of functions.
■ Referential Transparency
– In functional programs variables once defined do not change their value
throughout the program.
– Functional programs do not have assignment statements.
■ If we have to store some value, we define new variables instead.
■ This eliminates any chances of side effects because any variable can be
replaced with its actual value at any point of execution.
■ State of any variable is constant at any instant. 16
FUNCTIONAL PROGRAMMING …
■ The functions are isolated and independent, and they depend only on the arguments
passed to them and do not alter the program's state like modifying a global variable.
■ Treats data as being immutable
■ In functional programming, data is immutable, meaning once you
create an object, its state cannot be changed.
– This eliminates side effects and makes reasoning about code much
simpler.
■ Functions can take functions as arguments and return functions as results
■ You can make Java objects immutable by:
– Declaring fields final
– Not providing setters
– Ensuring any mutable objects are not exposed to the outside
17
PURE
■
FUNCTIONS
Pure functions are functions where the output value is determined only by its
input values, with no side effects.
■ In Java, this means you need to avoid things like modifying global
variables or performing I/O operations inside the function.
18
HIGHER-ORDER
FUNCTIONS
■ higher-order functions can be created using lambda expressions and
functional interfaces.
■ Higher-order functions are a fundamental aspect of functional
programming, providing a powerful and flexible way to create, combine,
and reuse code.
19
ADVANTAGES OF FUNCTIONAL
PROGRAMMING
■ Pure functions are easier to understand because they don’t change
any states and depend only on the input given to them.
■ The ability of functional programming languages to treat functions as
values and pass them to functions as parameters make the code more
readable and easily understandable.
■ Testing and debugging is easier. They use immutable values, so it
becomes easier to check some problems in programs written uses
pure functions.
■ It is used to implement concurrency/parallelism because pure
functions don’t change variables or any other data outside of it.
■ It adopts lazy evaluation which avoids repeated evaluation because
the value is evaluated and stored only when it is needed.
20
APPLICATIONS
21
1. JAVA API PACKAGES
• A package is a way to organize similar classes, interfaces, and sub-packages in
Java.
• By grouping your Java classes into namespaces, it makes the program easier to
manage, more modular, and manageable.
• Additionally, packages aid in preventing name conflicts, managing access, and
enhancing code reuse.
■ Java contains many predefined classes that are grouped into categories of related classes
called packages.
■ A great strength of Java is the Java API’s thousands of classes.
■ Some key Java API packages are described in Fig. 6.5.
■ Overview of the packages in Java SE 6:
■ download.oracle.com/javase/6/docs/api/
overview-summary.html
■ Java API documentation
■ download.oracle.com/javase/6/docs/api/
22
TYPES OF PACKAGES
■ 1. Built-in Packages: These are the packages that are part of the Java
API. Java provides a rich set of built-in classes and interfaces that are
grouped into packages,
– java.util: Contains utility classes like ArrayList, HashMap, Date,
etc.
– java.io: Contains classes for input and output operations, like File,
BufferedReader, PrintWriter, etc.
– java.lang: Contains fundamental classes like String, Math, System,
Thread, etc.
– java.net: Contains classes for network-related operations, such as
Socket, URL, etc.
■ 2. User-defined Packages: These are custom packages that developers
create to organize their own classes. They are defined by the user
based on project requirements.
23
24
25
26
JAVA PACKAGES
■ package: A collection of related classes.
■ Creating a Package
– Define a package in the .java file.
– Put the file in a folder structure that corresponds to the
package name.
27
PACKAGES AND
DIRECTORIES package com.example.utils;
■ package directory (folder)
public class MyClass{
■ class file public void myfunction() {
System.out.println("Hello from my function!");
■ A class named D in package a.b.c should }
reside in this file:
}
a/b/c/D.class
28
CONT…
29
A PACKAGE
DECLARATION
package name;
Example:
package pacman.model;
30
IMPORTING A
PACKAGE
import packageName.*; // all classes
Example:
package pacman.gui;
import pacman.model.*;
31
IMPORTING A CLASS &
REFERRING TO PACKAGES
import packageName.className; // one class
Referring to packages
packageName.className
Example:
java.util.Scanner console =
new java.util.Scanner(java.lang.System.in);
32
THE DEFAULT
PACKAGE
■ If you don't specify the package statement at the beginning of your Java file, the
class will belong to the default package.
■ The default package is an unnamed package that consists of all classes without an
explicit package declaration.
■ Compilation units (files) that do not declare a package are put into a default,
unnamed, package.
■ No Namespace:
– Classes in the default package are not associated with any named
package, so they don't have a namespace.
– This can lead to naming conflicts if there are classes with the same
name in different projects or parts of a large application.
■ Accessibility: Classes in the default package can only be accessed by other
classes in the default package.
– They cannot be imported by classes in named packages.
■ Organization:
– Using the default package makes it harder to organize and manage
large projects.
■ Convention: In professional and large-scale projects,
– it is highly discouraged to use the default package.
34
PACKAGE
ACCESS
■ Java provides the following access modifiers:
– public : Visible to all other classes.
– private : Visible only to the current class (and any nested types).
– protected : Visible to the current class, any of its subclasses, and
any other types within the same package.
– default (package): Visible to the current class and any other types
within the same package.
■ To give a member default scope, do not write a modifier:
package pacman.model;
public class Sprite {
int points; // visible to pacman.model.*
String name; // visible to pacman.model.*
35
COLLECTIONS
36
COLLECTIONS
■ Java collections framework
– prebuilt data structures
– interfaces and methods for manipulating those data structures
37
JCF
40
41
THE COLLECTION INTERFACE
■ The Collection interface is the foundation upon which the Collections Framework
is built because it must be implemented by any class that defines a collection.
– interface Collection<E>
■ Here, E specifies the type of objects that the collection will hold. Collection
extends
This means that all collections can be cycled through by use of the for-each
style for loop. (Recall that only classes that implement Iterable can be cycled
through by the for.)
42
• In addition to the collection interfaces, collections also use the
Comparator, RandomAccess, Iterator, ListIterator, and Spliterator
interfaces
• Comparator defines how two objects are compared;
• Iterator, ListIterator, and Spliterator enumerate the objects within a
collection.
• By implementing RandomAccess, a list indicates that it supports
efficient, random access to its elements.
• To provide the greatest flexibility in their use, the collection
interfaces allow some methods to be optional.
43
• The optional methods enable you to modify the contents of a
collection.
• Collections that support these methods are called modifiable.
• Collections that do not allow their contents to be changed are
called unmodifiable.
• If an attempt is made to use one of these methods on an
unmodifiable collection, an UnsupportedOperationException is
thrown. All the built-in collections are modifiable.
44
■ Collection declares the core methods that all collections will have.
collection.
■ interface List<E>
■ Here, E specifies the type of objects that the list will hold.
47
METHODS
■ Note again that several of these methods will throw an
UnsupportedOperationException if the list cannot be
modified, and
■ With one exception, it does not specify any additional methods of its
own.
■ Here, E specifies the type of objects that the set will hold. 49
THE SORTEDSET INTERFACE
■ The SortedSet interface extends Set and declares the behavior
of a set sorted in ascending order.
■ interface SortedSet<E>
■ Here, E specifies the type of objects that the set will hold.
50
EXCEPTION
■ Several methods throw a
NoSuchElementException when
no items are contained in the
invoking set.
■ A ClassCastException is thrown
when an object is incompatible
with the elements in a set.
■ A NullPointerException is thrown
if an attempt is made to use a
null object and null is not allowed
in the set.
■ An IllegalArgumentException is
thrown if an invalid argument is
used.
51
THE NAVIGABLESET INTERFACE
■ The NavigableSet interface extends SortedSet and declares the
behavior of a collection that supports the retrieval of elements based
on the closest match to a given value or values.
■ interface NavigableSet<E>
■ Here, E specifies the type of objects that the set will hold.
52
EXCEPTIONS
■ A ClassCastException is
thrown when an object is
incompatible with the
elements in the set.
■ A NullPointerException is
thrown if an attempt is made
to use a null object and null is
not allowed in the set. An
IllegalArgumentException is
thrown if an invalid argument
53
THE QUEUE INTERFACE
■ The Queue interface extends Collection and declares the
behavior of a queue, which is often a first-in, first-out list.
■ Here, E specifies the type of objects that the queue will hold.
54
■ Several methods throw a
ClassCastException when an
object is incompatible with the
elements in the queue.
■ A NullPointerException is thrown
if an attempt is made to store a
null object and null elements are
not allowed in the queue.
■ An IllegalArgumentException is
thrown if an invalid argument is
used.
■ An IllegalStateException is
thrown if an attempt is made to
add an element to a fixed length
queue that is full.
■ A NoSuchElementException is
thrown if an attempt is made to
remove an element from an
empty queue
55
THE DEQUE INTERFACE
56
METHOD
S
57
TYPE-WRAPPER CLASSES FOR
PRIMITIVE TYPES
■ Each primitive type has a corresponding type-wrapper class (in package
java.lang).
■ The type-wrapper classes are final classes, so you cannot extend them.
■ Primitive types do not have methods, so the methods related to a primitive type are
located in the corresponding type-wrapper class.
60
AUTOBOXING AND AUTO-UNBOXING
■ A boxing conversion converts a value of a primitive type to an object of the
corresponding type-wrapper class.
■ Example:
– // create integerArray
Integer[] integerArray = new Integer[ 5 ];
// assign Integer 10 to integerArray[ 0 ] integerArray[ 0 ]
= 10;
61
■ In this case, autoboxing occurs when assigning an int value (10) to
integerArray[0], because integerArray stores references to Integer objects, not
int values.
62
INTERFACE COLLECTION AND CLASS
COLLECTIONS
■ Interface Collection is the root interface from which interfaces Set, Queue
and List are derived.
■ Interface Set defines a collection that does not contain duplicates.
■ Interface Queue defines a collection that represents a waiting line.
■ Interface Collection contains bulk operations for adding, clearing and
comparing objects in a collection.
■ A Collection can be converted to an array.
■ Interface Collection provides a method that returns an Iterator object,
which allows a program to walk through the collection and remove elements from
the collection during the iteration.
■ Class Collections provides static methods that search, sort and perform
other operations on collections.
63
LISTS
■ A List (sometimes called a sequence) is a Collection that can contain duplicate
elements.
■ In addition to the methods inherited from Collection, List provides methods for
manipulating elements via their indices, manipulating a specified range of elements,
searching for elements and obtaining a ListIterator to access the elements.
■ Autoboxing occurs when you add primitive-type values to objects of these classes,
because they store only references to objects. 64
ARRAYLIST AND ITERATOR
■ List method add adds an item to the end of a list.
■ List method get retrieves an individual element’s value from the specified index.
– Lines 14 and 21 specify the type stored in the ArrayList (that is,
String) on the left and right sides of the initialization statements.
– Java SE 7 supports type inferencing with the <> notation in statements that
declare and create generic type variables and objects. For example, line 14
can be written as:
List< String > list = new ArrayList <>();
– Java uses the type in angle brackets on the left of the declaration (that is,
String) as the type stored in the ArrayList created on the right side of
the declaration.
69
ANONYMOUS CLASS
ANONYMOUS CLASS
■ Anonymous class is an inner class without a name, which means that we can
declare and instantiate class at the same time.
■ An anonymous class is used primarily when we want to use the class declaration
once.
71
ANONYMOUS CLASS …
import java.util.ArrayList; import java.util.Arrays;
import java.util.Comparator; import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(1, 3, 4, 5, 2) );
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
};
list.sort(comparator);
System.out.println(Arrays.toString(list.toArray()));
}
72
}
LAMBDA EXPRESSION
■ Output: [1, 2, 3, 4, 5]
■ Lambda Expression
■ Lambda operator ->: It's an arrow sign that appears after the list of
arguments. It connects the arguments-list with the body of the
expression.
75
OBJECT SERIALIZATION
76
OBJECT SERIALIZATION
■ Object serialization in Java refers to the process of converting an object's state (its
data and behavior) into a byte stream, which can then be stored on disk or
transmitted over a network.
■ The reverse process, in which an object is reconstructed from its serialized byte
stream, is called deserialization.
■ To read an entire object from or write an entire object to a file, Java provides
object serialization.
■ After a serialized object has been written into a file, it can be read from the file
and deserialized to recreate the object in memory.
77
OBJECT SERIALIZATION …
In Java, object serialization is achieved through the use of the java.io.Serializable
interface, which is a marker interface that indicates that a class can be serialized.
To make a class serializable, you simply need to implement the Serializable
interface, like this:
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
// other fields and methods
78
OBJECT SERIALIZATION …
Once a class is serializable, you can serialize and deserialize instances of that class
using the ObjectOutputStream and ObjectInputStream classes, respectively.
Here is an example of how to serialize an object:
82
DECLARATIVE PROGRAMMING
Declarative programming and imperative programming are two different paradigms
of programming, each with its own approach to writing code.
Declarative programming is a programming paradigm
■ emphasizes what the program should accomplish, rather than how it should
accomplish it.
■ the programmer specifies the rules, constraints, or logic that describe the desired
outcome.
■ That use a higher-level of abstraction, which enables the programmer to write
more concise and expressive code.
■ Examples of declarative programming in Java include functional programming,
the Stream API, and SQL. 83
DECLARATIVE PROGRAMMING
Imperative programming, on the other hand, is a programming paradigm that
emphasizes how the program should accomplish the task at hand.
Imperative programming,
■ the programmer specifies a series of step-by-step instructions for the computer
to execute.
■ are often low-level and closer to the hardware, making them more efficient for
certain types of tasks.
■ Java is primarily an imperative programming language, although Java 8
introduced functional programming features that allow for a more declarative
style of programming.
84
DECLARATIVE PROGRAMMING
■ while imperative programming is a better choice for tasks that require low-level
control over the computer's hardware resources.
85
EXAMPLE OF DECLARATIVE
PROGRAMMING
1.Functional programming: In Java 8 and later versions, you can write functions as
lambda expressions and pass them around as arguments.
■ This approach emphasizes what the code should do, rather than how it should do
it.
■ For example, the following code uses a lambda expression to sort a list of strings
in descending order:
3. SQL queries: You can use Java Database Connectivity (JDBC) to write declarative SQL queries to
interact with databases.
The SQL queries specify what data you want to retrieve or modify, rather than how to retrieve or
modify it.
For example, the following code retrieves all records from a database table:
String sql = "SELECT * FROM employees";
try (Connection conn = DriverManager.getConnection(url, user,password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
// process the results
}
catch (SQLException e) {
// handle the exception
88
■ Growth strategy
AGENDA ■ Market analysis
■ Financial overview
■ Innovative solutions
■ Future initiatives
89