1. Manuel Fomitescu, Java Developer, TFPM
Manuel.Fomitescu@gmail.com
Introduction to Java
Programming
Object-oriented programming on the Java platform
2. Topics covered
Java platform overview - What is JAVA
Setting up your Java development environment (Eclipse)
Your first Java application – hello world
Writing good Java code - Documentation, Code Convention, Best
practices
Java logging mechanism
The Java language (language elements)
Keywords
Strings and operators
Conditional operators and control statements
Loops
Data types
Object-oriented programming concepts (Principles of OOP)
Your first Java class
Packages, Classes and Interfaces
Exceptions Handling
Java Collections
3. Java platform overview - What is
JAVA
James Gosling
https://www.oracle.com/java/index.html
https://docs.oracle.com/javase/8/docs/api/
http://www.oracle.com/technetwork/java/java
se/downloads/jdk8-downloads-2133151.html
http://www.eclipse.org/downloads/package
s/eclipse-ide-java-ee-developers/neon1
4. Java platform overview - History
James Gosling, Mike Sheridan and Patrick Naughton
initiated the Java language project in June 1991.
Sun Microsystems released the first public
implementation as Java 1.0 in 1995
Versions
JDK 1.1 (February 19, 1997)
J2SE 1.2 (December 8, 1998)
J2SE 1.3 (May 8, 2000)
J2SE 1.4 (February 6, 2002)
J2SE 5.0 (September 30, 2004)
Java SE 6 (December 11, 2006)
Java SE 7 (July 28, 2011)
Java SE 8 (March 18, 2014)
As of 2015, only Java 8 is supported ("publicly").
5. Java platform overview - Principles
Principles - there were five primary goals in the
creation of the Java language:
It must be "simple, object-oriented and familiar"
It must be "robust and secure"
It must be "architecture-neutral and portable"
It must execute with "high performance"
It must be “multithreaded and dynamic“
Java is a compiled programming language, but
rather than compile straight to executable machine
code, it compiles to an intermediate binary form
called JVM byte code. The byte code is then
compiled and/or interpreted to run the program
6. Java platform overview – Type of apps
JSE (Standard Edition)
This is the base platform used to write desktop applications
and components (modules) that extend the Java ecosystem.
JME (Micro Edition)
A subset of the java standard edition that allows Java
applications to be run on micro devices including mobile
phones. (Android Runtime ART).
JEE (Enterprise Edition)
The platform provides an API and runtime environment for
developing and running enterprise software, including network
and web services and other large-scale, multi-tiered, scalable,
reliable, and secure network applications
10. Java platform overview – Memory mgt.
The garbage collector
Rather than forcing you to keep up with memory
allocation (or use a third-party library to do so),the
Java platform provides memory management out of
the box.
11. Java platform overview - Summary
The Java language - it 's programming paradigm is
based on the concept of OOP, which the language's
features support.
The Java compiler – you write source code in .java
files and then compile them; the compiler checks your
code against the language's syntax rules, then writes
out bytecode in .class files which are a set of
instructions that run on a JVM.
The JVM - reads and interprets .class files and
executes the program's instructions on the native
hardware platform for which the JVM was written. The
JVM is the heart of the Java language's WORA(write-
once, run-anywhere) principle.
The garbage collector – this approach to memory
handling is called implicit memory management.
13. Setting up your Java development
environment (Eclipse)
http://www.oracle.com/technetwork/java/javase/downl
oads/jdk8-downloads-2133151.html
http://www.eclipse.org/downloads/packages/eclipse-
ide-java-ee-developers/neon1
The Eclipse IDE sits atop the JDK as a useful
abstraction, but it still needs to access the JDK and its
various tools. Before you can use Eclipse to write
Java code, you must tell it where the JDK is located.
The Eclipse development environment has four main
components:
Workspace
Projects
Perspectives
Views
15. Java Application structure
A set of collaborating classes where one class
has “the main” method
public static void main(String[] args) { …
Classes are stored in files - .java files
One or many classes in same file
A JAVA file contains
package declaration [optional, but recommended]
import/s declaration [optional]
At least one class definition
16. JDK tools
javac – the compiler
java – the interpreter
jar – creates jar archives for easier distribution
javadoc – generates Javadoc documentation
Classpath concept
The way to access code outside your class
Allows adding any files to it
Executes only *.class files (including from jar files)
Applies per JVM (same classpath for any class
running)
17. Document the code - JavaDoc
Document code using Javadoc comments
Specific format /** java doc comment */
Supporting annotations
Generate documentation with Javadoc utility
HTML format
Other types of comments in java
/* multiple line comments */
//single line comments
these types of comments do not appear in generated
documentation (javadoc)
18. Naming conventions
Identifier type Rules & examples
Packages All lower; ISO-3166
com.ricoh.training
java.lang
Classes Camel case starting upper; nouns
Person, String, Car
Interfaces Same as classes, upper; nouns
Runnable, Comparable, Serializable
Methods Camel case starting lower; verbs
eat, startWorking, getName,
getPrice
Variables Camel case starting lower; attribute;
price, name, height, firstName,
lastName
Constants All upper and “_”
FILE_SIZE, MAX_AGE
19. Code conventions
Filenames
Name of the (public) class + “.java” suffix
Indentation
Package
Class
Member
Code block
o Sub code block
Comments
Javadoc
Block, line, end-of-line
Declarations
One per line; At the begging of the block
Statements
One per line
http://www.oracle.com/technetwork/java/codeconventions-150003.pdf
20. Core packages in Java SE 8
java.lang — basic language functionality and fundamental types (is
available without the use of an import statement)
java.util — collection data structure classes
java.io — file operations
java.math — multiprecision arithmetics
java.nio — the Non-blocking I/O framework for Java
java.net — networking operations, sockets, DNS lookups, ...
java.sql — Java Database Connectivity (JDBC) to access databases
java.awt — basic hierarchy of packages for native GUI components
javax.swing —packages for platform-independent rich GUI components
java.text — Provides classes and interfaces for handling text, dates,
numbers, and messages in a manner independent of natural languages.
java.rmi — Provides the RMI package.
java.time — The main API for dates, times, instants, and durations.
21. Java logging mechanism
Before Java 1.4 introduced built-in logging, the
canonical way to find out what your program was
doing was to make a system call like this one:
public void someMethod() {
// Do some stuff...
// System.out.println(“log something");
}
The Java language's built-in logging facility is a better
alternative. I never use System.out.println() in my
code, and I suggest you don't use it either.
Another alternative is the commonly used log4j
replacement library, part of the Apache umbrella
project.
22. Java logging mechanism
Java logging mechanism can be customized using a
logging.properties file
The system will look for this config file, first using a
system property specified at startup:
java -
Djava.util.logging.config.file=myLoggingConfigFilePat
h
If this property is not specified, then the config file is
retrieved from its default location at:
JDK_HOME/jre/lib/logging.properties
24. JAVA language – reserved words
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronize
d
this
throw
throws
transient
try
void
volatile
while
25. JAVA language – data types
There are tree types of JAVA data types:
Primitive data type: boolean, char, byte, short, int,
long, double, float (even these primitive data types
have associated classes (objects))
Objects (reference data types): String, Boolean,
System, etc.
Arrays: of primitives or objects (int[], String[] etc.)
The JAVA language data types can be extended
by providing new classes (objects): e.q. Person
27. JAVA language – variables
Instance Variables (Non-Static Fields) - objects store their individual
states in "non-static fields”. Non-static fields are also known as instance
variables because their values are unique to each instance of a class
(name of a Person).
Class Variables (Static Fields) - A class variable is any field declared
with the static modifier; this tells the compiler that there is exactly one
copy of this variable in existence, regardless of how many times the
class has been instantiated. Additionally, the keyword final could be
added to indicate that the value will never change. (using final we can
define constants!!)
Local Variables - Similar to how an object stores its state in fields, a
method will often store its temporary state in local variables. The syntax
for declaring a local variable is similar to declaring a field (for example,
int count = 0). Local variables are only visible to the methods in which
they are declared.
Parameters - In the main method of the “FirstApplication" application
we have a parameter variable. (public static void main(String[] args).
The important thing to remember is that parameters are always
classified as "variables" not "fields".
28. JAVA language – variables
Variables can be of primitive data types or of reference data types
(objects). Before using any variables you have to declare and initialize
it.
Assignments: assign “value” to a variable using “=“ operator
Transfers information to a variable from
A literal or constant
Another variable
Expression
Method result
final double PI = 3.14; //constant
int value = 100; //initialized – default value is 0
char c1=’j’, c2=’a’; //not correct – use one assignment per line – default ‘u0000’
String name = “Titi";
Person p; //default null
int height = p.getHeight();
33. The JAVA language is (mostly) object oriented.
Two qualities differentiate the Java language from
purely object-oriented languages such as Smalltalk.
First, the Java language is a mixture of objects and
primitive types.
Second, with Java, you can write code that exposes the
inner workings of one object to any other object that
uses it.
The Java language does give you the tools necessary
to follow sound OOP principles and produce sound
object-oriented code. Because Java is not purely
object-oriented, you must exercise some discipline in
how you write code — the language doesn't force you
to do the right thing, so you must do it yourself.
OOP concepts
34. OOP concepts
OOP - is a programming language model organized
around objects rather than actions. Instead of having
a data structure with fields (attributes) and passing
that structure around to all of the program logic that
acts on it (behavior), in an object-oriented language,
data and program logic are combined.
What is an object?
An object is an entity that contains attributes and
behavior.
For example: Bike, Car, Person, etc. It can be
physical and logical.
Class - is the template from which individual objects
are created.
35. OOP concepts
Parent and child objects
A parent object is one that serves as the structural basis for
its children. A child object is more specialized.
Using this relation you can reuse the common attributes
and behavior of the parent object, adding to its child
objects attributes and behavior that differ.
Object summary: A well-written object:
Has crisp boundaries
Performs a finite set of activities
Knows only about its data and any other objects that it needs
to accomplish its activities
36. OOP concepts
The Person object - an object has two primary
elements: attributes and behavior.
Attributes: What attributes can a person have?
Name, Age, Height
Weight, Gender
Behavior: What about the behavior of a person object?
We can answer this questions?
What is your name? What is your age? What is your height?
Etc.
Or more complex behavior - calculating a person's Body Mass
Index (BMI)
State and string - State is an important concept in
OOP. An object's state is represented at any moment in
time by the value of its attributes. The state of an object can
be represented as a string and can be saved on the disk
(serialized) and then loaded from there (de-serialized).
39. Principles of OOP - Encapsulation
is a mechanism of wrapping the data (attributes) and
code acting on the data (methods) together as single
unit.
is a mechanism of hiding the implementation of the
behavior from the clients that uses that behavior.
On the Java platform, you can use access modifiers
to vary the nature of object relationships from public to
private. Public access is wide open, where as private
access means the object's attributes are accessible
only within the object itself.
Encapsulation is a powerful feature of the Java
language.
40. Principles of OOP - Encapsulation
class Person {
private int height;
private int width;
public int getWidth() { …}
public int getBMI() {…}
}
We hide internal attributes
We expose operations / behavior
These are visible from the outside
These operations will internally work with the private attributes
Encapsulation benefits: The separation between the object interface
and its internal implementation allows changing internal implementation
without affecting its clients because these depend on the object
interface and not on the internal implementation.
41. Principles of OOP - Inheritance
specialized classes — without additional code — can
"copy" the attributes and behavior of the source
classes that they specialize. If some of those attributes
or behaviors need to change, you override them.
the source object is called the parent, and the new
specialization is called the child.
Inheritance at work
using the Person class as the basis (called the super
class) for a new class called Employee. Being the child of
Person, Employee would have all of the attributes of a
Person class, along with additional ones, such as:
Employee number
Salary
42. Principles of OOP - Inheritance
The most important hierarchies in the OOP are:
Class hierarchies (“is a” relation)
Object hierarchies (“part of” relation)
Inheritance (Class hierarchies)
We discuss this in the previous slide. Parent – Child
relation (general -> specialized)
Aggregation (Object hierarchies) - the relation
between two objects in which one object belongs to the
other.
For example: between the Person and the Address
there is a aggregation relation. Address is part of the
Person.
43. Principles of OOP - Polymorphism
Polymorphism means that objects that belong to the same branch
of a hierarchy, when sent the same message(that is, when told to
do the same thing), can manifest that behavior differently.
In JAVA, we use method overriding to achieve polymorphism.
In JAVA, we use interfaces to achieve polymorphism.
Example
for (Person person: persons) {
person.toString();
}
persons can contain Person, Employee, Students …
It is not known at compile-time what elements (sub-types of
Person) persons contain.
the actual type of person is not known at compile-time. It can be
any subclass (derived class) of Person.
The declared type of person is superclass (base class) Person
45. OOP in JAVA – objects/classes
All derive (implicitely) from java.lang.Object
Contains some useful methods (to be inherited by all
objects):
toString
equals
hashCode
notify
notifyAll
wait
clone
finalize
getClass
46. OOP in JAVA – object lifecycle
Classes are templates for objects
They do nothing by themselves
Object creation – object instantiation via constructors
Person person = new Person();
Each created object has its set of properties as defined
by the class
Object usage – via referring variable its members are
available
person.toString();
Object destruction – controlled by JVM Garbage
Collector
Cannot be triggered directly
Before objects destruction, finalize() method is
called
47. OOP in JAVA – objects creation
Constructors – special functions used to create
objects
Useful for setting values to data members or to perform
specific actions
Syntax
Can have parameters
No return type
Have same name as class name
Usage
Can be used only together with new keyword
Rules
Many constructors in same class
If no constructor is defined, a default no-arg constructor
is provided
48. OOP in JAVA – constructor chaining
this keyword
- Used to solve variable
shadowing - Used to refer
other constructors
- Used for referring current
object
49. OOP in JAVA – access control
Controls what members can be accessed from
outside
Controls entire class visibility from outside
Modifier Visibility
public Available anywhere
private Only inside the class
protected Inside the class, the package and inside its
sub-classes
“package-
private”/missing
Inside the class, the package
Modifier Class scenario
public When the class should be
available outside package
“package-private” Available only for other classes in
same package; package internals
50. OOP in JAVA – final keyword
final class Employee {
public double calculatePay(){
return …;
}
}
class Employee {
public final double calculatePay(){
return …;
}
}
class Employee {
public double calculatePay(){
final float factor = 0.25f;
return …;
}
}
Final instance members must be set until the end object creation !
Class cannot be
extended
Method cannot
be overrriden
Variable value can
be set only once
51. OOP in JAVA – this vs super
this
Used as prefix (this.age) refers members in current
object
Used to solve ambiguities (this.name = name) in
case of shadowing
Used to refer/chain constructors (this())
super
Used to refer to superclass constructor (super(18))
Used to refer methods from superclass
(super.execute())
Useful in case of method override
52. Interfaces Abstract classes
Declares a set of operations
available, but no implementation
Therefore they cannot be
instantiated
interface Car {
void start();
void stop();
}
class Truck implements Car {
public void start(){
…
}
public void stop(){
…
}
In between a class and an
interface
Can have methods with implementation
Cannot be instantiated
abstract class Car {
public abstract void start();
public void stop(){
…
}
}
class Truck extends Car {
public void start(){
…
}
}
53. Inner classes Anonymous
classes
Shares the members of the outer
class, the inner class can access
them
class Car {
private String type;
class Engine {
//can access type
}
}
Car c = new Car();
Car.Engine e = c.new Engine();
Classes without a name! Not
reusable!
Since there is no name, they are
declared when they are
instantiated with new.
Arrays.sort(T[], new
Comparator<T>() {
@Override
compare() { //code}
})
An interface is instantiated here!!!
54. Overload Override
class Person {
String name;
public String toString(){
return name;
}
public String toString(String prefix){
return prefix + “ “ +
name;
}
public String toString(int prefix){
return prefix + “. “ +
name;
}
}
Person p = new Person();
p.toString();
p.toString(“Person:”);
p.toString(1);
class Person {
String name;
Person(String name) {this.name = name;}
public String toString(){
return name;
}
}
class Employee extends Person {
String id;
Employee(name, id) {
super(name);
this.id = id;
public String toString(){
return name + id;
}
}
Person p = new Person(); p.toString();
Person e = new Employee(); e.toString();
55. OOP in JAVA - enum
enum is a new data type added to the JDK 5
It is special data type that enables for a variable
to be one of a set of predefined constants - each
constant is unique
Declaring constants before JDK 5 (using
class/interface)
public class Person {
public static final String MALE = "male";
public static final String FEMALE = "female";
}
Person { private String gender; }
57. OOP in JAVA
Questions / Discussions ?
Examples for the concepts
discussed
Extend FirstApplication and use
Person, Employee, Student objects
58. JAVA – Exceptions
An exception is an event that occurs during
program execution that disrupts the normal flow
of the program's instructions.
Main concepts:
Throwing an exception: the way your code tells the JVM that it
encountered an error
Catching an exception: the way your code tells the JVM that it
wants to “handle” an error (print a message or take an
alternate route)
Together, the throw, throws, try, catch, and finally
form a net for the Java exceptions mechanism.
59. JAVA – Exceptions - throw
Throwing an exception
throw new IllegalArgumentException(“exception");
What happens when throw is called?
The exception object is created
The JVM exception handling mechanism takes control
and
It looks for the “closest” catch clause that handles the
exception:
First in the current method
Then in the calling method
And so on up the call chain
If none is found (even in main) the program exits
The exception itself is just a normal Java object created
with new
60. JAVA – Exceptions - try/catch/finally
try{
//some code that throws exceptions
} catch (IllegalArgumentException e){
// handle exception
} finally {
// always executes
}
The try statement wraps code that might throw an
exception
A catch handles exceptions of the declared type and
all its subclasses
The finally statement executes always – for cleanup
62. JAVA – Exceptions -
checked/unchecked
Unchecked: derived from RuntimeException or its
subclasses. Unchecked exceptions are not verified,
so processing them is optional! (NullPointerException)
Checked: derived from Exception or its
subclasses, excluding RuntimeException
Checked exceptions must be processed:
Handled (catch clause)
Declared and pass them further (throws clause)
Throws informs the caller/client what type of
exceptions it can receive when using the method.
63. JAVA – Custom Exceptions
When none existing exceptions match semantics
Extends Exception if the exception case is recoverable
Extends RuntimeException when the client is not expected
to handle it
Extends Error or Throwable mostly when the code is part
of a library or framework
It is rarely used
class ValidationException extends Exception {
public ValidationException(String message) {
super(message);
}
}
64. JAVA – Exceptions – best practice
Don’t leave empty catch blocks, at least log the exception
In special cases, explain why it is empty
Prefer standard exceptions instead of defining new exceptions
Don’t catch Throwable, catch specific exceptions
Catching Errors is most of a time a bad idea since they are “end-
of-the-road” exceptions
Favor unchecked exceptions
Some checked exceptions might be not recoverable, so handling
them has no added value
66. JAVA Collections – Boxing and
unboxing
Every primitive type in the Java language has a
counterpart class
Wrappers provide behavior (methods) for primitive values
67. JAVA Collections –Strings
In the JAVA language, strings are first-class objects of
type String with methods that help you manipulate
them
Declaring strings objects (Strings are immutable)
String greeting = "hello";
greeting = new String("hello"); //new instance is created in
memory
chars[] newString = {‘h’. ‘e’, ‘l’, ‘l’, ‘o’}
greeting = new String(newString);
Concatenating Strings
string1.concat(string2); or “string1” + “string2”;
Useful methods in String class:
int stringSize = “hello”.length() //5
StringBuffer, StringBuilder
68. JAVA Collections - Arrays
Arrays are objects that store multiple variables of
the same type, or variables that are all
subclasses of the same type
Can hold primitives and object references
int[] testScores = new int[5]; Person[] p = new
Person[5];
69. JAVA Collections – comparing
objects
==, .equals(), compareTo(), and compare()
Comparison Primitives Objects
a == b,
a != b
Equal
values
Compares references, not values.
Comparing to see if a reference is null.
Comparing two enum values.
a.equals(b) N/A
Compares values for equality.
Is defined in Object class
Works as == for objects; override it
a.compareTo(b) N/A
Comparable<T> interface. All Java
classes that have a natural ordering
implement this (String, Integer, ...).
compare(a, b) N/A
Comparator<T> interface.
Arrays.sort(T[], Comparator<T>)
70. JAVA Collections
A collection is a data structure in which objects
can be stored and iterated over - similar to arrays
but much better
Operations that can be done on a collection:
Add objects to the collection
Remove objects from the collection
Find out if an object (or group of objects) is in the
collection
Retrieve an object from the collection (without
removing it)
Iterate through the collection, looking at each
element (object) one after another
71. JAVA Collections - types
Lists
lists of things (classes that implement List)
duplicates are allowed
Sets
unique things (classes that implement Set)
no duplicates are allowed
Maps
things with an unique ID (classes that implement Map)
Queues
things arranged by the order in which they are to be
processed
73. JAVA Collections - List
List interface:
a List relies on the index
the one thing that List has that non-lists don't
have is a set of methods related to the index
get(int index)
indexOf(Object o)
add(int index, Object obj) etc.
74. JAVA Collections – List
implementations
List
ArrayList
• fast iteration and fast random
access
• it is an ordered collection (by
index), but not sorted
• same as an ArrayList
• methods are synchronized
for thread safety => slower
LinkedList
• ordered by index position
• elements are doubly-linked
to one another => good for
adding and removing from
the beginning or end
Vector
75. JAVA Collections - Set
Set Interface
a Set relies on uniqueness
the equals() method determines whether two
objects are identical
76. JAVA Collections – Set
implementations
SetHashSet
TreeSet
• fast access,
• no duplicates
• provides no ordering
• no duplicates;
• iterates in
sorted order
LinkedHashSet• no duplicates;
• iterates by insertion order
77. JAVA Collections - Map
Map Interface
a Map relies on unique identifiers
a unique key (the ID) is mapped to a specific
value
the equals() method determines whether two
objects are identical
78. JAVA Collections – Map
Implementations
Map
Hashtable
LinkedHashMap
TreeMap
HashMap
• unsorted, unordered
• allows one null key and multiple
null values
• fast updates (key/values);
• synchronized
• doesn't allow null
keys or null values
• maintains insertion
order of keys (default
) or access order
• faster iteration
sorted map
79. JAVA Collections –
equals()/hashCode()
public boolean equals(Object o)
Is reflexive, symmetric, transitive, consistent
public int hashCode()
Should be overridden for correct behavior in collections
When two objects are equal their hash codes are equal too
Not overriding them lead to unique values for different objects
that are considered equal
Object implementations are based on location of the object in heap
The hashCode contract
When two objects are equal, their hash codes are same
None or both should be overridden
If two objects are not equal, it is possible that their hash codes are same, but
not recommended for performance reasons
81. JAVA Collections - Generics
//non-generic
ArrayList myList = new ArrayList();
String element = (String)myList.get(0);
//generic
ArrayList<String> myList = new ArrayList<String>();
String element = myList.get(0);
No cast
Safer because only String objects are stored
//generics mixed with inheritance
List<String> myList = new ArrayList<String>();
List<Number> numbers = new ArrayList<Integer>(); // not-allowed
82. JAVA Collections – best practice
Prefer using lists over arrays
Object[] objectArray = new Long[0];
objectArray[0] = "I don't fit in";
//throws ArrayStoreException
List<Object> ol = new ArrayList<Long>();
//compilation failure - Incompatible types
ol.add("I don't fit in");
83. JAVA Collections – best practice
Choose the right type of collection based on the
need.
Write programs in terms of interfaces not
implementations, it allows to change the
implementation easily at a later point of time
Use generic types
84. JAVA Collections - best practice
While being used in a Map or Set, keys of a Map and items in a
Set must not change state
hence, it is recommended that these items be immutable objects
Because, in general, collections are not immutable objects,
collection fields should not be unintentionally exposed to the
caller
one technique is to define a set of related methods which
prevent the caller from directly using the underlying collection by
returning an immutable collection
The for-each loop should be used with both collections and
arrays since it is intended to simplify the most common form of
iteration
it should be preferred over the for loop and iterators