advJava-lec01-2016

Download Report

Transcript advJava-lec01-2016

Advanced Java Programming
51037
Adam Gerber, PhD, SCJP
[email protected]
Lecture 01-02 Agenda:
1/ intro to course and introductions
2/ BitBucket register
3/ Course logistics
4/ Quick review of Java and ecosystem
5/ Maven
6/ Git
7/ Serialization and I/O
8/ Behavior Parameterization
9/ Streams (lecture 2)
10/ Some Design Patterns
2
Survey of the class
Your name, hailing from, what you studied in
undergrad, what you want to accomplish with this
degree?
3
51037 is a Graduate Seminar
You will be expected to do original research on Java and
Java ecosystem technologies.
You will be expected to present your research to the
class.
4
Team Projects
Each team will be responsible for:
1/ creating a deck of slides describing the architecture of the
technology
Each team member will be responsible for:
1/ creating a lab using the course tools Maven/Git/IntelliJ and
making their lab available on bitbucket as public repo.
2/ lecturing for 1/2 hour on that lab in weeks 8 or 9.
See course website for dates: http://javaclass.cs.uchicago.edu/adv/
5
Website
Course website:
http://java-class.cs.uchicago.edu/adv/
6
Using Slack
https://mythicmobile.slack.com/messages/aj2016/
7
Registering Bitbucket account
Remote source-control:
http://java-class.cs.uchicago.edu/adv/
8
Policy regarding As
Max 30% As awarded in any class.
There are a lot of smart people in this room.
You will need to do extraordinarily good work to
get an A.
9
Brief review Java
• Java is the McGyver of programming languages
aka the duct tape of Enterprise programming.
• Java has a huge eco-system of technologies that
work with it.
10
Java
• Java is Write Once Run Anywhere (WORA). A java
program can run on any platform that has a JVM.
• A Java WAR file can run on any JEE compliant
web-server, such as Tomcat, JBoss, Wirefly,
Glassfish.
• Java Messaging Service for interoperability flows
and microservices.
• You WILL see Java at your job – it is practically
unavoidable.
11
What Sun (now Oracle) says about Java
• “…we designed Java as closely to C++ as
possible in order to make the system more
comprehensible. Java omits many rarely used,
poorly understood, confusing features of C++
that, in our experience, bring more grief than
benefit.”
• “The network is the computer” Sun Micro
• Java has support for concurrency since version
1.0.
12
13
14
Architecture Neutral
Java Code is compiled to .class files which are interpreted as
bytecode by the JVM. (.NET does this too; only you’re trapped
in an MS op system.)
JIT compilers like HotSpot are very fast – little difference
between in performance between machine-binary and
15
interpreted byte-code.
Implementation Independence
• A java int is ALWAYS 32bits; regardless of
operating system.
• A java long is ALWAYS 64bits.
• hashcode() will always be consistent.
• Serialization is versioned and consistent.
• The same is not true of C/C++.
17
No Pointers
• There are no pointers in Java
• Instead Java uses references; which for all
intents and purposes, behave like pointers.
• C++ is like driving a manual transmission car,
Java is like driving an automatic transmission
car, and python is like sitting in an uber cab.
18
Version numbers in Java
•
•
•
•
Jdk1.5 == Java 5.0
Jdk1.6 == Java 6.0
Jdk1.7 == Java 7.0
Jdk1.8 == Java 8.0
19
Wrapper Classes
• Every primitive has a corresponding Wrapper
class.
• For example; double has Double, int has
Integer, boolean has Boolean, char has
Character, etc.
• These wrapper classes can be very useful
when storing values in collections which
require you to use objects, and forbid the use
of primitives.
• Useful for Streams.
20
The API Documentation of the Standard Java Library
http://docs.oracle.com/javase/8/docs/api/
Directly within IntelliJ via Cntrl+N (check box nonproject files)
21
Object heirarchies
• You can also see the API online. Determine the
version you're using by typing> java –version
http://docs.oracle.com/javase/8/docs/api/
• Class hierarchies.
• The Object class is the grand-daddy of ALL java
classes.
• Every class inherits methods from Object.
• And from all its other ancestry.
• Even if you create a class that extends no other
classes, you still extend Object by default.
22
Class
Object
• A blueprint is to a house as a class is to an object
• Class = Blueprint
23
Lambda
Function
• Functions are now first-class citizens
• Store a method in a Lambda for deferred
execution.
24
pass by value
pass by reference
Action: Tell my accountant how much
I intend to spend on a new car.
Action: Swipe debit card and enter
pin at the Bently dealership.
Change in bank account: no change.
Change in bank account: -125k.
25
Passing references around is
dangerous, particularly in a
multithreaded environment.
Java8 prefers recursion over
iteration, and stateless over
stateful (side-effects).
26
Maven
27
What is Maven?
A build tool
A dependency management tool
A documentation tool
Maven makes your builds boring…
• Building projects should be easy and
standardized. You should not be spending a
substantial amount of your project time on builds.
Builds should just work!
Benefits of Maven
• Portability and Standardization
• Fast and easy to set up a powerful build process
• Dependency management (automatic downloads)
• Project website generation, Javadoc
• Continuous Integration Server automatic
• Very useful for TDD and testing
Installation and Setup
•
Download Maven from http://maven.apache.org/
•
Unzip the distribution
•
Create environment variable M2_HOME, which points to
Maven directory, e.g. c:\tools\apache-maven-3.1.0
•
Add Maven’s bin directory to System Variable Path
•
Ensure JAVA_HOME is set to JDK
•
Run mvn –version to test install
C:\Users\alina.vasiljeva>mvn -version
Apache Maven 3.1.0 (893ca28a1da9d5f51ac03827af98bb730128f9f2;
2013-06-28 05:15:32+0300)
Maven home: C:\tools\apache-maven-3.1.0\bin\..
Maven Background

