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

Advanced Programming Ch1

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects, with Java being a strongly object-oriented language that emphasizes modularity, reusability, and maintainability. Key principles of OOP in Java include encapsulation, abstraction, inheritance, and polymorphism, which facilitate code organization and functionality. The document also covers functional programming concepts, Java packages, and the Java Collections Framework, highlighting their importance in software development.

Uploaded by

eyob.ketemaw
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Advanced Programming Ch1

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects, with Java being a strongly object-oriented language that emphasizes modularity, reusability, and maintainability. Key principles of OOP in Java include encapsulation, abstraction, inheritance, and polymorphism, which facilitate code organization and functionality. The document also covers functional programming concepts, Java packages, and the Java Collections Framework, highlighting their importance in software development.

Uploaded by

eyob.ketemaw
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 89

OOP

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.

■ Java is a strongly object-oriented language


that uses OOP principles to structure code
in a way that is modular, reusable, and
easier to maintain.

2
• Code is organized into classes,

Modularity making it easier to maintain,


update, and debug.

• Through inheritance and


composition, classes can be
Reusability reused in different programs or
parts of programs.

• OOP is suitable for large-scale


Scalability applications and makes it easier
to add new features.

Maintainability • Because objects are self-


contained, changes can be made
with minimal effect on the rest of
the system.
• OOP mirrors the real world by
Real-world representing entities as objects,
Modeling making the design process more
intuitive.

Benefits of Object-Oriented
Programming in Java: 3
IN JAVA, OOP
FOCUSES ON FOUR
MAIN PRINCIPLES:
Encapsulation

• restricting direct access to some of the object's components, which is done


using access modifiers (private, protected, public).
Abstraction

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

• It allows objects of different classes to be treated as objects of a common


superclass. The two types of polymorphism in Java are:
• Compile-time polymorphism (method overloading)
• Runtime polymorphism (method overriding)

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.

■ Types of Variables: (local global )


– Local Variable: Declared inside a
method and accessible only within that
method.
– Instance Variable: Declared inside a
class but outside any method. Each
instance of the class has its own copy
of the variable.
– Static Variable: Declared with the static
keyword. It is shared by all instances of
the class.
6
LOOP
STATEMENTS
IN JAVA
■ Loops are used to execute a block
of code repeatedly based on a
condition.
■ For Loop
■ While Loop
■ Do-While Loop:

7
CONDITIONAL STATEMENTS IN
JAVA

■ Conditional statements allow you to


execute different blocks of code
based on certain conditions.
■ If Statement:
■ If-Else Statement:
■ Switch Statement:

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.

■ It is a declarative style. Its main focus is on “what to solve,” in contrast to an


imperative style, where the main focus is on “how to solve.”

■ There are no “for” or “while” loop in functional languages.


– Iteration in functional languages is implemented through recursion.
– Recursive functions repeatedly call themselves, until it reaches the base case.

■ 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.

■ Pure functions are preferred in FP because they are predictable, reusable,


and easier to test.
■ These functions have two main properties.
– First, they always produce the same output for same arguments
irrespective of anything else.

– Secondly, they have no side-effects i.e. they do not modify any


arguments or local/global variables or input/output streams.

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.

■ A function accepting functions as an argument and return a


function as its return type/value

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

■ It is used in mathematical computations.


■ It is needed where concurrency or parallelism is required.

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.

■ Uses of Java packages:


– group related classes together
– as a namespace to avoid name collisions
– provide a layer of access / protection
– keep pieces of a project down to a manageable size

■ 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

– (relative to the root of your project)

28
CONT…

■ Importing a Package ■ Using the Class from a Package


■ To use the classes from a package, you ■ After importing the class, you can create
need to import them using the import objects of that class and use its methods.
keyword. There are two ways to import:
■ import com.example.utils.MyClass;
1. Import a single class:
public class Main {
import
com.example.utils.MyClass; public static void main(String[] args) {
3. Import all classes from a package // Using the class from the package
(useful for importing multiple classes at
once): MyClass utility = new MyClass();

import com.example.utils.*; utility.printMessage(); }


}

29
A PACKAGE
DECLARATION
package name;

