Lecture 2 Objectives Learn about objects and reference variables.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Introduction to Objects and Input/Output
Objectives Learn about objects and reference variables Explore how to use predefined methods in a program.
Java Programming, 3e Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 28, 2005.
COMP 14 Introduction to Programming Mr. Joshua Stough February 2, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.
Class Decimal Format ► Import package java.text ► Create DecimalFormat object and initialize ► Use method format ► Example: import java.text.DecimalFormat.
Input and Output The system console. In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT.
COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
Chapter 3: Input/Output
Chapter 3: Introduction to Objects and Input/Output.
Warm-Up: Monday, March 3 List all devices you can think of that can be used to input information into the computer.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Java Programming, 2E Introductory Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
11 Chapter 3 DECISION STRUCTURES CONT’D. 22 FORMATTING FLOATING-POINT VALUES WITH THE DecimalFormat CLASS We can use the DecimalFormat class to control.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
 Pearson Education, Inc. All rights reserved Formatted Output.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
CIS 260: App Dev I. 2 Objects and Reference Variables n Predefined Java classes you have used:  String —for defining and manipulating strings  Integer.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Using Classes BCIS 3680 Enterprise Programming. Overview 2  Using Classes  Using premade classes for input and output  Display output: System, JOptionPane.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Introduction Chapter 1 Overview 1. 2 Chapter Objectives Examine how a Java program is processed Learn what an algorithm is and explore problem-solving.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 3 Introduction to Objects and Input/Output.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
Chapter 2 – Continued Basic Elements of Java. Chapter Objectives Type Conversion String Class Commonly Used String Methods Parsing Numeric Strings Commonly.
File Input/Output. 2Java Programming: From Problem Analysis to Program Design, 3e File Input/Output File: area in secondary storage used to hold information.
Chapter 2: Java Fundamentals Type conversion,String.
1 Java Programming 1 Introduction to Basic GUI Lesson 4.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Java Fundamentals 5. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Objectives ► Become familiar with the class String ► ► Learn how to use input and output dialog boxes in a program ► ► Learn how to tokenize the input.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Data Types – Reference Types Objective To understand what reference types are The need to study reference types To understand Java standard packages To.
GUI Graphical User Interface Each onscreen component and window is an object Object interaction makes communication and scoping challenging Event-driven.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 3 Introduction to Objects and Input/Output.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 3: Using Classes and Objects Coming up: Creating Objects.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
JAVA 1.COMPARISON: JAVA AND C++ 2.KEYBOARD INPUT 3.OUTPUT 4.CONVERSION FROM STRING 5.OPERATORS AND EXPRESSIONS 6.DIALOG BOX – USER PROMPT January
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Chapter 3: Introduction to Objects and Input/Output
Chapter 3 Introduction to Classes, Objects Methods and Strings
Java Fundamentals 4.
Java Programming: Guided Learning with Early Objects
File Input / Output.
Java Programming Lecture 2
Outline Creating Objects The String Class Packages Formatting Output
Objectives You should be able to describe: Interactive Keyboard Input
University of Central Florida COP 3330 Object Oriented Programming
2.5 Another Java Application: Adding Integers
Java Programming: From Problem Analysis to Program Design, 4e
OUTPUT STATEMENTS GC 201.
Chapter 3: Introduction to Objects and Input/Output
Chapter 2: Basic Elements of Java
Chapter 3: Introduction to Objects and Input/Output
Introduction to Java Programming
Presentation transcript:

Lecture 2 Objectives Learn about objects and reference variables. Explore how to use predefined methods in a program. Become familiar with the class String. Learn how to use input and output dialog boxes in a program. Java Programming: From Problem Analysis to Program Design, Second Edition

Lecture 2 Objectives Explore how to format the output of decimal numbers with the String method format. Become familiar with file input and output. Java Programming: From Problem Analysis to Program Design, Second Edition

Object and Reference Variables Declare a reference variable of a class type. Allocate memory space for data. Instantiate an object of that class type. Store the address of the object in a reference variable. Java Programming: From Problem Analysis to Program Design, Second Edition

Object and Reference Variables int x; //Line 1 String str; //Line 2 x = 45; //Line 3 str = "Java Programming"; //Line 4 Java Programming: From Problem Analysis to Program Design, Second Edition

Object and Reference Variables String str; str = "Hello there!"; Java Programming: From Problem Analysis to Program Design, Second Edition

Object and Reference Variables Primitive type variables directly store data into their memory space. Reference variables store the address of the object containing the data. An object is an instance of a class and the operator new is used to instantiate an object. Java Programming: From Problem Analysis to Program Design, Second Edition