Is a Java build tool


An Apache Project


“project management and comprehension tool”
Mostly sponsored by Sonatype
History

Maven 1 (2003)



Maven 2 (2005)




Very Ugly
Used in Stack 1
Complete rewrite
Not backwards Compatible
Used in Stack 2.0,2.1,2.2,3.0
Maven 3 (2010)


Same as Maven 2 but more stable
Used in Stack 2.3, 3.1
32
The Maven Mindset

All build systems are essentially the same:






Compile Source code
Link resources and dependencies
Compile and Run Tests
Package Project
Deploy Project
Cleanup
33
Other Java Build Tools

Ant (2000)




Ant+Ivy (2004)


Granddaddy of Java Build Tools
Scripting in XML
Very flexible
Ant but with Dependency Management
Gradle (2008)


Attempt to combine Maven structure with Groovy
Scripting
Easily extensible
34
Maven Learning Resources

Maven Homepage

http://maven.apache.org



Reference Documentation for Maven
Reference Documentation for core Plugins
Sonatype Resources

http://www.sonatype.com/resource-center.html


Free Books
Videos
35
Project Name (GAV)

Maven uniquely identifies a project using:

groupID: Arbitrary project grouping identifier (no spaces or
colons)



artfiactId: Arbitrary name of project (no spaces or colons)
version: Version of project



Usually loosely based on Java package
Format {Major}.{Minor}.{Maintanence}
Add ‘-SNAPSHOT ‘ to identify in development
GAV Syntax: groupId:artifactId:version
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.lds.training</groupId>
<artifactId>maven-training</artifactId>
<version>1.0</version>
</project>
Check version and create a new maven quickstart project from CLI
36
Maven Conventions










Maven is opinionated about project structure
target: Default work directory
src: All project source files go in this directory
src/main: All sources that go into primary artifact
src/test: All sources contributing to testing project
src/main/java: All java source files
src/main/webapp: All web source files
src/main/resources: All non compiled source files
src/test/java: All java test source files
src/test/resources: All non compiled test source
files
37
Maven Build Lifecycle


A Maven build follow a lifecycle
Default lifecycle






compile
test
package
Install
site
deploy
38
Example Maven Goals


To invoke a Maven build you set a lifecycle “goal”
mvn install


mvn clean


Clean old builds and execute generate*, compile
mvn compile install


Invokes just clean
mvn clean compile


Invokes generate* and compile, test, package, integration-test,
install
Invokes generate*, compile, test, integration-test, package, install
mvn test clean

Invokes generate*, compile, test then cleans
39
Maven and Dependencies

Maven revolutionized Java dependency
management


Introduced the Maven Repository concept




No more checking libraries into version control
Established Maven Central
Created a module metadata file (POM)
Introduced concept of transitive dependency
Often include source and javadoc artifacts
40
Adding a Dependency

Dependencies consist of:

GAV
 Scope: compile, test, provided (default=compile). Provided
are those that are provided at runtime by the Server for
example.
<project>
 Type: jar, pom, war, ear, zip (default=jar)
...
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
41
Maven Repositories

Dependencies are downloaded from repositories


Downloaded dependencies are cached in a local
repository


Usually found in ${user.home}/.m2/repository
Repository follows a simple directory structure



Via http
{groupId}/{artifactId}/{version}/{artifactId}-{version}.jar
groupId ‘.’ is replaced with ‘/’
Maven Central is primary community repo

http://repo1.maven.org/maven2
Check the local system for .m2 dependencies
42
Proxy Repositories

Proxy (Private) Repositories are useful:



Organizationally cache artifacts
Allow organization some control over dependencies
Combines repositories
43
Defining a repository