public class name { ...

Example:
package pacman.model;

public class Ghost extends Sprite {


...
}

■ File Sprite.java should go in folder pacman/model .

30
IMPORTING A
PACKAGE
import packageName.*; // all classes

Example:
package pacman.gui;
import pacman.model.*;

public class PacManGui {


...
Ghost blinky = new Ghost();
}
■ PacManGui must import the model package in order to use it.

31
IMPORTING A CLASS &
REFERRING TO PACKAGES
import packageName.className; // one class

■ Importing single classes has high precedence:


– if you import .*, a same-named class in the current dir will
override

 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.

■ Classes in the default package:


– Cannot be imported
– Cannot be used by classes in other packages

■ Many editors discourage the use of the default package.

■ Package java.lang is implicitly imported in all programs by default.


33
CONT. . .

■ 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

■ The Collections Framework is a sophisticated hierarchy of


interfaces and classes that provide state-of-the-art technology
for managing groups of objects.

■ The Java Collections Framework (JCF) is a set of classes and


interfaces that implement commonly used collection data
structures such as lists, sets, maps, and queues. It provides a
well-organized architecture for handling groups of objects and
offers a wide variety of utilities to manage them efficiently.

■ The JCF is part of the java.util package and is central to Java


38
THE COLLECTIONS FRAMEWORK WAS
DESIGNED TO MEET SEVERAL GOALS.
■ First, the framework had to be high-performance. The
implementations for the fundamental collections (dynamic arrays,
linked lists, trees, and hash tables) are highly efficient.
■ Second, the framework had to allow different types of collections to
work in a similar manner and with a high degree of interoperability.
■ Third, extending and/or adapting a collection had to be easy. Toward
this end, the entire Collections Framework is built upon a set of
standard interfaces.
– Several standard implementations (such as LinkedList, HashSet,
and TreeSet) of these interfaces are provided that you may use
as-is.
■ Finally, mechanisms were added that allow the integration of
standard arrays into the Collections Framework.

■ algorithms operate on collections and are defined as static methods


39
COLLECTIONS OVERVIEW
■ The Collections Framework defines several core interfaces.
■ A collection is a data structure—actually, an object—that can hold references to
other objects.
– Usually, collections contain references to objects that are all of the same
type.
■ Figure 20.1 lists some of the interfaces of the collections framework.
■ Package java.util.

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.

■ Collection is a generic interface that has this declaration:

– interface Collection<E>

■ Here, E specifies the type of objects that the collection will hold. Collection
extends

the Iterable interface.

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.

■ Because all collections implement Collection, familiarity with its methods is

necessary for a clear understanding of the framework.

■ Several of these methods can throw an UnsupportedOperationException.

■ A ClassCastException is generated when one object is incompatible with

another, such as when an attempt is made to add an incompatible object to a

collection.

■ A NullPointerException is thrown if an attempt is made to store a null object and

null elements are not allowed in the collection.

■ 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


45
fixed length collection that is full.
46
THE LIST INTERFACE
■ The List interface extends Collection and declares the behavior
of a collection that stores a sequence of elements. Elements
can be inserted or accessed by their position

■ in the list, using a zero-based index. A list may contain


duplicate elements. List is a generic interface that has this
declaration:

■ 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

■ a ClassCastException is generated when one object is


incompatible with another, such as when an attempt is
made to add an incompatible object to a list.

■ Also, several methods will throw an


IndexOutOfBoundsException if an invalid index is used.

■ NullPointerException is thrown if an attempt is made to


store a null object and null elements are not allowed in
the list.

■ An IllegalArgumentException is thrown if an invalid


argument is used.
48
THE SET INTERFACE
■ The Set interface defines a set.

■ It extends Collection and specifies the behavior of a collection that does


not allow duplicate elements.

■ Therefore, the add( ) method returns false if an attempt is made to add


duplicate elements to a set.

■ With one exception, it does not specify any additional methods of its
own.

■ Set is a generic interface that has this declaration:

■ interface Set <E>

■ 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.

■ SortedSet is a generic interface that has this declaration:

■ 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.

■ NavigableSet is a generic interface that has this declaration:

■ 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.

■ However, there are types of queues in which the ordering is


based upon other criteria. Queue is a generic interface that has
this declaration:

■ interface Queue <E>

■ 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

■ The Deque interface extends Queue and declares the behavior of a


double-ended queue.

■ Double-ended queues can function as standard, first-in, first-out


queues or as last-in, first-out stacks.

■ Deque is a generic interface that has this declaration:

■ interface Deque Here,

■ E specifies the type of objects that the deque will hold.

56
METHOD
S

57
TYPE-WRAPPER CLASSES FOR
PRIMITIVE TYPES
■ Each primitive type has a corresponding type-wrapper class (in package
java.lang).

– Boolean, Byte, Character, Double, Float, Integer, Long and


Short.

■ Each type-wrapper class enables you to manipulate primitive-type values as


objects.

■ Collections cannot manipulate variables of primitive types.

– They can manipulate objects of the type-wrapper classes, because every


class ultimately derives from Object.
58
■ Several methods throw a ClassCastException when an object is
incompatible with the elements in the deque.

■ A NullPointerException is thrown if an attempt is made to store a null


object and null elements are not allowed in the deque.

■ 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 fixedlength deque that is full.

■ A NoSuchElementException is thrown if an attempt is made to


remove an element from an empty deque
59
TYPE-WRAPPER CLASSES FOR
PRIMITIVE TYPES (CONT.)

■ Each of the numeric type-wrapper classes—Byte, Short, Integer, Long,


Float and Double—extends class Number.

■ 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.

■ An unboxing conversion converts an object of a type-wrapper class to a value of


the corresponding primitive type.

■ These conversions can be performed automatically (called autoboxing and auto-


unboxing).

■ 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.

■ Auto-unboxing occurs when assigning integerArray[0] to int variable value,


because variable value stores an int value, not a reference to an Integer object.

■ Boxing conversions also occur in conditions, which can evaluate to primitive


boolean values or Boolean objects

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.

■ List indices are zero based.

■ 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.

■ Interface List is implemented by several classes, including ArrayList,


LinkedList and Vector.

■ 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 size return the number of elements.

■ List method get retrieves an individual element’s value from the specified index.

■ Collection method iterator gets an Iterator for a Collection.

■ Iterator- method hasNext determines whether a Collection contains more elements.


– Returns true if another element exists and false otherwise.

■ Iterator method next obtains a reference to the next element.

■ Collection method contains determine whether a Collection contains a specified


element.

■ Iterator method remove removes the current element from a Collection.


65
66
67
68
ARRAYLIST AND ITERATOR
■ New in Java SE 7: Type Inference with the <> Notation

– 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.

■ Anonymous classes usually extend a subclass or implement an interface.

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]

