Chapter 1 Functional Programming
Chapter 1 Functional Programming
Chapter 1 Functional Programming
programming.
Methods are procedures where we write a sequence of
functions as results
3
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/
8
package directory (folder)
class file
a/b/c/D.class
9
package name;
public class name { ...
Example:
package pacman.model;
public class Ghost extends Sprite {
...
}
10
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.
11
import packageName.className; // one class
Referring to packages
packageName.className
Example:
java.util.Scanner console =
new java.util.Scanner(java.lang.System.in);
12
Compilation units (files) that do not declare a package are put
into a default, unnamed, package.
package pacman.model;
public class Sprite {
int points; // visible to pacman.model.*
String name; // visible to pacman.model.*
14
15
Java collections framework
◦ prebuilt data structures
◦ interfaces and methods for manipulating those data structures
16
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.
17
18
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.
19
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
20
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;
// get int value of Integer int value =
integerArray[ 0 ];
21
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]
22
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.
23
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.
24
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.
25
26
27
28
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:
29
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
implement an interface.
30
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()));
}
} 31
Output: [1, 2, 3, 4, 5]
In this example, we created an anonymous inner class
33
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
34
Object Serialization
35
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
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
// other fields and methods
}
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:
41
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
44
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
45
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:
46
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
} 47