Using Predefined Classes and Methods in a Program There are many predefined packages, classes, and methods in Java. Library: A collection of packages. Package: Contains several classes. Class: Contains several methods. Method: A set of instructions. Java Programming: From Problem Analysis to Program Design, Second Edition

Using Predefined Classes and Methods in a Program To use a method you must know: Name of the class containing the method (Math). Name of the package containing the class (java.lang). Name of the method - (pow), its has two parameters Math.pow(x, y) = xy Java Programming: From Problem Analysis to Program Design, Second Edition

Using Predefined Classes and Methods in a Program Example method call: import java.lang; //imports package Math.pow(2, 3); //calls power method // in class Math Dot (.)operator: Used to access the method in the class. Java Programming: From Problem Analysis to Program Design, Second Edition

The class String String variables are reference variables. Given: String name; Equivalent statements: name = new String("Lisa Johnson"); name = "Lisa Johnson"; Java Programming: From Problem Analysis to Program Design, Second Edition

The class String A String object is an instance of class String. A String object with the value "Lisa Johnson" is instantiated. The address of the object is stored in name. The new operator is unnecessary when instantiating Java strings. String methods are called using the dot operator. Java Programming: From Problem Analysis to Program Design, Second Edition

Some Commonly Used String Methods Java Programming: From Problem Analysis to Program Design, Second Edition

Some Commonly Used String Methods Java Programming: From Problem Analysis to Program Design, Second Edition

Some Commonly Used String Methods Java Programming: From Problem Analysis to Program Design, Second Edition

Some Commonly Used String Methods Java Programming: From Problem Analysis to Program Design, Second Edition

Input/Output Input data Format output Output results Read from and write to files Java Programming: From Problem Analysis to Program Design, Second Edition

Formatting Output with printf The syntax to use the method printf to produce output on the standard output device is: System.out.printf(formatString); or System.out.printf(formatString, argumentList); formatString is a string specifying the format of the output and argumentList is a list of arguments. argumentList is a list of arguments that consists of constant values, variables, or expressions. If there is more than one argument in argumentList, the arguments are separated with commas. Java Programming: From Problem Analysis to Program Design, Second Edition

Formatting Output with printf System.out.printf("Hello there!"); Consists of only the format string and the statement: System.out.printf("There are %.2f inches in %d centimeters.%n", centimeters / 2.54, centimeters); Consists of both the format string and argumentList. %.2f and %d are called format specifiers. By default, there is a one-to-one correspondence between format specifiers and the arguments in argumentList. The first format specifier, %.2f, is matched with the first argument, which is the expression centimeters / 2.54. The second format specifier, %d, is matched with the second argument, which is centimeters. The format specifier %n positions the insertion point at the beginning of the next line. Java Programming: From Problem Analysis to Program Design, Second Edition

Formatting Output with printf A format specifier for general, character, and numeric types has the following syntax: %[argument_index$][flags][width][.precision]conversion The expressions in square brackets are optional. That is, they may or may not appear in a format specifier. The optional argument_index is a (decimal) integer that indicates the position of the argument in the argument list. The first argument is referenced by "1$," the second by "2$," etc. The optional flags is a set of characters that modify the output format. The optional width is a (decimal) integer that indicates the minimum number of characters to be written to the output. The optional precision is a (decimal) integer that is usually used to restrict the number of characters. The required conversion is a character that indicates how the argument should be formatted. Java Programming: From Problem Analysis to Program Design, Second Edition

Formatting Output with printf Java Programming: From Problem Analysis to Program Design, Second Edition

Parsing Numeric Strings A string consisting of only integers or decimal numbers is called a numeric string. To convert a string consisting of an integer to a value of the type int, we use the following expression: Integer.parseInt(strExpression) Integer.parseInt("6723") = 6723 Integer.parseInt("-823") = -823 Java Programming: From Problem Analysis to Program Design, Second Edition

Parsing Numeric Strings To convert a string consisting of a decimal number to a value of the type float, we use the following expression: Float.parseFloat(strExpression) Float.parseFloat("34.56") = 34.56 Float.parseFloat("-542.97") = -542.97 To convert a string consisting of a decimal number to a value of the type double, we use the following expression: Double.parseDouble(strExpression) Double.parseDouble("345.78") = 345.78 Double.parseDouble("-782.873") = -782.873 Java Programming: From Problem Analysis to Program Design, Second Edition

Parsing Numeric Strings Integer, Float, and Double are classes designed to convert a numeric string into a number. These classes are called wrapper classes. parseInt is a method of the class Integer, which converts a numeric integer string into a value of the type int. parseFloat is a method of the class Float and is used to convert a numeric decimal string into an equivalent value of the type float. parseDouble is a method of the class Double, which is used to convert a numeric decimal string into an equivalent value of the type double. Java Programming: From Problem Analysis to Program Design, Second Edition