■ In this example, we created an anonymous inner class i.e. new


Comparator<Integer>() {} that implements the Comparator interface and
overrides the compare() method.

■ Lambda Expression

■ Lambda expression is an anonymous function that takes in parameters and


returns a value. It is called an anonymous function because it doesn't require a
name.

■ Syntax: (parameter1, parameter2, ...) -> expression

(parameter1, parameter2, ...) -> { body } 73


JAVA LAMBDA EXPRESSION SYNTAX

■ The Syntax of Lambda Expression in Java consists of three


components.

■ Arguments-list: It is the first portion of the Lambda expression in


Java. It can also be empty or non-empty. In the expression, it is
enclosed by a round bracket.

■ 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.

■ Body: It contains the function body of lambda expression. It is


surrounded by curly brackets.
74
LAMBDA EXPRESSION …
import java.util.ArrayList; import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
int sum = list.stream().reduce(0, (a, b) -> a + b);
System.out.println(sum);
}
}
■ Output: 15

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:

Person person = new Person("Alice", 25);


try (FileOutputStream fos = new FileOutputStream("person.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
} 79
OBJECT SERIALIZATION …
In this example, we create a Person object and then use an ObjectOutputStream
to write the object to a file named person.ser. To deserialize the object, we would
use an ObjectInputStream:
try (FileInputStream fis = new FileInputStream("person.ser");
ObjectInputStream ois = new ObjectInputStream(fis)) {
Person person = (Person) ois.readObject();
System.out.println(person.getName()); // "Alice"
System.out.println(person.getAge()); // 25 }
catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} 80
OBJECT SERIALIZATION …
■ In this example, we read the serialized Person object from the file using an
ObjectInputStream and then cast the result to a Person object.
■ Once we have the Person object, we can use its methods to access its state.
■ Object serialization in Java is a powerful feature that allows you to save the state
of an object to disk or transmit it over a network, making it a useful tool for
many types of applications.
■ However, it is important to note that serialization can also be a security risk,
since a malicious user could potentially use a serialized object to execute
arbitrary code.
■ As a result, you should take care to properly validate any serialized objects that
your code receives. 81
DECLARATIVE
PROGRAMMING

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

■ Overall, declarative programming is a useful approach for tasks that require a


higher-level of abstraction,

■ while imperative programming is a better choice for tasks that require low-level
control over the computer's hardware resources.

■ Both paradigms can be used effectively in Java, depending on the specific


requirements of the task at hand.

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:

List<String> names = Arrays.asList("John", "Alice", "Bob"); names.sort((s1, s2) ->


s2.compareTo(s1));
86
EXAMPLE OF DECLARATIVE
PROGRAMMING
2. Stream API: The Stream API in Java provides a declarative way to process
collections of data.
You can chain together a series of operations, such as filter, map, and reduce, to
specify what you want to do with the data.
For example, the following code uses the Stream API to count the number of even
integers in a list:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
long count = numbers.stream()
.filter(n -> n % 2 == 0)
.count(); 87
EXAMPLE OF DECLARATIVE PROGRAMMING

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

You might also like