API, Wrapper classes, printf, and methods

Slides:



Advertisements
Similar presentations
Chapter 5 - Using Pre-Built Methods
Advertisements

Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
The printf Method The printf method is another way to format output. It is based on the printf function of the C language. System.out.printf(,,,..., );
Chapter 5 - Using Pre-Built Methods The API Library API Headings Math Class Wrapper Classes for Primitive Types Lottery Example Character Class String.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Class Library, Formatting, Wrapper Classes, and JUnit Testing
EPSII 59:006 Spring Introduction In this lecture  Formatted Input/Output scanf and printf  Streams (input and output) gets, puts, getchar, putchar.
1 2 2 Introduction to Java Applications Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 3 Introduction to Objects and Input/Output.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
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.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
Lecture 2 Objectives Learn about objects and reference variables.
© 2004 Pearson Addison-Wesley. All rights reserved September 7, 2007 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 3 Introduction to Objects and Input/Output.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
Java Variables, Types, and Math Getting Started Complete and Turn in Address/Poem.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
By Mr. Muhammad Pervez Akhtar
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CS 1704 Introduction to Data Structures and Software Engineering.
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
Simple Console Output. What we will briefly discuss System.out.println( … ) System.out.print( … ) System.out.printf( … )
Simple Console Output CS 21a. What we will briefly discuss System.out.println( … ) System.out.print( … ) System.out.printf( … )
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
CompSci 230 S Programming Techniques
28 Formatted Output.
Chapter 9 - Formatted Input/Output
More About Objects and Methods
Creating Your Own Classes
Chapter 5 - Using Pre-Built Methods
JAVA MULTIPLE CHOICE QUESTION.
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Formatting Output & Enumerated Types & Wrapper Classes
3 Introduction to Classes and Objects.
Introduction to Classes and Objects
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
TMF1414 Introduction to Programming
Primitive and Reference Data Values
Classes, Libraries & Packages
OUTPUT STATEMENTS GC 201.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Chapter 5 - Using Pre-Built Methods
CSC240 Computer Science III
IDENTIFIERS CSC 111.
Chapter 3: Introduction to Objects and Input/Output
Java Variables, Types, and Math Getting Started
Java Classes and Objects 3rd Lecture
Chapter 9 - Formatted Input/Output
Chapter 3: Introduction to Objects and Input/Output
Introduction to Java Applications
Java Programming Language
CS 1054 Introduction to Programming in Java
Presentation transcript:

API, Wrapper classes, printf, and methods

The API Library API stands for “Application Programming Interface” -In fact, you have been using it -The Scanner class is one small part In general, your programs must “import” the API classes they use import java.util.Scanner; java.util is a “package” Packages are collections of related classes Programs automatically import java.lang -java.lang contains critical classes that many programs need Math String -The automatic import is equivalent this line import java.lang.*; The * matches all classes in the package

Wrapper Classes For Primitive Types A wrapper class : surrounds a relatively simple item in order to add functionality. Java has wrappers for the primitive types: Wrapper Class Primitive Type Integer int Long long Float float Double double Character char Defined in java.lang