Private repositories are defined in the pom
Repositories can be inherited from parent
Repositories are keyed by id
Downloading snapshots can be controlled
<project>
...
<repositories>
<repository>
<id>lds-main</id>
<name>LDS Main Repo</name>
<url>http://code.lds.org/nexus/content/groups/main-repo</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
44
Transitive Dependencies

Transitive Dependency Definition:





A dependency that should be included when declaring
project itself is a dependency
ProjectA depends on ProjectB
If ProjectC depends on ProjectA then ProjectB is
automatically included
Only compile and runtime scopes are transitive
Transitive dependencies are controlled using:


Exclusions
Optional declarations
45
Dependency Exclusions


Exclusions exclude transitive dependencies
Dependency consumer solution
<project>
...
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.5.RELEASE</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
46
Dependency Management

What do you do when versions collide?

Allow Maven to manage it?


Take control yourself


Complex and less predictable
Manage the version manually
In Java you cannot use both versions
<project>
...
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
47
Super POM
•
Convention over configuration. The Super POM is
Maven's default POM
•
All POMs extend the Super POM unless explicitly set
•
The configuration specified in the Super POM is inherited
by the POMs you created for your projects
•
Super POM snippet can be found here:
http://maven.apache.org/guides/introduction/introductionto-the-pom.html
Standard directory organization
Having a common directory layout would allow for users familiar with one Maven
project to immediately feel at home in another Maven project.
src/main/java
Application/Library sources
src/main/resources
Application/Library resources
src/main/filters
Resource filter files
src/main/assembly
Assembly descriptors
src/main/config
Configuration files
src/main/webapp
Web application sources
src/test/java
Test sources
src/test/resources
Test resources
src/test/filters
Test resource filter files
src/site
Site
LICENSE.txt
Project's license
README.txt
Project's readme
Overview of common Goals
•
•
•
•
•
•
•
•
validate - validate the project is correct and all necessary information is
available
compile - compile the source code of the project
test - test the compiled source code using a suitable unit testing framework.
These tests should not require the code be packaged or deployed.
package - take the compiled code and package it in its distributable format,
such as a JAR
integration-test - process and deploy the package if necessary into an
environment where integration tests can be run
install - install the package into the local repository, for use as a dependency
in other projects locally
site – create documentation for the project.
deploy - done in an integration or release environment, copies the final
package to the remote repository for sharing with other developers and
projects
Create a new quickstart app and add StringEscapeUtils dependency
Add a dependency
• Add a new dependency in pom.xml
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.web.music</groupId>
<artifactId>my_project</artifactId>
<packaging>jar</packaging>
<version>1</version>
<name>my_project</name>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build/>
</project>
Maven console output
C:\Temp\my-app>mvn compile
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------------------------------------------------------------[INFO] Building my-app 1.0-SNAPSHOT
[INFO] -----------------------------------------------------------------------...
Downloading: http://repo1.maven.org/maven2/log4j/log4j/1.2.17/log4j-1.2.17.jar
Downloaded: http://repo1.maven.org/maven2/log4j/log4j/1.2.17/log4j-1.2.17.jar
(359 KB at 49.4 KB/sec)
[INFO] Not writing settings - defaults suffice
[INFO] Wrote Eclipse project for "my-app" to C:\Temp\my-app.
[INFO]
[INFO] -----------------------------------------------------------------------[INFO] BUILD SUCCESS
[INFO] -----------------------------------------------------------------------[INFO] Total time: 9.302s
[INFO] Finished at: Mon Sep 12 19:34:32 EEST 2012
[INFO] Final Memory: 9M/153M
[INFO] ------------------------------------------------------------------------
Local repository
•
What does Maven do with all the dependencies?
 C:\Documents and Settings\<username>\.m2