Using Dialog Boxes for Input/Output Use a graphical user interface (GUI). class JOptionPane Contained in package javax.swing. Contains methods showInputDialog and showMessageDialog. Syntax: str = JOptionPane.showInputDialog(strExpression) Program must end with System.exit(0); Java Programming: From Problem Analysis to Program Design, Second Edition

Parameters for the Method showMessageDialog Java Programming: From Problem Analysis to Program Design, Second Edition

JOptionPane Options for the Parameter messageType Java Programming: From Problem Analysis to Program Design, Second Edition

JOptionPane Example Java Programming: From Problem Analysis to Program Design, Second Edition

Formatting the Output Using the String Method format Example 3-13 double x = 15.674; double y = 235.73; double z = 9525.9864; int num = 83; String str; Java Programming: From Problem Analysis to Program Design, Second Edition

File Input/Output File: An area in secondary storage used to hold information. You can also initialize a Scanner object to input sources other than the standard input device by passing an appropriate argument in place of the object System.in. We make use of the class FileReader. Java Programming: From Problem Analysis to Program Design, Second Edition

File Input/Output Suppose that the input data is stored in a file, say prog.dat, and this file is on the floppy disk A. The following statement creates the Scanner object inFile and initializes it to the file prog.dat: Scanner inFile = new Scanner (new FileReader("a:\\prog.dat")); You use the object inFile to input data from the file prog.dat just the way you used the object console to input data from the standard input device using the methods next, nextInt, nextDouble, and so on. Java Programming: From Problem Analysis to Program Design, Second Edition

File Input/Output Java file I/O process: Import necessary classes from the packages java.util and java.io into the program. Create and associate appropriate objects with the input/output sources. Use the appropriate methods associated with the variables created in Step 2 to input/output data. Close the files. Java Programming: From Problem Analysis to Program Design, Second Edition

File Input/Output Example: Suppose an input file, say employeeData.txt, consists of the following data: Emily Johnson 45 13.50 Scanner inFile = new Scanner (new FileReader("a:\\employeeData.txt")); String firstName; String lastName; double hoursWorked; double payRate; double wages; firstName = inFile.next(); lastName = inFile.next(); hoursWorked = inFile.nextDouble(); payRate = inFile.nextDouble(); wages = hoursWorked * payRate; inFile.close(); //close the input file Java Programming: From Problem Analysis to Program Design, Second Edition

Storing (Writing) Output in a File To store the output of a program in a file, you use the class PrintWriter. Declare a PrintWriter variable and associate this variable with the destination. Suppose the output is to be stored in the file prog.out on floppy disk A. Consider the following statement: PrintWriter outFile = new PrintWriter("a:\\prog.out"); This statement creates the PrintWriter object outFile and associates it with the file prog.out on floppy disk A. You can now use the methods print, println, printf, and flush with outFile in the same way they have been used with the object System.out. Java Programming: From Problem Analysis to Program Design, Second Edition

Storing (Writing) Output in a File The statement: outFile.println("The paycheck is: $" + pay); stores the output—The paycheck is: $565.78—in the file prog.out. This statement assumes that the value of the variable pay is 565.78. Step 4 requires closing the file. You close the input and output files by using the method close. inFile.close(); outFile.close(); Closing the output file ensures that the buffer holding the output will be emptied; that is, the entire output generated by the program will be sent to the output file. Java Programming: From Problem Analysis to Program Design, Second Edition

Storing (Writing) Output in a File (throws clause) During program execution, various things can happen; for example, division by zero or inputting a letter for a number. In such cases, we say that an exception has occurred. If an exception occurs in a method, then the method should either handle the exception or throw it for the calling environment to handle. If an input file does not exist, the program throws a FileNotFoundException. If an output file cannot be created or accessed, the program throws a FileNotFoundException. For the next few chapters, we will simply throw the exceptions. Because we do not need the method main to handle the FileNotFoundException exception, we will include a command in the heading of the method main to throw the FileNotFoundException exception. Java Programming: From Problem Analysis to Program Design, Second Edition

Skeleton of I/O Program Java Programming: From Problem Analysis to Program Design, Second Edition

Lecture 2 Summary Primitive type variables store data into their memory space. Reference variables store the address of the object containing the data. An object is an instance of a class. Operator new is used to instantiate an object. Garbage collection reclaims memory that is not being used. Java Programming: From Problem Analysis to Program Design, Second Edition

Lecture 2 Summary To use a predefined method, you must know its name and the class and package it belongs to. The dot (.) operator is used to access a certain method in a class. Methods of the class String are used to manipulate input and output data. Dialog boxes can be used to input data and output results. Data can be read from and written to files. Data can be formatted using the String method format. Java Programming: From Problem Analysis to Program Design, Second Edition