Manuel - SPR - Intro to Java Language_2016

Click here to load reader

download Manuel - SPR - Intro to Java Language_2016

of 86

Transcript of Manuel - SPR - Intro to Java Language_2016

Introduction to Java Programming

Manuel Fomitescu, Java Developer, [email protected]

Introduction to Java Programming Object-oriented programming on the Java platform

Topics coveredJava platform overview - What is JAVASetting up your Java development environment (Eclipse)Your first Java application hello worldWriting good Java code - Documentation, Code Convention, Best practicesJava logging mechanismThe Java language (language elements)KeywordsStrings and operatorsConditional operators and control statementsLoopsData typesObject-oriented programming concepts (Principles of OOP)Your first Java classPackages, Classes and InterfacesExceptions HandlingJava Collections

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/javase/downloads/jdk8-downloads-2133151.htmlhttp://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/neon1

Java platform overview - HistoryJames 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 1995VersionsJDK 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").

Java platform overview - PrinciplesPrinciples - 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 dynamicJava 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

Java platform overview Type of appsJSE (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

Java platform overview Type of apps

Java platform overview - Ecosystem

Code

Compile

Run

Java platform overview - JVM

Java platform overview Memory mgt.The garbage collectorRather 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.

Java platform overview - SummaryThe 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.

Java platform overview

Questions / Discussions ?

Setting up your Java development environment (Eclipse)http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.htmlhttp://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/neon1The 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:WorkspaceProjectsPerspectivesViews

Your first Java Application

Java Application structureA set of collaborating classes where one class has the main methodpublic static void main(String[] args) {

Classes are stored in files - .java filesOne or many classes in same file

A JAVA file containspackage declaration [optional, but recommended]import/s declaration [optional]At least one class definition

JDK toolsjavac the compilerjava the interpreterjar creates jar archives for easier distributionjavadoc generates Javadoc documentation

Classpath conceptThe way to access code outside your classAllows adding any files to itExecutes only *.class files (including from jar files)Applies per JVM (same classpath for any class running)

Document the code - JavaDocDocument code using Javadoc comments Specific format /** java doc comment */Supporting annotationsGenerate documentation with Javadoc utilityHTML formatOther types of comments in java/* multiple line comments *///single line commentsthese types of comments do not appear in generated documentation (javadoc)

Naming conventionsIdentifier typeRules & examplesPackagesAll lower; ISO-3166com.ricoh.trainingjava.langClassesCamel case starting upper; nounsPerson, String, CarInterfacesSame as classes, upper; nounsRunnable, Comparable, SerializableMethodsCamel case starting lower; verbseat, startWorking, getName, getPriceVariablesCamel case starting lower; attribute;price, name, height, firstName, lastNameConstantsAll upper and _FILE_SIZE, MAX_AGE

Code conventionsFilenamesName of the (public) class + .java suffixIndentationPackageClassMemberCode blockSub code blockCommentsJavadocBlock, line, end-of-lineDeclarationsOne per line; At the begging of the blockStatementsOne per line

http://www.oracle.com/technetwork/java/codeconventions-150003.pdf

Core packages in Java SE 8java.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.

Java logging mechanismBefore 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.

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=myLoggingConfigFilePath

If this property is not specified, then the config file is retrieved from its default location at: JDK_HOME/jre/lib/logging.properties

Your first JAVA Application

Questions / Discussions ?

JAVA language reserved wordsabstractassertbooleanbreakbytecasecatchcharclassconstcontinuedefaultdodoubleelseenumextendsfinalfinallyfloatforgotoifimplementsimportinstanceofintinterfacelongnativenewpackageprivateprotectedpublicreturnshortstaticstrictfpsuperswitchsynchronizedthisthrowthrowstransienttryvoidvolatilewhile

JAVA language data typesThere 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

JAVA language primitive data types

JAVA language variablesInstance 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".

JAVA language variablesVariables 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 = operatorTransfers information to a variable fromA literal or constantAnother variableExpressionMethod result

final double PI = 3.14; //constantint value = 100; //initialized default value is 0char c1=j, c2=a; //not correct use one assignment per line default u0000String name = Titi";Person p; //default nullint height = p.getHeight();

JAVA language arithmetic operators

JAVA language conditional operators

JAVA language control statementsif-elseswitch

whiledo-whileforcontinuebreak

return

JAVA language

Questions / Discussions ?

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

OOP conceptsOOP - 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.

OOP conceptsParent and child objectsA 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 boundariesPerforms a finite set of activitiesKnows only about its data and any other objects that it needs to accomplish its activities

OOP conceptsThe Person object - an object has two primary elements: attributes and behavior. Attributes: What attributes can a person have?Name, Age, HeightWeight, GenderBehavior: 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).

OOP concepts

Principles of OOP - Encapsulationis 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.

Principles of OOP - Encapsulationclass Person {private int height;private int width;public int getWidth() { }public int getBMI() {}}We hide internal attributesWe expose operations / behaviorThese are visible from the outsideThese 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.

Principles of OOP - Inheritancespecialized 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 workusing 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 numberSalary

Principles of OOP - InheritanceThe 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.

Principles of OOP - PolymorphismPolymorphism 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.Examplefor (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

OOP concepts

Questions / Discussions ?

OOP in JAVA objects/classesAll derive (implicitely) from java.lang.ObjectContains some useful methods (to be inherited by all objects):toStringequalshashCodenotifynotifyAllwaitclonefinalizegetClass

OOP in JAVA object lifecycleClasses are templates for objectsThey do nothing by themselvesObject creation object instantiation via constructorsPerson person = new Person();Each created object has its set of properties as defined by the classObject usage via referring variable its members are availableperson.toString();Object destruction controlled by JVM Garbage CollectorCannot be triggered directlyBefore objects destruction, finalize() method is called

OOP in JAVA objects creationConstructors special functions used to create objectsUseful for setting values to data members or to perform specific actionsSyntaxCan have parametersNo return typeHave same name as class nameUsageCan be used only together with new keywordRulesMany constructors in same classIf no constructor is defined, a default no-arg constructor is provided

OOP in JAVA constructor chaining

this keyword- Used to solve variable shadowing - Used to refer other constructors- Used for referring current object

OOP in JAVA access controlControls what members can be accessed from outside

Controls entire class visibility from outside

ModifierVisibilitypublicAvailable anywhereprivateOnly inside the classprotectedInside the class, the package and inside its sub-classespackage-private/missingInside the class, the package

ModifierClass scenariopublicWhen the class should be available outside packagepackage-privateAvailable only for other classes in same package; package internals

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 extendedMethod cannot be overrridenVariable value can be set only once

OOP in JAVA this vs superthisUsed as prefix (this.age) refers members in current objectUsed to solve ambiguities (this.name = name) in case of shadowingUsed to refer/chain constructors (this()) superUsed to refer to superclass constructor (super(18))Used to refer methods from superclass (super.execute())Useful in case of method override

Interfaces Abstract classesDeclares a set of operations available, but no implementationTherefore 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 interfaceCan have methods with implementationCannot be instantiated

abstract class Car {public abstract void start();public void stop(){}}

class Truck extends Car {public void start(){}}

Inner classes Anonymous classesShares the members of the outer class, the inner class can access themclass 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() {@Overridecompare() { //code}})

An interface is instantiated here!!!

Overload Overrideclass 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();

OOP in JAVA - enumenum is a new data type added to the JDK 5It is special data type that enables for a variable to be one of a set of predefined constants - each constant is uniqueDeclaring 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; }

OOP in JAVA - enumDeclaring constants after JDK 5 (using enum class)public enum Gender { MALE; FEMALE;}Person { private Gender gender; }Built-in supportpublic enum DayOfWeek { Mon, Tue, Wed, Thu, Fri, Sat, Sun; }

values() [Mon, Tue, Wed, Thu, Fri, Sat, Sun] valueOf(String) Wed Wedname() Wed Wedordinal() Wed 2

OOP in JAVA

Questions / Discussions ?Examples for the concepts discussedExtend FirstApplication and use Person, Employee, Student objects

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

JAVA Exceptions - throwThrowing an exceptionthrow new IllegalArgumentException(exception");

What happens when throw is called?The exception object is createdThe JVM exception handling mechanism takes control andIt looks for the closest catch clause that handles the exception:First in the current methodThen in the calling methodAnd so on up the call chainIf none is found (even in main) the program exitsThe exception itself is just a normal Java object created with new

JAVA Exceptions - try/catch/finallytry{ //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 subclassesThe finally statement executes always for cleanup

JAVA Exceptions hierarchy

JAVA Exceptions - checked/uncheckedUnchecked: 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 RuntimeExceptionChecked 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.

JAVA Custom ExceptionsWhen none existing exceptions match semanticsExtends Exception if the exception case is recoverableExtends RuntimeException when the client is not expected to handle itExtends Error or Throwable mostly when the code is part of a library or frameworkIt is rarely used

class ValidationException extends Exception { public ValidationException(String message) { super(message); } }

JAVA Exceptions best practice

Dont leave empty catch blocks, at least log the exceptionIn special cases, explain why it is empty

Prefer standard exceptions instead of defining new exceptions

Dont 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 exceptionsSome checked exceptions might be not recoverable, so handling them has no added value

JAVA Exceptions

Questions / Discussions ?

JAVA Collections Boxing and unboxingEvery primitive type in the Java language has a counterpart classWrappers provide behavior (methods) for primitive values

JAVA Collections StringsIn the JAVA language, strings are first-class objects of type String with methods that help you manipulate themDeclaring strings objects (Strings are immutable)String greeting = "hello";greeting = new String("hello"); //new instance is created in memorychars[] newString = {h. e, l, l, o}greeting = new String(newString);Concatenating Stringsstring1.concat(string2); or string1 + string2;Useful methods in String class:int stringSize = hello.length() //5StringBuffer, StringBuilder

JAVA Collections - ArraysArrays are objects that store multiple variables of the same type, or variables that are all subclasses of the same typeCan hold primitives and object referencesint[] testScores = new int[5]; Person[] p = new Person[5];

JAVA Collections comparing objects==, .equals(), compareTo(), and compare()

ComparisonPrimitivesObjectsa == b,a != bEqual valuesCompares references, not values.Comparing to see if a reference is null.Comparing two enum values. a.equals(b)N/ACompares values for equality. Is defined in Object classWorks as == for objects; override ita.compareTo(b)N/AComparable interface. All Java classes that have a natural ordering implement this (String, Integer, ...).compare(a,b)N/AComparator interface.Arrays.sort(T[], Comparator)

JAVA CollectionsA collection is a data structure in which objects can be stored and iterated over - similar to arrays but much betterOperations that can be done on a collection:Add objects to the collectionRemove objects from the collectionFind out if an object (or group of objects) is in the collectionRetrieve an object from the collection (without removing it)Iterate through the collection, looking at each element (object) one after another

JAVA Collections - typesLists lists of things (classes that implement List)duplicates are allowedSets 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

JAVA Collections hierarchy

JAVA Collections - ListList interface:a List relies on the indexthe one thing that List has that non-lists don't have is a set of methods related to the indexget(int index)indexOf(Object o)add(int index, Object obj) etc.

JAVA Collections List implementations

ListArrayListfast iteration and fast random accessit is an ordered collection (by index), but not sorted

same as an ArrayListmethods are synchronized for thread safety => slower

LinkedListordered by index positionelements are doubly-linked to one another => good for adding and removing from the beginning or endVector

JAVA Collections - SetSet Interfacea Set relies on uniquenessthe equals() method determines whether two objects are identical

JAVA Collections Set implementations

SetHashSetTreeSetfast access, no duplicatesprovides no orderingno duplicates; iterates in sorted orderLinkedHashSetno duplicates; iterates by insertion order

JAVA Collections - MapMap Interfacea Map relies on unique identifiersa unique key (the ID) is mapped to a specific valuethe equals() method determines whether two objects are identical

JAVA Collections Map Implementations

MapHashtableLinkedHashMapTreeMapHashMapunsorted, unorderedallows one null key and multiple null valuesfast updates (key/values);synchronizeddoesn't allow null keys or null valuesmaintains insertion order of keys (default ) or access orderfaster iterationsorted map

JAVA Collections equals()/hashCode()public boolean equals(Object o)Is reflexive, symmetric, transitive, consistentpublic int hashCode()Should be overridden for correct behavior in collectionsWhen two objects are equal their hash codes are equal tooNot overriding them lead to unique values for different objects that are considered equalObject implementations are based on location of the object in heap

The hashCode contractWhen two objects are equal, their hash codes are sameNone or both should be overriddenIf two objects are not equal, it is possible that their hash codes are same, but not recommended for performance reasons

JAVA Collections classes overview

JAVA Collections - Generics//non-genericArrayList myList = new ArrayList();String element = (String)myList.get(0);

//generic ArrayList myList = new ArrayList();String element = myList.get(0);No castSafer because only String objects are stored

//generics mixed with inheritanceList myList = new ArrayList();List numbers = new ArrayList(); // not-allowed

JAVA Collections best practicePrefer using lists over arrays

Object[] objectArray = new Long[0];objectArray[0] = "I don't fit in"; //throws ArrayStoreException

List ol = new ArrayList(); //compilation failure - Incompatible typesol.add("I don't fit in");

JAVA Collections best practiceChoose 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

JAVA Collections - best practiceWhile 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 notimmutable objects, collectionfieldsshould notbe 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

Thefor-eachloop 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 theforloop and iterators

JAVA Collections

Questions / Discussions ?

THANK YOU!

JAVA resourceshttps://docs.oracle.com/javase/tutorial/https://docs.oracle.com/javase/specs/https://docs.oracle.com/javase/8/docs/api/http://stackoverflow.com/questions/tagged/javahttp://www.ibm.com/developerworks/learn/java

Thinking in Java (4th Edition): Bruce EckelEffective Java: Joshua BlochClean Code: Robert C. Martin