100% found this document useful (1 vote)
273 views

JavaSE11 ProgrammingComplete StudenstGuide

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
100% found this document useful (1 vote)
273 views

JavaSE11 ProgrammingComplete StudenstGuide

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 444
University Student Guide D107120GC10 | 107910 Learn more from Oracle University at education.oracle.com Unauthorized reproduction.g Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Author Vasily Strelnikov Technical Contributors and Reviewers Joo Greenwald ‘Svetlana Sawvina Jacobo Marcos Editors Moushmi Mukherjee Aju Kumar Graphic Editor Kavya Bellur Publishers ‘Sujatha Nagendra Veena Narasimhan Pavithran Adka Stividya Rameshkumar 1003242020 Copyright © 2020, Oracle andior its aflites. All rights reserved. Disclaimer “This document contains proprietary information and is protected by copyright and ‘other intelactual property laws. You may capy and pant ths document solely or your ‘oun use in an Oracle taiing course. The document may not be morified or altered in any way. Except where your use constitites fir use" under eopyrght aw, yot ‘may nat use, share, dowmload, upload, copy, print, splay, periorm, reproduce, Publish, icense, post, wansmit or cisrbute his document in whole orn pat without the express authorization of Oracle ‘The information contained in his document is subject to change without notice. you find any problems in the document please report them in wing to: Oracte Universiy, 500 Oracie Parkway, Redwood Shores, California 94085 USA. This documents nat warranted to be eo-e. Restricted Rights Notice It this documentation is delivered to the United States Government or anyone using the documentation on behalf ofthe United States Government, the following notice is applicable: US, GOVERNMENT RIGHTS. ‘The USS. Goverment’ rights to use, modiy, reproduce, release, perform, cispay. of ‘evince thowe tnning matarile arm tastier tetra oppentie Cet Teense agreement andlor the appicable US. Gavemment contact “Trademark Notice Oracle and Java are registered wademarks of Oracle andlor tiiates. Other names may be trademarks of thei especive owners Contents 1 Introduction to Java Course Goals 1-2 Audience 1-3 Course Schedule 1-4 Course Practices 1-5 Lesson Objectives 1-6 What Is Java? 1-7 How Java Works? 1-8 Classes 1-9 Objects 1-10 Inheritance 1-11 Java APIs 1-12 Java Keywords, Reserved Words, and a Special Identifier 1-13 Java Naming Conventions 1-14 Java Basic Syntax Rules 1-16 Define Java Class 1-17 Access Classes Across Packages 1-18 Use Access Modifiers 1-19 Greate Main Application Class 1-20 Compile Java Program 1-21 Execute Java Program 1-22 Comments and Documentation 1-23 Summary 1-25 Practices 1-26 Primitive Types, Operators, and Flow Control Statements Objectives 2-2 Declare and Initialize Primitive Variables 2-4 Restrictions on Primitive Dectarations and Initializations 2-5 Java Operators 2-6 Assignment and Arithmetic Operators 2-7 Arithmetic Operations and Type Casting 2-8 More Mathematical Operations 2-9 Binary Number Representation 2-10 Bitwise Operators 2-11 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Equality, Relational, and Conditional Operators 2-12 Short-Circuit Evaluation 2-13 Flow Control Using ifelse Construct 2-14 Temary Operator 2-15 Flow Control Using switch Construct 2-16 JShell 2-17 Summary 2-18 Practices 2-19 Text, Date, Time, and Numeric Objects Objectives 3-2 String Initialization 3-3 String Operations 3-4 String Indexing 3-5 StrinyBuiluer. Intiwduction 3-6 Wrapper Classes for Primitives 3-7 Representing Numbers Using BigDecimal Class 3-8 Method Chaining 3-9 Local Date and Time 3-10 More Local Date and Time Operations 3-11 Instants, Durations, and Periods 3-13 Zoned Date and Time 3-14 Represent Languages and Countries 3-15, Format and Parse Numeric Values 3-17 Formal and Parse Dale and Time Values 3-18 Localizable Resources 3-21 Format Message Pattems 3-22 Formatting and Localization: Example 3-23 Summary 3-24 Practices 3-25 Classes and Objects Objectives 4-2 UML: Introduction 4-3 Modeling Classes 4-4 Modeling Interactions and Activities 4-6 Designing Classes 4-7 Creating Objects 4-8 Define Instance Variables 4-9 Define Instance Methods 4-10 Object Creation and Access: Example 4-11 Local Variables and Recursive Object Reference 4-12 Local Variable Type Inference 4-14 Define Constants 4-15 Static Context. 4-16 Accessing Static Context 4-17 Combining Static and Final 4-18 Other Static Context Use Cases 4-19 NetBeans IDE: Introduction 4-21 Summary 4-22 Practices 4-23 Improved Class Design Objectives 5-2 Overload Methods 5-3 Variable Number uf Arguments 5-4 Define Constructors 5-5 Reuse Constructors 5-6 Access Modifiers Summary 5-7 Define Encapsulation 5-8 Define Immutability 5-9 Constants and Immutability 5-10 Enumerations §-11 Complex Enumerations 5-12 Java Memory Allocation 5-13 Parameter Passing 5-14 Java Memory Cleanup 5-15 Summary 5-16 Practices 5-17 Inheritance Objectives 6-2 Extend Classes 6-3 Object Class 6-4 Reuse Parent Class Code Through Inheritance 6-6 Instantiating Classes and Accessing Objects 6-7 Rules of Reference Type Casting 6-8 Verify Object Type Before Casting the Reference 6-9 Reference Code Within the Current or Parent Object 6-10 Define Subclass Constructors 6-11 Class and Object Initialization Summary 6-12 Override Methods and Use Polymorphism 6-14 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Reuse Parent Class Logic in Overwritten Method 6-16 Define Abstract Classes and Methods 6-17 Define Final Classes and Methods 6-19 Override Object Class Operations: toString 6-20 Override Object Class Operations: equals 6-21 Override Object Class Operations: hashCode 6-22 Compare String Objects. 6-23 Factory Method Pattern 6-24 Summary 6-25 Practices 6-26 Interfaces Objectives 7-2 Java Interfaces 7-3 Mulliple Inlwzritance Problem 7-4 Implement interfaces 7-5 Default, Private, and Static Methods in Interfaces 7-6 Interface Hierarchy 7-7 Interface Is a Type 7-8 Functional Interfaces 7-9 Generics 7-10 Use Generics 7-11 Examples of Java Interfaces: java.lang.Comparable 7-13, Examples of Java Interfaces: java.util Comparator 7-14 Examples of Java Interfaces: java.lang.Cloneable 7-15 Composition Pattern 7-16 Summary 7-17 Practices 7-18 Arrays and Loops Objectives 6-2 Arrays 8-3 Combinad Declaration, Creation, and Initialization of Arrays 8-4 Multidimensional Arrays 8-5 Copying Array Content 8-6 Arrays Class 8-7 Loops 8-8 Processing Arrays by Using Loops 8-9 Complex for Loops 8-10 Embedded Loops 6-11 Break and Continue 8-12 vi 10 Summary 6-13 Practices 8-14 Collections Objectives 9-2 Introduction to Java Collection API 9-3 Java Collection API Interfaces and Implementation Classes 9-4 Create List Object 9-5 Manage List Contents 9-6 Create Set Object 9-7 Manage Set Contents 9-8 Create Deque Object 9-9 Manage Deque Contents 9-10 Create HashMap Object 9-11 Manraye HeslMap Guitars 8-12 lterate through Collections 9-13 Other Collection Behaviors 9-14 Use java.util Collections Class 9-15 Access Collections Concurrently 9-16 Prevent Collections Corruption 9-17 Legacy Collection Classes 9-19 Summary 9-20 Practices 9-21 Nested Classes and Lambda Expressions Objectives 10-2 Types of Nested Classes 10-3 Static Nested Classes 10-6 Member Inner Classes 10-7 Local Inner Classes 10-9 Anonymous Inner Classes 10-10 Anonymous Inner Classes and Functional Interfaces 10-12 Understand Lambda Expressions 10-13 Define Lambda Expression Parameters and Body 10-14 Use Method References 10-15 Default and Static Methods in Functional Interfaces 10-16 Use Default and Static Methods of the Comparator Interface 10-17 Use Default and Static Methods of the Predicate Interface 10-18 Summary 10-19 Practices 10-20 vii Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates 41 Java Streams API Objectives 11-2 Characteristics of Streams 11-3 Create Streams Using Stream API 11-4 Stream Pipoline Processing Operations 11-5 Using Functional Interfaces 11-6 Primitive Variants of Functional Interfaces 11-7 Bi-argument Variants of Functional Interfaces 11-9 Perform Actions with Stream Pipeline Elements 11-10 Perform Filtering of Stream Pipeline Elements 11-11 Perform Mapping of Stream Pipeline Elements 11-12 Join Streams using flatMap Operation 11-13 Other Intermediate Stream Operations 11-14 Shorl-Circuil Tenninal Operatives 14-15 Process Stream Using count, min, max, sum, average Operations 11-16 Aggregate Stream Data using reduce Operation 11-17 General Logic of the collect Operation 11-19 Using Basic Collectors 11-20 Perform a Conversion of a Collector Result 11-21 Perform Grouping or Partitioning of the Stream Content 11-22 Mapping and Filtering with Respect to Groups or Partitions 11-23 Parallel Stream Processing 11-25 Parallel Stream Processing Guidelines 11-26 Restrictions on Parallel Stream Processing 11-27 Summary 11-29 Practices 11-30 12 Handle Exceptions and Fix Bugs Objectives 12-2 Using Java Logging API. 12-3 Logging Method Categories. 12-4 Guarded Logging 12-6 Log Writing Handling 12-7 Logging Configuration 12-9 Describe Java Exceptions 12-10 Create Custom Exceptions 12-11 Throwing Exceptions 12-12 Catching Exceptions 12-13 Exceptions and the Execution Flow 12-14 Example Throwing an Unchecked Exception 12-15 13 Example Throwing a Checked Exception 12-16 Handling Exceptions 12-17 Resource Auto-Closure 12-18 Suppressed Exceptions 12-19 Handle Exception Cause 12-20 Java Debugger 12-21 Debugger Actions 12-22 Manipulate Program Data in Debug Mode 12-23 Validate Program Logic Using Assertions 12-24 Normal Program Flow with No Exceptions 12-25 Program Flow Producing a Runtime Exception 12-27, Program Flow Catching Specific Checked Exception 12-29 Program Flow Catching Any Exceptions 12-31 Summary 12-33 Praviives 12-34 Java 10 API Objectives 13-2 Java Input-Output Principals 13-3 Java Input-Output API. 13-4 Reading and Writing Binary Data 13-5 Basic Binary Data Reading and Writing 13-6 Reading and Writing Character Data 13-8 Basic Character Data Reading and Writing 13-9 Connecting Streams 13-10 Standard Input and Output 13-11 Using Console 13-12 Understand Serialization 13-14 Serializable Object Graph 13-15 Object Serialization 13-16 Serialization of Sensitive Information 13-17 Customize Serialization Process 13-18 Serialization and Versioning 13-19 Working with Fllesystems 13-20 Constructing Filesystem Paths 13-22 Navigating the Filesystem 13-24 Analyse Path Properties 13-25 Set Path Properties 13-26 Create Paths 13-28 Create Temporary Files and Folders 13-29 Copy and Move Paths 13-30 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates 14 15 Delete Paths 13-31 Handle Zip Archives 13-32 Represent Zip Archive as a FileSystem 13-33 Access HTTP Resources 13-35 Summary 13-36 Practices 13-87 Java Concurrency and Multithreading Objectives 14-2 Java Concurrency Concepts 14-3 Implement Threads 14-5 Thread Lite Cycle 14-6 Interrupt Thread 14-7 Block Thread 14-8 Make Thiead Wait Until Notified 14-9 Common Thread Properties 14-10 Create Executor Service Objects 14-11 Manage Executor Service Life Cycle 14-15 Implementing Executor Service Tasks 14-17 Locking Problems 14-19 Writing Thread-Safe Code 14-20 Ensure Consistent Access to Shared Data 14-22 Non-Blocking Atomic Actions 14-23 Ensure Exclusive Object Access Using Intrinsic Locks 14-24 Intrinsic Lock Automation 14-25 Non-Blocking Concurrency Automation 14-27 Alternative Locking Mechanisms 14-28 Summary 14-29 Practices 14-30 Java Modules Objectives 15-2 Compile, Package, and Execute Non-Modular Java Applications 15-3 What Is a Module? 15-5 Java Platform Module System (JPMS) 15-7 JPMS Module Categories 15-8 Define Module Dependencies 15-9 Export Module Content 15-10 Modules Example 15-11 Open Module Content 15-12 Open an Entire Module 15-13 Produce and Consume Services 15-14 Services Example 15-15 Mulli-Release Module Archives 15-16 Compile and Package aModule 15-17 Execute a Modularized Application 15-18 Migrating Legacy Java Applications Using Automatic Modules 15-19 Create Custom Runtime Image 15-20 Execute Runtime Image 15-22 Optimize a Custom Runtime Image 15-23 Summary 15-25 Practices 15-26 Annotations Objectives A-2 Introuctiun to Annotations AS Design Annotations A-4 Apply Annotations A-5 Dynamically Discover Annotations A-7 Document the Use of Annotations A-9 Annotations that Validate Design A-10 Deprecated Annotation A-11 Suppress Compiler Wamings A-12 Var-args and Heap Pollution A-13 Summary A-14 Java Database Connectivity Objectives B-2 Java Database Connectivity (JDBC) B-3 JDBC API Structure B-4 Manage Database Connections B-5 Create and Execute Basic SQL Statements B-6 Create and Execute Prepared SQL Statements 8-7 Create and Execute Callable SQL Statements 8-8 Process Query Results B-9 Control Transactions B-11 Discover Metadata B-12 Customize ResultSet B-13 Set Up ResultSet Type B-14 Set Up ResultSet Concurrency and Holdability B-16 Summary 8-17 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates © Java Security Objectives C-2 Security Threats C-3 Denial of Service (DoS) Attack C-4 Define Security Policies C-5 Control Access Using Permissions C-6 Execute Privileged Code C-7 Secure Filesystem and 10 Operations C-8 Best Practices for Protecting your Code C-9 Erroneous Value Guards C-10 Protect Sensitive Data (Part 1) C-11 Protect Sensitive Data (Part 2) C-12 Prevent JavaScript Injections C-14 Preven XML Injectivns 0-15 Discover and Document Security Issues C-16 Summary C-17, D Advanced Generics Objectives D-2 Compiler Erases Information About Generics D-3 Generic and Raw Type Compatibility 0-4 Generics and Type Hierarchy 0-5 Wildcard Generics D-6 Upper Bound Wildcard D-7 Lower Bound Wildcard D-8 Collections and Generics Best Practices D-9 Summary 0-10 Introduction to Java istri ed Programming Complete 1-2 Java SE 11 SO}EMIYJE Sy! JO/PUE 9IDeIO OZOZ © JUBUAdOD ‘payigiyosd UONqUIsIP JO UONONpoJdel pezLOUJNeUy Audience ‘The target audience includes those who: + Have some non-Java programming experience and want to learn Java + Have basic knowledge of Java and want fo improve it + Prepare for the Java SE 11 Certification exams Briefly introduce yourself: + Name + Title or position + Company + Experience with programming + Reasons for attending Java SE 11: Programming Complete 1-3 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Course Schedule GEIS Lesson 4: introduction to Java Lesson 2: Primitive Types, Operators, and Flow Control Statements Lesson 3: Text, Date, Time, and Numeric Objects Lesson 4; Classes ard Objects Lesson 5: Improved Class Design Lesson Inhertance [EVERIESD Lesson 7: interfaces Lesson 8: Arrays and Loops Lesson 8: Collections Lesson 10; Nested Classes and Lambda Expressions es Lesson {1: Java Steams API + Aopen A: Annotations Lesson 12: Handle Exeepons and Fix Bugs ef clmeininares WEIRD [asso Jaa OA a + Aowendt C: Secunty Leson 14: Java Concurency and Mutithreading : : Lesson 15: Java Modules: {Append D; Genesis This schedule is for guidance purposes only. Depending on the pace of practices, exact timings may vary. Java SE 11: Programming Complete 1-4 Course Practices During the course practice sessions, you: + Explore the features of Java language + Apply the knowledge gained throughout the course to develop # product management application ‘The practice environment uses: + sDK1T + JShel + NetBeans 11 Java SE 11: Programming Complete 1-5 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Lesson Objectives ‘After completing this lesson, you should be able to: + Discover Java language origins and use-cases + Explain Java portability and provider neutrality + Explain object oriented concepts + Describe Java syntax and coding conventions. + Create Java class with main method + Compile and execute a Java application Java SE 11: Programming Complete 1-6 What Is Java? + General purpose programming language similar to C and C++ + Object-Oriented and Platform-Independent + Originally designed in 1995 for use in consumer electronics 6 + Moder uses include wn'ting applications for ntemet of things, Cloud computing, and soon. <9. * This course covers Java SE (Standard Edition) version 11. — Java R sy, QS Rs ava Editsone. Java Card ~ Saact card Edition Java EE ~ Enterprise Edition ‘vava 88 is the base adition on which other editions are based. = You start learning Java with Java SE because this is the base edition, representing the core of the Java language. All other Java editions represent more specialized use-cases of Java that are targeting particular environments, such as SIM cards (Java card), smart TVs (Java ME), or Application Servers (Java EE). Starting from version 9, new versions of Java are released every 6 months. However, only some of these new versions are considered to be LTS (Long Term Support) versions. This course is based on Java SE version 11, which is the LTS version, previous LTS version is 8. Java SE 11: Programming Complete 1-7 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates ites ted. Copyright © 2020 Oracle and/or its affi Unauthorized reproduction or distribution proh How Java Works? Java sa plattorm-inéependent programming language. "ava source cove is writen a plain fet «java fle, * Source codes comic Ilo byte coe class Ms for SVM a + Java Vital Machine must be installed on a target computer + JVM executes your application by translating Java byle-code instructions to platform-specific code aoe (EE You need to have Java Virlual Machine (JVM) installed on a target computer Where you want your Java program to be executed. JVM is itself platform specific and its purpose is to translate platform-independent byte-code instructions containad in .class files into platform-specific instructions that the target computer would be able to execute. Optionally, since Java 9, itis possible to package your Java program. Its deployment would contain a JVM and can be installed to a target computer as, a platform-specific executable; therefore, you do not require a separate JVM installation. Java SE 11: Programming Complete 1-8 Classes Class and Object are two key object-oriented concepts, Java code is structured with classes. O° + Glass represents a type of thing or a concept, such as Dog, Cat, Bal, Person f\ 1 Eucla cnt thao fae nan ate (\¢ ‘ADog could have a name, color, size. cos MS pesicaattes eeet o cl Ta + Each class defines what kind of behaviors (operations) containing program logic (loorths) its capable of + Objects are covered next ‘ADog could bark and fetch a Ball. ‘A.Cat could meow but isnot likly to play fotch You may consider the words “function,” “procedure,” “operation,” "method," and "behavior" to be synonymous. They all represent the same concept, a way of defining logic and algorithms within the class. You may also consider the words “variable,” “attribute,” and "field" to be synonymous. They all represent the same concept, a way of defining information and data storage within the class. Java has procedural language capabilites, that is, you write algorithms contained within functions defined by your classes. Java SE 11: Programming Complete 1-9 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Objects An Object is a specific instance (example of) a Class. + Each object would be capable of having specilic valuos for each attribute defined by a class that represents ils ype. For example: ‘A dog could be called Fido, and be brown and small ‘Another could be called Rex, and be orange and big + To operate on an object, you can reference it using a variable of a relevant type. + Each object would be capablo of behaviors defined by a class that represents its typo: ‘Atrun time, objects invoke operations upon each ether to execute program logic. cass Person T void play) ( Seren ieee ail) Note: The term Class means type and Object means instance of that type. However, sometimes people use these terms interchangeably, which can be quite confusing. Java SE 11: Programming Complete 1-10 Wy Fox & Inheritance You can reuse (inherit) attributes and behaviors across class hierarchy. * Classos can form hierarchical relationships. + Superclass represents a more generic, parent type (living organism) + Superclasses define common altibutes and behaviors (eal, propagate) + A subclass represents a more specific, child type (animal, plant, and 30 on). + There could be any number of levels in the hierarchy, rom very generic to " spect child types (dog, cat, and s0 on}. + Subclasses inhorit all attributes and behaviors from their parents. + Subclasses can define more specific attibutes and behaviors (swim. fy). “Bs Java SE 11: Programming Complete 1-11 ere hen Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Java APIs Java Development Kit (JDK) provides hundreds of classes for various programming purposes: + To represent basic data types, for example, String, LocalDateTine, BiaDecinal, and soon + To manipulate collections, for example, Enumeration, ArrayList, HashMap, and s0 on + To handle generic behaviors and perform system actions, for example, System, 063 + To perform input/output (VO) operations, for example, F 1eInputstrean, P5120: + Many other API classes are used to access databases, manage concurrency, enable network communications, execute scripts, manage transactions, security, logging, build graphical user intertaces, and so on putStream, and soon ++ Applicaton Progamming ltrace (APD is te that descbes 2 Colecton of asses thal ae designe fo serve a common purpose. “All lava APIs are thoroughly documenind for nach vecson af the 6 Tanguage. ror examplo, Java 11 documentation cane found a = Java hips aoes ona omlanfavafaase” doen! i Java SE 11: Programming Complete 1-12 Java Keywords, Reserved Words, and a Special Identifier Keywords available since 1.0, Smplenente boolean secort Keywords no longer in use ontende toy a Keywords added in 1.2 interface catch. module Keywords added in 1.4 geatic ehrow trancitive Keywords added in 5.0 final throws exports to Keywords added in 2.0 otura pew tees transient this provides case void super xen Reserved words forliterals values Geraute, byte instanceof Spene eo private chore, aitive r srotected int Synchronized true ‘Special identifier added in 10 protec’ ee aynehron tue, import. chee goto nal package Float, Sense Ebeteace, dowle sericesp, var + Keywords and Literals cannot be used as idenifiers (names of classes, variables, methods, and soon). + Actual use and meaning of these keywords and Maras are covered later in this couse. All Java keywords and literals are lowercase. You cannot use a keyword or a literal as an identifier, that is, the name of a package, variable, class, or method. You can use a special identifier as a variable name (bad idea, code looks very confusing), but not as a class name. Java SE 11: Programming Complete 1-13 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Java Naming Conventions + Java's case-sensitive; Dogs not the same as dog + Package name is ¢ reverse of your company domain name, plus the naming system adopted within your compa. + Class name should be a noun, in mixed case with the first leer of each word capitalized. + Variable name shouldbe in mixed case staring with a lowercase letter: turlher words Star with capital leters + Nemes should not stant wth numeri charactors (0-9), underscore _or dolar $ symbols + Constant name is typically written in uppercase with underscore symbols between word. + Mothod name shouldbe a verb in mixed case starting witha loworeaso ler futhor words start wih capital etors. package Clase: variable: fnethoa: giv “Note: The use of tne _ symbol as a fist or enly character ina variable name Produces a compiler warning in Java 8 and an ertorin Java 9 onward, The prefix of a unique package name is always written in lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981. Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names. Class names should be nouns, in mixed case, with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words: avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). Java SE 11: Programming Complete 1-14 Variable names are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed. Variable names should be short yet meaningful. The choice of a variable name should be mnemonic, that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, K, m, and n for integers, c, d, and e for characters. A constant name is typically written in uppercase with the underscore symbol between words. The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.) Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. Java SE 11: Programming Complete 1-15 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates ites ted. Copyright © 2020 Oracle and/or its affi Unauthorized reproduction or distribution proh Java Basic Syntax Rules + AllJava statements must be terminated with the" ;* symbol. + Code blocks must be enclosed with” {* and} symbols. + Indentations and spaces help readability ut are syntactically irelevant. package dence .aninate; Pless. Soi ot while {ostl == ewll) { keoptooking (0 ) , oid meketioise() 4 fe aun t= mw) ¢ “4 Note: Example shows some consinicis such as {/al-s= and whe that are covered later inthe course Java SE 11: Programming Complete 1-16 Define Java Class + Class name is typically represented by one or more nouns, or example, Dos, SabreToothedat, Person. + Class must be saved into 2 fle withthe same name as the class and extension - 23. + Classes are grouped into packages. + Packages are represented as folders where class files are saved. + Eesloze mane spall a revere of yeurcompany domain rame, pus naming sem adopted win your company. sample: con.oracle.deras, or9.scne.£0netning + Package and class name must form a unique combination. “Note: package detntion i missing, class wouts belong toa “deta” package and would not be placed into any package folder. However, thi isnot a recommended practice Typically each java contains only one class definition. However, in some cases, for example with Nested and Inner classes, it is possible to define more than one class in a single java file. These cases are covered in later lessons. Java SE 11: Programming Complete 1-17 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Access Classes Across Packages To access a class in another package: + Profx the class name wit the package name + Use the import statement ta import specific classes or the entie package content — The import of all classes from the 3ava.1ang.> package is implicitly assumed. ‘The example shows three alternative ways of referencing the class as in the package animale rom the class Owner in the package peo Notes 4 Imports are not present ina compiled cade. An statement has no effect at runtime efiiency of the class. tis «2 simple convenience to avoid prfiing lass name with package name throughout your source code, + Aoooss modifiers (such a8 pb ic) are explained in the following sie. Java SE 11: Programming Complete 1-18 Use Access Modifiers ‘Access modifiers describe the visibility of classes, variables, and methods. «Visible to any other class ‘ectec- Visible lo classes that are in the same package or lo subelasses - Visible only to classes in the same package Notes ‘ cdefaule> means thal no access modifier is explcily set. + Subelass-Supercass relationship (use of Me extends KeYoWs) 1 covered ater inthe course + Any nonprivate parts of your class should be kept as stable as possible, because changes of such code may adversely affect any numberof other classes that may be using your code In this example, class Y is a subclass of class X, as defined by the extends clause. Therefore, class Y can access protected members of class X, although it is in a different package. However, because class Y is in a different package from class X, class Y is unable to access the default members of class X. Java SE 11: Programming Complete 1-19 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Create Main Application Class ‘The main method is the entry point into your application. + Itis the starting point of program execution. + The method name must be called ais, + tmust be = ‘You intend to invoke this method from outside of this clas. + ltmust be <=>. Such methods can be invoked without creating an instance of this class. + Itmust be vos. H{does not retu a value. + lRmust accept array of Sting objects as the only parameter, (The name of this parameter “2rgs"is irelevant.) + Noto: Uso of = You can define the main method in different ways: public static void main (String[] args) { } public static void main (String args{]) { } public static void main (String... args) { } There is no practical difference between these approache: one is probably the most common. jowever, the first Java SE 11: Programming Complete 1-20 Compile Java Program Compile classes with the javae Java compiler. + The ~ctasspath or ~cp parameter points to Iocations of other classes that may be required to compile your code. + The ~d parameter points toa path 19 stove compilation result (The compitor creates package subfolders with compiled class files in this path.) + Provide path to source code. javac ep /project/classes -a /project/classes /preject/scurces/denos/Whatever java You do not have to use the ~cp parameter to compile or execute a class if this class is not referencing any other classes of yours. You do not have to use the =< parameter if your class is in a default package; however, this is not a recommended practice. Java SE 11: Programming Complete 1-21 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Execute Java Program Execute program using java executable Java Virtual Machine (JVM). + Specify ~clacspath oF ~cp to point to folders where your classes are located. + Specify fully qualified olass name. Use package prefix; do not use the «class extension. + Provide a space separate lst of parameters after the class name ‘Access command-line parameters: package deros: + Use array object to access parameters. public clasa + Array index starts at 0 (lst parameter). ponte stasis = esi Java cp /project/ciasses dence whatever Jo Joha "A Mane” Jane = Belle Joke + Sinoo Java 11, itis also possible to run single filo courco code as it itie a eompilod otacc. JVM will interpret your code, bul no compiled class file would be created: jeve /project/sources/denos/Whatever ja Also, consider this example: cd /projects/classes javac -d /project/classes /project/sources/demos/Whatever java java demos.Whatever This example works without setting the class path because both Java compiler and virtual machine consider the current folder as the default class path. It is also possible to set class path as an environment variable Launching single-file source code as if itis a compiled program ability is anew feature in Java 11. However, itis not very practical; the alternative is to use the JShell utility, which is covered later in the course. Java SE 11: Programming Complete 1 - 22 Comments and Documentation + Code Comments can be placed anywhere in your source code, + Documentation Comments: ~ May contain HTML markups single-1ine come: + May contain descriptive ‘20s prefixed with @ sing . ~ Ate used by the 32¥240c tool fo generale documentation peleicline Peckage o> Class Whatever pbliccoswereer er eke ee evades —¢ + Noo: Al APIs in tho Java dovolopment Kt are documantod using tho javadoc uly. For more information about how to write doc comments for the Javadoc Tool, see: * hitps://does.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.htm ! + http:/Awmw.oracle.com/technetwork/java/javase/documentationindex- 187868.html The Javadoc tool parses the declarations and documentation comment: set of Java source files and produces a corresponding set of HTML pages describing (by default) the public and protected classes, nested classes (but not anonymous inner classes), interfaces, constructors, methods, and fields. You can use it to generate the API (Application Programming Interface) documentation or the implementation documentation for a set of source files. You can run the Javadoc tool on entire packages, individual source files, or both. When documenting entire packages, you can either use subpackages for traversing recursively down from a top-level directory or pass in an explicit list of package names. When documenting individual source files, you pass in allist of source (. java) filenames. a Java SE 11: Programming Complete 1-23 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Javadoc tags: Add author names: @author Display text in code font: (@code ) Place relative path to the root directory from any documentation page: {@docRoot } Describe reasons why an API should no longer be used: ¢deprecated Describe an exception that a method throws: exception The @throws and @except ion tags are synonyms: @throws Inherit documentation comments from a superclass class or an interface that class implements: (@inheritDoc} Insert a link pointing to another Java documentation article: ( ¢1ink ) Describe method parameter: @param Name> ‘Add "See Also” link to another Java documentation article: @see « ‘Add description of a serializable field: @serial | include | exclude Document the data written by the writeObject( ) orwriteBxternal( ) methods: @serialbata Document an object StreamField component: @serialField Display the value of a constant: (@value package. class#field} Describe in which Java release the API was introduced: ¢since ‘Add version attribute: @version Java SE 11: Programming Complete 1-24 Summary In this lesson, you should have learned how to: + Discover Java language origins and use-cases + Explain Java portability and provider neutrality + Explain object-oriented concepts + Describe Java syntax and coding conventions + Create a Java class by using the main method + Compile and execute a Java application Java SE 11: Programming Complete 1-25 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Practices In this practice, you will: + Verity the JDK Installation * Create HelloWorld java application class with main method. + Compile and execute this application Java SE 11: Programming Complete 1-26 TMM SMOLIN and Flow Control Statements istri ed Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Objectives ‘After completing this lesson, you should be able to: + Desoribe primitive types + Desoribe operators + Explain primitives type casting + Use Math class + Implement flow control with i£/else and switch statements + Desoribe JShell Java SE 11: Programming Complete 2-2 Java Primitives Java language provides eight priv lypes to represen simple numeric, character. and boolean valves. Wolo numbers ating point aombers int tong i Float soubie: a3, ca8| 9,200,396 BHT, 000 Tae Tae 307485 e179, 005,502 sere, 7e0,000) | Sodisisssresa) 1 TSTeSSLSUREESL=Tes0n siniinown| eiastvale 007 6:6 ora sen 2 Boolean CCharacor(wproents sgl charactor value) Ea = ale ae re oie [ erseortatees 2 elaveioe “5000 The slide shows the capacity of each type, minimum and maximum values for each type (axcept boolean), default value, and ways of expressing values. You can print integral values, formatted as binary, octal, or hex, using Integer or Long class methods toBinaryString toOctalstring toHexs tring. Use uppercase L and F to indicate float and long values to make your code more readable. The default value for the char type is "\u0000'. It does not correspond to any character on a keyboard and is not the same as space that has a code of "0020" Java SE 11: Programming Complete 2-3 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Declare and Initialize Primitive Variables Primitive declaration and initialization rules: \Vatable declaration and intaizaton ey + A variable can be declared wih no immediate intia:zaton, so long as itis inalized before use [Numeric values can be expressed as binary, octal, decimal, and hex. Float and double values can be expressed in normal or exponential notations. + Muliple variables ofthe same type can be declared and intialized simultaneously ‘Assignment of one variable to another creates & copy of valve. ‘Smallor typos are automaticaly promoted to bigger lypes. + Character valves must be enclosed in single quotation marks, In the example in the slide, variables a, b, c, d are all set to 42 using binary, octal, decimal, and hex value expressions. Char values are stored as character codes. For example, character'A’ has a character code of 65 expressed as a decimal number. However, when expressing an ASCII code for this character, you should use its octal representation, which is ‘\101', or for Unicode, use hex representation, which is \uo041". ‘Automatic promotion means that a value of a smaller type (for example, float) can be directly assigned to a variable of a bigger type (for example, double), Java SE 11: Programming Complete 2-4 Restrictions on Primitive Declarations and Initializations Primitive declaration and iniialization restrictions: + Varlabios must be ikalized betoro uso. + A bigger type value cannot be assigned toa smaller type vaiabe, + Character values must not be enclesed in double quotation marks. +A charactor value cannct contain more than one characer. + Boolean valves can be expressed only a8 crue or “aise + Note: Each inconct example givan hore would cause Java code not to eomgil. Java SE 11: Programming Complete 2-5 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Java Operators List of Java operators in the order of precedence: six inerement and decrement ++ — prefix increment and decrement, and unary ** — mutpicaiva + / = asta + bitsht <<>> 25> folajonal < > <= >= snovanceor equally == = bwiso AND & biwiee exchasve OR ~ bitwise inclusive OR | logical AND ss logical OR 11 Details of these operators are covered later in this lesson with the exception of the instanced operator, which is covered later in the course. Java SE 11: Programming Complete 2-6 Increment and decroment operators has profi and post positions: Assignment and Arithmetic Operators ‘Aselgnments and arthmaties Compound assignments are combinations of an operation and ‘an assignment that is acting onthe same variable. ‘Operator evaluation der can be changed using round brackets. oO =x 8 incremented fst and then the result assigned oy +x decremented fst and then the result is assigned to y. wy is assigned the velus of frst and then xis inremented ~ yi assigned the value of x fist ard then xis decremented. ‘Modulus finds a remainder of division of two numbers. The slide shows an example of 15%6, and it works like this: divide 15/6 and round the result down to get 2, then multiply 2°6, which is 12 and finally find the modulus as 15-12 Which will be 3. Compound assignments covered in this slide used arithmetic operators (+ - = *= /= &=), However, the same technique can also be used with Bitwise and Bit Shift operators (5= = 9= >>9=). These operators are covered later. Operator ~ can be used to invert the sign of the expression Operator + can be used to indicate a positive number; however, itis considered excessive, since numbers are assumed to be positive anyway. Java SE 11: Programming Complete 2-7 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Arithmetic Operations and Type Casting ae Rules of Java arithmetic operations and type casting: a4 ~ Sale fps ae alomateay cased prota) tigger pes : byte-pshort-dchar-pint-biong->Zloat->double ae + Abiggor type value cannot bo assigned toa smallor type vatablo without expt ype cating. s + Type cen be expliciy casted using the folowing syntax: (cnex type>) + When easing bigger value o a smaller fype, beware ofa possible overt. + Resuling type of arithmetic operations on fypes smaller than ’ of alargest paricipart © ODSOEDEDS @ Type casting makes sense if you think about similarities between different types. For example, you could say that a whole number is a variant of a floating point number. For example, an int can be imagined as a double, which has no actual floating point part. Therefore, if you assign an int value to a double variable, it works perfectly fine and explicit type casting is not required. However, the other way around, assigning double to an int is possible only if you choose to ignore the floating point part of the double value. This could case a truncation of the double value and would require explicit casting. Note that char is treated as character code for the purposes of arithmetic operations. Java SE 11: Programming Complete 2-8 More Mathematical Operations Class java . lang Math provides various mathematical operations: + Exponential such as = + Logarithmic such as «95. (::) ‘Trigonomettic such a =< ::) 228 (x) and many moro. Ware tangent ‘greater of wo values {Salon of two valves For more examples of Math class functions, see the Java documentation at: httpsy/does. oracle.com/en/java/javase/t 1/docs/api/java.base/java/lang/Math.h tml The number rounding example demonstrates that Java allows you to perform mathematical operations on numbers that are not necessarily decimal. To round a number to a set number of digits after the decimal point, you need to consider if this is a binary, octal, decimal, or hex number that you want to handle. General rounding formula looks like this: Math . round (a*b*) /b* where a is a double or float number you want to round, » is the number base (2,8, 10,16), and ¢ is the number of fraction digits you need to get as a result of rounding Also, because the result of any arithmetic operation on types smaller than int. is an int, make sure that at least one participant of the expression is a float or a double number, in order for the result to be a floating point number. This slide discusses mathematical rounding. Do not confuse with numeric text formatting, which is not operating on a number, but on text instead. Ihis would be explained later in the course. Java SE 11: Programming Complete 2-9 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Binary Number Representation All Java numeric primitives are signed (that i, could represent positive and negative values). + Java uses a two's comploment implementation ofa signed magnitude representation of an integer. + For example, a byte zero value is represented as the 00000000 sequence of bits. + Skanaing 2 sign negative ox postive) is done by inverting ll he bits and then adcing one tothe rest + For example, a byle value of one is represeniad as 00000901 and minus ono is int value range Bitwise Complement operater inverts all bits of a number: ‘The result ofthe bitwise compliment operator ~a would be its “mirrored” binary value: - (2+1) + The next slike shows the rst ofthe bitwise operators. Byte zero value is stored as 00000000 (8 zero bits), short as 16 zero bits, int a8 32, and so on. Bitwise operators enable direct bit manipulations of numeric values. Their uses are mostly in low-level programming cases, such as communications over network sockets, encryption, compression, graphics, and so on. Most of the time Java application programmers are not directly exposed to such low- level operations and are using high-level APIs to program. However, under the hood, these high-level APIs would use these kind of operations anyway. Java SE 11: Programming Complete 2-10 Bitwise Operators Compare corresponding bits of two operands with bitwise operators: ~ Bitwioe AND s wren both bt ate the esUR or her fe DKS is ot he Fes + Bitwise OF : when ee of he bis is +, He resus 1 otherwise, the resus o + Bitwise Exclusive OR ~ wien coresponding bi ae arnt, he result 2: otherwise eeu o ‘Shit bts othe fet or ight with biwise operators: Signed Let Shift <= snes each othe elt speed ruber of priions, is ow onder pasion wih 9 vies 1 Signed Right Shil>> sits each ite eighty spactiad number peatons Unsigned Right Shit >> same ae above, bu is heart pions wih it ales Bitwise operators result in int type, just like other arithmetic operations. Therefore, explicit casting is required if you want results of these operations to be assigned to types smaller than int Java SE 11: Programming Complete 2-11 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates ites ted. Copyright © 2020 Oracle and/or its affi Unauthorized reproduction or distribution proh Equality, Relational, and Conditional Operators ‘Compare values to determine the boolean result: + Equal to == * Not equal to :~ + Groator than > + Groator than or equal to >= + Loss than < + Less than or equal to <= + NOT : (boolean inversion) + ANDES & OR) Exclusive OR ~ FEAT) (srot-creut evatiaton) (ta vation) owes “+ Round brackets () are not requied but could improve code readabilty. +The eiference between fll and shor-cuit evaluation is explained in the next sie, Java SE 11: Programming Complete 2-12 Short-Circuit Evaluation ‘Short-circuil evaluation enables you to not evaluate the right-hand side of the AND and OR expressions, when the overall result can be predicted from the left-hand side value. “Note: tis not advisable to mix boolean logic ang action in the same expression Ina short-circuit «& evaluation, when the lef side of expression is true, the right side still has to be evaluated to determine the result. However when the left side of the expression is false, the overall result can be determined without evaluating the right-hand side of the expression. This is precisely what is going to happen—Java would not attempt to evaluate the right-hand side of the expression when the overall result can be predicted by looking at the left side. Likewise, the short-circuit | | evaluation would not evaluate the right side of the expression, when the left side yields true and both sides will be evaluated when the left side yields false. Do not confuse assignment = with equality The following code example will not compile: int x = 1, y = 2; operator. boolean z = (x=y); The following code example will compile: int x= 1, y= 27 boolean z = ((x-y) == 2); // 2 is true Java SE 11: Programming Complete 2-13 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Flow Control Using if /e1se Construct Conditional execution of the algorithm using the i =/e1se construct: + The ££ code block is executed wien the boolean expression yields true; otherwise cl.ce block is executed. + The ese clause is optional + Theta is no e120/1 operator in Java, but you can embed an i f/e1se inside another :£/e1se construct. ‘Nove: Compilation ae bacause a oe conating Tro than one sntemnt mist be enclose ih ase bas + Not: tis optimal pt eu oes «) round ess Cite Macks ofcade, wen fy conan nly ingle Eplomer:. Ths coe ragmen! ientcali tte example ‘Shove: bui |" oncsionecouumaka Hitwurie faa. “Note: Gamage rons anainentatons na improve ecb, but ar eleven ‘rom te comer perspective Java SE 11: Programming Complete 2-14 Ternary Operator ‘The ternary operator is used to perform conditional assignment. + You can use the temary operator 2: instead of writing an ##/eise construct, if you only need to assign a value based on a condition. “+ When the boolean expression yields rue, value after the 2 is assigned. When the boolean expression yields fais, value after the : is assigned evarsanies= (ceoolean oxprosaion) 7 GSI ons) | cwsiue Sioby = aa 2? a> ‘Note: The ternary operator should bo used to cimpliy condional asigrment logic: Do not use i insiead of ¢/o1se staiemenis fo perdom oer actions, as ‘can make your code less readable The if/else example works fine, but may be harder to understand that all it actually does is perform an assignment. Use of the ternary operator can disambiguate this. Java SE 11: Programming Complete 2-15 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Flow Control Using switch Construct Control program flow using the switch construct. «Switch expression must be of one ofthe following types: byte, short, int, char, String, enum Case labels must match the expression type. Execution flow proceeds to the case in which the label matches the expression value. Execution flow continues until reaches the end of switch or encounters an optional break statement. I the switch expression did not match any of the eases, then the etault case is executed. It does not have to be the last case in the sequence and its optional Earstcases PE Sm Spal assay Za Pagers a ~ Discounted, decrease price by 4 ~ Expired, sei pice to 0 ‘Any oor, st pico to 3 when sears" (New) “Note: Stings and enums are covered later in the course. Java SE 11: Programming Complete 2-16 JShell + Shell is an interactive Read-Evaluate-Print Loop (REPL) commandline too + Its purpose is to help to learn Java programming language and prototype Java code. + Ievaluates declarations, statements, and expressions as they are entered. + Itshows the results immediateh Sea fetene sey geneni> = Java SE 11: Programming Complete 2-17 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Summary In this lesson, you should have learned how to: + Desoribe primitive types + Desoribe operators + Explain primitives type casting + Use Math class + Implement flow control with i£/else and switch statements + Desoribe JShell Java SE 11: Programming Complete 2-18 Practices In this practice, you will: + Use JShell too! + Declare, Initialise and Perform Operations on Primitives + Use the + £/e1s2 and switch Constructs and use a Ternary Operator Java SE 11: Programming Complete 2-19 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates soy IE Sj! JO/PUL BJDBIO OZOZT © JYBUAdOD ‘payiqiyoud uo!NquysIp JO UOONposdas pezoU;NeUy, Text, Date, Time, and Numeric Objects Ap od Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Objectives Aller completing this lesson, you should be able to: + Manipulate text values using String and StringBuilder classes + Describe primitive wrapper classes + Perform string and primitive conversions + Handle decimal numbers using BigDecimal class + Handle date and time values + Describe Localization and Formatting classes Java SE 11: Programming Complete 3-2 The java.lang.String class represents a sequence of characters, + String is a class (not a primitive. ts instances represent sequences of characters. + Just ike any other Java object, the String object can be instantiated by using the new keyword. + However, String is the only Java object that allows simplified instantiation as a text value enclosed with double quotes: "soe text" and that is a recommended approach. + JVM can optimize memory allocated to store String objects by maintaining 2 single copy of each ‘Siting literal in the Sting Pool memory area, regardless of how many variables reference this copy. (This process is called interning.) + The inteza () method retums a reference to an interned (single) copy of a String literal Asin 93" ialzaon Using nes tomer Eire me Eek Eto String Initialization On “4 Rominder: A primitive chaz “4 Note: Example usos a char artay char atrays ao covered lato inthe coutso. Interning String objects means that in the example on the right, only one copy of the String literal "Hello" will actually be placed in memory. All variables a, b, and c will be referring to the same copy of this String literal. This approact guaranteed to be safe, because String objects are immutable. In the other example, String objects a and b are not interned, but objects ¢ and d are. From the perspective of the application developer, String objects appear to represent its content as char]. However, because Java 9 onward String objects use the "Compact String " internal storage mechanism, JVM can store values not just as char{] but also as byte(]. It can also use UTF-16 encoding only as necessary, reducing the programs memory utilization and improving garbage collector performance. Java SE 11: Programming Complete 3-3 epresents a single character. is values are enclosed in single quotes: ‘2. Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates String Operations String objects are immutable. + Once a string object is initialized, it cannot be changed. + String operations such as trim (), conta Lowercase (), touppercase (), and so ‘on would always return a new String, but would not moity the original String + Itis possible to reassign the string reference to point to another string object. + For convenience reasons, String allows the use of the + operator instead of the 22221 () ‘method. However, remember that - is also an arithmetic operator. Cane EOE ‘HelloWorld” There are two more methods that allow removing leading and trailing spaces from the String, stzipLeadins () and stripTrailins () (available since version 11), in addition to the trim method. For more information about String class and its methods, see Java documentation: 3s://docs oracle. com/en/java/javase/t 1/docs/api/java base/java/lang/String. him! Java SE 11: Programming Complete 3-4 String Indexing String contains a sequence character inciexed by integer. * String index starts from 0 + When gelting a sxi:s=rsng of string, the begin index fs inclusive ofthe result, but end index is not + a substring is not found, the inciexo* method retums ->. + Both inciexOf and tasttndex0t operations are overicadod (have more than one version) and accept 2 char or a String parameter and may also accept a search starting from the index postion. + Anattempt to access text beyond the last valid index position (length) will produce an exception. “4+ Note: Exception handling is covered iter in the course. Java SE 11: Programming Complete 3-5 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates StringBuilder: Introduction ‘Another way of handing tot in Java's wih tho 333. 1ang.se ass. + StringBuilder ebjects are mutable, allowing modifications ofthe character sequences they store. + Handing text modifications with StringBuilder reduces the number of sting objects you need to create. + Some methods such as =: ‘are identical to that ofa String clas. . severae accepiing String or char parameters. continuous. It may contain spaces, bul you may not leave Gaps of no Extra methods are available: Sequence of characters must ‘charactors at al Like other classes, StingBulllor objocis are instantiated using the nex keyword. You may instantiate a StringBuilder with predefined content or capacity. Strings represent an easy and convenient way to produce output or capture user input, but they could prove to be not very efficient when you need to perform more complex text handling. That is why Java provides an alternative class StringBuilder designed to manipulate with text in a more efficient way. StringBuilder will automatically expand its capacity as needed (if you add more text), but performance-wise itis best to set the expected capacity immediately when you create a StringBuilder object. For more information about StringBuilder, see Java documentation: https/docs.oracle.com/en/java/javase/t 1 Jdocs/api/java.base/java/lang/String Builder.htmt There is an alternative to the StringBuilder class called StringBuffer. They generally work in the same way and provide equivalent operations; however, StringBuffer is designed as thread-safe and StringBuilder is not. Thread safety means that object would not allow multiple threads to modify its content, concurrently. Unfortunately, thread-safely costs resources and has a decremental ettact on program's pertormance. Many Java APIs provide thread-safe and unsafe versions of classes. It is generally recommended to se thread-unsafe versions, for performance reasons unless thread-safety is really required. Java SE 11: Programming Complete 3-6 Wrapper Classes for Primitives Wrapper classes apply object-oriented capabilities to primitives. ‘A wrapper class is capable of holding a primitive value provided for every Java primitive. ‘Construct wrapper object out of primitive or string using the va1ueot () methods. Ex\ract primitive values out of the wrapper using the xxxxvaie () methods, + Instead of formal conversion of wrapper to primitive and back, you can use direct assignment Notes + known as auto-boxing and aulo-unboxing. Create wrapper or primitive out ofthe string using tho ‘You may conver a primitive to a string using the string..va: Wrapper classes provide constants, such as min) an max values for every type. “Advanced tex formating and parsing is covered later. ‘Aveidte0 mary auto-Ddang ane auto-untexing operations for performance reacons, : Since Java 9, itis recommended not to use wrapper class constructors. new Integer () andnew Integer () constructors are deprecated. You may construct a wrapper out of text using customer radix value: Integer.valueOf ("B2B", 16) ; will construct a decimal value of 2859 out of the text representation of a 16-base number. ‘Auto boxing/unboxing process copies values between two memory areas known as stack and heap, which is an expensive operation. Using boxing/unboxing extensively would consume excessive amount of CPU resources. Stack and heap memory areas are covered in the lesson titled "Improve Class. Design.” Java SE 11: Programming Complete 3-7 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Representing Numbers Using BigDecimal Class Tho java.math.2igbecimal clas is useful in handling decimal numbers thal require exact precision. + Al primitive wrappers and 2qoecima2 are immutable and signed (cannot be changed and may represen posive or negative numbers). + However, unlike other numeric wrapper classes. SigDecima1 has arbitrary precision {for examle, Doubt has limited precision asa binary 64 bit number). + itis designed to work specifically wth decimal numbers and provide convenient © + It provides arithmetic operations as methods such as = + itis typically used to represent decimal number thal require exact precision, such as fiscal values. ue Classes that you have used so far in the course were located in the package java. lans. Content of the java lang package is available (implicitly imported) to all other Java classes. However, you may wish to add an import statement for the BigDecimal class, since it is located in another package java.math. Roundinglode is an enum from the java.math package that defines different rounding algorithms and is used to control exact rounding for the igDecimal operations. When working with decimal whole numbers, consider using the java -math. BigInteger class instead of simple primitives or wrapper classes. BigInteger provides similar decimal number handling capabilities as BigDecimal. Java SE 11: Programming Complete 3-8 Method Chaining When an operation retums an object you may invoke next operation upon this object immediately «tis possible to chiain method invocations technique with any operation that retums an object. + Examples: ~ Arithmetic operations of 2igDectnal retun 2: gDecima} objects. ~ Text manipulating operations of Serine return String objects, 4 Note: Method chaining is a common coding technique used when a method relurns an object, {allowed by an invocation of another method upon that object and soon. 4 Without meld chaining code appears lobe cltlered with unneozssay intermedia variables: Java SE 11: Programming Complete 3-9 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Local Date and Time Local date and time API s used to handle date and time values. * Classes LocsiDaze, Lecalzine, and Le: {ire from java-time package + Date and time objects ean be created using methods: Mo get curent date and ime, or PSS, oy tor specie dat and ie oF combining ater date and ime objects wing Ties (andor iovatDav, iocatTine) or ‘extracting dale and ie portions from LocalDateTime using == “Noto: Dato and Time API (3373. Eatlior Java vorsions usod 3 The of () operation is overloaded (has several versions) to enable constructing partial date or time values. For example, not setting nanoseconds or seconds would still work, but the time will set seconds and nanoseconds to zero. Example on this page uses an enum java.time.Month, which represents 12 months. Another useful enum is java. time. DayOsWeek, which represents seven days of the week. Enums are covered later in the course. The java.util.Date class is significantly less sophisticated than the new Java data and time API. It represents an offset (specified number of milliseconds) since the standard base time known as "the epoch,” namely January 1, 1970, 00:00:00 GMT. Date someTime = new Date(); // create current date and time object ime package) was inroducod in Java SE 8, long milliseconds = someTime.getTime(); // get amount of illiseconds elapsed from "the epoch" someTime. setTime (milliseconds+(1000*60)); // modify date object by adding one minute to it Note that Date class is mutable; that is, you can change date and time value for the samo instance of Date object Java SE 11: Programming Complete 3-10 More Local Date and Time Operations Characteristics of local date and time operations + Local Date and Time objects are immutable. + Alldate and time manipulation methods will produce new date and time objocts. + New date and time objects can be produced out of existing objects using Pu or ssnsexx () ores () methads, + Ihis possible to chain method invocations together, because all date and time manipulation ‘operations return date and time objects. + Individual portions of date and time objects can be retrieved with 220° () methods. + Operations isbefore () and ishzcex() check i a date or time is before or after another. | Reminder: Method chaining helps to avoid chitering cade with unnecessary intermediate variables Classes that you have used so far in the course were located in the package java. lans. Content of the java. lang package is available (implicitly imported ) to all other Java classes. However, this is not the case with other packages, so you would need to add import statements to access. java.time.LocalDate java.time.LocalTime and Java. time. LocalDateTime classes. Java SE 11: Programming Complete 3-11 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Methods to create new date and time by changing specific portion of existing date or time: withYear (int year) hDayOfYear(int dayofYear) hMonth (int month) withDayOfMonth (int dayOfMonth) withHour (int hour) nute (int minute) withSecond(int second) withNano (int nanoofsecond) Methods to create new date and time by adjusting existing date or time forward or backward: plusYears (long years) minusYears(long years) sMonths (long months) minusMonths (long months) plusWeeks (long weeks) minusWeeks (long weeks) plusDays (long days) minusDays (long days) plusHours (long hours) minusHours (long hours) nutes (long minutes) — minusMinutes (long minutes) plusSeconds(long seconds) —_ minusSeconds (long seconds) plusNanos (long nanos) minusNanos (long nanos) Methods to get specific portions of date and time: getYear() qetDayofvear () getMonth () getDayOf¥ionth () getDayOflleek() getHour() getMinute() getSecond() getNano() Java SE 11: Programming Complete 3-12 Instants, Durations, and Periods In addition to dates and times, the API can also represent periods and durations of time. + The java. time-Duration class can represent an amount of time in nanoseconds. + Tho Java.time. Period class can represent an amount of time in units such as years or days. ‘The 3ava.time. Instant class can represent an instantaneous point on the time-line (time-stamp). ‘Just lke the rest ofthe Local Date and Time API, Duration, Period, and Instant objects are immutable. Provide methods such a$ nos (), o£ ¥%(), piwskX% () minus () wi HOM (), and see 0) + Provide methods such as 22tycon (), is%csat ive) to handle distances between points in time. + Use idontical coding techniques such as method chaining, “= Note: Instant and Duratlon axe mare sulable fr implementing system tasks, sueh as using ‘a lmesiamp when wring log. Peed is more sutable for implementing business logic. Java SE 11: Programming Complete 3-13 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates ites Zoned Date and Time ‘Time zones can be appliad to local date and time values. ‘The Java.tine. ZonedDateTine lass: Represents date and time values according to time zone rules Has the same time management capabiities as LocalDateTime Provides time zone spect operations such as wr "zonesanetnotant ‘Accounts for daylight saving time and time zone differences ZoneId london = Zonerd. = + The Java.tine. zoner¢ class detnes time zone e 3 «Timezone can be set as: Zonetd-of (Manerica/ios Angeles"); 0, we Zoneia.of (rUTE-05:00") 7 Zoneid systenDefesl® (2 led. Copyright © 2020 Oracle and/or its affi Java SE 11: Programming Complete 3-14 Unauthorized reproduction or distribution proh Represent Languages and Countries Java provides APIs to make your application adjustable to diferent languages and locations around the world. ‘The java.util. Locale elass represents languages and courires. ‘The {SO 639 language and ISO 3166 or country cades or UN M49 area codes are used to set up locale ebjects Locale can represent just language or combination of language pls county or area. \Varant isan optional parameter, designed to produce custom locale variations. ‘Language tag sting allows constructing locales for various calendars, numbering systems, currencies, and so on. Language Country Variant Commonly used locales are available as constants in the Locale class. For example: Locale us = Locale.US+ is the same as Locale us = new Locale("en", "US") ; Instances of the Locale can also be constructed with a variant argument (custom variant), for examp! GB", "EURO’ new Locale ("en" (Or with the use of the Locale. Builder class: Locale uk = new Locale.Builder () .setLanguage ("en") .setRegion ("GB") build ( i (Or with the use of the Language tag: Locale uk = Locale. forLanguageTag ("en-GB") ; Java SE 11: Programming Complete 3-15 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates ites Examples of Language tag extension are: cu (currency type) fu (Zirst day of the week) rg (region override) tz (time zone) u-ea (calendar) u-nu (numbering system) For more information, see Java Locale documentation: httpsy/does.oracle.com/en/java/javase/1 1/docs/api/java.base/java/util/Locale.h tml Also, see the list of supported Locales, examples of calendars, and numbering systems: httus://www.oracle.com/technetworkvjava/javase/dooumentation/javat tlocales -5069639.html ted. Copyright © 2020 Oracle and/or its affi Java SE 11: Programming Complete 3-16 Unauthorized reproduction or distribution proh Format and Parse Numeric Values Tho java.cext.thunberFornat dass is used to parse and format numeric values. + Works with any Java Number, including primitives, wrapper classes and BigDecimal objects value hiatizations Ipsaleintiaization jalatons | ho78 o.n2 Saaz The NumberFormat.parse () method return type is java. lang. Number. Class Number is extended by all primitive wrapper classes as well as the BigDecimal class. This means that once the value is parsed, you can convert it to any type that you want to use in your program. In this example, values are converted to BigDecimal, Double, and int. Number format parse method will throw a Pax seException if parsed String does not conform to the expected format, such as wrong or missing currency symbols, wrong thousand or decimal separators, and so on. Use the java text DecimalFormat class fo set up custom format for decimal numeric values. Java SE 11: Programming Complete 3-17 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Format and Parse Date and Time Values ‘The java.cime. format. bateTineFormatter dass is used to parse and format date and time values. * You can soup custom formal pattorn o use standard formal patlrns defined by Jva.tine. format Fors rosatomator —_| ie By default, Date and Time values are formatted using ISO format, in the order of years months days hours minutes seconds. For example: 2011-12- 03710:15:30 Alternatively, you can set specific format using patterns predefined by the FormatStyle enum (FULL , LONG, MEDIUM, SHORT) or define custom pattern DateTimeFormatter.ofPattern (String pattern, Locale locale) Date and time pattern symbols: symbol Meaning Examples 6 era AD: Anno Domini; A 2 year 2004; 04 y year-of-era 2004; 04 D day-of-year 19 M/L — month-or-year 7; 07; gui; uly: 3 a day-of-month 10 a modified-julian-day 2451334 oa quarter-of-year 3; 03; Q3; 3rd quarter Java SE 11: Programming Complete 3-18 Y W E ese F a bh K k B n s a n Nn v 2; -08: 2 ° x 08:30; 08:30; z P -based-year 1996; 96 ~of-week-based~year 27 week-of-month 4 day-of-week Tue; Tuesday; T localized day-of-week 2; 02; Tue; Tuesday; T day-of-week-in-month 3 am-pn-of-day PM clock-hour-of-am-pm (1-12) 12 hour-of-am-pm (0-11) 0 clock-hour-of-day (1-24) 24 hour-of-day (0-23) o minute-of-hour 30 second-of-minnte 55 fraction~of-second 978 milli-of-day 1234 nano-of-second 987654321 nano-of-day 1234000000 time-zone ID America/Los_Angeles: 30 generic time-zone name Pacific Time; PT time-zone name Pacific Standard Time; PST localized zone-offset GMI+8; GMT+08:00; UTC-08:00 zone-offset 'Z' for zero 2; -08; -0830; ~ -083015; -08:30:15 zone-offset +0000; -08; -0830; - 083015; 08:30:15 zone-of fset +0000; -0800; -08:00 pad next i escape for text single quote Java SE 11: Programming Complete 3-19 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Example of custom pattern: LocalDateTime someTime = LocalDateTime.of (2019,Month .APRIL,1,17,42)7 DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("EEEE dd MMMM YYYY, hl new Locale("en", "GB"))¢ String result = dateFormatter. format (someTime) ; Produces the following result: Monday 01 April 2019, 0: Note: LocalDate, LocalTime, LocalDateTime, ZonedDateTime and DateTimeFormatter, all have format and parse methods; use whichever is convenient. 42 pm Java SE 11: Programming Complete 3-20 Localizable Resources Resource bundles contain lealizale resources Resource bundle can be represented as plain text file wih the extension «= Focourcos. or example sor vsble messages, replaced ilo rosoures bundles 3 + Bundles may contain messages or message pattems with substitution parameters. + The java.util Reso + Default uncle can he used ino locale is spectied RezourceBunie.getGundie (chindle (vate substions ar expla ater) :nate clase loads bundles an retrieves resources, ‘Fife resource you're tying to gets not present in another (language and country specifi) bund, Resource bundles are treated as classes (loaded from classpath). This means that a bundle can be placed into a package folder, in which case, you need to specify package prefix to load the bundle file. For example, assume that property file is placed into the “demos.resources" package folder: demos\propert ies \messages_en_GB.properties In which case, use package prefix to fully qualify bundle name: Locale locale = new Locale ("en", "GB" ResourceBundle bundle = ResourceBundle. getBundle ("demos . resources messages", local es Resource bundle can be defined not only as a property file, but also as a Java class. However, this is not very commonly used because it could be harder to maintain than a plain text fle. Java SE 11: Programming Complete 3-21 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates Format Message Patterns Formatter classes parse and format messages, numbers, date and time values. + The jave-text.tessageFornst class substiules values inio message pallems. + Message patterns can be stored in recourse bundles. For example, resovrcas/nessages_en_C3.properties ‘containing product message pater: iniiaize locale 4. best before 1 Apr 2019 and MessageFormat. provides both format and parse capabilities, in the same Way DateTimeFormatter Of NumberFormat do: MessageFormat formatter = new MessageFormat ("(0}, price » quantity {2}, best before (3)"); Object {] values = formatter.parse quantity 4, best before 1 Apr 201 "Cookie, price £2.99, ne This method returns an object array of values extracted from the string, according to the patter set for this message format. Java SE 11: Programming Complete 3-22 Formatting and Localization: Example sesources/acastgea en oB.propertics ss Bat ose Cookie, price £2.55, quantity ¢, beer hetore 1 Apr 2019 Java SE 11: Programming Complete 3-23 Unauthorized reproduction or distribution prohibited. Copyright © 2020 Oracle and/or its affiliates

You might also like