Wrapper Classes help convert Strings Number wrappers help with string conversion Wrapper Class string  number number  string Integer Integer.parseInt(<string>) Integer.toString(<#>) Long Long.parseLong(<string>) Long.toString(<#>) Float Float.parseFloat(<string>) Float.toString(<#>) Double Double.parseDouble(<string>) Double.toString(<#>) Various uses, esp. GUI programming

Conversions of Primitive Types Conversion examples - strings to numbers: String yearStr = "2011"; String scoreStr = "78.5"; int year = Integer.parseInt(yearStr); double score = Double.parseDouble(scoreStr); Conversion examples - numbers to strings : int year = 2011; double score = 78.5; String yearStr = Integer.toString(year); String scoreStr = Double.toString(score);

Formatted Output with the printf Method You should strive to make program output be understandable and attractive. To further that goal, format your output. Here's an example of formatted output: Account Actual Budget Remaining ------- ------ ------ --------- Office Supplies 1,150.00 1,400.00 250.00 Photocopying 2,100.11 2,000.00 (100.11) Total remaining: 149.89 The System.out.printf method is in charge of generating formatted output. Mostly useful for controlling format of numbers

Formatted Output with the printf Method Here's how to generate the "Total remaining" line in the previous slide's budget report: System.out.printf( "\nTotal remaining: $%.2f\n", remaining1 + remaining2); You can have as many format specifiers as you like in a given format string. For each format specifier, you should have a corresponding data item/argument. format specifier

Format Specifier Details Format specifier syntax: %[flags][width][.precision]conversion-character -Square brackets mean optional.

Conversion Character The conversion character tells the Java Virtual Machine (JVM) the type of thing that is to be printed. Here is a partial list of conversion characters: s This displays a string. d This displays a decimal integer (an int or a long). f This displays a floating-point number (a float or a double) e This displays a floating-point number (float or double) in scientific notation.

Conversion Character This code fragment illustrates how to use the conversion characters: System.out.printf("Planet: %s\n", "Neptune"); System.out.printf("Number of moons: %d\n", 13); System.out.printf("Orbital period (in earth years): %f\n", 164.79); System.out.printf( "Average distance from the sun (in km): %e\n", 4_498_252_900.0); Here is the output: Planet: Neptune Number of moons: 13 Orbital period (in earth years): 164.790000 Average distance from the sun (in km): 4.498253e+09

Precision and Width Precision: Only for floating-point numbers Consists of a dot and then the number of digits that will be printed to the right of the decimal point. If the data item has extra fractional digits, then rounding occurs. If the data item has fewer fractional digits, then zeros are added at the righ. Width: Specifies the minimum number of characters that are to be printed. If the data item contains fewer than the specified number of characters, then spaces are added. By default, output values are right aligned, so when spaces are added, they go on the left side.

Precision and Width This code fragment illustrates how to specify precision and width in a format specifier: System.out.printf("Cows are %6s\n", "cool"); System.out.printf("But dogs %2s\n", "rule"); System.out.printf("PI = %7.4f\n", Math.PI); Here is the output: Cows are cool But dogs rule PI = 3.1416 6 characters 7 characters

METHODS Methods reduce code size by factoring similar code into one program location Using this feature makes code more self-documenting, (b) smaller, and (c) less error prone

METHOD DECLARATIONS Visibility modifier (e.g. public, private, protected) Non-access modifiers (e.g. static, final ) Return Type (e.g. void, String, int, boolean[]) Name Parameter List Body

VISIBILITY A private method can be invoked only from the class in which it is declared A public method can be invoked from anyone A protected method can be invoked from the package the method in which it is declared

STATIC MODIFIER (IN ACTION) Math-Class Methods(partial list)

RETURN TYPES A void method returns no value (but can still return;) A non-void is marked with a specific return type and must return a value of type on all code paths

RETURN TYPES (VOID) public static void printPrimes(int[] numbers) { if (numbers == null || numbers.length == 0) { return; // Explicit "early-out" from void method } for (int number : numbers) { if (isPrime(number)) { System.out.println(number); // No return _necessary_ from void functions

RETURN TYPES public static double getMax(double[] numbers) { if (numbers == null || numbers.length == 0) { return Double.NaN;// Explicit "early-out" with a value } double runningMax = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (runningMax < numbers[i]) { runningMax = numbers[i]; return runningMax; // Return necessary from all code paths

RETURN TYPES (POSSIBLE RETURNS) public static String probPrompt(Scanner s, float prob) { if (Math.random() < prob) { System.out.print("Enter something: "); return s.nextLine(); } // Illegal, method may not produce a value but is non-void

RETURN TYPES (POSSIBLE RETURNS) public static String probaPrompt(Scanner s, float prob) { if (Math.random() < prob) { System.out.print("Enter something: "); return s.nextLine(); } return null; }

PARAMETER LIST Parameters are the method's name for input variables Each parameter has a name and type - can also be final Arguments are the values someone gives the method When invoking a method, the arguments and parameters must align

FINAL PARAMETERS public static void cantChangeMe(final double x) { x = y + 1; // ILLEGAL } public static void canModifyButNotAssignRefTypes(final double[] x) { x[0] = x[1] / 2; // Go for it x[1] = x[2] / 2; // Go for it x = new double[5]; // ILLEGAL }

OVERLOADING Two methods can have the same name as long as their parameters differ (in length or type) The method which is invoked is determined by the method which matches the argument list most closely

OVERLOADING (DIFFERING ARITY) public static void f(String s) { System.out.print(s); } public static void f(String s, int i) {System.out.print(s+i); } public static void test() { f("foobar"); // ?? f("foobar", 2); // ?? }

OVERLOADING (DIFFERING TYPE) public static void f(int i, int j) { /* body omitted */ } public static void f(float i, float j) { /* body omitted */ } public static void test() { f(204, 304); //? f(2.4, 304); //? f(204, 3.4); //? f(2.4, 3.4); //? }

OVERLOADING (DIFFERING TYPE) public static void f(int i, int j) { /* body omitted */ } public static void f(float i, float j) { /* body omitted */ } public static void test() { f(204, 304); // first f(2.4, 304); // second f(204, 3.4); // second f(2.4, 3.4); // second }

OVERLOADING (SPECIFIC MATCH) public static void f(char i, int j) { /* body omitted */ } public static void f(char i, double j) { /* body omitted */ } public static void test() { f('a', 'a'); // first (char -> int more specific than -> double) }

OVERLOADING (AMBIGUOUS MATCH) public static void f(char i, int j) { /* body omitted */ } public static void f(double i, char j) { /* body omitted */ } public static void test() { f('a', 'a'); // none, is a compiler error (ambiguous call) }