Java Se 8 Tutorial Pdf Download

Java SE 8 Fundamentals Ed 1 (Student Guide Volume 1)

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 299

Java SE 8 Fundamentals Student Guide – Volume I  D83527GC10 Edition 1.0 June 2014 D87049  uthors  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Kenneth Somerville  Disclaimer  Jill Moritz Cindy Church  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Nick Ristuccia  Technical Contributors and Reviewers Kenneth Somerville Peter Fernandez  This document contains proprietary information and is protected by copyright and other intellectual property laws. You may copy and print this document solely for your own use in an Oracle training course. The document may not be modified or altered in any way. Except where your use constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display, perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization of Oracle. The information contained in this document is subject to change without notice. If you find any problems in the document, please report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not warranted to be error-free.  Jill Moritz Cindy Church Nick Ristuccia Tom McGinn Mike Williams Matt Heimer  Restricted Rights Notice If this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United States Government, the following notice is applicable: U.S. GOVERNMENT RIGHTS The U.S. Government's rights to use, modify, reproduce, release, perform, display, or disclose these training materials are restricted by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.  Editors Anwesha Ray Raj Kumar  Graphic Designers Divya Thallap Rajiv Chandrabhanu Daniel Milne  Publishers Michael Sebastian Veena Narasimhan Nita Brozowski  Trademark Notice Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Contents  1  Introduction About This Course 1-2 Audience 1-3 Course Objectives 1-4 Schedule 1-6 Course Environment 1-9 Test Your Lab Machines 1-11 How Do You Learn More After the Course? 1-12 Quiz 1-13 Summary 1-14  2  What Is a Java Program? Objectives 2-2 Topics 2-3 Purpose of a Computer Program 2-4 Translating High-Level Code to Machine Code 2-5 Linked to Platform-Specific Libraries 2-6 Platform-Dependent Programs 2-7 Topics 2-8 Key Features of the Java Language 2-9 Java Is Platform-Independent 2-10 Java Programs Run In a Java Virtual Machine 2-11 Procedural Programming Languages 2-12 Java Is an Object-Oriented Language 2-13 Topics 2-14 Verifying the Java Development Environment 2-15 Examining the Installed JDK (Linux Example): The Tools 2-16 Examining the Installed JDK (Windows Example): The Libraries Topics 2-18 Compiling and Running a Java Program 2-19 Compiling a Program 2-20 Executing (Testing) a Program 2-21 Output for a Java Program 2-22 Exercise 2-1 2-23  iii  2-17  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz 2-24 Summary 2-25 3  Creating a Java Main Class Objectives 3-2 Topics 3-3 Java Classes 3-4 Program Structure 3-5 Java Packages 3-6 Using the Java Code Console 3-7 Using the Java Code Console: Creating a New Java Class 3-8 Using the Java Code Console: Creating a New Java Class for an Exercise 3-9 Exercise 3-1: Creating a Class 3-10 Topics 3-11 The main Method 3-12 A main Class Example 3-13 Output to the Console 3-14 Fixing Syntax Errors 3-15 Exercise 3-2: Creating a main Method 3-16 Quiz 3-17 Summary 3-18  4  Data in a Cart Objectives 4-2 Topics 4-3 Variables 4-4 Variable Types 4-5 Naming a Variable 4-6 Uses of Variables 4-7 Topics 4-8 Variable Declaration and Initialization 4-9 String Concatenation 4-10 String Concatenation Output 4-11 Exercise 4-1: Using String Variables 4-12 Quiz 4-13 Topics 4-14 int and double Values 4-15 Initializing and Assigning Numeric Values 4-16 Topics 4-17 Standard Mathematical Operators 4-18 Increment and Decrement Operators (++ and --) 4-19  iv  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Operator Precedence 4-20 Using Parentheses 4-22 Exercise 4-2: Using and Manipulating Numbers Quiz 4-24 Summary 4-26  4-23  5  Managing Multiple Items Objectives 5-2 Topics 5-3 Making Decisions 5-4 The if/else Statement 5-5 Boolean expressions 5-6 Relational Operators 5-7 Examples 5-8 Exercise 5-1: Using if Statements 5-9 Quiz 5-10 Topics 5-11 What If There Are Multiple Items in the Shopping Cart? 5-12 Introduction to Arrays 5-13 Array Examples 5-14 Array Indices and Length 5-15 Declaring and Initializing an Array 5-16 Accessing Array Elements 5-18 Exercise 5-2: Using an Array 5-19 Quiz 5-20 Topics 5-22 Loops 5-23 Processing a String Array 5-24 Using break with Loops 5-25 Exercise 5-3: Using a Loop to Process an Array 5-26 Quiz 5-27 Summary 5-28 Play Time! 5-29 About Java Puzzle Ball 5-30 Tips 5-31  6  Describing Objects and Classes Interactive Quizzes 6-2 Objectives 6-3 Topics 6-4 Java Puzzle Ball 6-5  v  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Puzzle Ball Debrief 6-6 Object-Oriented Programming 6-7 Duke's Choice Order Process 6-8 Characteristics of Objects 6-9 Classes and Instances 6-10 Quiz 6-11 Topics 6-12 The Customer Properties and Behaviors 6-13 The Components of a Class 6-14 Modeling Properties and Behaviors 6-15 Exercise 6-1: Creating the Item Class 6-16 Topics 6-17 Customer Instances 6-18 Object Instances and Instantiation Syntax 6-19 The Dot (.) Operator 6-20 Objects with Another Object as a Property 6-21 Quiz 6-22 Topics 6-23 Accessing Objects by Using a Reference 6-24 Working with Object References 6-25 References to Different Objects 6-28 References and Objects in Memory 6-30 Assigning a Reference to Another Reference 6-31 Two References, One Object 6-32 Exercise 6-2: Modify the ShoppingCart to Use Item Fields 6-33 Topics 6-34 Arrays Are Objects 6-35 Declaring, Instantiating, and Initializing Arrays 6-36 Storing Arrays in Memory 6-37 Storing Arrays of Object References in Memory 6-38 Quiz 6-39 Topics 6-41 Java IDEs 6-42 The NetBeans IDE 6-43 Creating a Java Project 6-44 Creating a Java Class 6-45 Avoiding Syntax Problems 6-46 Compile Error: Variable Not Initialized 6-47 Runtime Error: NullPointerException 6-48 Compiling and Running a Program by Using NetBeans 6-49 Topics 6-50  vi  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Soccer Application 6-51 Creating the Soccer Application 6-52 Soccer Web Application 6-53 Summary 6-54 Challenge Questions: Java Puzzle Ball 6-55 Practice 6-1 Overview: Creating Classes for the Soccer League 6-56 Practice 6-2 Overview: Creating a Soccer Game 6-57 7  Manipulating and Formatting the Data in Your Program Objectives 7-2 Topics 7-3 String Class 7-4 Concatenating Strings 7-5 String Method Calls with Primitive Return Values 7-8 String Method Calls with Object Return Values 7-9 Topics 7-10 Java API Documentation 7-11 Java Platform SE 8 Documentation 7-12 Java Platform SE 8: Method Summary 7-13 Java Platform SE 8: Method Detail 7-14 indexOf Method Example 7-15 Topics 7-16 StringBuilder Class 7-17 StringBuilder Advantages over String for Concatenation (or Appending) 7-18 StringBuilder: Declare and Instantiate 7-19 StringBuilder Append 7-20 Quiz 7-21 Exercise 7-1: Use indexOf and substring Methods 7-22 Exercise 7-2: Instantiate the StringBuilder object 7-23 Topics 7-24 Primitive Data Types 7-25 Some New Integral Primitive Types 7-26 Floating Point Primitive Types 7-28 Textual Primitive Type 7-29 Java Language Trivia: Unicode 7-30 Constants 7-31 Quiz 7-32 Topics 7-33 Modulus Operator 7-34 Combining Operators to Make Assignments 7-35 More on Increment and Decrement Operators 7-36  vii  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Increment and Decrement Operators (++ and ––) 7-37 Topics 7-38 Promotion 7-39 Caution with Promotion 7-40 Type Casting 7-42 Caution with Type Casting 7-43 Using Promotion and Casting 7-45 Compiler Assumptions for Integral and Floating Point Data Types 7-46 Automatic Promotion 7-47 Using a long 7-48 Using Floating Points 7-49 Floating Point Data Types and Assignment 7-50 Quiz 7-51 Exercise 7-3: Declare a Long, Float, and Char 7-52 Summary 7-53 Play Time! 7-54 Practice 7-1 Overview: Manipulating Text 7-55 8 Creating and Using Methods Objectives 8-2 Topics 8-3 Basic Form of a Method 8-4 Calling a Method from a Different Class 8-5 Caller and Worker Methods 8-6 A Constructor Method 8-7 Writing and Calling a Constructor 8-8 Calling a Method in the Same Class 8-9 Topics 8-10 Method Arguments and Parameters 8-11 Method Parameter Examples 8-12 Method Return Types 8-13 Method Return Types Examples 8-14 Method Return Animation 8-15 Passing Arguments and Returning Values 8-16 More Examples 8-17 Code Without Methods 8-18 Better Code with Methods 8-19 Even Better Code with Methods 8-20 Variable Scope 8-21 Advantages of Using Methods 8-22 Exercise 8-1: Declare a setColor Method 8-23  viii  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics 8-24 Java Puzzle Ball 8-25 Java Puzzle Ball Debrief 8-26 Static Methods and Variables 8-27 Example: Setting the Size for a New Item 8-28 Creating and Accessing Static Members 8-29 When to Use Static Methods or Fields 8-30 Some Rules About Static Fields and Methods 8-31 Static Fields and Methods vs. Instance Fields and Methods 8-32 Static Methods and Variables in the Java API 8-33 Examining Static Variables in the JDK Libraries 8-34 Using Static Variables and Methods: System.out.println 8-35 More Static Fields and Methods in the Java API 8-36 Converting Data Values 8-37 Topics 8-38 Passing an Object Reference 8-39 What If There Is a New Object? 8-40 A Shopping Cart Code Example 8-41 Passing by Value 8-42 Reassigning the Reference 8-43 Passing by Value 8-44 Topics 8-45 Method Overloading 8-46 Using Method Overloading 8-47 Method Overloading and the Java API 8-49 Exercise 8-2: Overload a setItemFields Method 8-50 Quiz 8-51 Summary 8-52 Challenge Questions: Java Puzzle Ball 8-53 Practice 8-1 Overview: Using Methods 8-54 Practice 8-2 Overview: Creating Game Data Randomly 8-55 Practice 8-3 Overview: Creating Overloaded Methods 8-56 9  Using Encapsulation Interactive Quizzes 9-2 Objectives 9-3 Topics 9-4 What Is Access Control? 9-5 Access Modifiers 9-6 Access from Another Class 9-7 Another Example 9-8  ix  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Using Access Control on Methods 9-9 Topics 9-10 Encapsulation 9-11 Get and Set Methods 9-12 Why Use Setter and Getter Methods? 9-13 Setter Method with Checking 9-14 Using Setter and Getter Methods 9-15 Exercise 9-1: Encapsulate a Class 9-16 Topics 9-17 Initializing a Shirt Object 9-18 Constructors 9-19 Shirt Constructor with Arguments 9-20 Default Constructor and Constructor with Args 9-21 Overloading Constructors 9-22 Quiz 9-23 Exercise 9-2: Create an Overloaded Constructor 9-24 Summary 9-25 Play Time! 9-26 Practice 9-1 Overview: Encapsulating Fields 9-27 Practice 9-2 Overview: Creating Overloaded Constructors 9-28 10 More on Conditionals Objectives 10-2 Topics 10-3 Review: Relational Operators 10-4 Testing Equality Between String variables 10-5 Common Conditional Operators 10-9 Ternary Conditional Operator 10-10 Using the Ternary Operator 10-11 Exercise 10-1: Using the Ternary Operator 10-12 Topics 10-13 Java Puzzle Ball 10-14 Java Puzzle Ball Debrief 10-15 Handling Complex Conditions with a Chained if Construct 10-16 Determining the Number of Days in a Month 10-17 Chaining if/else Constructs 10-18 Exercise 10-2: Chaining if Statements 10-19 Topics 10-20 Handling Complex Conditions with a switch Statement 10-21 Coding Complex Conditions: switch 10-22 switch Statement Syntax 10-23  x  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  When to Use switch Constructs 10-24 Exercise 10-3: Using switch Construct 10-25 Quiz 10-26 Topics 10-27 Working with an IDE Debugger 10-28 Debugger Basics 10-29 Setting Breakpoints 10-30 The Debug Toolbar 10-31 Viewing Variables 10-32 Summary 10-33 Challenge Question: Java Puzzle Ball 10-34 Practice 10-1 Overview: Using Conditional Statements 10-35 Practice 10-2 Overview: Debugging 10-36 11 Working with Arrays, Loops, and Dates Interactive Quizzes 11-2 Objectives 11-3 Topics 11-4 Displaying a Date 11-5 Class Names and the Import Statement 11-6 Working with Dates 11-7 Working with Different Calendars 11-9 Some Methods of LocalDate 11-10 Formatting Dates 11-11 Exercise 11-1: Declare a LocalDateTime Object 11-12 Topics 11-13 Using the args Array in the main Method 11-14 Converting String Arguments to Other Types 11-15 Exercise 11-2: Parsing the args Array 11-16 Topics 11-17 Describing Two-Dimensional Arrays 11-18 Declaring a Two-Dimensional Array 11-19 Instantiating a Two-Dimensional Array 11-20 Initializing a Two-Dimensional Array 11-21 Quiz 11-22 Topics 11-23 Some New Types of Loops 11-24 Repeating Behavior 11-25 A while Loop Example 11-26 Coding a while Loop 11-27 while Loop with Counter 11-28  xi  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Coding a Standard for Loop 11-29 Standard for Loop Compared to a while loop 11-30 Standard for Loop Compared to an Enhanced for Loop 11-31 do/while Loop to Find the Factorial Value of a Number 11-32 Coding a do/while Loop 11-33 Comparing Loop Constructs 11-34 The continue Keyword 11-35 Exercise 11-3: Processing an Array of Items 11-36 Topics 11-37 Nesting Loops 11-38 Nested for Loop 11-39 Nested while Loop 11-40 Processing a Two-Dimensional Array 11-41 Output from Previous Example 11-42 Quiz 11-43 Topics 11-45 ArrayList Class 11-46 Benefits of the ArrayList Class 11-47 Importing and Declaring an ArrayList 11-48 Working with an ArrayList 11-49 Exercise 11-4: Working with an ArrayList 11-50 Summary 11-51 Play Time! 11-52 Practice 11-1 Overview: Iterating Through Data 11-53 Practice 11-2 Overview: Working with LocalDateTime 11-54 12 Using Inheritance Objectives 12-2 Topics 12-3 Java Puzzle Ball 12-4 Java Puzzle Ball Debrief 12-5 Inheritance in Java Puzzle Ball 12-6 Implementing Inheritance 12-8 More Inheritance Facts 12-9 Topics 12-10 Duke's Choice Classes: Common Behaviors Code Duplication 12-12 Inheritance 12-13 Clothing Class: Part 1 12-14 Shirt Class: Part 1 12-15 Constructor Calls with Inheritance 12-16  xii  12-11  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Inheritance and Overloaded Constructors 12-17 Exercise 12-1: Creating a Subclass 12-18 Topics 12-19 Overriding Methods 12-20 Review: Duke's Choice Class Hierarchy 12-21 Clothing Class: Part 2 12-22 Shirt Class: Part 2 12-23 Overriding a Method: What Happens at Run Time? 12-24 Exercise 12-2: Overriding a Method in the Superclass 12-25 Topics 12-26 Polymorphism 12-27 Superclass and Subclass Relationships 12-28 Using the Superclass as a Reference 12-29 Polymorphism Applied 12-30 Accessing Methods Using a Superclass Reference 12-31 Casting the Reference Type 12-32 instanceof Operator 12-33 Exercise 12-3: Using the instanceof Operator 12-34 Topics 12-35 Abstract Classes 12-36 Extending Abstract Classes 12-38 Summary 12-39 Challenge Questions: Java Puzzle Ball 12-40 Practice 12-1 Overview: Creating a Class Hierarchy 12-42 Practice 12-2 Overview: Creating a GameEvent Hierarchy 12-43 13 Using Interfaces Interactive Quizzes 13-2 Objectives 13-3 Topics 13-4 The Object Class 13-5 Calling the toString Method 13-6 Overriding toString in Your Classes 13-7 Topics 13-8 The Multiple Inheritance Dilemma 13-9 The Java Interface 13-10 Multiple Hierarchies with Overlapping Requirements 13-11 Using Interfaces in Your Application 13-12 Implementing the Returnable Interface 13-13 Access to Object Methods from Interface 13-14 Casting an Interface Reference 13-15  xiii  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz 13-16 Topics 13-18 The Collections Framework 13-19 ArrayList Example 13-20 List Interface 13-21 Example: Arrays.asList 13-22 Exercise 13-1: Converting an Array to an ArrayList 13-24 Topics 13-25 Example: Modifying a List of Names 13-26 Using a Lambda Expression with replaceAll 13-27 Lambda Expressions 13-28 The Enhanced APIs That Use Lambda 13-29 Lambda Types 13-30 The UnaryOperator Lambda Type 13-31 The Predicate Lambda Type 13-32 Exercise 13-2: Using a Predicate Lambda Expression 13-33 Summary 13-34 Practice 13-1 Overview: Overriding the toString Method 13-35 Practice 13-2 Overview: Implementing an Interface 13-36 Practice 13-3 (Optional) Overview: Using a Lambda Expression for Sorting 13-37 14 Handling Exceptions Objectives 14-2 Topics 14-3 What Are Exceptions? 14-4 Examples of Exceptions 14-5 Code Example 14-6 Another Example 14-7 Types of Throwable classes 14-8 Error Example: OutOfMemoryError 14-9 Quiz 14-10 Topics 14-11 Normal Program Execution: The Call Stack 14-12 How Exceptions Are Thrown 14-13 Topics 14-14 Working with Exceptions in NetBeans 14-15 The try/catch Block 14-16 Program Flow When an Exception Is Caught 14-17 When an Exception Is Thrown 14-18 Throwing Throwable Objects 14-19 Uncaught Exception 14-20  xiv  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exception Printed to Console 14-21 Summary of Exception Types 14-22 Exercise 14-1: Catching an Exception 14-23 Quiz 14-24 Exceptions in the Java API Documentation 14-25 Calling a Method That Throws an Exception 14-26 Working with a Checked Exception 14-27 Best Practices 14-28 Bad Practices 14-29 Somewhat Better Practice 14-30 Topics 14-31 Multiple Exceptions 14-32 Catching IOException 14-33 Catching IllegalArgumentException 14-34 Catching Remaining Exceptions 14-35 Summary 14-36 Interactive Quizzes 14-37 Practice 14-1 Overview: Adding Exception Handling 14-38 15 Deploying and Maintaining the Soccer Application Objectives 15-2 Topics 15-3 Packages 15-4 Packages Directory Structure 15-5 Packages in NetBeans 15-6 Packages in Source Code 15-7 Topics 15-8 SoccerEnhanced.jar 15-9 Set Main Class of Project 15-10 Creating the JAR File with NetBeans 15-11 Topics 15-13 Client/Server Two-Tier Architecture 15-14 Client/Server Three-Tier Architecture 15-15 Topics 15-16 Client/Server Three-Tier Architecture 15-17 Different Outputs 15-19 The Soccer Application 15-20 IDisplayDataItem Interface 15-21 Running the JAR File from the Command Line 15-22 Text Presentation of the League 15-23 Web Presentation of the League 15-24  xv  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics 15-25 Enhancing the Application 15-26 Adding a New GameEvent Kickoff 15-27 Game Record Including Kickoff 15-28 Summary 15-29 Course Summary 15-30 A Java Puzzle Ball Challenge Questions Answered Topics A-2 Question 1 A-3 Question 2 A-4 Question 3 A-5 Question 4 A-6 Topics A-7 Question 1 A-8 Topics A-9 Question 1 A-10 Topics A-12 Question 1 A-13 Topics A-14 Question 1 A-15 Question 2 A-16 B Introducing the Java Technology Java's Place in the World B-2 Java Desktops B-3 Java Mobile Phones B-4 Java TV and Card B-5 The Story of Java B-6 Identifying Java Technology Product Groups B-7 Java SE B-8 Java EE B-9 Java ME B-10 Java Card B-11 Product Life Cycle (PLC) Stages B-12  xvi  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  About This Course  12 13 14 15 16 17 18 19 20  Shirt myShirt = new Shirt(); Shirt yourShirt = new Shirt(); myShirt = yourShirt; myShirt.colorCode = 'R'; yourShirt.colorCode = 'G'; System.out.println("Shirt color: " + myShirt.colorCode);  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  During this course, you will: • Write Java code using a code console and integrated development environment • Complete interactive quizzes • Play a game  Java SE 8 Fundamentals 1 - 2  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Audience •  •  •  Beginners to programming who have basic mathematical, logical, and analytical problem-solving skills and who want to begin learning the Java programming language Novice programmers and those programmers who prefer to start learning the Java programming language at an introductory level Students who want to begin their study of the Oracle Certified Java Associate exam  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The audience for this course is a beginner to programming who has basic mathematical and problem-solving skills. The course is targeted at technical writers, web developers, technical managers, project managers, program managers, and individuals with a technical, nonprogramming background such as system administrators.  Java SE 8 Fundamentals 1 - 3  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Course Objectives After completing this course, you should be able to: • Demonstrate knowledge of basic programming language concepts • Demonstrate knowledge of the Java programming language • Implement intermediate Java programming and objectoriented (OO) concepts  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Demonstrate knowledge of basic programming language concepts. For example, be able to describe the following: Source code versus machine code • Platform dependence and platform independence • The use of APIs and libraries Demonstrate knowledge of the Java programming language • Compile and run a Java program from both the command line and from NetBeans. • Create a Java class with fields and methods. • Declare and use arrays. • Use methods of the StringBuilder, String, and ArrayList classes. • Display and manipulate dates using one or two classes from the new java.time package. • Write conditional statements. • Write loop statements (enhanced for, for, while, do/while). • Write nested loops. • Implement a try block to handle exceptions.  Java SE 8 Fundamentals 1 - 4  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Implement intermediate Java programming and object-oriented (OO) concepts • Instantiate an object and invoke its methods. • Explain how objects vs. primitive types or references are stored in memory. • Create a hierarchy of Java classes. • Implement inheritance by creating a subclass. • Overload a method and a constructor. • Encapsulate the fields of a class. • Use modifiers to control access to a field or a method. • Implement a Java Interface. • Create superclasses, abstract classes, and Interfaces and use them as reference types. • Use a Predicate lambda expression as the argument to a method.  Java SE 8 Fundamentals 1 - 5  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Schedule Day One • Getting Started – Lesson 1: Introduction – Lesson 2: What Is a Java Program?  •  The Basic Shopping Cart – Lesson 3: Creating a Java Main Class – Lesson 4: Data in a Cart – Lesson 5: Managing Multiple Items  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 1 - 6  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Schedule Day Two • Filling the Cart – Lesson 6: Describing Objects and Classes – Lesson 7: Manipulating and Formatting the Data in Your Program  •  Improving Cart Efficiency – Lesson 8: Creating and Using Methods  Day Three – Lesson 9: Using Encapsulation  •  Expanding the Business – Lesson 10: More on Conditionals  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 1 - 7  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Schedule Day Four – Lesson 11: Working with Arrays, Loops, and Dates  •  Bringing It Home – Lesson 12: Using Inheritance  Day Five – Lesson 13: Using Interfaces – Lesson 14: Handling Exceptions – Lesson 15: Deploying and Maintaining the Soccer Application  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 1 - 8  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Course Environment  Classroom Computer  Java SE 8  Java Code Console  Exercises  Student Guide  NetBeans  Practices  Activity Guide  Java Puzzle Ball  Quizzes  Java SE 8 Fundamentals Quiz.html  Practices  Exercises  labs folder Lesson folders  Solutions  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In this course, the following products are preinstalled for the lesson practices: • JDK 8: The Java SE Development Kit includes the command-line Java compiler (javac) and the Java Runtime Environment (JRE), which supplies the java command needed to execute Java applications. • Firefox: A web browser is used to view the HTML documentation (Javadoc) for the Java SE Platform libraries. • NetBeans 8: The NetBeans IDE is a free and open-source software development tool for professionals who create enterprise, web, desktop, and mobile applications. • Student Guide: The guide contains the instructional material for all the topics discussed in class and includes appendices with additional information. It also includes some introductory instructions for completing the exercises and practices. • Activity Guide: These are resources to use during the practice portions of the course. The Activity Guide has instructions for completing the practices. • Lab Folder: The lab folder includes interactive quizzes, practices, exercises, and solution files.  Java SE 8 Fundamentals 1 - 9  • •  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  • •  Java API Documentation: The API documentation is the application programming interface specification. Java Code Console: This is an IDE developed by Oracle Java Curriculum Developers that you use to perform short coding exercises. Interactive Quizzes: The quizzes are self-paced and help you remember the key points learned in each lesson. Java Puzzle Ball: This game is available for you to play on your machines. It will be used to introduce and reinforce concepts taught in the course.  Java SE 8 Fundamentals 1 - 10  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Test Your Lab Machines 1. 2. 3. 4.  Go to your lab machine. Open the Firefox browser. Enter http://localhost:8080/JavaCC. Click the Cloud IDE link.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  To ensure that your lab environment is working, access your lab machine and start the Java Code Console.  Java SE 8 Fundamentals 1 - 11  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  How Do You Learn More After the Course? To find more resources, bookmark the URL: Oracle.com/oll/java Look for the Java SE 8 Fundamentals Collection.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the Oracle Learning Library, there is a list of resources that you can use to learn more about Java programming. Look for the collection on the oracle.com/oll/java page.  Java SE 8 Fundamentals 1 - 12  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz a. b. c. d.  What is your name? What do you do for a living, and where do you work? What is the most interesting place you have visited? Why are you interested in Java?  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 1 - 13  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Summary In this lesson, you reviewed the course objectives and the tentative class schedule. You met your fellow students, and you saw an overview of the computer environment that you will use during the course. Enjoy the next five days of Java SE 8 Fundamentals.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 1 - 14  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Objectives After completing this lesson, you should be able to: • Contrast the terms "platform-dependent" and "platformindependent" • Describe the purpose of the JVM • Explain the difference between a procedural program and an object-oriented program • Describe the purpose of javac and java executables • Verify the Java version on your system • Run a Java program from the command line  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 2 - 2  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • •  Introduction to computer programs Introduction to the Java language Verifying the Java development environments Running and testing a Java program  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 2 - 3  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Purpose of a Computer Program A computer program is a set of instructions that run on a computer or other digital device. • At the machine level, the program consists of binary instructions (1s and 0s). – Machine code  •  Most programs are written in high-level code (readable). – Must be translated to machine code  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 2 - 4  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Translating High-Level Code to Machine Code  Solaris OS C Compiler Solaris OS Binary  Linux C Compiler  Linux Binary  C Code  Microsoft Windows C Compiler  Microsoft Windows Binary  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Programs written in most languages usually require numerous modifications to run on more than one type of computing platform, (a combination of a CPU and operating system). This platform-dependence is because most languages require you to write code specific to the underlying platform. Popular programming languages, such as C and C++, require programmers to compile and link their programs, resulting in an executable program unique to a platform. A compiler is an application that converts a program that you write into a CPUspecific code called machine code. These platform-specific files (binary files) are often combined with other files, such as libraries of prewritten code, using a linker to create a platform-dependent program, called an executable, which can be executed by an end user. Unlike C and C++, the Java programming language is platform-independent. The image illustrates how a compiler creates a binary file.  Java SE 8 Fundamentals 2 - 5  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Linked to Platform-Specific Libraries  Project Libraries Solaris OS C Compiler Solaris OS Binary  Solaris OS Executable Project Libraries Linux C Compiler  Linux Binary  Linux Executable  Project Libraries  Microsoft Windows Binary  Microsoft Windows C Compiler  Microsoft Windows Executable  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The image illustrates how a binary file is linked with libraries to create a platform-dependent executable.  Java SE 8 Fundamentals 2 - 6  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Platform-Dependent Programs  Solaris OS Workstation Solaris OS Executable  Linux Executable  Microsoft Windows Executable  Linux Workstation  Microsoft Windows Workstation  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The image illustrates how platform-dependent executables can execute only on one platform.  Java SE 8 Fundamentals 2 - 7  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • •  Introduction to computer programs Introduction to the Java language Verifying the Java development environment Running and testing a Java program  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 2 - 8  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Key Features of the Java Language Some of the features that set Java apart from most other languages are that: • It is platform-independent • It is object-oriented  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  There are several other key features of the Java language, but in this course, only the two mentioned above will be discussed.  Java SE 8 Fundamentals 2 - 9  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Is Platform-Independent  Project Libraries Java Compiler Java Code  Java Bytecode  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  A Java program can run on several different CPUs and operating system combinations, such as the Solaris OS on a SPARC chip, Mac OS X on an Intel chip, and Microsoft Windows on an Intel chip, usually with few or no modifications. As illustrated above, Java programs are compiled using a Java compiler. The resulting format of a compiled Java program is platform-independent Java bytecode instead of CPU-specific machine code. After the bytecode is created, it is interpreted by a bytecode interpreter called the Java Virtual Machine or JVM. A virtual machine is a platform-specific program that understands platformindependent bytecode and can execute it on a particular platform. For this reason, the Java programming language is often referred to as an interpreted language, and Java technology programs are said to be portable or executable on any platform. Other interpreted languages include Perl.  Java SE 8 Fundamentals 2 - 10  Java Programs Run In a Java Virtual Machine  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  JRE  Solaris OS Workstation  Java Bytecode (.class file)  JRE  Linux Workstation JRE  Java Virtual Machine (JVM) Microsoft Windows Workstation  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The image illustrates a Java bytecode file executing on several platforms where a Java runtime environment exists. A virtual machine gets its name because it is a piece of software that runs code, a task usually accomplished by the CPU or hardware machine. For Java programs to be platformindependent, a virtual machine called the JVM is required on every platform where your program will run. The JVM is responsible for interpreting Java code, loading Java classes, and executing Java programs. However, a Java program needs more than just a JVM to execute. A Java program also needs a set of standard Java class libraries for the platform. Java class libraries are libraries of prewritten code that can be combined with the code that you write to create robust applications. Combined, the JVM software and Java class libraries are referred to as the Java Runtime Environment (JRE). Java Runtime Environments are available from Oracle for many common platforms.  Java SE 8 Fundamentals 2 - 11  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Procedural Programming Languages •  •  •  Many early programming languages followed a paradigm called Procedural Programming. These languages use a sequential pattern of program execution.  1  Step 1  2  Step 2  3  Step 3  4  Step 4  5  Step 5  Drawbacks to procedural programming: – Difficult to translate real-world use cases to a sequential pattern – Difficult to maintain programs – Difficult to enhance as needed  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Earlier programming languages were based on a programming paradigm called "procedural". Procedural languages use a sequential pattern of program execution such as you see in the diagram above. Some examples of procedural programming languages are COBOL, Fortran, C, and Pascal. This style of programming has become less popular due to the difficulty of designing realworld applications using sequential pattern. It has also proven difficult to maintain and enhance programs structured in this way.  Java SE 8 Fundamentals 2 - 12  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Is an Object-Oriented Language • • •  Interaction of objects No prescribed sequence Benefits: – – – –  Modularity Information hiding Code reuse Maintainability  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Object-oriented programming differs from procedural programming, because procedural programming stresses the sequence of coding steps required to solve a problem, whereas object-oriented programming stresses the interaction of objects. Java is an object-oriented programming (OO) language. One of the main goals of an OO language is to create objects— pieces of autonomous code—that can interact with other objects to solve a problem. OO programming languages began in 1967 and have led to popular programming languages such as C++, upon which Java is loosely based. This provides many benefits: • Modularity: The source code for an object can be written and maintained independently of the source code for other objects. After it is created, an object can be easily passed around inside the system. • Information hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. • Code reuse: If an object already exists (perhaps written by another software developer), you can use that object in your program. • Maintainability: If a particular object is found to be problematic, you can create another, slightly modified one and simply replace the original one in your application. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace the bolt, not the entire machine. The diagram illustrates an object-oriented program's focus on objects and object interactions. Java SE 8 Fundamentals 2 - 13  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • •  Introduction to computer programs Introduction to the Java language Verifying the Java development environment Running and testing a Java program  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 2 - 14  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Verifying the Java Development Environment 1. Download and install the Java Development Kit (JDK) from oracle.com/java. 2. Explore the Java Help menu. 3. Compile and run a Java application by using the command line.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Setting up your Java development environment is a simple task. The JDK is available for free from the Oracle Java website. • After you have installed the JDK, you can explore the Java environment by typing some commands at the command line. For example, open a terminal window and enter java. • • •  Review the command options displayed. Enter java –version to see what Java version is installed on your system. Compile and run a Java application using the command line.  Java SE 8 Fundamentals 2 - 15  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Examining the Installed JDK (Linux Example): The Tools  PATH points here Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE (Standard Edition) Development Kit The Java SE Development Kit includes both the tools and classes that you will use to develop a Java program. The tools and utilities are stored in the bin directory. These are shown in the screenshot on the right. They include: • A Java Virtual Machine (JVM) for the platform you choose. Here you see a Linux example. The runtime engine is started by running the java program. • A Java compiler, started by running the javac program • Additional utilities, such as utilities for creating Java archive files (JAR files) and for debugging Java programs • The bin directory, which must be on the system PATH in order to run or compile a Java program. The Java installer automatically adds the bin to your system PATH. • Note: The Java Runtime Environment used in production (commonly called the JRE) is also included with Java SE Development Kit. This is found in the jre directory.  Java SE 8 Fundamentals 2 - 16  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Examining the Installed JDK (Windows Example): The Libraries  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE Development Kit In addition to the executable files found in the bin directory of the JDK, various class libraries are installed that conform to the particular platform that you chose. Here you see a Windows example. The core libraries are found in the lib directory as shown above. The Java runtime engine requires these libraries. In addition to the Java SDK download, other items are available as a separate download, such as the Java class library (API) documentation and the Java Language Specification.  Java SE 8 Fundamentals 2 - 17  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • •  Introduction to computer programs Introduction to the Java language Verifying the Java development environment Running and testing a Java program  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 2 - 18  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Compiling and Running a Java Program  .java  javac  .class  java  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The diagram above shows what happens when you compile and run a Java program. • The Java code is written in a file with the extension .java. This is called the "Java source code." • You use the javac executable to compile the source code (the "c" stands for "compiler") into a bytecode file with the extension .class. This is called a Java class. • You use the java executable to run the Java class. This is your Java program.  Java SE 8 Fundamentals 2 - 19  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Compiling a Program 1. Go to the directory where the source code files are stored. 2. Enter the following command for each .java file you want to compile. •  Syntax:  javac SayHello.java  •  Example:  javac SayHello.java  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Compiling converts the source files that you write into bytecode that can be executed by a Java Virtual Machine. The source file has a .java extension. It also defines a public class of the same name. For example, the class, SayHello, must be saved in a file called SayHello.java. (You learn more about classes later in this course.) To compile the SayHello source code, perform the following steps: 1. Go to the directory where the source code files are stored. 2. Enter the following command for each .java file that you want to compile (Note that the .java extension is required.): Example: javac SayHello.java After the compilation has finished, and assuming no compilation errors have occurred, you should have a new file called          .class in your directory for each source code file that you compiled. Example: SayHello.class  Java SE 8 Fundamentals 2 - 20  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Executing (Testing) a Program 1. Go to the directory where the class files are stored. 2. Enter the following for the class file that contains the main method: • Syntax: java                          •  Example:  Do not specify .class.  java SayHello  •  Output:  Hello World!  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  When you have successfully compiled your source code files, you can execute and test them using the Java Virtual Machine. To execute and test your program: 1. Go to the directory where the class files are stored. 2. Enter the following command for the class file that contains the main method. Note that here the file extension (.class) should not be included. Example: java SayHello This command runs the SayHello class. The SayHello class contains the main method. This is the entry point to a Java application. The java executable only works with a class containing a main method. In the above example, the main method contains code that prints the string "Hello World!".  Java SE 8 Fundamentals 2 - 21  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Output for a Java Program A Java program can output data in many ways. Here are some examples: • To a file or database • To the console • To a webpage or other user interface  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In this course, we will be outputting data only to the console. You can learn more about writing to other destinations, such as a file, database, or webpage, by taking the Java SE 8 Programming course.  Java SE 8 Fundamentals 2 - 22  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 2-1 • •  From a Terminal window, enter java –version to see the system's Java version. Look for SayHello.java in: /labs/02-GettingStarted/Exercises/Exercise1  • •  Compile it: javac SayHello.java Run the resulting class file: java SayHello —  Did you see the output?  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In this exercise, you look at the Java version installed on your system, and then you run a simple Java program from the command line. • Open a terminal window by double-clicking the Terminal shortcut on your desktop. It will open at your home directory, which is /home/oracle. - Note: A handy shortcut to navigate to your home directory from anywhere is ~. Example: cd ~ to go to /home/oracle. • Enter java to see the available command options. • Enter java -version to verify that JDK 1.8.0 is installed on your system. • Navigate to the folder containing the Java source file for this exercise: cd labs/02-GettingStarted/Exercises/Exercise1 • •  Enter javac SayHello.java to compile it. Enter java SayHello to run it. You should see a "Hello World!" message as output.  Java SE 8 Fundamentals 2 - 23  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Which of the following is correct? (Choose all that apply.) a. javac OrderClass b. java OrderClass c. javac OrderClass.java d. java OrderClass.java  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: b, c The .java extension is needed only when you compile a class (using javac).  Java SE 8 Fundamentals 2 - 24  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Summary In this lesson, you should have learned how to: • Describe the distinction between high-level language and machine code • Describe what platform-independence means • Describe how a Java program is compiled and to what format • Explain what it means to say that Java is an objectoriented language • Determine the version number of a Java install • Use the javac tool to compile Java source code and the java tool to run or test your program  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 2 - 25  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Objectives After completing this lesson, you should be able to: • Create a Java class • Write a main method • Use System.out.println to write a String literal to system output  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 3 - 2  Java Classes  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  A Java class is the building block of a Java application. Includes code that: ShoppingCart.java  • Allows a customer to add items to the shopping cart • Provides visual confirmation to the customer  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 3 - 4  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Program Structure •  A class consists of: – The class name. Class names begin with a capital letter. – The body of the class surrounded with braces — —  •  { }  Data (called fields) Operations (called methods)  Example:  Java is case-sensitive! public class Hello { // fields of the class // methods }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  • •  • • • •  A class is declared using the keyword, class, followed by the class name. Convention dictates that the class name start with a capital letter. If there are two words in the class name (SayHello), each word should begin with a capital letter. In the example above, the class name is Hello. The keyword public is called a modifier. You learn about these in the lesson titled "Using Encapsulation." Java is case-sensitive. It does not recognize the following two words as being the same thing: class and Class. A class would typically contain data (called fields) and operations (called methods). You learn about this a little later. Notice that the body of the Hello class is enclosed in braces ({ }).  Java SE 8 Fundamentals 3 - 5  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Packages •  A package provides a namespace for the class. – This is a folder in which the class will be saved. – The folder name (the package) is used to uniquely identify the class. – Package names begin with a lowercase letter.  •  Example:  Package name package greeting; public class Hello { // fields and methods here }  The class's unique name is: greeting.Hello  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The use of a package when you create a Java class is not mandatory, but it is strongly recommended. Notice the semicolon after package greeting; Semicolons are required at the end of each statement. It is similar to the period at the end of a sentence. The sentence may wrap to another line, but it is not complete until the period. The Java compiler interprets a statement as being complete when it encounters the semicolon.  Java SE 8 Fundamentals 3 - 6  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Using the Java Code Console For the exercises in this course, you use a browser-based Java IDE. 1. Open a browser and enter: http://localhost:8080/JavaCC 2. Click the Lessons link. 3. Click the exercise number for the current lesson.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  IDE stands for Integrated Development Environment. This is a type of software that makes it easier to develop applications. In the practices for the lesson titled "Describing Objects and Classes" and beyond, you use the NetBeans IDE, which is a full-featured Java IDE. For the short exercises that are sprinkled throughout the lecture portions of this course, you will use a simple web-based IDE called Java Code Console. It was written specifically for this purpose. This IDE is hosted on your student machine.  Java SE 8 Fundamentals 3 - 7  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Using the Java Code Console: Creating a New Java Class 1. Click the New button to create a new file. 2. Select the Java category and Java Class file type. 3. Click Next.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Most of the exercises provide a pre-existing Java class or classes, to which you add code. If the exercise you selected has a pre-existing .java file for you, it will appear in a tabbed view on this page. In some cases, however, you need to create a new Java class. The steps are described here and in the next slide. • Click the New button as shown in the top screenshot. • The Create New File Wizard opens. Select Java in the Category column. Select Java Class in the File Type column. • Click Next. • Instructions are also displayed on the Java Code Console page, just below the code editor panel. However, if no Java file is provided and you are going to create a new one, the code editor is not shown. Therefore, the instructions appear just below the toolbar.  Java SE 8 Fundamentals 3 - 8  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Using the Java Code Console: Creating a New Java Class for an Exercise 4. Enter a class name and a package name. 5. Click Finish.  Run code  Code editor  Return to List of Lessons  Show solution  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Enter a class name and package name, as specified in the exercise instructions. When you click Finish, the code for this class appears in a tabbed page, bearing the class name. • In the left screenshot, you see the ShoppingCart.java tab, containing the package statement and the class declaration. This is the code editor panel. • You will write your code between the braces. • To test your code, click the Run button as indicated above. • To return to the list of exercises, click the Index link. • To view the solution for the exercise, click the Solution link. It will replace the current .java file with the solution .java file in the same tab, but you will be able to toggle between your code and the solution.  Java SE 8 Fundamentals 3 - 9  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 3-1: Creating a Class In this exercise, you use the Java Code Console to create a new Java Class. • Click New to create a new class: – Class name = ShoppingCart – Package name = exercise  •  Leave the tabbed view open in the browser because you will modify the code in the next exercise.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The fully-qualified class name should be exercise.ShoppingCart. Do not click the Solution link until after exercise 3-2.  Java SE 8 Fundamentals 3 - 10  The main Method  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  • •  It is a special method that the JVM recognizes as the starting point for every Java program. The syntax is always the same: public static void main (String args[]) // code goes here in the code block }  •  It surrounds entire method body with braces { }  {  .  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  •  The main method is a special method that the Java Virtual Machine recognizes as the starting point for a Java program. • Any program that you want to run must have a public main method. • A class containing a main method is referred to as a "main class." Note: Brackets ([]) can be placed to the right of String or to the right of args, but the former is recommended: (String[] args) (String args[])  Java SE 8 Fundamentals 3 - 12  A main Class Example  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Class name public class Hello { public static void main (String[] args)  {  // Entry point to the program. Comments // Write code here: System.out.println ("Hello World!"); } }  Program output  main method Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Here you see a simple example of a class (Hello) that includes a main method. The main method writes a message to the console ("Hello World!"). This is called program output. You can include comments that the compiler will ignore, by preceding the comment line with two forward slashes: //  Java SE 8 Fundamentals 3 - 13  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Output to the Console •  Syntax: System.out.println ();  String literal  •  Example: System.out.println ("This is my message.");  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Use the System.out.println method to print a message to the console. Use double quotation marks to enclose the text of the message (called a String literal).  Java SE 8 Fundamentals 3 - 14  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Fixing Syntax Errors • •  If you have made a syntax error, the error message appears in the Output panel. Common errors: – Unrecognized word (check for case-sensitivity error) – Missing semicolon – Missing close quotation mark – Unmatched brace  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The Java Code Console helps you out by using color coding. Keywords (such as class) are in purple. String literals are shown in blue. When you click Run, it will attempt to compile your code and then run it. Syntax errors will be caught during compilation. The error message may or may not be helpful in troubleshooting, so here are some common errors to avoid: • Unrecognized class (It may say "Cannot find symbol."). This happens when you misspell a method or class name, or if you get the case wrong. Remember, Java is casesensitive! • Every Java statement must end with a semicolon. This example error is shown above in line 5. • An uneven number of symbols such as braces, brackets, and quotation marks will also cause errors.  Java SE 8 Fundamentals 3 - 15  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 3-2: Creating a main Method In this practice, you manually enter a main method that prints a message to the console. • In the code editor, add the main method structure to the ShoppingCart class. • In the code block, use a System.out.println method to print "Welcome to the Shopping Cart!" • Click the Run button to test program.  Example Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the example above, you see a class called Hello. Within the braces that define the scope of the class, you see the main method. The method body is also surrounded by braces. When you click the Run button as indicated in the image on the right, the program is both compiled (using javac) and executed (using java). The println statement results in the "Hello World!" string appearing in the Output tab.  Java SE 8 Fundamentals 3 - 16  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Which main method syntax is correct? a. Public static void main (String[ ] args){ } b. public Static void Main (String[ ] args){ } c. public static void main (String ( ) args)[ ] d. public static void main (String[ ] args){ }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: d • • • •  a is incorrect. It should be "public", not "Public". b is incorrect. Both "Static" and "Main" should begin with a lowercase letter. c is incorrect because there should be brackets following "String" and braces defining the method scope. d is correct.  Java SE 8 Fundamentals 3 - 17  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Summary In this lesson, you should have learned how to: • Create a class using the Java Code Console • Create (declare) a Java class • Define a main method within a class • Use System.out.println to write to the program output • Run a program in the Java Code Console  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 3 - 18  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Objectives After completing this lesson, you should be able to: • Describe the purpose of a variable in the Java language • List and describe four data types • Declare and initialize String variables • Concatenate String variables with the '+' operator • Make variable assignments • Declare and initialize int and double variables • Modify variable values by using numeric operators • Override default operator precedence using ( )  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 4 - 2  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • •  Introducing variables Working with String variables Working with numbers Manipulating numeric data  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 4 - 3  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Variables •  A variable refers to something that can change. – Variables can be initiated with a value. – The value can be changed. – A variable holds a specific type of data.  The type of data  Variable name  The value of the variable  String firstName = "Mary";  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  A variable is simply a storage location in memory that holds a specific value. That value can be changed by copying (or "assigning") a different value to that variable.  Java SE 8 Fundamentals 4 - 4  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Variable Types •  Some of the types of values a variable can hold: – – – –  •  String (example: "Hello") int (examples: -10, 0, 2, 10000) double (examples: 2.00, 99.99, -2042.09) boolean (true or false)  If uninitialized, variables have a default value: – – – –  String : "" (the empty string) int: 0 double: 0.0 boolean: false  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Variables are declared to hold a specific type of data. Some of the more common types are: • String: This is text data, such as "Hello". • int: This is integer data—positive or negative whole numbers. • double: These are positive or negative real numbers containing a decimal portion. • boolean: This data type has a value of either true or false. Most variables that have not been initialized are given a default value. The default values for String, int, double, and boolean are shown above. (Local variables are the exception. You will learn about local variables in the lesson titled "Creating and Using Methods.") Notice that String begins with an uppercase letter, but the other types do not. You will learn the reason for this later, when you also learn about some other data types.  Java SE 8 Fundamentals 4 - 5  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Naming a Variable Guidelines: • Begin each variable with a lowercase letter. Subsequent words should be capitalized: –  • • •  myVariable  Names are case-sensitive. Names cannot include white space. Choose names that are mnemonic and that indicate to the casual observer the intent of the variable. – outOfStock (a boolean) – itemDescription (a String)  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 4 - 6  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Uses of Variables •  Holding data used within a method: String name = "Sam" ; double price = 12.35; boolean outOfStock = true;  •  Assigning the value of one variable to another: String name = name1;  •  Representing values within a mathematical expression: total = quantity * price ;  •  Printing the values to the screen: System.out.println(name);  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Variables are used extensively in the Java programming language for tasks such as: • Holding data used within a method, such as the main method • Assigning the value of one variable to another. In the first example above, the name variable is initialized with the value, "Sam", and in the second example, its value is changed to the value of name1 (unknown here). • Representing values within a mathematical expression (* is the symbol for multiplication) • Printing the values to the screen. For example, the same System.out.println method that you used in the last exercise to print out the text literal, "Welcome to the Shopping Cart", can also be used to print out the value stored in the name variable.  Java SE 8 Fundamentals 4 - 7  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • •  Introducing variables Working with String variables Working with numbers Manipulating numeric data  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 4 - 8  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Variable Declaration and Initialization •  Syntax : type identifier [= value];  •  Examples:  Variable declared  String customer; String name, city;  Two variables declared  String address = "123 Oak St";  Variable declared and initialized  Two variables declared and initialized String country = "USA", state = "CO";  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The syntax for declaring and initializing a variable is: type identifier [= value];  where: • type represents the type of information or data held by the variable. In the examples above, you see only String variable types declared. • identifier is the variable name. In the first example above, the variable name is customer. • The second example shows how you can declare multiple variables of the same type on a single line without initializing them. Notice that they are separated by a comma. • You can either declare a variable without assigning an initial value (as you saw in the first example) or you can initialize the variable at the same time you declare it (as shown in the example that declares and initializes the address variable). • The final example shows how to declare and initialize multiple variables of the same type. Once again, each initialization is separated by a comma. Some of the multiple variables declared on a single line can be initialized, whereas others are just declared.  Java SE 8 Fundamentals 4 - 9  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  String Concatenation •  String variables can be combined using the '+' operator. – stringVariable1 + stringVariable2 – stringVariable1 + "String literal" – stringVariable1 + "String literal" + stringVariable2  •  Example:  String greet1 = "Hello"; String greet2 = "World"; String message = greet1 + " " + greet2 + "!"; String message = greet1 + " " + greet2 + " " + 2014 +"!";  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Combining multiple Strings is called "concatenation." You can concatenate a String variable to another String variable. You can also concatenate a String literal to a String variable. As you can see in the example above, you can concatenate any number of String variables and String literals to achieve your goal. You may find the last example surprising. You can also concatenate a number into a String variable. The compiler converts the numeric value to its equivalent String value. If we were to print the message variable after the last example, the output would be "Hello World 2014!"  Java SE 8 Fundamentals 4 - 10  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  String Concatenation Output You can concatenate String variables within a method call: System.out.println(message); System.out.println(greet1 + " " + greet2 +  "!");  Output: Hello World! Hello World!  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the examples above, you see two variations of printing out String data by using the System.out.println method. • In the first example, the message variable that you saw in the previous slide will be printed. • In the second example, the expression containing the concatenation of variables plus String literals can be used within the method parentheses. The concatenation will be completed by the runtime engine before the println method is executed. • As you can see, the output of both method invocations is the same.  Java SE 8 Fundamentals 4 - 11  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 4-1: Using String Variables In this exercise, you declare, initialize, and concatenate String variables and literals.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  •  Open the Java Code Console and access 04-Variables > Exercise1.  •  Follow the instructions below the code editor to declare and initialize variables, and also to concatenate a string message. Print the message by using System.out.println.  Note: If you need help, the solution for this exercise can be found by clicking the Solution link.  Java SE 8 Fundamentals 4 - 12  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Which of the following variable declarations and/or initializations are correct? a. int count = 5; quantity = 2; b. string name, label; c. boolean complete = "false"; d. boolean complete = true;  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: d • • • •  a is incorrect because each int declaration and assignment must be separated by a comma and not a semicolon. b is incorrect because String is not capitalized. c is incorrect because a boolean type variable does not hold String values. It holds only true and false. d is correct.  Java SE 8 Fundamentals 4 - 13  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • •  Introducing variables Working with String variables Working with numbers Manipulating numeric data  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 4 - 14  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  int and double Values •  int variables hold whole number values between: – –2,147,483,648 – 2,147,483,647 – Examples: 2, 1343387, 1_343_387  •  double variables hold larger values containing decimal portions. – Use when greater accuracy is needed. – Examples: 987640059602230.7645 , -1111, 2.1E12  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  •  •  The int data type stores 32 bits of data. This means that you can store whole numbers within the range: -2,145,483,648 and 2,147,483,647. You cannot use commas to make the number more readable when you assign a value to an int variable. However, you can use underscores (_) to make your code more readable, as shown in one of above int examples. The compiler ignores these underscores. If you print the number to system output, the underscores will not appear. The only benefit of this is readability in your code. The double data type stores 64 bits of data. This means that you can store extremely large values—either negative or positive. The examples above show: - An extremely large number with four decimal points of precision - A negative whole number - A decimal number using exponential notation  Java SE 8 Fundamentals 4 - 15  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Initializing and Assigning Numeric Values •  int variables: – int quantity = 10; – int quantity = 5.5;  •  Compilation fails!  double variables: – double price = 25.99; – double price = 75;  Run time will interpret as 75.0.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 4 - 16  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • •  Introducing variables Working with String variables Working with numbers Manipulating numeric data  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 4 - 17  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Standard Mathematical Operators Purpose  Operator  Example  Addition  +  sum = num1 + num2; If num1 is 10 and num2 is 2, sum is 12.  Subtraction  –  diff = num1 – num2; If num1 is 10 and num2 is 2, diff is 8.  Multiplication  *  prod = num1 * num2; If num1 is 10 and num2 is 2, prod is 20.  Division  /  quot = num1 / num2; If num1 is 31 and num2 is 6, quot is 5.  Comments  Division by 0 returns an error. The remainder portion is discarded.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The table above assumes that all operands and result variables are integers (int). Mixing double and int types can alter the results. For instance, in the division example, if the quotient and dividend (or if all three) are double values, the quotient would show the decimal portion: double quot, num1; num1 = 31; int num2 = 5; quot = num1 / num2; Answer: quot = 6.2  Java SE 8 Fundamentals 4 - 18  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Increment and Decrement Operators (++ and --) The long way: age = age + 1; or count = count – 1; The short way: age++; or count--;  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  A common requirement in programs is to add or subtract 1 from the value of a variable. You can do this by using the + operator as follows: age = age + 1;  Java SE 8 Fundamentals 4 - 19  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Operator Precedence Here is an example of the need for rules of precedence. Is the answer to the following problem 34 or 9? int c = 25 - 5 * 4 / 2 - 10 + 4;  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 4 - 20  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Operator Precedence Rules of precedence: 1. Operators within a pair of parentheses 2. Increment and decrement operators (++ or --) 3. Multiplication and division operators, evaluated from left to right 4. Addition and subtraction operators, evaluated from left to right  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In a complex mathematical statement with multiple operators on the same line, how does the computer pick which operator it should use first? To make mathematical operations consistent, the Java programming language follows the standard mathematical rules for operator precedence. Operators are processed in the following order: 1. Operators within a pair of parentheses 2. Increment and decrement operators 3. Multiplication and division operators, evaluated from left to right 4. Addition and subtraction operators, evaluated from left to right If standard mathematical operators of the same precedence appear successively in a statement, the operators are evaluated from left to right.  Java SE 8 Fundamentals 4 - 21  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Using Parentheses Examples: int int int int int int  c c c c c c  = = = = = =  (((25 - 5) * 4) / (2 - 10)) + 4; ((20 * 4) / (2 - 10)) + 4; (80 / (2 - 10)) + 4; (80 / -8) + 4; -10 + 4; -6;  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Your expression will be automatically evaluated with the rules of precedence. However, you should use parentheses to provide the structure you intend: int c = (((25 - 5) * 4) / (2 - 10)) + 4; int c = ((20 * 4) / (2 - 10)) + 4; int c = (80 / (2 - 10)) + 4; int c = (80 / -8) + 4; int c = -10 + 4; int c = -6;  Java SE 8 Fundamentals 4 - 22  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 4-2: Using and Manipulating Numbers In this exercise, you declare, initialize, and concatenate String variables and literals.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  •  Open the Java Code Console and access Lessons > 04-Variables > Exercise2  •  Follow the instructions below the code editor to: - Declare and initialize two double variables to hold the price and the tax - Declare an int to hold the number of items the shopper wishes to purchase - Declare another double variable, total, but do not initialize it yet - Change the existing message variable to include the number of items desired - Calculate the total cost and then print it with a suitable descriptive String - Run the project  Note: If you need help, the solution for this exercise can be found by clicking the Solution link.  Java SE 8 Fundamentals 4 - 23  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Which of the following statements are correct Java code? a. int count = 11.4; b. double amount = 11.05; c. int cost = 133_452_667; d. double total = 1.05 * amount;  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: b, c, d • • • •  a is incorrect because the assignment of a decimal value to an int is a possible loss of precision and therefore will not compile. b is correct. c is correct because underscores can be used to make a number more readable. d is correct.  Java SE 8 Fundamentals 4 - 24  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Given: String name = "Bob"; String msg; int num = 3;  Which of the following statements correctly assigns the value "Bob wrote 3 Java programs." to the msg variable? a. b. c. d.  msg = name + " wrote " + num " Java programs."; msg = name + " wrote " + 3 + " Java programs."; msg = "Bob wrote "+ (2+1) + " Java programs."; msg = name + " wrote " + 2+1 + " Java programs.";  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: b, c • • • •  a is incorrect because it is missing a + sign between the num variable and the final String literal. b is correct because the compiler converts the int of value 3 to a String. c is correct because, due to the use of parentheses, the addition operation is performed first, before the concatenation. d is incorrect because it would result in "Bob wrote 21 Java programs." The compiler converts each number to a String separately and concatenates them together.  Java SE 8 Fundamentals 4 - 25  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Summary In this lesson, you should have learned how to: • Describe the purpose of a variable in the Java language • List and describe four data types • Declare and initialize String variables • Concatenate String variables with the '+' operator • Make variable assignments • Declare and initialize int and double variables • Modify numeric values by using operators • Override default operator precedence using ( )  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 4 - 26  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Objectives After completing this lesson, you should be able to: • Explain what a Boolean expression is • Create a simple if/else statement • Describe the purpose of an array • Declare and initialize a String or int array • Access the elements of an array • Explain the purpose of a for loop • Iterate through a String array using a for loop  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE8 Fundamentals 5 - 2  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Making Decisions  Which way shall I go?  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In your daily life, you have to make a lot of decisions, and you often use the word "if" with some condition when making those decisions. For example, "If I can see my destination on the left, I will turn left, otherwise I'll turn right." One of the tasks that programs often perform is to evaluate a condition and, depending on the result, execute different blocks or branches of code. This is called conditional logic, and it is handled through the use of an if/else statement.  Java SE8 Fundamentals 5 - 4  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  The if/else Statement Boolean expression if (                                  ) { // do something } else { // do something different  if block  else block  }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The if/else statement is one way of branching your code depending upon some condition. It uses the two Java keywords, if and else. • •  If some condition is true, execute the code within the if block. Else, if that condition is false, execute the code in the else block.  The condition to be evaluated is surrounded by parentheses. It is referred to as a Boolean expression because it must evaluate to either true or false.  Java SE8 Fundamentals 5 - 5  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Boolean expressions Review: • boolean data type has only two possible values: – true – false  A Boolean expression is a combination of variables, values, and operators that evaluate to true or false. • length > 10; • size <= maxSize; • total == (cost * price); Relational operators Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Remember that a boolean data type can have only two possible values: true and false. In the same way, a Boolean expression, made up of some combination of variables, values and operators, must also evaluate to either true or false. This usually involves a special kind of operator called a relational operator. Several of these are used in the three examples above: • Greater than ( > ) • Less than or equal to ( <= ) • Equal to ( == ). In the example above, the result of cost * price is compared to the value of total. If they are equal, the entire expression evaluates to true.  Java SE8 Fundamentals 5 - 6  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Relational Operators Condition  Operator  Example  Is equal to  ==  int i=1; (i == 1)  Is not equal to  !=  int i=2; (i != 1)  Is less than  <  int i=0; (i < 1)  Is less than or equal <= to  int i=1; (i <= 1)  Is greater than  >  int i=2; (i > 1)  Is greater than or equal to  >=  int i=1; (i >= 1)  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Here you see a more complete list of relational operators. The table lists the different conditions you can test by using relational operators. The result of all relational operators is a boolean value. All of the examples in the table yield a boolean result of true. Note: The equal sign (=) is used to make an assignment, whereas the == sign merely makes a comparison and returns a boolean.  Java SE8 Fundamentals 5 - 7  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Examples Sometimes there is a quicker way to meet your objective. Boolean expressions can be used in many ways. 24 25 26 27 28 29 30 31 32 33 34 35 36  int attendees = 4; boolean largeVenue; // if statement example if (attendees >= 5){ largeVenue = true; } else { largeVenue = false; } // same outcome with less code largeVenue = (attendees >= 5);  Assign a boolean by using an if statement. Assign the boolean directly from the Boolean expression.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the slide above, you see examples of two different ways to set the largeVenue boolean value: • In lines 28–33, an if statement tests the value of the attendees variable. If it is greater than 5, largeVenue is set to true; otherwise it is set to false. •  In line 36, the same outcome is achieved with one line of code. The result of the same Boolean expression that was evaluated in the if statement (attendees >=5) is directly assigned to the largeVenue boolean.  Java SE8 Fundamentals 5 - 8  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 5-1: Using if Statements In this exercise, you use an if and an if/else statement: • Declare a boolean, outOfStock. • if quantity > 1 – Change the message variable to indicate plural  •  if/else: – if item is out of stock: —  Inform the user that the item is unavailable  – else —  Print the message  —  Print the total cost  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  • •  Open the Java Code Console and access Lessons > 05-ConditionsArraysLoops > Exercise1. Follow the instructions below the code editor to write two if statements in the main method.  Note: If you need help, the solution for this exercise can be found by clicking the Solution link.  Java SE8 Fundamentals 5 - 9  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz What is the purpose of the else block in an if/else statement? a. To contain the remainder of the code for a method b. To contain code that is executed when the expression in an if statement is false c. To test if an expression is false  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: b  Java SE8 Fundamentals 5 - 10  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  What If There Are Multiple Items in the Shopping Cart? 01 02 03 04 05 06 07  // Without an array String itemDesc1 = "Shirt"; String itemDesc2 = "Trousers"; String itemDesc3 = "Scarf";  Not realistic if 100s of items!  Much better! // Using an array String[] items = {"Shirt","Trousers","Scarf"};  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Think about how your code would look if there were multiple items in the shopping cart. You would have to initialize each item description separately. Imagine if you had a thousand items! As you continued to build out this shopping cart application, the amount of code needed to handle each item individually would not only be time-consuming, but would make your code hard to read and difficult to maintain. The code example above shows a better alternative that we will explore now: the array.  Java SE8 Fundamentals 5 - 12  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Introduction to Arrays • • • •  An array is an indexed container that holds a set of values of a single type. Each item in an array is called an element. Each element is accessed by its numerical index. The index of the first element is 0 (zero). – A four-element array has indices: 0, 1, 2, 3. 0 27  1  2  3  12  82  70  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The array is a container that holds a set of String values, or a set of int values, or a set of double values, and so on. The elements (items) of the array are accessed through a numeric index. Using this index, you can set or get a value from a specific element.  Java SE8 Fundamentals 5 - 13  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Array Examples Array of int types 27  12  82  70  54  1  30  34  Array of String types  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Arrays can be of any data type, but all elements have to share the same type.  Java SE8 Fundamentals 5 - 14  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Array Indices and Length  The ages array has eight elements. First index  Element at index 5  00  1  2  3  4  5  6  7  27  12  82  70  54  11  30  34  Indices  Array length is 8. (ages.length)  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  •  •  •  An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, the length of an array cannot be changed. Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the diagram above, index numbering begins with 0. For example, the eighth element would be accessed at index 7. The length of an array can be accessed using dot notation to access the length field. Assuming that the array in the diagram is called ages, you can determine how many elements are in the array by using: int agesLength = ages.length;  Java SE8 Fundamentals 5 - 15  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Declaring and Initializing an Array •  Syntax:  type[] arrayIdentifier = {comma-separated list of  •  values};  Declare arrays of types String and int:  String[] names = {"Mary", "Bob", "Carlos"}; int[] ages = {25, 27, 48};  All in one line  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In this slide, you see the syntax and an example of how to declare the array and initialize the values. (This assumes that you know at this time what the values will be). • Syntax for declaring an array: type [] arrayIdentifier = {comma-separated list of values}; -  Note: Another acceptable syntax is: type arrayIdentifier[] = {commaseparated list of values};  where: • type represents the data type for each of the values stored in the array • [ ] informs the compiler that you are declaring an array • arrayIdentifier is the variable name that you use when you refer to the array • You can list as many values as you need. Separate the values with a comma.  Java SE8 Fundamentals 5 - 16  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Declaring and Initializing an Array • 1 2 3 4 5 6 7 8 9  Examples: int[] ages = new int[3]; ages[0] = 19; Multistep ages[1] = 42; approach ages[2] = 92; String[] names[0] names[1] names[2]  names = new String[3]; = "Mary","Bob","Carlos"; = "Mary","Bob","Carlos"; = "Mary","Bob","Carlos";  Multistep approach  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In this example, the int array, ages, is instantiated with a size of 3 on line 1. The creation of the array uses the new keyword. You will learn much more about the purpose of this keyword in the lesson titled "Describing Objects and Classes." On lines 2 through 4, the elements of the ages array are initialized. Likewise, on line 6, the String array, names, is instantiated with a size of 3, and its elements are initialized on lines 7 through 9.  Java SE8 Fundamentals 5 - 17  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Accessing Array Elements •  Get values from the ages array: int[] ages = {25, 27, 48}; int myAge = ages[0]; int yourAge = ages[1]; System.out.println("My age is " + ages[0]);  •  Set values from the names array: String[] names = {"Mary", "Bob", "Carlos"}; names[0] = "Gary"; names[1] = "Rob";  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Elements of the array are accessed by referencing the index of that element. For example: • To get the value from the first element of the ages array, use ages[0]. • To get the value from the second element of the ages array, use ages[1]. • You can directly use the value of an array element in an expression by using the same syntax. In the third example, you see ages[0] referenced directly when calling System.out.println. • To set a value in the first element of the names array, use names[0] = "some value".  Java SE8 Fundamentals 5 - 18  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 5-2: Using an Array In this exercise, you declare and initialize a String array to hold names. Then you experiment with accessing the array: • Declare a String array, names, and initialize it with four String values. • Print the number of items the customer wants to buy. • Print one of the array elements.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  • •  Open the Java Code Console and access Lessons > 05-ConditionsLoopsArrays > Exercise2 In the ShoppingCart class, follow the instructions below the code editor to: - Declare and initialize a String array to hold four distinct String values. - Change the message variable to reflect not only the customer name, but a message that includes the number of items the customer wants to purchase. (Hint: Use the length property of the array.) - Print the message. - Print the third element of the names array. - Run the file. - Change the element index number in the print statement to 4 and run the file again. You will get an error. Why?  Note: If you need help, the solution for this exercise can be found by the clicking the Solution link.  Java SE8 Fundamentals 5 - 19  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Why does the following code not compile? Select all that apply. int[] lengths = {2, 4, 3.5, 0, 40.04}; a. lengths cannot be used as an array identifier. b. All of the element values should have the same format (all using double values, or all using int values). c. The array was declared to hold int values. double values are not allowed.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: c a is incorrect because lengths is a perfectly valid array identifier. b is incorrect because it implies that this array could contain elements of type double. c is correct.  Java SE8 Fundamentals 5 - 20  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Given the following array declaration, which of the following statements are true? int[] classSize = {5, 8, 0, 14, 194}; a. classSize[0] is the reference to the first element in the array. b. classSize[5] is the reference to the last element in the array. c. There are 5 integers in the classSize array. d. classSize.length = 5  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: a, c, d a is correct. b is incorrect because the array index begins with 0. Thus, the index for the last element is one less than the total number of elements. c is correct. d is correct.  Java SE8 Fundamentals 5 - 21  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Loops Loops are used in programs to repeat blocks of statements • Until an expression is false or  •  For a specific number of times: – I want to print each element of an array. – I want to print each element of an ArrayList. (The ArrayList class is covered in the lesson titled "Working with Arrays, Loops, and Dates."  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE8 Fundamentals 5 - 23  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Processing a String Array Loop accesses each element in turn.  names array of String types George  Jill  Xinyi  Ravi  for (String name : names ) { System.out.println("Name is " + name); }  Each iteration returns the next element of the array.  Output: Name Name Name Name  is George is Jill is Xinyi is Ravi  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The for loop syntax is: for (                                          :                      ) {                                                  } where: • for indicates that a loop is being defined •                                                      is the data type of each of the elements within the array •                                                          is a placeholder used to store each element of an array • : indicates that the object reference that follows is an array •                                                              is the array, whose length determines the number of iterations to perform • code_block is the code that will be executed in each iteration of the loop In the example above, there are four elements in the names array. Therefore, the code block will be executed four times. Each time, the name variable holds a different array element.  Java SE8 Fundamentals 5 - 24  Using break with Loops  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  break example: 01 02 03 04 05 06 07 08 09 10  int passmark = 12; boolean passed = false; int[] scores = {4,6,2,8,12,35,9}; for (int unitScore : scores){ No need to go if (unitScore >= 12){ passed = true; through the loop again, so use break. break; } } System.out.println("At least one passed? " +passed);  Output: At least one passed? true  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Occasionally, some condition occurs that makes it unnecessary to continue the loop. The break keyword enables you to do this. When break is encountered, the program execution moves to the first line of code outside the for block. • The example in the slide shows the use of break. You will notice that it uses an if statement within the for block. This if statement is executed on each iteration of the loop. • Assuming that the purpose of the code is to find out whether any of the scores in the array are equal or above the passmark, you can set passed to true and jump out of the loop as soon as the first such score is found. • When break is called on line 7, execution of the program skips to line 10.  Java SE8 Fundamentals 5 - 25  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 5-3: Using a Loop to Process an Array In this exercise, you loop through an array called itemPrices to print a message indicating each item price.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  • •  Open the Java Code Console and access Lessons > 05-ConditionsLoopsArrays > Exercise3 Follow the instructions below the code editor to process the itemPrices array.  Note: If you need help, the solution for this exercise can be found by clicking the Solution link.  Java SE8 Fundamentals 5 - 26  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Given the following code, int[] sizes = {4, 18, 5, 20}; for (int size : sizes){ if (size > 16){break;} System.out.println("Size: "+size + ", "); }  which option below shows the correct output? a.  Size: 4,  b. c.  Size: 4 Size: 4, Size: 5,  d. There is no output.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: a a is correct. b is incorrect because the comma appears within each println method. c is incorrect because when the first size greater than 16 is found, the loop breaks and does not return. d is incorrect because the first iteration of the loop would print.  Java SE8 Fundamentals 5 - 27  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Summary In this lesson, you should have learned how to: • Use a Boolean expression • Create a simple if/else block • Describe the purpose of an array • Declare and initialize a String or int array • Access the elements of an array • Explain the purpose of a for loop • Iterate through a String Array using a for loop  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE8 Fundamentals 5 - 28  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Play Time! Play Basic Puzzles 1 through 5 before the lesson titled "Describing Objects and Classes." Your Goal: Design a solution that deflects the ball to Duke.  Consider the following: What happens when you put a triangle wall or simple wall icon on the blue wheel?  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  You are welcome to play beyond Basic Puzzle 5. Puzzles beyond Basic.05 are associated with later lessons.  Java SE8 Fundamentals 5 - 29  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  About Java Puzzle Ball • • • • • •  It is used throughout the course. Play a set of puzzles. Become familiar with the game mechanics. Consider a question as you play. The lesson titled "Describing Objects and Classes" debriefs on what you have observed. Apply your observations to understand Java concepts.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  At certain points throughout the course, you will be asked to play levels of Java Puzzle Ball. The game reflects Java concepts through game mechanics. It's more important to become familiar with these mechanics than it is to solve every puzzle. Don't worry if the connection between game mechanics and Java concepts is not immediately apparent. You will debrief in future slides and realize the connection during this debriefing. As you develop an understanding for how the game works, you will be able to apply what you have learned as a foundation for understanding difficult Java concepts.  Java SE8 Fundamentals 5 - 30  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Interactive Quizzes  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Before you start today's lessons, test your knowledge by answering some quiz questions that relate to yesterday's lessons. Open your quiz file from labs > Quizzes > Java SE 8 Fundamentals Quiz.html. Click the links for Lessons 1, 2, 3, 4, and 5.  Java SE 8 Fundamentals 6 - 2  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Objectives After completing this lesson, you should be able to: • List the characteristics of an object • Define an object as an instance of a class • Instantiate an object and access its fields and methods • Describe how objects are stored in memory • Instantiate an array of objects • Describe how an array of objects is stored in memory • Declare and instantiate an object as a field • Use the NetBeans IDE to create and test Java classes  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 3  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • • •  Describing objects and classes Defining fields and methods Declaring, instantiating, and using objects Working with object references Doing more with arrays Introducing NetBeans IDE Introducing the soccer league use case  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 4  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Puzzle Ball Have you played Basic Puzzle 5? Consider the following: What happens when you put a triangle wall or simple wall icon on the blue wheel?  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 5  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Puzzle Ball Debrief What happens when you put a triangle wall or simple wall icon on a blue wheel? • A wall appears on every instance of a blue bumper object. • Walls give bumpers behaviors that deflect and interact with the ball. • All blue bumper instances share these same behaviors. instance instance  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  A blue bumper is an object, and every instance of these objects will share the same behavior for interacting with the ball. These behaviors may include deflection via triangle or the simple wall.  Java SE 8 Fundamentals 6 - 6  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Object-Oriented Programming • •  Interaction of objects No prescribed sequence  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  You have seen this diagram before in the "What Is a Java Program?" lesson. The diagram illustrates how object-oriented programming stresses the interaction of objects. The current lesson teaches you how to identify the objects that are required for the application that you would like to build. You first identify what the objects are, you determine the object's characteristics or properties, and then you determine the object's behaviors or operations. You then translate that analysis into Java code to create your application. It is time to learn more about objects.  Java SE 8 Fundamentals 6 - 7  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Duke's Choice Order Process  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the first five lessons, the exercises mention a shopping cart class that contains items. Take another look at the shopping cart scenario. Imagine an online store called Duke's Choice. His number one shopper is his mother, Mrs. Duke. As Mrs. Duke shops, she places items in a shopping cart. Mrs. Duke likes shirts, so she places shirts in her cart. After she fills the cart, she checks out. The checkout process applies the purchase to a credit card, which is verified, and then Mrs. Duke receives an order number so that she can track her order or return it. As a software developer, when you are presented with a scenario such as Duke's Choice for an application that you need to develop, you can analyze the scenario by breaking it into steps and defining the objects of the scenario.  Java SE 8 Fundamentals 6 - 8  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Characteristics of Objects Objects are physical or conceptual. • Objects have properties: – – – –  •  Size Shape Name Color  Objects have behaviors:  Mrs. Duke Color property value is red  – Shop – Put item in cart – Pay  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  To validate objects in a problem domain, such as the Duke's Choice order process, you identify the properties of all objects: • Objects can be physical or conceptual. A customer's credit card account is an example of a conceptual object, because it is not something you can physically touch. A shirt is an example of a physical object. • Objects have properties (attributes) such as size, name, and shape that represent the state of the object. For example, a person has a name (Mrs. Duke), and an object might have a color property. The value of all of an object's properties is often referred to as the object's current state. An object might have a color property with the value of red and a size property with a value of large. • Objects also have behaviors (things they can do) such as, in our example, shop, put an item in the cart, and purchase.  Java SE 8 Fundamentals 6 - 9  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Classes and Instances •  A class: – Is a blueprint or recipe for an object – Describes an object's properties and behaviors – Is used to create object instances  Object instances  Class -Properties -Behaviors  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  You just learned about some of the objects, characteristics, and behaviors in the Duke's Choice scenario. Here is an example of one of Duke's Choice objects, the Customer, and its function in the store. Customer is the class, and a class is a blueprint or recipe for an object. The class describes an object's properties and behaviors. Classes are used to create object instances, such as the three Customer object instances, as illustrated by the three images.  Java SE 8 Fundamentals 6 - 10  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Which of the following statements is true? a. An object is a blueprint for a class. b. An object and a class are exactly the same. c. An object is an instance of a class. d. A class is an instance of an object.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: c • • • •  a is false because a class is a blueprint for an object. b is false because an object is an instantiation of a class, and a class serves as a blueprint for the object. c is correct. d is false because an object is an instance of a class.  Java SE 8 Fundamentals 6 - 11  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • • •  Describing objects and classes Defining fields and methods Declaring, instantiating, and using objects Working with object references Doing more with arrays Introducing NetBeans IDE Introducing the soccer league use case  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  You have just learned about objects, classes, and their characteristics (properties and behaviors). Now it is time to look at fields and methods.  Java SE 8 Fundamentals 6 - 12  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  The Customer Properties and Behaviors  Properties: • Name • Address • Age • Order number • Customer number  Behaviors: • Shop • Set Address • Add item to cart • Ask for a discount • Display customer details  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Think of some properties and behaviors that are in the Customer class of Duke's Choice. Think about how you would write this information as a Java class.  Java SE 8 Fundamentals 6 - 13  The Components of a Class  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Class declaration  1 public class Customer { 2 public String name = "Junior Duke"; 3 public int custID = 1205; public String address; 4 public int orderNum; 5 6 public int age; 7 8 public void displayCustomer(){ 9 System.out.println("Customer: "+name); 10 } 11 }  Fields (Properties) (Attributes)  Methods (Behaviors)  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the previous slide, you have identified some properties and behaviors that might be in the Customer class. This code example demonstrates how the properties and methods are created in Java. The basic components of a Java class are: • The class declaration. Notice that the entire class is surrounded by braces. • Fields of the class. These represent the properties or attributes of the class. • Methods of the class. These represent the behaviors or operations. Here you see just one method, displayCustomer. Note: In the code example above, the word "public" is a modifier, and you learn about modifiers later in the course.  Java SE 8 Fundamentals 6 - 14  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Modeling Properties and Behaviors  Class name  Customer class name address billing info age customer number order number requestDiscount() setAddress() shop() displayCustomer()  Fields  Methods  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  As you design an application, it is often helpful to create a simple model that describes the components of a class. In the table above, the class name is listed at the top. The properties or fields are listed in the second row, and the behaviors, or methods, are listed in the third row. If you compare this modeling in terms of language, you can think of the class as a noun, the properties or fields as adjectives, and the behaviors or methods as verbs.  Java SE 8 Fundamentals 6 - 15  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 6-1: Creating the Item Class In this exercise, you create the Item class and declare public fields for ID (int), descr, quantity (int), and price (double).  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  •  In the Java Code Console, access Lessons > 06-Objects > Exercise1.  •  Follow the instructions below the code editor to create the Item class and declare public fields for ID (int), descr, quantity (int), and price (double). You will not be able to test the Item class until Exercise 6-2. If you need help, click the Solution link. To go back to your code, click the Exercise link again. Any changes that you have made will have been saved.  •  Java SE 8 Fundamentals 6 - 16  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • • •  Describing objects and classes Defining fields and methods Declaring, instantiating, and using objects Working with object references Doing more with arrays Introducing NetBeans IDE Introducing the soccer league use case  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 17  Customer Instances  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  customer01  customer02 public static void main(String[] args){ Customer customer01 = new Customer(); Customer customer02 = new Customer();  Create new instances (instantiate).  customer01.age = 40; customer02.name = "Duke";  Fields are accessed.  customer01.displayCustomer(); customer02.displayCustomer(); }  Methods are called.  }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the code example, two new instances of the Customer object called customer01 and customer02 are created. (Another term for created is "instantiated.") After the objects are instantiated, the reference variables customer01 and customer02 can be used to access fields and methods of the objects. The next two slides explain variations on instantiation, and the dot operator. There is more information on methods in the lesson titled "Creating and Using Methods."  Java SE 8 Fundamentals 6 - 18  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Object Instances and Instantiation Syntax variable becomes a reference to that object. The new keyword creates (instantiates) a new instance.  The syntax is:                                                                  variable = new                                  () public static void main(String[] args){ Customer customer01 = new Customer();  //Declare and instantiate  Customer customer02; customer02 = new Customer();  //Declare the reference //Then instantiate  new Customer();  //Instantiation without a reference //We can't use this object later //without knowing how to reference it.  } }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  By using the new keyword, a new instance of the class is now available to be accessed through the variable, which stores a reference to that object. It can be referred to as a reference variable or an object reference. Notice that, following the new keyword, you see the class name followed by parentheses. This looks similar to calling a method, doesn't it? You are calling a method—the constructor method of the Customer class. Every class has a constructor method that has the same name as the class. Constructors are covered in more detail in the lesson titled "Creating and Using Methods." To summarize, there are three steps to getting an object reference: 1. Declare the reference. 2. Instantiate the object using the new keyword and the class constructor method. 3. Assign the object to the reference. Note that the way that the assignment operator (an = symbol) works requires that the reference and the newly created object must be in the same statement. (Statements are ended with the semicolon symbol and are not the same as lines. The end of a line means nothing to the Java compiler; it only helps make the code more readable.)  Java SE 8 Fundamentals 6 - 19  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  The Dot (.) Operator Follow the reference variable with a dot operator (.) to access the fields and methods of an object. public static void main(String[] args){ Customer class  Customer customer01 = new Customer();  name address billing info age customer number order number  //Accessing fields System.out.println(customer01.name); customer01.age = 40; //Calling methods customer01.requestDiscount(); customer01.displayCustomer();  requestDiscount() setAddress() shop() displayCustomer()  } }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 20  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Objects with Another Object as a Property Customer class  Cart class  customer number *cart name address billing info order number  Item[] date total  requestDiscount() setAddress() shop() displayCustomer()  addItem() checkOut() cancel()  public static void main(String[] args){ Customer customer01 = new Customer(); customer01.cart.cancel();  //How to access methods of an //object within another object  }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  So far you have seen objects with properties such as boolean, int, double, and String. What if you wanted an object's property to be another object with its own set of properties and behaviors, such as a costumer with a cart property? That way, an instance of a Customer would have access to the properties and behaviors found in a Cart. This would enable the customer to add items to the cart and then checkOut (purchase) the cart. Can this be done? The answer is yes. You can access fields and methods of objects within another object by applying the dot operator multiple times. Note: A best practice is to use attribute and operation names that clearly describe the attribute or operation. The asterisk (*) denotes an attribute that is a reference to another object.  Java SE 8 Fundamentals 6 - 21  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Which of the following lines of code instantiates a Boat object and assigns it to a sailBoat object reference? a. Boat sailBoat = new Boat(); b. Boat sailBoat; c. Boat = new Boat() d. Boat sailBoat = Boat();  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: a  Java SE 8 Fundamentals 6 - 22  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • • •  Describing objects and classes Defining fields and methods Declaring, instantiating, and using objects Working with object references Doing more with arrays Introducing NetBeans IDE Introducing the soccer league use case  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 23  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Accessing Objects by Using a Reference  The camera is like the object that is accessed using a reference.  The remote is like the reference used to access the camera.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  What you have learned up to this point is: • Objects are accessed using references. • Objects are instantiated objects of their class type. • Objects consist of properties and operations, which in Java are fields and methods. To work with an object, you need to access it using a reference. A good analogy is using a remote control to operate an electronic device. The buttons on the remote control can be used to modify the behavior of the device (in this case, a camera). For example, you can make the camera stop, play, or record by interacting with the remote.  Java SE 8 Fundamentals 6 - 24  Working with Object References 1  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  1  Pick up the remote to gain access to the camera.  Create a Camera object and get a reference to it.  11 Camera remote1; 12 13 remote1 = new Camera(); 14 15 remove1.play();  2  Press the remote's controls to have camera do something.  2  Call a method to have the Camera object do something.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Consider the analogy of using a remote control to operate an electronic device. To operate an electronic device with a remote, you need to: 1. Pick up the remote (and possibly turn it on) 2. Press a button on the remote to do something on the camera Similarly, to do something with a Java object, you need to: 1. Get its "remote" (called a reference) 2. Press its "buttons" (called methods)  Java SE 8 Fundamentals 6 - 25  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Working with Object References  remote2  remote1  12 13 14 15 16 17 18  Camera remote1 = new Camera(); Camera remote2 = new Camera();  There are two Camera objects.  remote1.play(); remote2.play();  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  There are two camera objects in this example. Each camera has its own unique remote. remote2 will not work on remote1's camera, and remote1 will not work on remote2's camera. This reflects how in Java, two different objects can be instantiated with their own unique references. These references can be used to call methods on their respective objects.  Java SE 8 Fundamentals 6 - 26  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Working with Object References  There is only one Camera object. remote2  remote1  12 13 14 15 16 17 18  Camera remote1 = new Camera(); Camera remote2 = remote1; remote1.play(); remote2.stop();  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The diagram shows another important aspect of how references work. In this example, a Camera object is created and its reference assigned to a Camera reference, remote1. This reference is then assigned to another Camera reference, remote2. Now both references are associated with the same Camera object, and methods called on either reference will affect the same Camera object. Calling remote1.play is no different than calling remote2.play. Both remotes operate the same camera.  Java SE 8 Fundamentals 6 - 27  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  References to Different Objects  Television  Camcorder  Camcorder remote  Television remote  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  To extend the analogy just a little further, to work with a different type of object (for example, a television), you need a remote for that object. In the Java world, you need a reference of the correct type for the object that you are referencing. You can ignore the fact that there is such a thing as a universal remote controller, although later in the course you will discover that Java also has the concept of references that are not limited to a single object type! For the moment, let's just say that a reference of the same type as the object is one of the reference types that can be used, and is a good place to start exploring the world of Java objects.  Java SE 8 Fundamentals 6 - 28  References to Different Objects  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Reference type Reference variable Create a new object. 6 7 8 9 10 11 12 13 14 15 16  Camera remote1 = new Camera(); remote1.menu(); TV remote2 = new TV(); remote2.menu(); Shirt myShirt = new Shirt(); myShirt.display(); Trousers myTrousers = new Trousers(); myTrousers.display();  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  remote1 references a Camera object. remote2 references a TV object. myShirt references a Shirt object. myTrousers references a Trousers object.  Java SE 8 Fundamentals 6 - 29  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  References and Objects in Memory 12 int counter = 10; 13 Shirt myShirt = new Shirt(); 14 Shirt yourShirt = new Shirt();  Sta ck  Heap  0x034009  15.99  shirtID price  B  colorCode  12  counter  10  myShirt  0x034009  yourShirt  0x99f311  0x99f311  Variables  shirtID  12 15.99  price  B  colorCode  Objects  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  This diagram shows how references point to a particular object in memory. Note that there are two objects in memory, although they are both of type Shirt. Also note that there are two Shirt references pointing to these two Shirt objects. The diagram also shows two types of memory that Java uses: the stack and the heap. The stack holds local variables, either primitives or reference types, whereas the heap holds objects. Later in this course, you will learn a little more about local variables, but for now it is sufficient to know that local variables are not fields of an object.  Java SE 8 Fundamentals 6 - 30  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Assigning a Reference to Another Reference  myShirt = yourShirt;  0x034009 12 15.99 B  counter  10  0x99f311  myShirt  0x99f311  yourShirt  0x99f311  12  shirtID  15.99  price  B  colorCode  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The diagram shows what happens if the myShirt reference, after having its own object (in the previous slide), is now assigned the reference yourShirt. When this happens, the myShirt reference will drop its current object and be reassigned to the same object that yourShirt has. As a result, two references, myShirt and yourShirt, now point to the same object. Any changes to the object made by using one reference can be accessed using the other reference, and vice versa. Another effect of assigning the reference yourShirt to the reference myShirt is that if the previous object referred to by myShirt has no other references, it will now be inaccessible. In due course, it will be garbage collected, meaning that its memory will become available to store other objects.  Java SE 8 Fundamentals 6 - 31  Two References, One Object  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Code fragment: 12 13 14 15 16 17 18 19 20  Shirt myShirt = new Shirt(); Shirt yourShirt = new Shirt(); myShirt = yourShirt;  //The old myShirt object is //no longer referenced  myShirt.colorCode = 'R'; yourShirt.colorCode = 'G'; System.out.println("Shirt color: " + myShirt.colorCode);  Output from code fragment: Shirt color: G  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  This example now shows what happens if you use either reference to make a change or get a value from the object. References yourShirt and myShirt refer to the same object, so making a change or getting a field value by using one reference is exactly the same as doing it with the other reference. The old object that was previously referenced by myShirt goes away.  Java SE 8 Fundamentals 6 - 32  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 6-2: Modify the ShoppingCart to Use Item Fields •  In this exercise, you: – Declare and instantiate two variables of type Item in the ShoppingCart class – Experiment with accessing properties and calling methods on the object  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  •  In the Java Code Console, access Lessons > 06-ObjectsClasses > Exercise2.  •  Follow the instructions below the code editor to: - Declare and instantiate two variables of type Item. - Initialize only the desc field.  •  - Use different values for each object. - Display the description of each object. If you need help, click the Solution link. To go back to your code, click the Exercise link again. Any changes that you have made will have been saved.  Java SE 8 Fundamentals 6 - 33  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • • •  Describing objects and classes Defining fields and methods Declaring, instantiating, and using objects Working with object references Doing more with arrays Introducing NetBeans IDE Introducing the soccer league use case  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 34  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Arrays Are Objects Arrays are handled by an implicit Array object. • The Array variable is an object reference, not a primitive data type. • It must be instantiated, just like other objects. – Example: int[] ages = new ages[4];  •  This array can hold four elements.  Previously, you have been using a shortcut to instantiate your arrays. – Example: int[] ages = {8,7,4,5};  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  An array is actually an object type and is handled implicitly through a class called Array (not available in the Java API documentation). Therefore, like other object types (String is an exception) it must be instantiated using the new keyword. • In the top example, an int array called ages is declared and instantiated with a capacity to hold four elements.  Java SE 8 Fundamentals 6 - 35  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Declaring, Instantiating, and Initializing Arrays • 1 2 3 4 5 6  •  All in one line  Examples:  String[] names = {"Mary","Bob","Carlos"}; int[] ages = new int[3]; ages[0] = 19; ages[1] = 42; ages[2] = 92;  Multistep approach  Not permitted (compiler will show an error): int [] ages; ages = {19, 42, 92};  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  As introduced in the lesson titled "Managing Multiple Items," there are two approaches for creating and initializing arrays. Using the new keyword allows you to declare and instantiate an array of a particular size and initialize it at a later time.  Java SE 8 Fundamentals 6 - 36  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Storing Arrays in Memory  int age = 35; int[] ages = {19, 42, 92};  Primitive variable of type int 0x034009 age  35  ages  0x034009  0  19  1  42  2  92  Primitive variables of type int held as array elements  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Arrays are objects referred to by an object reference variable. The diagram in the slide illustrates how a primitive array is stored in memory in comparison to how a primitive data type is stored in memory. The value of the age variable (an int primitive) is 35. The value of ages is 0x034009, an object reference pointing to an object of type array (of int types) with three elements. • • •  The value of ages[0] is 19. The value of ages[1] is 42. The value of ages[2] is 92.  Java SE 8 Fundamentals 6 - 37  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Storing Arrays of Object References in Memory Item item = new Item(); Item[] items = { new Item(), new Item(), new Item() };  item  0x034009  items  0x99f311  0x99f311 0x00099 0x00327 0x00990  0 0.0 U  itemId price colorCode  0 0.0 U  itemId price colorCode  0 0.0 U  itemId price colorCode  0 0.0 U  itemId price colorCode  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The diagram in the slide illustrates how an object reference array is stored in memory. The value of the item object reference is x034009, which is an address to an object of type Item with the values 0, 0.0, and U. The value of the items[ ] object reference is x99f311, which is an address to an object of type Array (of Item object references) containing three object references: • The value of the items[0] index is 0x00099, which is an object reference pointing to an object of type Item. • The value of the items[1] index is 0x00327, which is an object reference pointing to another object of type Item. • The value of the items[2] index is 0x00990, which is an object reference pointing to another object of type Item.  Java SE 8 Fundamentals 6 - 38  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz The following code is the correct syntax for an array: array_identifier = new type[length]; a. b. c. d.  Declaring Setting array values for Instantiating Declaring, instantiating, and setting array values for  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: c a is incorrect. Declaring the array would look like this, assuming an array of object types: Type[] array_identifier; b is incorrect. Setting array values would look like this, assuming an array of object types: array_identifier[0]= new Type(); c is correct. The code example shows the array being initialized to a specific size. d is incorrect. Declaring, instantiating, and setting array values would look like this, assuming an array of object types: Type[] array_identifier = {new Type(), new Type(), new Type()};  Java SE 8 Fundamentals 6 - 39  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Given the following array declaration, which of the following statements are true? int [ ] ages = new int [13];  a. ages[0] is the reference to the first element in the array. b. ages[13] is the reference to the last element in the array. c. There are 13 integers in the ages array. d. ages[5] has a value of 0.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: a, c, d  Java SE 8 Fundamentals 6 - 40  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • • •  Describing objects and classes Defining fields and methods Declaring, instantiating, and using objects Working with object references Doing more with arrays Introducing NetBeans IDE Introducing the soccer league use case  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 41  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java IDEs A Java Integrated Development Environment (IDE) is a type of software that makes it easier to develop Java applications. • An IDE provides: – Syntax checking – Various automation features – Runtime environment for testing  •  It enables you to organize all your Java resources and environment settings into a Project.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Some well-known Java IDEs are NetBeans (used in this class to perform the practices), Eclipse, and JDeveloper.  Java SE 8 Fundamentals 6 - 42  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  The NetBeans IDE Project Navigator  Code Editor  Class Navigator  Program Output  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The Java project provides a mechanism by which you can organize all of the source and class files and other resources (connection profiles, configuration information, and so on) required by the Java application. • When you begin working in NetBeans, you either create a project or open an existing one. • The Project Navigator gives you a visual representation of the project contents. • You can open files from your project in the code editor by double-clicking the file or using the context menu. When you select a class within the project, the structure of that class is displayed in the Class Navigator, shown in the lower left part of the NetBeans window. When you run a file or the entire Java program, any program output appears in the Output panel in the lower right part of the window.  Java SE 8 Fundamentals 6 - 43  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Creating a Java Project 1. Select File > New Project. 2. Select Java Application. 3. Name and set the location for the project. 4. Select "Create Main Class" if you want it done for you automatically. 5. Click Finish.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  A NetBeans project is a mechanism for organizing the related files and resources used in a Java Application. To create a new project, perform the following steps: 1. Select File > New Project from the menu. 2. On the first page of the New Project Wizard (not shown here), select Java as the category and Java Application as the project type. Click Next. 3. On the second page of the wizard (shown above), enter a name for the project, and then enter or browse to the directory location to store project files. 4. It is possible to have NetBeans automatically generate a main class for the project. 5. Click Finish.  Java SE 8 Fundamentals 6 - 44  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Creating a Java Class 1. 2. 3. 4. 5.  Select File > New File. Select your project and choose Java Class. Name the class. Assign a package. Click Finish.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  To create a class within your new project, perform the following steps: 1. Select File > New File from the menu. 2. On the first page of the New File Wizard, select your project, and then accept the default file type of Java Class. Click Next. 3. On the next page of the wizard, enter a name for the Java class. By convention, Java classes should start with an uppercase letter and each subsequent word in the class name should be capitalized (for example, SayHello). This is illustrated in the screenshot above. 4. Assign a package for the class. 5. Click Finish. Note: If the package for this new class already exists, you can create the class by right-clicking the package in the Project Navigator panel in NetBeans and selecting New > Java class from the context menu instead of starting from the File menu.  Java SE 8 Fundamentals 6 - 45  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Avoiding Syntax Problems The code editor will tell you when you have done something wrong.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Most Java editors check the code syntax and show alerts by using icons and red underlines where there are errors in the code. To avoid syntax problems, be sure to do the following: • Observe any red bubble indicators in the code editor to locate syntax errors. • Have a semicolon at the end of every line where one is required. • Have an even number of symbols such as braces, brackets, and quotation marks. The screenshot shows an error in Line 13, in which there is a missing semicolon. If you place your cursor over the red bubble, the editor offers a suggestion for fixing the error.  Java SE 8 Fundamentals 6 - 46  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Compile Error: Variable Not Initialized 1 public static void main(String[] args){ 2 3 Customer customer01; //Declare the reference 4 //No instantiation 5 customer01.name = "Robert"; 9 10 }  NetBeans indicates that the variable may not have been initialized.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  If you try to use a reference that has been declared but has had no object assigned to it, the class will not compile. This is because there is no Customer object assigned to the customer01 reference. NetBeans will flag this, and indicate that "the variable may not have been initialized."  Java SE 8 Fundamentals 6 - 47  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Runtime Error: NullPointerException 1 public static void main(String[] args){ 2 3 Customer customer01; //Declare the reference 4 customer01 = new Customer(); //Instantiate and assign customer01.name = "Robert"; 5 6 7 Customer[] customers = new Customer[5]; 8 customers[0].name = "Robert"; 9 10 }  This reference has not been assigned.  NetBeans output window indicates a NullPointerException.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  If an array has been created but the individual elements have had no objects assigned, the class will compile, but you will get a runtime error. The error is a NullPointerException. Later in the lesson titled "Handling Exceptions," you will learn exactly what this means; for now it is just important to recognize that a NullPointerException indicates that a reference has no object assigned; that it is null.  Java SE 8 Fundamentals 6 - 48  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Compiling and Running a Program by Using NetBeans  Save is equivalent to javac. Run is equivalent to java. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Save invokes the javac                                                                          command for all .java files in the project. Rightclicking the source code and selecting Run File invokes the java                                                                              command. Be sure to look for red bubble indicators in the code editor to locate syntax errors.  Java SE 8 Fundamentals 6 - 49  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • • •  Describing objects and classes Defining fields and methods Declaring, instantiating, and using objects Working with object references Doing more with arrays Introducing NetBeans IDE Introducing the soccer league use case  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 50  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Soccer Application Practices 6 through 14 build a soccer league application with the following features: • Any number of soccer teams, each with up to 11 players • Set up an all-play-all league. • Use a random play game generator to create test games. • Determine the rank order of teams at the end of the season.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the remaining practices in this course, you will build an application that manages a Soccer League. The application will keep details on teams and players, as well as the results of games. You will also write code that will randomly generate game results so that you can then develop code to list the Teams in rank order.  Java SE 8 Fundamentals 6 - 51  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Creating the Soccer Application A separate project for each practice  Sample output showing events in a game  Sample output showing rank order of teams  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Initially, your application will be developed in NetBeans and you will see the results of running your code as text in the output window.  Java SE 8 Fundamentals 6 - 52  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Soccer Web Application  Teams listed in rank order  Click the score of a game to show game details.  Points and goals scored used for ordering  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The code that you write in the practices can be used by a simple web application to view the results of games in the league. You will see a demonstration of this.  Java SE 8 Fundamentals 6 - 53  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Summary In this lesson, you should have learned how to: • Describe the characteristics of a class • Define an object as an instance of a class • Instantiate an object and access its fields and methods • Describe how objects are stored in memory • Instantiate an array of objects • Describe how an array of objects is stored in memory • Declare an object as a field • Use the NetBeans IDE  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 54  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Challenge Questions: Java Puzzle Ball • • • •  How many objects can you identify in the game? Given that a class is a blueprint for an object, which game components best reflect the class/instance relationship? How many object properties can you find? Can you guess what some of the methods might be?  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  When you have an opportunity to play the game, see if you can answer these questions, applying the object-oriented concepts that you learned in this lesson. For some possible answers to these questions and more discussion, see "Appendix A: Java Puzzle Ball Challenge Questions Answered."  Java SE 8 Fundamentals 6 - 55  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Practice 6-1 Overview: Creating Classes for the Soccer League This practice covers creating the five classes required for the soccer application: • Goal • Game • Player • Team • League  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 56  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Practice 6-2 Overview: Creating a Soccer Game This practice covers the following topics: • Creating a new game • Adding some goals  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 6 - 57  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Objectives After completing this lesson, you should be able to: • Describe the String class and use some of the methods of the String class • • • •  Use the JDK documentation to search for and learn how to use a class Describe the StringBuilder class Explain what a constant is and how to use it Explain the difference between promoting and casting of variables  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 7 - 2  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • •  Using the String class Using the Java API docs Using the StringBuilder class Doing more with primitive data types Using the remaining numeric operators Promoting and casting variables  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 7 - 3  String Class  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  String hisName = "Fred Smith";  Standard syntax  The new keyword can be used, but it is not best practice: String herName = new String("Anne Smith");  •  A String object is immutable; its value cannot be changed.  •  A String object can be used with the string concatenation operator symbol (+) for concatenation.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  •  •  The String class is one of the many classes included in the Java class libraries. The String class provides you with the ability to store a sequence of characters. You will use the String class frequently throughout your programs. Therefore, it is important to understand some of the special characteristics of strings in the Java programming language. Because a String object is immutable, its value cannot be changed. (There are technical reasons, beyond the scope of this course, as to why this immutability is useful. One simple example is that this immutability ensures that a String can be used by several different classes safely because it cannot be changed.) Creating a String object using the new keyword creates two String objects in memory, whereas creating a String object by using a string literal creates only one object; therefore, the latter practice is more memory-efficient. To avoid the unnecessary duplication of String objects in memory, create String objects without using the new keyword.  Java SE 8 Fundamentals 7 - 4  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Concatenating Strings  String myString = "Hello";  0x034009  Hello  myString  0x034009  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Because String is immutable, concatenating two strings requires creating a new string. The diagram shows a String object containing the string "Hello".  Java SE 8 Fundamentals 7 - 5  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Concatenating Strings  String myString = "Hello"; myString = myString.concat(" World");  0x034009  "Hello"  0x99f311  myString  0x99f311  "Hello World"  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Here is the string " World" being concatenated to the original string. The concat method is being used here, but whether you use that or the concatenation operator (+), a new String object is created and a new String reference is returned that points to this new object. In the diagram, this is shown by the fact that the String reference myString is no longer 0x034009, and because that object is no longer referred to, it is now inaccessible and will be garbage collected.  Java SE 8 Fundamentals 7 - 6  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Concatenating Strings String myString = "Hello"; myString = myString.concat(" World"); myString = myString + "!"  0x99f311  "Hello World"  0x74cd23  myString  0x74cd23  "Hello World!"  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Finally, on concatenating another string, this time using the concatenation operator, the same thing happens again. A new object is created and the reference for this object is assigned to myString.  Java SE 8 Fundamentals 7 - 7  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  String Method Calls with Primitive Return Values A method call can return a single value of any type. • An example of a method of primitive type int: String hello = "Hello World"; int stringLength = hello.length();  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Like most classes, the String class has a number of useful methods. Almost all of these methods do their useful work by returning a single value (Java allows only a single return from a method). The return type (essentially the type of the method) can be a primitive or a reference to an object. To be able to use the return value in your code, you will typically use the assignment operator to assign the value (or reference) to a type that you have declared for this purpose. The example in the slide shows the use of reference hello to call the method length. Because the object this reference refers to is the string Hello World, this method call will return the value 11 and place it in the variable stringLength. int is the type of the method length.  Java SE 8 Fundamentals 7 - 8  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  String Method Calls with Object Return Values Method calls returning objects: String greet = " HOW ".trim(); String lc = greet + "DY".toLowerCase(); Or String lc = (greet + "DY").toLowerCase();  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  This example shows several method calls that return object references. First, the String object " HOW " is instantiated and has the method trim called on it. Because a string literal returns an object reference, this is exactly the same as calling the method trim on the reference. Notice that the string " HOW " has two spaces on either side of the word. The string returned will be just three characters long because these spaces will be removed. This new string will be referenced by greet. The next example shows a method call not being assigned to a type, but simply used in an expression. The method toLowerCase is called on the string "DY", returning "dy". lc now references an object containing "HOWdy". Finally, note how an alternative version with parentheses ensures that the two strings are concatenated (creating a new string) before toLowerCase is called. lc now references an object containing "howdy".  Java SE 8 Fundamentals 7 - 9  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • •  Using the String class Using the Java API docs Using the StringBuilder class Doing more with primitive data types Using the remaining numeric operators Promoting and casting variables  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 7 - 10  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java API Documentation Consists of a set of webpages; • Lists all the classes in the API – Descriptions of what the class does – List of constructors, methods, and fields for the class  • •  Highly hyperlinked to show the interconnections between classes and to facilitate lookup Available on the Oracle website at: http://download.oracle.com/javase/8/docs/api/index.html  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  All of the Java technology JDKs contain a series of prewritten classes for you to use in your programs. These Java technology class libraries are documented in the Java API documentation for the version of the JDK that you are using. The class library specification is a series of HTML webpages that you can load in your web browser. A Java class library specification is a very detailed document outlining the classes in the API. Every API includes documentation describing the use of classes and their fields and methods. When you are looking for a way to perform a certain set of tasks, this documentation is the best source for information about the classes in the Java class libraries. You learn more about constructors in the "Using Encapsulation" lesson.  Java SE 8 Fundamentals 7 - 11  Java Platform SE 8 Documentation  Select All Classes or a particular package. The classes for the selected package(s) are listed here.  Java SE 8 Fundamentals 7 - 12  Details about the class selected  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Platform SE 8 Documentation  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the screenshot in the slide, you can see the three main panels of the webpage. The top-right panel allows you to select a package. Java classes are organized into packages, but if you do not know the package of a particular class, you can select All Classes. The bottom-left panel gives the list of classes in a package, or all classes if that has been selected. In this panel, the class String has been selected, populating the main panel on the right with the details of the class String. The main panel on the right contains a lot of information about the class, so you need to scroll down to access the information you need.  Java SE 8 Fundamentals 7 - 13  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Platform SE 8: Method Summary public int charAt(String str) The type of the parameter that must The name of be passed into the method the method The return type of the method  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  If you keep scrolling through the details for the String class, you will come to the list of methods (only a small subset of this list is shown here). This master list of methods gives the basic details for the method. In this case, you can see that the name of the method is charAt, its type is char, and it requires an index (of type int) to be passed in. There is also a brief description that this method returns the char value at a particular index in the string. For any of the methods, the method name and the parameter types are hyperlinked so that you can get more details.  Java SE 8 Fundamentals 7 - 14  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Platform SE 8: Method Detail Click here to get the detailed description of the method.  Detailed description for the indexOf() method  Further details about parameters and return value are shown in the method list.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  For any of the methods, the method name and the parameter types are hyperlinked so that you can get more details. The example here shows the detailed description for one of the indexOf() methods of String.  Java SE 8 Fundamentals 7 - 15  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  indexOf Method Example  1 2 3 4 5 6 7  String phoneNum = "404-543-2345"; The 1-arg version int idx1 = phoneNum.indexOf('-'); System.out.println("index of first dash: "+ idx1); The 2-arg version int idx2 = phoneNum.indexOf('-', idx1+1); System.out.println("second dash idx: "+idx2);  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  This example shows how to get the location of the first '-' character by using the 1-arg version of indexOf, and then by using the 2-arg version to get the location of the second '-'. If you wanted to convert the phone number to an int, you could do something like this: 1. Find the dashes by using the indexOf method (as shown above). 2. Build a new String without dashes by using the substring method and concatenation. 3. Convert this String to an int by using the parseInt method of Integer. The parseInt method of the Integer class is covered in the lesson "Using Encapsulation."  Java SE 8 Fundamentals 7 - 16  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • •  Using the String class Using the Java API docs Using the StringBuilder class Doing more with primitive data types Using the remaining numeric operators Promoting and casting variables  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 7 - 17  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  StringBuilder Class StringBuilder provides a mutable alternative to String. StringBuilder: • Is instantiated using the new keyword • Has many methods for manipulating its value • Provides better performance because it is mutable • Can be created with an initial capacity String is still needed because: • It may be safer to use an immutable object • A method in the API may require a string • It has many more methods not available on StringBuilder  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The StringBuilder class is "mutable." This means that it can be changed in place. You will recall that when you modify the value of a String variable, a new String object is created for the new value. String objects are "immutable." A String object's value cannot be changed. • Unlike String, there is no shortcut to instantiate a StringBuilder. It is simply instantiated like any other object by using the new keyword. • A small sampling of the StringBuilder methods for manipulation of data values are: append, delete, insert, and replace. • StringBuilder provides better performance because it does not create new objects in memory whenever a change is made. Performance is also benefited whenever you can set an initial capacity for the object, as opposed to letting it grow and allocate memory dynamically. • StringBuilder is not a complete replacement for String, but it is more suitable if many modifications are likely to be made to its value.  Java SE 8 Fundamentals 7 - 18  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  StringBuilder Advantages over String for Concatenation (or Appending) •String concatenation String myString = "Hello"; myString = myString + " • Costly in terms of World"; creating  new objects  0x99f311  "Hello "  0x74cd23 myString  0x74cd23  "Hello World"  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  This slide offers a reminder of what happens when the strings "Hello" and " World" are concatenated. A new String object is created, and the reference for that object is assigned to myString.  Java SE 8 Fundamentals 7 - 19  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  StringBuilder: Declare and Instantiate  StringBuilder mySB = new StringBuilder("Hello");  0x034009  "Hello" mySB  0x034009  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  This diagram shows the start of a sequence involving a StringBuilder. A new StringBuilder is instantiated, populated with the string "Hello", and the reference for this new object is assigned to mySB.  Java SE 8 Fundamentals 7 - 20  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  StringBuilder Append  StringBuilder mySB = new StringBuilder("Hello"); mySB.append(" World");  0x034009  "Hello World" mySB  0x034009  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  To append the string " World", all you need to do is call the append method and pass in "World". Note that no assignment (=) is necessary because there is already a reference to the StringBuilder object, and this StringBuilder object now contains a representation of the combined strings "Hello World". Even if you did assign the return type of the append method (which is StringBuilder), there would still be no object creation cost; the append method modifies the current object and returns the reference to that object, the one already contained in mySB.  Java SE 8 Fundamentals 7 - 20  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Which of the following statements are true? (Choose all that apply.) a. The dot (.) operator creates a new object instance. b. The String class provides you with the ability to store a sequence of characters. c. The Java API specification contains documentation for all of the classes in a Java technology product. d. String objects cannot be modified.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: b, c, d  Java SE 8 Fundamentals 7 - 21  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 7-1: Use indexOf and substring Methods In this exercise, you use indexOf and substring methods to get just the customer's first name and display it.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  • •  •  Open the Java Code Console and access 07-ManipulateFormat > Exercise1. Follow the instructions below the code editor to: - Use the indexOf method to get the index of the space character (" ") within custName. Assign it to spaceIdx. - Use the substring method and the spaceIdx to get just the first name portion of custName. Assign it to firstName. Print firstName. If you need help, click the Solution link. To go back to your code, click the Exercise link again. Any changes that you have made will have been saved.  Java SE 8 Fundamentals 7 - 22  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 7-2: Instantiate the StringBuilder object In this exercise, you instantiate a StringBuilder object, initializing it to firstName using the StringBuilder constructor.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  • •  Open the Java Code Console and access 07-ManipulateFormat > Exercise2. Follow the instructions below the code editor to: - Instantiate the StringBuilder object (sb), initializing it to firstName, using the StringBuilder constructor. - Use the append method of the StringBuilder object to put the customer full name back together again, and then print the StringBuilder object.  •  If you need help, click the Solution link. To go back to your code, click the Exercise link again. Any changes that you have made will have been saved.  Java SE 8 Fundamentals 7 - 23  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • •  Using the String class Using the Java API docs Using the StringBuilder class Doing more with primitive data types Using the remaining numeric operators Promoting and casting variables  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 7 - 24  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Primitive Data Types • • • •  Integral types (byte, short, int, and long) Floating point types (float and double) Textual type (char) Logical type (boolean)  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Many of the values in Java technology programs are stored as primitive data types. The slide lists the eight primitive types built in to the Java programming language. You have already learned about some of these and have been using them in your exercises and practices. Now you will see the remaining primitive types.  Java SE 8 Fundamentals 7 - 25  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Some New Integral Primitive Types Type  Length  Range  byte  8 bits  –27 to 27 –1 (–128 to 127, or 256 possible values)  short  16 bits  –215 to 215 – 1 (–32,768 to 32,767, or 65,535 possible values)  int  32 bits  –231 to 231 –1 (–2,147,483,648 to 2,147,483,647, or 4,294,967,296 possible values)  long  64 bits  –263 to 263 –1 (–9,223,372,036854,775,808 to 9,223,372,036854,775,807, or 18,446,744,073,709,551,616 possible values)  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  There are four integral primitive types in the Java programming language. You have already been using the int data type, so the focus here is on the other three. Integral types are used to store numbers that do not have decimal portions. They are shown here in order of size. • byte: If you need to store people's ages, a variable of type byte would work because byte types can accept values in that range. • short: A short will hold 16 bits of data. • long: When you specify a literal value for a long type, put a capital L to the right of the value to explicitly state that it is a long type. Integer literals are assumed by the compiler to be of type int unless you specify otherwise by using an L indicating long type. • You can express any of the integral types as binary (0s and 1s). For instance, a binary expression of the number 2 is shown as an allowed value of the byte integral type. The binary value is 0b10. Notice that this value starts with 0b (that is, zero followed by either a lowercase or uppercase letter B). This indicates to the compiler that a binary value follows.  Java SE 8 Fundamentals 7 - 26  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Examples of allowed literal values: • byte = 2, -114, 0b10 (binary number) • short = 2, -32699 • int (default type for integral literals) = 2, 147334778, 123_456_678 • long = 2, –2036854775808L, 1 Note: The only reason to use the byte and short types in programs is to save memory consumption. Because most modern desktop computers contain an abundance of memory, most desktop application programmers do not use byte and short types. This course uses primarily int and long types in the examples.  Java SE 8 Fundamentals 7 - 27  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Floating Point Primitive Types Type  Float Length  float  32 bits  double (default type for floating point literals)  64 bits  Example: public float pi = 3.141592F;  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  There are two types for floating point numbers: float and double. Again, the focus is on the new data type here, the float. Floating point types are used to store numbers with values to the right of the decimal point, such as 12.24 or 3.14159. • float is used to store smaller floating point numbers. A float variable can hold 32 bits. • Floating point values are assumed to be of type double unless you specify by putting a capital F (float) to the right of the value to explicitly state that it is a float type, not a double type. Examples of allowed literal values:  float = 99F, -327456,99.01F, 4.2E6F (engineering notation for 4.2 * 106 ) double = -1111, 2.1E12, 99970132745699.999 Note: Use the double type when a greater range or higher accuracy is needed.  Java SE 8 Fundamentals 7 - 28  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Textual Primitive Type • • •  The only primitive textual data type is char. It is used for a single character (16 bits). Example: – public char colorCode = 'U'; Single quotes must be used with char literal values.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Another data type that you use for storing and manipulating data is single-character information. The primitive type used for storing a single character (such as a 'y') is char, which is 16 bits in size. The Shirt class shows the use of one textual literal value to specify the default value for a colorCode: public char colorCode = 'U';  When you assign a literal value to a char variable, you must use single quotation marks around the character as shown in the code example above.  Java SE 8 Fundamentals 7 - 29  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Language Trivia: Unicode Another primitive type is Unicode. • Unicode uses a 16-bit character set. • It can store all the necessary characters from most languages. • Programs can be written so they display the correct language for most countries.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Did You Know? Many older computer languages use American Standard Code for Information Interchange (ASCII), an 8-bit character set that has an entry for every English character, punctuation mark, number, and so on. The Java programming language uses a 16-bit character set called Unicode that can store all the necessary displayable characters from the vast majority of languages used in the modern world. Therefore, your programs can be written so that they work correctly and display the correct language for most countries. Unicode contains a subset of ASCII (the first 128 characters).  Java SE 8 Fundamentals 7 - 30  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Constants •  Variable (can change): – double salesTax = 6.25;  •  Constant (cannot change): – final int NUMBER_OF_MONTHS = 12;  The final keyword causes a variable to be read only.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In this lesson, you have learned about variables that have values that you can change. In this section, you learn how to use constants to represent values that cannot change. Assume that you are writing part of a scheduling application, and you need to refer to the number of months in a year. Make the variable a constant by using the final keyword to inform the compiler that you do not want the value of the variable to be changed after it has been initialized. Example: final int NUMBER_OF_MONTHS = 12;  Any values that do not need to change are good candidates for a constant variable (for example, MAX_COUNT, or PI). If someone attempts to change the value of a constant after it has already been assigned a value, the compiler gives an error message. If you modify your code to provide a different value for the constant, you need to recompile your program. Guidelines for Naming Constants You should name constants so that they can be easily identified. Generally, constants should be capitalized, with words separated by an underscore (_).  Java SE 8 Fundamentals 7 - 31  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz The variable declaration public int myInteger=10; adheres to the variable declaration and initialization syntax. a. True b. False  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: a  Java SE 8 Fundamentals 7 - 32  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • •  Using the String class Using the Java API docs Using the StringBuilder class Doing more with primitive data types Using the remaining numeric operators Promoting and casting variables  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 7 - 33  Modulus Operator  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Purpose Operator Example Remainder  % modulus  num1 = 31; num2 = 6; mod = num1 % num2; mod is 1  Comments Remainder finds the remainder of the first number divided by the second number. 5 R 1 6 31 30 ----1 Remainder always gives an answer with the same sign as the first operand.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Programs do a lot of mathematical calculating, from the simple to the complex. Arithmetic operators let you specify how the numerical values within variables should be evaluated or combined. The standard mathematical operators (often called binary operators) used in the Java programming language are shown in the tables in this section. Note: The % is known as the modulus operator.  Java SE 8 Fundamentals 7 - 34  Combining Operators to Make Assignments  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Purpose  Operator Examples int a = 6, b = 2;  Result  Add to and assign  +=  a += b  a=8  Subtract from and assign  -=  a -= b  a=4  Multiply by and assign  *=  a *= b  a = 12  Divide by and assign  /=  a /= b  a=3  Get remainder and assign  %=  a %= b  a=0  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Several very useful shortcuts are shown in the table above. You can combine any operator with the equal sign to abbreviate your code. For example: a = a + b; can be expressed as: a += b;  Java SE 8 Fundamentals 7 - 35  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  More on Increment and Decrement Operators Operator  Purpose  Example  ++  Preincrement (++variable)  int id = 6; int newId = ++id; id is 7, newId is 7  Postincrement (variable++)  int id = 6; int newId = id++; id is 7, newId is 6  Predecrement (--variable)  (same principle applies)  --  Postdecrement (variable--)  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  You have used increment and decrement operators before, placing them after the variable that you wish to affect. But did you know that these operators can come before (preincrement and predecrement) or after (postincrement and postdecrement) a variable. When you put the ++ or -- operator before a variable, the value is changed immediately. When you put the operator after the variable, it is not changed until after that expression is evaluated. • In the first code example above, id is initialized to 6. In the next line, you see newId = ++id. Because the operator precedes id, this increment is immediately evaluated and, therefore, the value assigned to newId is 7. • In the second code example, the ++ operator follows id, rather than precedes it. id was incremented after the assignment occurred. Therefore, newId is 6. • These same behaviors apply to a decrement (--) operator, in regard to its placement before or after the variable.  Java SE 8 Fundamentals 7 - 36  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Increment and Decrement Operators (++ and ––) Examples: 1 2 3 4 5 6 7  int count=15; int a, b, c, d; a = count++; b = count; c = ++count; d = count; System.out.println(a + ", " + b + ", " + c + ", " + d);  Output: 15, 16, 17, 17  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The example in the slide shows basic use of the increment and decrement operators: int count=15; int a, b, c, d; a = count++; b = count; c = ++count; d = count; System.out.println(a + ", " + b + ", " + c + ", " + d);  The result of this code fragment is: 15, 16, 17, 17 Discussion: What is the result of the following code? int i = 16; System.out.println(++i + " " + i++ + " " + i);  Java SE 8 Fundamentals 7 - 37  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • • •  Using the String class Using the Java API docs Using the StringBuilder class Doing more with primitive data types Using the remaining numeric operators Promoting and casting variables  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 7 - 38  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Promotion •  Automatic promotions: – If you assign a smaller type to a larger type byte  short  int  long  – If you assign an integral type to a floating point type 3  •  3.0  Examples of automatic promotions: – long intToLong = 6; – double intToDouble = 3; Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In some circumstances, the compiler changes the type of a variable to a type that supports a larger size value. This action is referred to as a promotion. Some promotions are done automatically by the compiler if data would not be lost by doing so. These promotions include: • If you assign a smaller type (on the right of the =) to a larger type (on the left of the =) • If you assign an integral type to a floating point type (because there are no decimal places to lose)  Java SE 8 Fundamentals 7 - 39  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Caution with Promotion Equation: 55555 * 66666 = 3703629630  Example of potential issue: 1 2 3 4  int num1 = 55555; int num2 = 66666; long num3; num3 = num1 * num2;  //num3 is -591337666  Example of potential solution: 1 2 3 4  int num1 = 55555; long num2 = 66666; long num3; num3 = num1 * num2;  Changed from int to long //num3 is 3703629630  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Before being assigned to a variable, the result of an equation is placed in a temporary location in memory. The location's size is always equal to the size of an int type or the size of the largest data type used in the expression or statement. For example, if your equation multiplies two int types, the container size will be an int type in size, or 32 bits. If the two values that you multiply yield a value that is beyond the scope of an int type, (such as 55555 * 66666 = 3,703,629,630, which is too big to fit in an int type), the int value must be truncated to fit the result into the temporary location in memory. This calculation ultimately yields an incorrect answer because the variable for your answer receives a truncated value (regardless of the type used for your answer). To solve this problem, set at least one of the variables in your equation to the long type to ensure the largest possible temporary container size.  Java SE 8 Fundamentals 7 - 40  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Caution with Promotion Equation: 7 / 2 = 3.5  Example of potential issue: 1 2 3 4  int num1 = 7; int num2 = 2; double num3; num3 = num1 / num2;  //num3 is 3.0  Example of potential solution: 1 2 3 4  int num1 = 7; double num2 = 2; double num3; num3 = num1 / num2;  Changed from int to double //num3 is 3.5  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The same issue occurs with other data types. Before being assigned to a variable, the result of an equation is placed in a temporary location in memory. The location's size is always equal to the size of the largest data type used in the expression or statement. For example, if your equation divides two int types, the container size will be an int type in size, or 32 bits. If the two values that you use yield a value that is beyond the scope of an int type, (such as 7 / 2 = 3.5), the value must be truncated to fit the result into the temporary location in memory. This calculation ultimately yields an incorrect answer because the variable for your answer receives a truncated value (regardless of the type used for your answer). To solve this problem, set at least one of the variables in your equation to the double type to ensure the largest possible temporary container size.  Java SE 8 Fundamentals 7 - 41  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Type Casting •  When to cast: – If you assign a larger type to a smaller type byte  short  int  long  – If you assign a floating point type to an integral type 3  •  3.0  Examples of casting: – int longToInt = (int)20L; – short doubleToShort = (short)3.0; Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Type casting lowers the range of a value, chopping it down to use a smaller amount of memory, by changing the type of the value (for example, by converting a long value to an int value). You do this so that you can use methods that accept only certain types as arguments, so that you can assign values to a variable of a smaller data type, or so that you can save memory. The syntax for type casting a value is: identifier = (target_type) value, where: • identifier is the name you assign to the variable • value is the value you want to assign to the identifier • (target_type) is the type to which you want to type cast the value. Notice that the target_type must be in parentheses.  Java SE 8 Fundamentals 7 - 42  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Caution with Type Casting Example of potential issue: 1 int myInt; 2 long myLong = 123987654321L; 3 myInt = (int) (myLong); // Number is "chopped" 4 // myInt is -566397263  Safer example of casting: 1 int myInt; 2 long myLong = 99L; 3 myInt = (int) (myLong); // No data loss, only zeroes. 4 // myInt is 99  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The loss of precision with casting can sometimes lead to situations where numbers are truncated, leading to errors in calculations.  Java SE 8 Fundamentals 7 - 43  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Caution with Type Casting •  Be aware of the possibility of lost precision.  Example of potential issue: 1 int myInt; 2 double myPercent = 51.9; 3 myInt = (int) (myPercent); // Number is "chopped" 4 // myInt is 51  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  If you type cast a float or double value with a fractional part to an integral type such as an int, all decimal values are lost. However, this method of type casting is sometimes useful if you want to truncate the number down to the whole number (for example, 51.9 becomes 51).  Java SE 8 Fundamentals 7 - 44  Using Promotion and Casting  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Example of potential issue: 1 2 3 4  int num1 = 53; int num2 = 47; byte num3; num3 = (num1 +  // 32 bits of memory to hold the value // 32 bits of memory to hold the value // 8 bits of memory reserved num2); // causes compiler error  Solution using a larger type for num3: 1 2 3 4  int num1 = 53; int num2 = 47; int num3; Changed from byte to int num3 = (num1 + num2);  Solution using casting: 1 2 3 4  int num1 = 53; // 32 bits of memory to hold the value int num2 = 47; // 32 bits of memory to hold the value byte num3; // 8 bits of memory reserved num3 = (byte)(num1 + num2); // no data loss Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Assigning a variable or an expression to another variable can lead to a mismatch between the data types of the calculation and the storage location that you are using to save the result. Specifically, the compiler will either recognize that precision will be lost and not allow you to compile the program, or the result will be incorrect. To fix this problem, variable types have to be either promoted to a larger size type, or type cast to a smaller size type. In the above example, the compiler assumes that because you are adding int values, the result will overflow the space allocated for a byte. A byte, though smaller than an int, is large enough to store a value of 100. However, the compiler will not make this assignment and, instead, issues a "possible loss of precision" error because a byte value is smaller than an int value. To fix this problem, you can either type cast the right-side data type down to match the left-side data type, or declare the variable on the left side (num3) to be a larger data type, such as an int.  Java SE 8 Fundamentals 7 - 45  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Compiler Assumptions for Integral and Floating Point Data Types •  Most operations result in an int or long: – byte, char, and short values are automatically promoted to int prior to an operation. – If an expression contains a long, the entire expression is promoted to long.  • If an expression contains a floating point, the entire expression is promoted to a floating point. • All literal floating point values are viewed as double.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The Java technology compiler makes certain assumptions when it evaluates expressions. You must understand these assumptions to make the appropriate type casts or other accommodations. The next few slides give examples.  Java SE 8 Fundamentals 7 - 46  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Automatic Promotion Example of potential problem: short a = 1 b = 2 c = a  a, b, c; ; a and b are automatically promoted to integers. ; + b ; //compiler error  Example of potential solutions: •  Declare c as an int type in the original declaration: int c;  •  Type cast the (a+b) result in the assignment line: c = (short)(a+b);  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the following example, an error occurs because two of the three operands (a and b) are automatically promoted from a short type to an int type before they are added. In the last line, the values of a and b are converted to int types and the converted values are added to give an int result. Then the assignment operator (=) attempts to assign the int result to the short variable (c). However, this assignment is illegal and causes a compiler error. The code works if you do either of the following: • Declare c as an int in the original declaration: int c;  •  Type cast the (a+b) result in the assignment line: c = (short)(a+b);  Java SE 8 Fundamentals 7 - 47  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Using a long 1 public class Person { 2 Using the L to indicate a long 3 public int ageYears = 32; will result in the compiler 4 recognizing the total result as 4 public void calculateAge() { a long. 5 6 int ageDays = ageYears * 365; 7 long ageSeconds = ageYears * 365 * 24L * 60 * 60; 8 9 System.out.println("You are " + ageDays + " days old."); 10 System.out.println("You are " + ageSeconds + " seconds old."); 11 12 } // end of calculateAge method 13 } // end of class  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The code example uses principles from this section to calculate a person's age in days and seconds. Because the ageSeconds variable is declared as a long, one of the literal values used as operands in the assigned expression must be initialized as a long value ('L') so that the compiler will allow the assignment.  Java SE 8 Fundamentals 7 - 48  Using Floating Points  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Example of potential problem:  Expressions are automatically promoted to floating points.  int num1 = 1 + 2 + 3 + 4.0; int num2 = (1 + 2 + 3 + 4) * 1.0;  //compiler error //compiler error  Example of potential solutions: •  Declare num1 and num2 as double types: double num1 = 1 + 2 + 3 + 4.0; double num2 = (1 + 2 + 3 + 4) * 1.0;  •  //10.0 //10.0  Type cast num1 and num2 as int types in the assignment line: int num1 = (int)(1 + 2 + 3 + 4.0); int num2 = (int)((1 + 2 + 3 + 4) * 1.0);  //10 //10  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  If an expression contains a floating point, the entire expression is promoted to a floating point.  Java SE 8 Fundamentals 7 - 49  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Floating Point Data Types and Assignment •  Example of potential problem: float float1 = 27.9; //compiler error  •  Example of potential solutions: – The F notifies the compiler that 27.9 is a float value: float float1 = 27.9F;  – 27.9 is cast to a float type: float float1 = (float) 27.9;  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Just as integral types default to int under some circumstances, values assigned to floating point types always default to a double type, unless you specifically state that the value is a float type. For example, the following line causes a compiler error. Because 27.9 is assumed to be a double type, a compiler error occurs because a double type value cannot fit into a float variable. float float1 = 27.9; //compiler error Both of the following work correctly: • The F notifies the compiler that 27.9 is a float value: float float1 = 27.9F;  •  27.9 is cast to a float type: float float1 = (float) 27.9;  Java SE 8 Fundamentals 7 - 50  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Which statements are true? a. There are eight primitive types built in to the Java programming language. b. byte, short, char, and long are the four integral primitive data types in the Java programming language. c. A boolean type variable holds true, false, and nil. d. short Long = 10; is a valid statement that adheres to the variable declaration and initialization syntax.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: a, d • • • •  a is correct. b is incorrect. It should be byte, short, int, and long. c is incorrect because a boolean type variable holds only true and false. d is correct. long is a reserved keyword but Long is not.  Java SE 8 Fundamentals 7 - 51  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 7-3: Declare a Long, Float, and Char In this exercise, you experiment with the data types introduced in this lesson. You: • Declare and initialize variables • Cast one numeric type to another  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  • •  •  Open the Java Code Console and access 07-ManipulateFormat > Exercise3. Follow the instructions below the code editor to: - Declare a long, using the L to indicate a long value. Make it a very large number (in the billions). - Declare and initialize a float and a char. - Print the long variable with a suitable label. - Assign the long to the int variable. Correct the syntax error by casting the long as an int. - Print the int variable. Note the change in value when you run it. If you need help, click the Solution link. To go back to your code, click the Exercise link again. Any changes that you have made will have been saved.  Java SE 8 Fundamentals 7 - 52  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Summary In this lesson, you should have learned how to: • Describe the String class and use some of the methods of the String class • Use the JDK documentation to search for and learn how to use a class • Use the StringBuilder class to manipulate string data • Create a constant by using the final keyword in the variable declaration • Describe how the Java compiler can use promotion or casting to interpret expressions and avoid a compiler error  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 7 - 53  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Play Time! Play Basic Puzzle 8 before the lesson titled "Creating and Using Methods." Consider the following: What happens when you rotate the blue wheel? How else can you affect the rotation of bumpers?  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  You will be asked these question in the lesson titled "Creating and Using Methods."  Java SE 8 Fundamentals 7 - 54  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Practice 7-1 Overview: Manipulating Text This practice covers the following topics: • Searching for a particular player and printing out the last name • Reversing the player name so that the family name is printed first  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 7 - 55  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Objectives After completing this lesson, you should be able to: • Instantiate a class and call a method on the object • Describe the purpose of a constructor method • Create a method that takes arguments and returns a value • Access a static method from a different class • Use a static method of the Integer class to convert a string into an int •  Overload a method  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 2  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • •  Using methods and constructors Method arguments and return values Using static methods and variables Understanding how arguments are passed to a method Overloading a method  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 3  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Basic Form of a Method The void keyword indicates that the method does not return a value.  Empty parentheses indicate that no arguments are passed to the method.  1 public void display () { 2 System.out.println("Shirt description:" + description); System.out.println("Color Code: " + colorCode); 3 System.out.println("Shirt price: " + price); 4 5 } // end of display method  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  This is an example of a simple method that does not receive any arguments or return a value.  Java SE 8 Fundamentals 8 - 4  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Calling a Method from a Different Class 1 2 3 4 5 6  public class ShoppingCart { public static void main (String[] args) { Shirt myShirt = new Shirt(); myShirt.display(); } Method }  Dot operator Reference variable  Output: Item description:-description requiredColor Code: U Item price: 0.0  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the example in this slide, display is called by typing the reference variable for the object, the dot operator, followed by the method to be called. The default values, as set in the Shirt constructor, are displayed.  Java SE 8 Fundamentals 8 - 5  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Caller and Worker Methods  Caller  Worker  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the previous example, the ShoppingCart class calls the display method on a Shirt object from within the main method. The main method is referred to as the calling method because it is invoking or "calling" another method to do some work. Conversely, the display method is referred to as the worker method because it does some work for the main method. When a calling method calls a worker method, the calling method stops execution until the worker method is done. After the worker method has completed, program flow returns to the point after the method invocation in the calling method.  Java SE 8 Fundamentals 8 - 6  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  A Constructor Method A constructor method is a special method that is invoked when you create an object instance. • It is called by using the new keyword. • Its purpose is to instantiate an object of the class and store the reference in the reference variable. Shirt myShirt = new Shirt();  •  Constructor method is called.  It has a unique method signature.                                                                                  ClassName()  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  A constructor is invoked using the new keyword. Its job is to instantiate an object of the class and to provide a reference to the new object. If you do not write your own constructor in a class, Java will provide one for you. The constructor's name is the same as the class name. In the Shirt example above, the reference returned by the Shirt constructor is assigned to the myShirt reference variable.  Java SE 8 Fundamentals 8 - 7  Writing and Calling a Constructor  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  1 2  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19  public static void main(String[] args){ Shirt myShirt = new Shirt(); 3 } public class Shirt { //Fields public String description; public char colorCode; public double price; //Constructor public Shirt(){ description = "--description required--"; colorCode = 'U' price = 0.00; } //Methods public void display(){ System.out.println("Shirt description:" + description); System.out.println("Color Code: " + colorCode); System.out.println("Shirt price: " + price); }…  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The constructor is the first method called when an object is instantiated. Its purpose is primarily to set default values.  Java SE 8 Fundamentals 8 - 8  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Calling a Method in the Same Class 1 public class Shirt { 2 public String description; 3 public char colorCode; 4 public double price; 5 6 public Shirt(){ 7 description = "--description required--"; 8 colorCode = 'U' 9 price = 0.00; 10 11 display(); //Called normally 12 this.display(); //Called using the 'this' keyword 13 } 14 15 public void display(){ 16 System.out.println("Shirt description:" + description); 17 System.out.println("Color Code: " + colorCode); 18 System.out.println("Shirt price: " + price); 19 } 20 …  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Calling a method in the same class is very straightforward. You can simply use the method name without a reference. This is the same as when accessing a field; you can simply use the field name. However, if you have local variables with similar names and you want to make it obvious that your code is accessing a field or method of the current object, you can use the this keyword with dot notation. this is a reference to the current object. In this example, the display method is called twice from the constructor.  Java SE 8 Fundamentals 8 - 9  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • •  Using constructors and methods Method arguments and return values Using static methods and variables Understanding how arguments are passed to a method Overloading a method  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 10  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Method Arguments and Parameters •  An argument is a value that is passed during a method call: Calculator calc = new Calculator(); double denominator = 2.0  Arguments calc.calculate(3, denominator);  •  //should print 1.5  A parameter is a variable defined in the method declaration: 3  2.0  public void calculate(int x, double y){ System.out.println(x/y); Parameters }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Note: A value passed into the method when it is called is called an argument, whereas a variable that is defined in the method declaration is called a method parameter. In this example, 3 and 2.0 are passed to be the values of x and y within the calculate method.  Java SE 8 Fundamentals 8 - 11  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Method Parameter Examples •  Methods may have any number or type of parameters: public void calculate0(){ System.out.println("No parameters"); } public void calculate1(int x){ System.out.println(x/2.0); } public void calculate2(int x, double y){ System.out.println(x/y); } public void calculate3(int x, double y, int z){ System.out.println(x/y +z); }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Methods can take any number of parameters and use these values within the method code block.  Java SE 8 Fundamentals 8 - 12  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Method Return Types •  Variables can have values of many different types: long int[]  •  Method calls can also return values of many different types: long int[]  •  How to make a method return a value: – Declare the method to be a non-void return type. – Use the keyword return within a method, followed by a value.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Variables may have values of many different types, including primitive data types, objects, and arrays. Likewise, methods may return values of many different types, including primitive data types, objects, and arrays. Note: Constructors are special. They cannot have a return type, not even void.  Java SE 8 Fundamentals 8 - 13  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Method Return Types Examples •  Methods must return data that matches their return type: public void printString(){ System.out.println("Hello"); }  Void methods cannot return values in Java.  public String returnString(){ return("Hello"); } public int sum(int x, int y){ return(x + y); } public boolean isGreater(int x, int y){ return(x > y); }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Void methods and constructors should not have a return statement. Void methods are incapable of returning a value in Java. The type of value a method returns must match the return type you declare. For instance, a boolean type method must return a boolean. A String type method must return a String.  Java SE 8 Fundamentals 8 - 14  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Method Return Animation •  The following code examples produce equivalent results: public static void main(String[] args){ int num1 = 1, num2 = 2; int result = num1 + num2; System.out.println(result); } public static void main(String[] args){ int num1 = 1, num2 = 2; int result = = sum( sum(num1, num2); num1 int result 1 3, num2 2 ); System.out.println(result); } public int sum sum(int x, y){ (int , int ){ 1 x 2 y return(x y); x1 + y return( ); 3 2 } } Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the top example, num1 and num2 are added together. In the bottom example, this logic is put into the sum method. Values are passed to the sum method and added, with the resulting integer value being passed back and assigned to the result variable.  Java SE 8 Fundamentals 8 - 15  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Passing Arguments and Returning Values 2  1 Value passed from caller method to worker method  Value received by worker method  Object  method 1 2 3 4 5 6 7  1 2 3 4  3  Value returned to caller method  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 16  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  More Examples 1 public void setCustomerServices() { 2 String message ="Would you like to hear " Itemabout parameter required 3 +"special deals in your area?"; 4 if (cust.isNewCustomer()) { 5 6 cust.sendEmail(message); 7 } 8 } 1 public class Customer{ public boolean isNew; 2 3 4 public boolean isNewCustomer(){ return isNew; 5 Return a boolean 6 } public void sendEmail(String message){ 7 // send email 8 String argument required 9 } 10 }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Here you see a caller method, setCustomerServices, invoking worker methods in the Customer class. • The example at the bottom of the slide shows the Customer class, which defines two methods: - isNewCustomer is defined with a return value of type boolean, but it does not define any input parameters. - sendEmail is defined with an input parameter of type String, called message. This method does not return a value. • The example at top of the slide shows the setCustomerServices method in the ShoppingCart class invoking the methods of a Customer object by using dot notation (object_reference.method). - In line 4, isNewCustomer is called on the cust object reference. Because the method returns a boolean, the method invocation becomes a boolean expression evaluated by the if statement. - In line 6, sendEmail is called on the cust object reference, passing the message string as an argument.  Java SE 8 Fundamentals 8 - 17  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Code Without Methods 1 public static void main(String[] args){ 2 Shirt shirt01 = new Shirt(); 3 Shirt shirt02 = new Shirt(); 4 Shirt shirt03 = new Shirt(); 5 Shirt shirt04 = new Shirt(); 6 7 shirt01.description = "Sailor"; 8 shirt01.colorCode = 'B'; 9 shirt01.price = 30; 10 11 shirt02.description = "Sweatshirt"; 12 shirt02.colorCode = 'G'; 13 shirt02.price = 25; 14 15 shirt03.description = "Skull Tee"; 16 shirt03.colorCode = 'B'; 17 shirt03.price = 15; 18 19 shirt04.description = "Tropical"; 20 shirt04.colorCode = 'R'; 21 shirt04.price = 20; 22 }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Why are methods useful? To answer that question, take a look at this code without methods. For every instance of the Shirt object that you want to create, you need many more lines of code to edit each object. Methods can help this code be more efficient and less cumbersome to work with.  Java SE 8 Fundamentals 8 - 18  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Better Code with Methods 1 public static void main(String[] args){ 2 Shirt shirt01 = new Shirt(); Shirt shirt02 = new Shirt(); 3 Shirt shirt03 = new Shirt(); 4 5 Shirt shirt04 = new Shirt(); 6 7 shirt01.setFields("Sailor", 'B', 30); 8 shirt02.setFields("Sweatshirt", 'G', 25); 9 shirt03.setFields("Skull Tee", 'B', 15); 10 shirt04.setFields("Tropical", 'R', 20); 11 } 1 public class Shirt { 2 public String description; 3 public char colorCode; 4 public double price; 5 6 public void setFields(String desc, char color, double price){ 7 this.description = desc; 8 this.colorCode = color; 9 this.price = price; 10 } 11 … Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  With a little bit of extra coding in the Shirt class, we can create a method that sets all the appropriate fields. This reduces the amount of code needed in the main method to create and edit Shirt objects.  Java SE 8 Fundamentals 8 - 19  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Even Better Code with Methods 1 2 3 4 5  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  public static void main(String[] args){ Shirt shirt01 = new Shirt("Sailor", "Blue", 30); Shirt shirt02 = new Shirt("SweatShirt", "Green", 25); Shirt shirt03 = new Shirt("Skull Tee", "Blue", 15); Shirt shirt04 = new Shirt("Tropical", "Red", 20); 6 } public class Shirt { public String description; public char colorCode; public double price; //Constructor public Shirt(String desc, String color, double price){ setFields(desc, price); setColor(color); } public void setColor (String theColor){ if (theColor.length() > 0) colorCode = theColor.charAt(0); } } } Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Taking advantage of a Shirt constructor can further reduce the amount of code needed in the main method. Another issue is maintenance. Imagine if you wanted to change the constructor so that the color passed in is a String, but the instance variable, colorCode, remains a char type. You could create a method setColor that receives a String as an argument and then modifies it so that it sets colorCode correctly. Remember, methods can call other methods (as shown by the call to setColor).  Java SE 8 Fundamentals 8 - 20  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Variable Scope  Instance variable (field)  1 public class Shirt { 2 public String description; 3 public char colorCode; public double price; 4 Local variable 5 6 public void setColor (String theColor){ if (theColor.length() > 0) 7 colorCode = theColor.charAt(0); 8 9 } 10 } 11 12 public String getColor(){ return theColor; //Cannot find symbol 13 14 } 15 16 }  Scope of theColor Not scope of theColor  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  This code illustrates the scope of two different types of variables. Variables live in the block where they are defined. This is called "scope." The scope of a variable determines its accessibility and also how long you can count on its value to persist. • The colorCode variable is an instance variable, usually called a field. It is a member of the Shirt class. It is accessible from any code within this class. The value of fit is stored only during the lifespan of an instance. • theColor is a local variable. It is accessible only from within the setColor method. The value of theColor is deleted from memory when the method ends. Another way of saying this is that its scope is the setColor method. • •  Regardless of whether a local variable is declared within a method, a loop (discussed later), or an if statement, its scope is always the block within which it is declared. In the example above, the setColor method uses the charAt method of the String object to extract the first character in the theColor String. It assigns it to the fit instance variable, which is a char.  Note: Local variables are stored in short-term memory, called "the stack," whereas instance variables (fields) are stored in a longer-term area of memory called "the heap."  Java SE 8 Fundamentals 8 - 21  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Advantages of Using Methods Methods: • Are reusable • Make programs shorter and more readable • Make development and maintenance quicker • Allow separate objects to communicate and to distribute the work performed by the program  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 22  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 8-1: Declare a setColor Method In this exercise you: • Declare a setColor method that takes a char as an argument • In the ShoppingCart class, call the setColor method on item1 •  Test the method with both a valid color and an invalid one  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  • • •  Open the Java Code Console and access Lessons > 08-Methods > Exercise1. Follow the instructions below the code editor. If you need help, click the Solution link. To go back to your code, click the Exercise link again. Any changes that you have made will have been saved.  Java SE 8 Fundamentals 8 - 23  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • •  Using constructors and methods Method arguments and return values Using static methods and variables Understanding how arguments are passed to a method Overloading a method  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 24  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Puzzle Ball Have you played through Basic Puzzle 8? Consider the following: What happens when you rotate the blue wheel? How else can you affect the rotation of bumpers?  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  These are the questions that you were asked to think about before this lesson began. What conclusions did you reach? In this topic, some Java concepts and principles will be discussed that can help explain this behavior.  Java SE 8 Fundamentals 8 - 25  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Java Puzzle Ball Debrief •  What happens when you rotate the blue wheel? – The orientation of all blue bumpers change. – All blue bumpers share the orientation property of the wheel.  •  How else can you affect the rotation of bumpers? – After the ball strikes a rotation wall, the rotation of an individual bumper changes.  Rotation wall  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 26  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Static Methods and Variables The static modifier is applied to a method or variable. It means the method/variable: • Belongs to the class and is shared by all objects of that class • Is not unique to an object instance • Can be accessed without instantiating the class Comparison: • A static variable is shared by all objects in a class. • An instance variable is unique to an individual object.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  So far you learned how to access variables and methods by creating an object instance of the class that the variable or method belongs to. The Java language allows you to declare a variable or method as static. This means that you can access it without creating an object instance of the class. Sometimes these are referred to as class variables or class methods.  Java SE 8 Fundamentals 8 - 27  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Example: Setting the Size for a New Item 1 public class ItemSizes { 2 static final String mSmall = "Men's Small"; 3 static final String mMed = "Men's Medium"; 4 } Passing the static mMed variable to the setSize method Item item1 = new Item(); item1.setSize(ItemSizes.mMed); 1 public class Item { 2 public String size; 3 public void setSize(String sizeArg){ 4 this.size = sizeArg; 5 } 6 }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the example above, the class ItemSizes contains two static variables of type String: mSmall and mMed. These are initialized to a description of a particular men's size. These values can be used without instantiating ItemSizes. •  •  The code snippet shown in the middle of the slide shows an Item object being instantiated and then the setSize method of the Item object is invoked, passing in ItemSizes.mMed as an argument. The code example at the bottom of the slide shows the Item class. It contains a String field, size. The setSize method requires a String parameter to set the size field.  Java SE 8 Fundamentals 8 - 28  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Creating and Accessing Static Members •  To create a static variable or method: static String mSmall; static void setMSmall(String desc);  •  To access a static variable or method: ‒ From another class ItemSizes.mSmall; ItemSizes.setMSmall("Men's Small"); – From within the class mSmall; setMSmall("Men's Small");  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Variables and methods that are unique to an instance are referred to as instance variables or methods. If they are accessed from an object of another class, you qualify the reference with the object reference (shirt01.size). • When accessing a static variable or method from an object of a different class, you qualify the reference with the class name as shown above: ItemSizes.setMSmall("Men's Small") or ItemSizes.mSmall • •  If you are referencing the static variable or method from within the class, there is no need to qualify it. The main method is an example of a static method. As you know, it is used as the entry point to an application. Because the main method is static, the Java runtime can implicitly invoke it on the class without first instantiating the class.  Java SE 8 Fundamentals 8 - 29  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  When to Use Static Methods or Fields •  • •  •  Performing the operation on an individual object or associating the variable with a specific object type is not important. Accessing the variable or method before instantiating an object is important. The method or variable does not logically belong to an object, but possibly belongs to a utility class, such as the Math class, included in the Java API. Using constant values (such as Math.PI)  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 30  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Some Rules About Static Fields and Methods • •  Instance methods can access static methods or fields. Static methods cannot access instance methods or fields. Why? 1 public class Item{ 2 int itemID; 3 public Item(){ 4 setId(); 5 } 6 static int getID(){ 7 // whose itemID?? 8 }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The code example above illustrates why a static method is not allowed to access an instance method or field. • itemID is an instance variable. That means that each Item object has its own (presumably) unique itemID. In this example, its value is set in the constructor. • The getID method is static, so it can be invoked even if there are no Item objects created. Instance methods and fields are only available by referencing the individual object instance.  Java SE 8 Fundamentals 8 - 31  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Static Fields and Methods vs. Instance Fields and Methods public class Item{ static int staticItemID; int instanceItemID; static main(){ Item item01 = new Item();  1  staticItemId = 6;  2  instanceItemID = 3  3  showItemID();  4  item01.showItemID();  } showItemID(){ ...println(staticItemId); ...println(instanceItemId); } }  Object (instance) referenced by item01. static int staticItemID; int instanceItemID; static main(){ ... } showItemID(){  5  ...println(staticItemID);  6  ...println(instanceItemID);  }  Other instances of Item  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The code example above shows a more complex example of an Item class that has an instance variable instanceItemID and a static variable staticItemID. In its main method, it instantiates an object referenced by item01. Look at the six lines of code and see the explanations below for why some work and some do not. 1. staticItemID is a static variable, and referenced from within a static method, main, so it does not need to access an instance. 2. instanceItemID is an instance variable, and referenced from within a static method, main, so it cannot be accessed unless a reference points to the particular object whose instance variable needs to be set. 3. showItemID() is a call to an instance method, and referenced from within a static method, main, so it cannot be accessed without a reference. 4. item01.showItemID() is a call to an instance method, but in this case the reference points to the particular object whose instance method needs to be called. 5. ...println(staticItemID) refers to a static variable, but it is referred to from an instance. Instances can always access static variables. 6. ...println(instanceItemID refers to an instance variable, but it is referred to from an instance. No object reference is given, so it accesses the instance variable on the object itself.  Java SE 8 Fundamentals 8 - 32  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Static Methods and Variables in the Java API Examples: • Some functionality of the Math class: – – – – –  •  Exponential Logarithmic Trigonometric Random Access to common mathematical constants, such as the value PI (Math.PI)  Some functionality of the System class: – Retrieving environment variables – Access to the standard input and output streams – Exiting the current program (System.exit method)  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Certain Java class libraries, such as the System and the Math class, contain only static methods and variables. The System class contains utility methods for handling operating system–specific tasks. (They do not operate on an object instance.) For example, the getProperties() method of the System class gets information about the computer that you are using. The Math class contains utility methods for math operations. Because these methods and variables are static, you do not need to create a new object every time you want your program to do some math.  Java SE 8 Fundamentals 8 - 33  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Examining Static Variables in the JDK Libraries  out is a static field of System and contains and is an object reference to a PrintStream  object.  System is a class in java.lang. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The next few slides show how you might use the Java API documentation to find out more about System.out.println(). As you will see, this is a little unusual, because the class that has the methods that you need to investigate is not System. Rather, it is the class that is the type of the out field of the System object. Consider the following: System is a class (in java.lang). out is a static field of System. This is the reason that you reference it from the class name, not from an object instance: System.out out is a reference type that allows calling println() on the object type it references. To find the documentation: 1. Go to System class and find the type of the out field. 2. Go to the documentation for that field. 3. Review the methods available.  Java SE 8 Fundamentals 8 - 34  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Using Static Variables and Methods: System.out.println  Some of the methods of PrintStream  The field, out, on System is of type PrintStream.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The diagram shows the Field Summary for the class System. Here, you can see that there is indeed a field called out, and it is of type PrintStream. By clicking PrintStream, you can now see the details for that class and, if you scroll down to the Method Summary, you will find (among many other methods) the print method and the println method. The print method is very similar to println, except that it does not create a new line after printing, like println does. Example: println("Hello"); Hello Hello  println("Hello") yields the following output:  Print("Hello, "); print("Hello "); yields the following output: Hello, Hello  Java SE 8 Fundamentals 8 - 35  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  More Static Fields and Methods in the Java API Java provides wrapper classes for each of the primitive data types. • Boolean: Contains a single field of type boolean • Double: Contains a single field of type double • Integer: Contains a single field of type int They also provide utility methods to work with the data.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  A wrapper class is a class with the same name as one of the primitive data types. Wrapper classes are instantiated to contain a single value of the primitive type. Integer myInt = new Integer(10); These are very useful classes because they provide methods to help you work with the primitive values stored within.  Java SE 8 Fundamentals 8 - 36  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Converting Data Values •  Methods often need to convert an argument to a different type. • Most of the object classes in the JDK provide various conversion methods. Examples: • Converting a String to an int int myInt1 = Integer.parseInt(s_Num);  •  Converting a String to a double double myDbl = Double.parseDouble(s_Num);  •  Converting a String to boolean boolean myBool = Boolean.valueOf(s_Bool);  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The examples show static conversion methods for Integer, Double, and Boolean. There are also some conversion methods for the object classes (Integer, Double, and so on) that are not static. These methods are invoked on an object reference for one of these classes and convert the value of that specific object.  Java SE 8 Fundamentals 8 - 37  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • •  Using constructors and methods Method arguments and return values Using static methods and variables Understanding how arguments are passed to a method Overloading a method  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 38  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Passing an Object Reference An object reference is similar to a house address. When it is passed to a method: • The object itself is not passed • The method can access the object using the reference • The method can act upon Paint my house. the object  Thank you!  11 00 11  2  1  Here's the address.  101  House myHouse = new House(); PainterMan.paint(myHouse);  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  An object reference is not the same as the object. It simply provides a reference for access to that object. This is similar to the way a house address provides directions for finding a particular house. In the graphic above, the house (call it myHouse) has an address (the myHouse reference) of 101. When the painter gets this address, he jots it down in his notebook (he makes a copy of it). This enables the house painter to find the house and paint it. When you send an object reference as an argument to a method, you are sending a copy of the reference—not the object nor the actual reference. The receiving method has the information it needs to act directly upon the object itself.  Java SE 8 Fundamentals 8 - 39  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  What If There Is a New Object? myHouse = new House();  2  11 00 11  Move to new house.  Hey! My house wasn't painted!  3  Paint my house. 1 Here's the address.  1 0 2  101  House myHouse = new House(); PainterMan.paint(myHouse); Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Suppose that the owner of the house moves to another house before the job is finished. Will the painter be able to find the owner's new house in order to paint it? The object reference (myHouse) has changed to point to a new house, but the notation in the painter's notebook still refers to the old house. If the owner expects the new house to be painted, he or she will be disappointed.  Java SE 8 Fundamentals 8 - 40  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  A Shopping Cart Code Example  1 public class ShoppingCart { 2 public static void main (String[] args) { 3 Shirt myShirt = new Shirt(); System.out.println("Shirt color: " + myShirt.colorCode); 4 changeShirtColor(myShirt, 'B'); 5 6 System.out.println("Shirt color: " + myShirt.colorCode); 7 } 8 public static void changeShirtColor(Shirt theShirt, char color) { 9 theShirt.colorCode = color; } 10 }  theShirt is a new reference of type Shirt.  Output: Shirt color: U Shirt color: B  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  When a method is invoked, the values of the arguments are used to initialize the parameter variables before the body of the method is executed. This is true for both primitive types and reference types. (Objects are not passed to methods.) In the example shown in the slide, the reference myShirt is passed by value into the changeShirtColor method. The reference, theShirt is assigned the value of the myShirt reference (the address). They now both point to the same object, so the change to the color made using theShirt is printed out by accessing myShirt.color. Note: The call to the changeShirtColor method is made from the main method, which is static. Remember that a static method can only access other static methods. The changeShirtColor method is also static.  Java SE 8 Fundamentals 8 - 41  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Passing by Value  Shirt myShirt = new Shirt(); changeShirtColor(myShirt, 'B');  0x034009 myShirt  theShirt  0x034009  12  shirtID  15.99  price  B  colorCode  0x034009  Before changeShirtColor() is invoked, this value is U.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The diagram in the slide shows how the value of the myShirt reference passed into the changeShirtColor() method is used to initialize a new Shirt reference (in this case, called theShirt). Remember that when a new Shirt is created, the colorCode is initialized to "U".  Java SE 8 Fundamentals 8 - 42  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Reassigning the Reference  1 public class ShoppingCart { 2 public static void main (String[] args) { 3 Shirt myShirt = new Shirt(); 4 System.out.println("Shirt color: " + myShirt.colorCode); 5 changeShirtColor(myShirt, 'B'); 6 System.out.println("Shirt color: " + myShirt.colorCode); 7 } 9 public static void changeShirtColor(Shirt theShirt, char color) { 10 theShirt = new Shirt(); 11 theShirt.colorCode = color; 12 }  Output: Shirt color: U Shirt color: U  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Here is another example with a small change in the code of the changeShirtColor() method. In this example, the reference value passed into the method is assigned to a new shirt. The reference now points to a different Shirt object than the myShirt reference does. As before, the Shirt.color is changed to 'B'. The println method called on line 6 shows the color of the myShirt object still is 'U' (Unset). These references point to two different Shirt objects. This illustrates that the reference myShirt is indeed passed by value. Changes made to a reference passed into a worker method (reassignment to a different object, for instance) do not affect the references in the calling method.  Java SE 8 Fundamentals 8 - 43  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Passing by Value  Shirt myShirt = new Shirt(); changeShirtColor(myShirt, 'B');  0x034009 myShirt  0x034009  12  shirtID  15.99  price  U  colorCode  0x99f311 12  theShirt  0x99f311  shirtID  15.99  price  B  colorCode  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The diagram in the slide shows the situation that results from the code in the previous slide. When myShirt is passed into the changeShirtColor() method, a new reference variable, theShirt, is initialized with the value of myShirt. Initially, this reference points to the object that the myShirt reference points to. But after a new Shirt is assigned to theShirt, any changes made using theShirt affect only this new Shirt object.  Java SE 8 Fundamentals 8 - 44  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Topics • • • • •  Using constructors and methods Method arguments and return values Using static methods and variables Understanding how arguments are passed to a method Overloading a method  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 45  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Method Overloading Overloaded methods: • Have the same name • Have different signatures – The number of parameters – The types of parameters – The order of parameters  • •  May have different functionality or similar functionality Are widely used in the foundation classes  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  In the Java programming language, a class can contain several methods that have the same name but different arguments (so the method signature is different). This concept is called method overloading. Just as you can distinguish between two students named "Jim" in the same class by calling them "Jim in the green shirt" and "Jim with the beeper," you can distinguish between two methods by their name and arguments.  Java SE 8 Fundamentals 8 - 46  Using Method Overloading  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  The method signature 1 public final class Calculator { The method type 2 3 public static int sum(int num1, int num2){ 4 System.out.println("Method One"); 5 return num1 + num2; 6 } 7 8 public static float sum(float num1, float num2) { 9 System.out.println("Method Two"); 10 return num1 + num2; 11 } 12 public static float sum(int num1, float num2) { 13 System.out.println("Method Three"); 14 return num1 + numb2; 15 }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The example in the slide shows three methods to add two numbers, such as two int types or two float types. With method overloading, you can create several methods with the same name and different signatures. The first sum method accepts two int arguments and returns an int value. The second sum method accepts two float arguments and returns a float value. The third sum method accepts an int and a float as arguments and returns a float. The callout shows the part of the method declaration that is called the method signature. The method signature of a method is the unique combination of the method name and the number, types, and order of its parameters. The method signature does not include the return type. To invoke any of the sum methods, the compiler compares the method signature in your method invocation against the method signatures in a class.  Java SE 8 Fundamentals 8 - 47  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Using Method Overloading 1 public class CalculatorTest { 2 3 public static void main(String[] args) { 4 5 int totalOne = Calculator.sum(2, 3); 6 System.out.println("The total is " + totalOne); 7 8 float totalTwo = Calculator.sum(15.99F, 12.85F); 9 System.out.println(totalTwo); 10 11 float totalThree = Calculator.sum(2, 12.85F); 12 System.out.println(totalThree); 13 } 14 }  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  The code example in the slide has a main method that invokes each of the previous sum methods of the Calculator class.  Java SE 8 Fundamentals 8 - 48  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Method Overloading and the Java API  Method  Use  void println()  Terminates the current line by writing the line separator string  void println(boolean x)  Prints a boolean value and then terminates the line  void println(char x)  Prints a character and then terminates the line  void println(char[] x)  Prints an array of characters and then terminates the line  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Many methods in the Java API are overloaded, including the System.out.println method. The table in the slide shows four variations of the println method.  Java SE 8 Fundamentals 8 - 49  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Exercise 8-2: Overload a setItemFields Method In this exercise, you create an overloaded method in the Item class: • setItemFields with three parameters that returns void • setItemFields with four parameters that returns an int • Then you invoke these from ShoppingCart.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  • • •  Open the Java Code Console and access 08-Methods > Exercise2. Follow the instructions below the code editor. If you need help, click the Solution link. To go back to your code, click the Exercise link again. Any changes that you have made will have been saved.  Java SE 8 Fundamentals 8 - 50  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Quiz Which method corresponds to the following method call? myPerson.printValues(100, 147.7F, "lavender"); a.  public void printValues (int i, float f)  b.  public void printValues (i, float f, s)  c.  public void printValues (int i, float f, String s)  d.  public void printValues (float f, String s, int i)  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Answer: c  Java SE 8 Fundamentals 8 - 51  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Summary In this lesson, you should have learned how to: • Add an argument to a method • Instantiate a class and call a method • Overload a method • Work with static methods and variables • Convert data values using Integer, Double, and Boolean object types  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 52  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Challenge Questions: Java Puzzle Ball Which of the scenarios below reflect the behavior of: • •  A static variable? An instance variable?  1.  A single bumper rotates after being struck by the ball.  2.  Rotating the red wheel changes the orientation of all red bumpers.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  When you have an opportunity to play the game, see if you can answer these questions, applying the object-oriented concepts that you learned in this lesson. For some possible answers to these questions and more discussion, see "Appendix A: Java Puzzle Ball Challenge Questions Answered."  Java SE 8 Fundamentals 8 - 53  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Practice 8-1 Overview: Using Methods This practice covers the following topics: • Creating a static method, createTeams, to return an array of teams • Creating another static method, createGames, that takes an array of teams and returns an array of games  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 54  Unauthorized reproduction or distribution prohibitedฺ Copyright 2012, Oracle and/or its affiliatesฺ  Practice 8-2 Overview: Creating Game Data Randomly This practice covers creating a method for playing a soccer game that randomly creates Goal objects.  Copyright © 2014, Oracle and/or its affiliates. All rights reserved.  Java SE 8 Fundamentals 8 - 55                                                                                                                                                                                                                                                                                                                                                                                                                        

Source Exif Data:

File Type                       : PDF File Type Extension             : pdf MIME Type                       : application/pdf PDF Version                     : 1.5 Linearized                      : No Page Count                      : 299 Language                        : es-MX Tagged PDF                      : Yes Author                          : LUZZYO Creator                         : Microsoft® Word 2013 Create Date                     : 2016:11:10 21:23:55-06:00 Modify Date                     : 2016:11:10 21:23:55-06:00 Producer                        : Microsoft® Word 2013        

EXIF Metadata provided by EXIF.tools

Posted by: cesarkunise079570.blogspot.com

Source: https://usermanual.wiki/Document/Java20SE20820Fundamentals20Ed20120Student20Guide2020Volume201.1700011659/help

Posting Komentar

0 Komentar