•
Advantages: No need to keep anything in the repo other
than your own source code, saves space in the repo and
rebuild / transfer time
•
Can download dependencies from a local intranet repo
instead of repo1.maven.org, etc
•
IntelliJ needs to know the path to the local Maven
repository. Therefore the classpath variable M2_REPO
has to be set:
•
Java > Build Path > Classpath Variables
Installing JARs to local repository
•
•
•
Sometimes you need to put some specific JARs in your
local repository for use in your builds
The JARs must be placed in the correct place in order for
it to be correctly picked up by Maven
To install a JAR in the local repository use the following
command:
mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=jar
•
Now can include
dependency in
pom.xml:
<dependency>
<groupId><group-id></groupId>
<artifactId><artifact-id></artifactId>
<version><version></version>
</dependency>
run mvn site on jaLabJava
Creating project website
• Execute mvn site goal
• Maven will start downloading and creating things
left and right
• Eventually in the \target dir you end up with a
\site dir, with an apache-style project website
• Javadoc, various reports, and custom content can be
added
Website features
•
•
•
•
•
•
•
Continuous Integration
Dependencies (JUnit is listed)
Issue Tracking
Mailing Lists
Project License
Project Team
Source Repository
Using Maven Plugins
• Plugins in Maven 2.0 look much like a
dependency
• For example, configure the Java compiler
...
to allow
<build>
<plugins>
JDK 6.0
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
sources
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
...
Good things about Maven
•
•
•
•
•
•
•
•
•
•
•
•
•
Standardization
Reuse
Dependency management
Build lifecycle management
Large existing repository
IDE aware
One directory layout
A single way to define
dependencies
Setting up a project is really fast
Transitive dependencies
Common build structure
Use of remote repository
Web site generation
•
•
•
•
•
•
•
•
•
•
•
Build best practices enforcement
Automated build of application
Works well with distributed teams
All artifacts are versioned and are
stored in a repository
Build process is standardized for all
projects
A lot of goals are available
It provides quality project
information with generated site
Easy to learn and use
Makes the build process much easier
at the project level
Promotes modular design of code
Many, many templates!
Alternatives
• There are also alternative build tools
An up-and-coming star in the build world
Groovy, Ant and Ivy combined.
Ruby Java building with Maven repositori
The agile dependency manager
from Apache
http://www.streamhead.com/maven-alternatives/
References
•
Maven Home
http://maven.apache.org/
•
Maven Getting Started Guide
http://maven.apache.org/guides/getting-started/index.html
•
Steps for creating a Maven-based Website
http://www.javaworld.com/javaworld/jw-02-2006/jw-0227-maven_p.html
•
Maven 3 Plugins Project
http://mojo.codehaus.org/
Where to install maven?
https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
why modelVersion in a maven file?
http://stackoverflow.com/questions/19759338/why-modelversion-of-pom-xml-isnecessary-and-always-set-to-4-0-0
mvn archetype:generate -DgroupId=edu.uchicago.gerber.ajava -DartifactId=maven02 DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
StringEscapeUtils
https://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
<p>Hello from Html.</p>
StringEscapeUtils.escapeHtml4(paragraph);
use site to generate documentation
http://books.sonatype.com/mvnref-book/reference/site-generation-sect-customdescript.html
Git
A distributed version control system
62
4/2/2017
Git History
• Came out of Linux development community
• Linus Torvalds, 2005
• Initial goals:
•
•
•
•
Speed
Support for non-linear development (thousands of parallel
branches)
Fully distributed
Able to handle large projects like Linux efficiently
When I say I hate CVS with a passion, I have to
also say that if there are any SVN
[Subversion] users in the audience, you might
want to leave. Because my hatred of CVS has
meant that I see Subversion as being the
most pointless project ever started. The
slogan of Subversion for a while was "CVS
done right", or something like that, and if you
start with that kind of slogan, there's nowhere
you can go. There is no way to do CVS right.
--Linus Torvalds, as quoted in
Wikipedia
64
Git uses a distributed model
Centralized Model
Distributed Model
(CVS, Subversion, Perforce)
(Git, Mercurial)
Result: Many operations are local
Git uses checksums
• In Subversion each modification to the central repo
incremented
the version # of the overall repo.
• How will this numbering scheme work when each user
has their own copy of the repo, and commits changes to
their local copy of the repo before pushing to the central
server?????
• Instead, Git generates a unique SHA-1 hash – 40 character
string
of hex digits, for every commit. Refer to commits by this
ID rather
Get ready to use Git!
1. Set the name and email for Git to use when you commit:
$ git config --global user.name “Bugs Bunny”
$ git config --global user.email [email protected]
1. You can call git config –list to verify these are set.
2. These will be set globally for all Git projects you work
with.
3. You can also set variables on a project-only basis by not
using the
--global flag.
4. You can also set the editor that is used for writing commit
messages:
Create a new javafx quickstart project and call it proClient, proImageshop
mvn archetype:generate DarchetypeGroupId=org.codehaus.mojo.archetypes DarchetypeArtifactId=javafx
Assuming you already have either a maven or intellij project.
Make sure you have the .ignore plugin
Select the project view from the project window drop-down
On the main menu, choose VCS | Import into Version Control | Create Git
Repository.
By default, IntelliJ IDEA suggests the root of the current project, but select
the root if not selected.
Right click the root dir in the project window and select new || .ignore ||
git.ignore
search for JetBrains and Maven and allow the .gitignore plugin to generate
a new .ignore file for you.
68
Right click root directory from the project window again and select || Git ||
Add
You will see all the files turn green (except those being ignored which will
be muted grey)
Create a remote on bitbucket by going to bitbucket.org
repository | create repository
give the project a name (probably best to give it the same name as the
local project).
Go to access management and add:
csgerber, johnhb, davidselvaraj with READ access
click on overview on the left panel
click on the "I have an existing project" drop-down
copy the second line into the clipboard -- the one that looks similar to this:
git remote add origin [email protected]:csgerber/proclient.git
69
open a terminal in intelliJ
paste contents of clipboard and press enter.
Test that you did it correctly by typing:
git remote -v
From intelliJ, press Command + K or Ctrl + K
uncheck all checkboxes on right
type your commit message such as "initial commit."
commit || push
make changes to the working directory and always remember if prompted
to add files to git, add them.
commit || push as required ad infititum.
70
Version control systems
•
Version control is all about managing multiple versions of
documents, programs, web sites, etc.
•
•
•
Some well-known version control systems are CVS, Subversion,
Mercurial, and Git
•
•
•
Almost all “real” projects use some kind of version control
Essential for team projects, but also very useful for individual projects
CVS and Subversion use a “central” repository; users “check out” files,
work on them, and “check them in”
Mercurial and Git treat all repositories as equal
Distributed systems like Mercurial and Git are newer and are
gradually replacing centralized systems like CVS and
Subversion
71
Why version control?
• For working by yourself:
•
•
Gives you a “time machine” for going back to earlier
versions
Gives you great support for different versions (standalone,
web app, etc.) of the same basic project
• For working with others:
•
Greatly simplifies concurrent work, merging changes
• Create a portfolio of projects
72
Introduce yourself to Git
• Enter these lines (with appropriate changes):
•
•
git config --global user.name "John Smith"
git config --global user.email [email protected]
• You only need to do this once
• If you want to use a different name/email address for a
particular project, you can change it for just that project
•
•
cd to the project directory
Use the above commands, but leave out the --global
73
Git Resources
• At the command line: (where verb = config, add, commit,
etc.)
$ git help <verb>
$ git <verb> --help
$ man git-<verb>
•
•
•
•
Free on-line book: http://git-scm.com/book
Git tutorial: http://schacon.github.com/git/gittutorial.html
Reference page for Git: http://gitref.org/index.html
Git website: http://git-scm.com/
A Local Git project has three areas
Unmodified/modified Staged
Files
Files
Committed
Files
Note: working directory sometimes called the “working tree”, staging area sometimes called the “index”.
Fork, clone the lab, then create new remote called gerber.
76
The difference between a fork and a clone
A fork is NOT a git operation. It is an operation of a Git
Web Hosting Service like Bitbucket or Github.
A clone is a git operation. It creates a local copy of the
remote repo.
77
78
79
Git file lifecycle
How IntelliJ stages files.
Examine SourceTree versus CLI versus IntelliJ.
IntelliJ defers staging until the last step (Cmd+K or Ctrl+K)
In CLI or SourceTree, you just stage before committing.
81
add/reset/commit:
move files from working-dir to stage-dir(aka index)
git add .
git add src/.
git add src/lec01/glab/DigitalToBinary.java
move files from stage-dir(aka index) to working-dir
git reset HEAD .
git reset head src/.
git reset head src/lec01/glab/DigitalToBinary.java
git commit -m “your commit message.”
82
Amending:
Every commit is associated with a sha-1 hash. That hash
is derived from 1/ the file changes in that commit and
2/ the previous commit.
You can not change any commit unless that commit is at
the head. Since no other commits depend on the head,
you may safely change the head.
To change the head, use
git commit --amend -m “your message”
git commit --amend --no-edit
83
Reverting:
You can roll back a commit (reverse it) by identifying it's
sha1 hash like so.
git revert --no-edit 71ac
84
Branching:
To list the branches in a project:
git branch
git branch -r
git branch --all
To create a branch:
git checkout -b branchName c39b
git checkout -b branchName
To delete a branch:
git branch -D branchName
To checkout a branch:
git checkout 7afe
git checkout master
85
Pushing to remotes:
To see the remotes:
git remote -v
To push to a remote:
git push origin master:master
git push origin master
git push --all
86
Pulling from remotes:
To see the remotes:
git remote -v
To pull from a remote:
git pull --all
git pull origin eval
87
Show the history of a single file in IntelliJ
How to resolve merge conflicts.
How to force push a branch
How to delete a remote branch
How to do a FFWD merge
88
Basic Workflow in IntelliJ
Basic Git workflow:
1.Modify files in your working directory.
2.Do a commit, (Cmd+K, or Ctrl+K) which takes the files
as they are in the staging area and stores that snapshot
permanently to your Git directory.
Create a local copy of a repo
2. Two common scenarios: (only do one of these)
a) To clone an already existing repo to your current directory:
$ git clone <url> [local dir name]
This will create a directory named local dir name, containing a working
copy of the files from the repo, and a .git directory (used to hold
the staging area and your actual repo)
b) To create a Git repo in your current directory:
git init
This will create a .git directory in your current directory.
Then you can commit files in that directory into the repo:
$ git add file1.java
$ git commit –m “initial project version”
$
Status
• To view the status of your files in the working directory
and staging area:
$ git status
or
$ git status –s
(-s shows a short one line version similar to svn)
Show Diff
• To see the Diff between the working directory and the local
git repo, press Ctrl+K or Cmd+K. Examine the files and
cancel
Searching commits
• You can use the filter ominbox to search for a particular
commit.
• You can sort by Author or date as well.
Git color coding for files in IntelliJ
•
•
•
•
•
•
Untracked files are brown (dark orange).
New files are green.
Modified files are blue.
Settled files in repo are black.
Ignored files are muted gray.
Conflicted files are red.
Dealing with untracked files
• Dragging a file into your project (not
added to git automatically)
Viewing logs (same as log in IntelliJ)
To see a log of all changes in your local repo:
•$ git log
or
•$ git log --oneline (to show a shorter version)
1677b2d Edited first line of readme
258efa7 Added line to readme
0e52da7 Initial commit
•git log -5
(to show only the 5 most recent updates, etc.)
Note: changes will be listed by commitID #, (SHA-1 hash)
Note: changes made to the remote repo before the last time
you cloned/pulled from it will also be included here
SVN vs. Git
• SVN:
•
•
central repository approach – the main repository is the only
“true” source, only the main repository has the complete file
history
Users check out local copies of the current version
• Git:
•
•
•
Distributed repository approach – every checkout of the
repository is a full fledged repository, complete with history
Greater redundancy and speed
Branching and merging repositories is more heavily used as a
result
Imperative versus Declarative
Imperative: is a style of programming where you program the
algorithm with control flow and explicit steps.
Declarative: is a style of programming where you declare what needs
be done without concern for the control flow.
Functional programming: is a declarative programming paradigm that
treats computation as a series of functions and avoids state and
mutable data to facilitate concurrency. “Functional programming has its
roots in lambda calculus, a formal system developed in the 1930s to
investigate computability, the Entscheidungsproblem, function
definition, function application, and recursion. Many functional
programming languages can be viewed as elaborations on the lambda
calculus”. Wikipedia
See BigDecimalMain
Behavior Parameterization
100
How did Java deal with “functional”
programming prior to Java8
Urma/behaviorParam/_01TheProblemDefined
Another example of anon class
Our first Lambda expression
1/ start with a “functional interface” - a functional interface
has ONE abstract method.
2/ create an anonymous class and implement its method
3/ use the format as seen above
4/ no need for return statements, that's implied
Another example
Another example
Type of Lambda Expression
• The java ‘Type’ of a lamba expression is a “Functional
Interface”
• Functional Interface is an interface with only ONE
abstract method
• The concept of “Functional Interface” is new, but
many of the interfaces in Java7 and before are
“functional interfaces” such as Runnable,
Comparable, etc.
• Java8 defines many more functional interfaces in the
java.util.function.* pacakge.
• Older functional interfaces have been decorated with
default methods to preserve backwards compatibility
Location of Functional Interfaces
• You may define your own “Functional
Interfaces”
• Java8 defines many in: java.util.function.*
• 43 interfaces in 4 categories, such as Function,
Supplier, Consumer, Predicate.
Can I store a Lamba Expression in
a variable in Java?
• Yes!
• Wherever a method requires an
anonymous inner class (with one method),
you may put a lamba expression.
• For example: Collections.sort(list, compL);
• You may also use lambda expressions
with Streams
See functionalIterfaceTest
Is a Lambda expression an
Object?
• Not really. It is an ‘object without identity’.
• It does not inherit from Object and so you
can’t call the .equals(), .hashcode(), etc.
• There is no ‘new’ keyword in lamba, so
there is far less overhead both at compileand run-time.
• You can't use this keyword to identify it
using reflection.
References
A lot of the material in this lecture is discussed in much more
detail in these informative references:
•
•
•
•
The Java Tutorials,
http://docs.oracle.com/javase/tutorial/java/index.html
Lambda Expressions,
http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaex
pressions.html
Adib Saikali, Java 8 Lambda Expressions and Streams,
www.youtube.com/watch?v=8pDm_kH4YKY
Brian Goetz, Lambdas in Java: A peek under the hood.
https://www.youtube.com/watch?v=MLksirK9nnE
111
Event-Source
(Button)
No Event-Listener
listening
Event
(onClick)
No Catcher
No Event Listener
112
Event-Source
(Button)
Event-Listener listening
Event
(onClick)
OnClickListener
Any Object
Catcher ready to catch
113
Behavior Parameterization
Objects are first-class citizens in Java.
You can now store references to functions.
Functions too are first class citizens in Java.
114
The Lambda Calculus
•
•
•
The lambda calculus was introduced in the 1930s by Alonzo
Church as a mathematical system for defining computable
functions.
The lambda calculus serves as the computational model
underlying functional programming languages such as Lisp,
Haskell, and Ocaml.
Features from the lambda calculus such as lambda
expressions have been incorporated into many widely used
programming languages like C++ and now very recently Java 8.
115
Example of a Lambda Expression
•
The lambda expression
λ x . (x + 1) 2
represents the application of a function λ x . (x + 1)
with a formal parameter x and a body x + 1 to the
argument 2. Notice that the function definition
λ x . (x + 1) has no name; it is an anonymous
function.
•
In Java 8, we would represent this function definition
by the Java 8 lambda expression x -> x + 1.
116
More Examples of Java 8 Lambdas
•
•
A Java 8 lambda is basically a method in Java without a declaration usually written
as (parameters) -> { body }. Examples,
1.
(int x, int y) -> { return x + y; }
2.
x -> x * x
3.
( ) -> x
A lambda can have zero or more parameters separated by commas and their type
can be explicitly declared or inferred from the context.
•
Parenthesis are not needed around a single parameter.
•
( ) is used to denote zero parameters.
•
The body can contain zero or more statements.
•
Braces are not needed around a single-statement body.
117
What is Functional Programming?
•
A style of programming that treats computation as
the evaluation of mathematical functions
•
Eliminates side effects
•
Treats data as being immutable
•
•
•
Expressions have referential transparency – this
reference will do this and this only.
Functions can take functions as arguments and
return functions as results
Prefers recursion over explicit for-loops
118
Why do Functional Programming?
•
•
•
Allows us to write easier-to-understand, more
declarative, more concise programs than
imperative programming
Allows us to focus on the problem rather than
the code
Facilitates parallelism
119
Java 8
•
•
•
•
Java 8 is the biggest change to Java since the
inception of the language
Lambdas are the most important new addition
Java is playing catch-up: most major
programming languages already have support
for lambda expressions
A big challenge was to introduce lambdas
without requiring recompilation of existing
120
binaries
Benefits of Lambdas in Java 8
•
Enabling functional programming
•
Writing leaner more compact code
•
Facilitating parallel programming
•
•
Developing more generic, flexible and
reusable APIs
Being able to pass behaviors as well as data to
functions
121
Java 8 Lambdas
•
Syntax of Java 8 lambda expressions
•
Functional interfaces
•
Variable capture
•
Method references
•
Default methods
122
Example 1:
Print a list of integers with a lambda
List<Integer> intSeq = Arrays.asList(1,2,3);
intSeq.forEach(x -> System.out.println(x));
•
x -> System.out.println(x) is a lambda expression that
defines an anonymous function with one parameter
named x of type Integer
123
Example 2:
A multiline lambda
List<Integer> intSeq = Arrays.asList(1,2,3);
intSeq.forEach(x -> {
x += 2;
System.out.println(x);
});
•
Braces are needed to enclose a multiline body in a lambda
124
expression.
Example 3:
A lambda with a defined local variable
List<Integer> intSeq = Arrays.asList(1,2,3);
intSeq.forEach(x -> {
int y = x * 2;
System.out.println(y);
});
•
Just as with ordinary functions, you can define local
variables inside the body of a lambda expression
125
Example 4:
A lambda with a declared parameter type
List<Integer> intSeq = Arrays.asList(1,2,3);
intSeq.forEach((Integer x -> {
x += 2;
System.out.println(x);
});
•
You can, if you wish, specify the parameter type.
126
Functional Interfaces
•
•
Design decision: Java 8 lambdas are assigned to functional
interfaces.
A functional interface is a Java interface with exactly one nondefault method. E.g.,
public interface Consumer<T> {
void accept(T t);
}
•
The package java.util.function defines many new
useful functional interfaces.
127
Implementation of Java 8 Lambdas
•
•
•
The Java 8 compiler first converts a lambda expression into a
function
It then calls the generated function
For example, x -> System.out.println(x) could be
converted into a generated static function
public static void genName(Integer x) {
System.out.println(x);
}
Urma/behaviorParam/UsingConsumers.java
128
Variable Capture
•
Lambdas can interact with variables defined
outside the body of the lambda
•
Using these variables is called variable capture
•
These variables must be effectively final.
129
Local Variable Capture Example
public class LVCExample {
public static void main(String[] args) {
List<Integer> intSeq = Arrays.asList(1,2,3);
int var = 10;
intSeq.forEach(x -> System.out.println(x + var));
}
}
130
Static Variable Capture Example
public class SVCExample {
private static int var = 10;
public static void main(String[] args) {
List<Integer> intSeq = Arrays.asList(1,2,3);
intSeq.forEach(x -> System.out.println(x + var));
}
}
131
Method References
•
•
Method references can be used to pass an
existing function in places where a lambda is
expected
The signature of the referenced method needs
to match the signature of the functional
interface method
132
Summary of Method References
Method Reference
Type
Syntax
Example
static
ClassName::StaticMethodName
String::valueOf
constructor
ClassName::new
ArrayList::new
specific object
instance
objectReference::MethodName
x::toString
arbitrary object of a
given type
ClassName::InstanceMethodName Object::toString
133
Conciseness with Method
References
We can rewrite the statement
intSeq.forEach(x -> System.out.println(x));
more concisely using a method reference
intSeq.forEach(System.out::println);
134
Default Methods
Java 8 uses lambda expressions and default
methods in conjunction with the Java collections
framework to achieve backward compatibility
with existing published interfaces
For a full discussion see Brian Goetz, Lambdas in
Java: A peek under the hood.
https://www.youtube.com/watch?v=MLksirK9nnE
135
Streams
What is a Stream
• A stream is a limitless iterator that allows you to process
collections.
• You can chain operations. This chain is called a pipeline.
• You must have at least one terminal operation and zero or
more intermediary operations.
• The pipeline usually takes the form of map-filter-reduce
pattern.
• Any stream operation that returns a Stream<T> is an
intermediate operation, and any object that returns void is
terminal.
• Intermediate operations are lazy, whereas terminal operations
are eager.
• A terminal operation will force the stream to be “spent” and
you can NOT re-use that reference, though you can always
get a new stream.
• May be parallelized and optimized across cores.
See StreamMain
Iterator
See IteratorDriver
4 categories of Functional
Interfaces
Functional Interface
archetypes
Example used in
Consumer
forEach(Consumer),
peek(Consumer)
Predicate
filter(Predicate)
Function
map(Function)
Supplier
reduce(Supplier)
collect(Supplier)
See java.util.function.*
ConsumerMain
4 categories of Functional
Interfaces
Method references
You can refer to static or non-static
method simply by using the double colon
(method reference) notation like so:
System.out::println
stringLenComparator::compare
See MethodRefsMain
Map is a transform
• The .map() method is not an associative
data structure, rather it is a transformative
operation. It takes a Stream<T> and it
returns either a Stream<T> or Stream<U>.
• Example: Stream<String> to
Stream<String>
• Example: Stream<String> to
Stream<Date>
Intermediary operation
• Intermediary operation: A method that
takes a Stream and returns a Stream.
• They are lazily loaded and will only be
executed if you include a terminal
operation at the end.
– The peek() method
– The map() method
– The filter() method
Terminal operation
• Terminal operation: A method that takes a
Stream<T> and returns void.
• They are eagerly loaded and will cause the
entire pipeline to be executed.
• A terminal operation will “spend” the stream.
– The forEach() method
– The count() method
– The max() method
– The collect() method
– The reduce() method
Slide references
Lambdas: Alfred V. Aho ( http://www.cs.columbia.edu/~aho/cs6998/)
145
Stream API
•
•
The new java.util.stream package provides utilities to support
functional-style operations on streams of values.
A common way to obtain a stream is from a collection:
Stream<T> stream = collection.stream();
•
•
Streams can be sequential or parallel.
Streams are useful for selecting values and performing actions
on the results.
146
Stream Operations
•
•
An intermediate operation keeps a stream
open for further operations. Intermediate
operations are lazy.
A terminal operation must be the final
operation on a stream. Once a terminal
operation is invoked, the stream is consumed
and is no longer usable.
147
Example Intermediate Operations
•
filter excludes all elements that don’t
match a Predicate.
•
map performs a one-to-one transformation of
elements using a Function.
148
A Stream Pipeline
A stream pipeline has three components:
1.
A source such as a Collection, an array, a
generator function, or an IO channel;
2.
Zero or more intermediate operations; and
3.
A terminal operation
149
Stream Example
int sum = widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();
Here, widgets is a Collection<Widget>. We create a stream of
Widget objects via Collection.stream(), filter it to produce a
stream containing only the red widgets, and then transform it into a
From
Java Docs
stream of int values representing the weight of each red
widget.
150
Interface Stream<T>
Then this stream is summed to produce a total weight.
Parting Example: Using lambdas and stream to
sum the squares of the elements on a list
List<Integer> list = Arrays.asList(1,2,3);
int sum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get();
System.out.println(sum);
•
Here map(x -> x*x) squares each element and
http://viralpatel.net/blogs/lambda-expressions-java-tutorial/
151
then reduce((x,y) -> x + y) reduces all elements
Outline
1.
What is the lambda calculus?
2.
What is functional programming?
3.
What are the benefits of functional
programming?
4.
Functional programming in Java 8
5.
Java 8 lambda expressions
6.
Implementation of Java 8 lambda expressions
7.
Streams
152