Chapter 3: Object Oriented Programming

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Scanner Class Constructor

- Scanner( InputStream dataSource ): creates a Scanner object that will read from the InputStream dataSource. To read from the keyboard, we will use the predefined " InputStream System.in " Return Value | Method Name and Argument List byte | nextByte( ): returns the next input as a byte short | nextShort( ): returns the next input as a short int | nextInt( ): returns the next input as an int long | nextLong( ): returns the next input as a long float | nextLong( ): returns the next input as a long double | nextDouble( ): returns the next input as a double boolean | nextBoolean( ): returns the next input as a boolean String | next( ): returns the next token in the input line as a String String | nextLine( ): returns the unread characters of the input line as a String - the Scanner class is defined in the java.util package, so we need to include the following import statement: import java.util.Scanner; - the following statement will instantiate a Scanner object named scan and associate the keyboard as its data source: Scanner scan = new Scanner( System.in );

Application Programming Interface < API >

- a block of code in the operating system that software applications need to interact with - the authors of classes publish their API so that their clients know what methods are available and how to call those methods - a class API consists of the class method names, their return values, and their argument lists

String Class

- a class that holds a group of characters - often used with user ID and passwords - does not require an import statement string constructors include: String ( String str ) - allocates a String object with the value of str, which can be a String object or a String literal String ( ) - allocates an empty String object example of string concatenation: System.out.println( "The sum of 1 and 2 is " + ( 1 + 2 ) );

Object Oriented Programming < OOP >

- a program that uses classes and objects - every java programs contains at least one class - creating an object of a class is called " instantiating an object ," and this object is called an " instance of the class " - many objects can be instantiated from one class: student1, student2, student3 - the data associated with an object of a class are called " instance variables ," or " fields , " and can be variables and constants of any primitive data type (byte, short, int, long, float, double, char, and boolean), or they can be objects of a class - object names, instance variables, and method names conventionally start with a lowercase letter

Constructor

- a sequence of statements for initializing a newly instantiated object - assigns initial values to the data of the class

Random Class Constructor

- syntax: Random( ) = creates a random number generator with a seed generated using the system time - nextInt Method: return value = int, method name and argument list: nextInt(integer number) ; returns a random integer ranging from 0 up to, but not including, number in uniform distribution

Char Method

- the charAt method returns the character at a specified index in a String; one of the uses of this method is for extracting just the first character of a String, which might be advantageous when prompting the user for an answer to a question example: char answerChar = answerString.charAt( 0 );

Index Method

- the indexOf methods are useful for searching a String for a specific character or String - there are two versions of this method, one that accepts a single char as the argument and one that accepts a String as an argument

Length Method

- the length method returns the number of characters in a String, including any spaces and punctuation

Encapsulation

- the methods of the class provide the only interface to set or change the data values from outside the class - only the methods of the class can change the data of an object, and thus the methods provide a protective layer around the data - benefit from this encapsulation is that the class methods ensure that only valid values are assigned to an object - encapsulation of a class's data and methods helps to isolate operations on the data

Min and Max Method

- the min and max methods return the smaller or larger of their two arguments < examples: int smaller = Math.min( 8, 2 ); 10 System.out.println( "The smaller of 8 and 2 is " + smaller ); int larger = Math.max( 8, 2 ); 13 System.out.println( "The larger of 8 and 2 is " + larger ); < int a = 8, b = 5, c = 12; int tempSmaller = Math.min( a, b ); int smallest = Math.min( tempSmaller, c ); System.out.println( "The smallest of " + a + ", " + b + ", and " 19 + c + " is " + smallest ); the min method can also be used to compute the smallest of three variables; >

Method

- the operations of a class that set the values of the data, retrieve the current values of the data, and perform other class-related functions on the data - the JVM < Java Virtual Machine > transfers control to the method and starts executing instructions in the method. When the method finishes executing, the JVM transfers control back to the program immediately after the point the method was called and continues executing instructions in the program - the argument list for a method indicates the order and number of arguments to send to the method, along with the data type of each argument - a method may or may not return a value, as indicated by a data type, class type, or the keyword void in front of the method name - to call a method use dot notation: objectReference.methodName ( arg1, arg2, arg3, . . . )

Round Method

- the round method converts a double to its nearest integer using these rules: any fractional part .0 to .4 is rounded down any fractional part .5 and above is rounded up < example : System.out.println( "23.4 rounded is " + Math.round( 23.4 ) ); System.out.println( "23.49 rounded is " + Math.round( 23.49 ) );

Substring Method

- the substring methods are useful for creating a new String from characters in an existing String - the substring method returns a group of characters, or substring, from a String; the original string is unchanged

Java White Space Characters

Character | Unicode Equivalent space | \u00A0, \u2007, \u202F tab | \u0009, \u000B line feed | \u000A form feed | \u000C carriage return | \u000D file, group, unit, and record separators | \u001C, \u001D, \u001E, \u001F

Static Constants of the Math Class

Constant | Value E | e, the base of the natural logarithm PI | pi, the ratio of the circumference of a circle to its diameter - the Math class is also part of the java.lang package; do not need to use the import statement - they are referenced using the name of the Math class and the dot notation as follows: Math.E Math.PI

Static Constants of the System Class

Constant | Value in | static constant that represents the standard input stream, by default the keyboard out | static constant that represents the standard output stream, by default the Java console Return Value | Method Name and Argument List void | exit( int exitStatus) is a static method that terminates the Java Virtual Machine. A value of 0 for exitStatus indicates a normal termination. Any other values indicate an abnormal termination and are used to signal that the program ended because an error occurred. - System.out is an object of the PrintStream class, which is also an existing Java class; it can be found in the java.io package

Java Packages

Package | Category of Class java.lang | basic functionality common to many programs, such as the String class, Math class, and object wrappers for the primitive data types java.text | classes for formatting numeric output java.util | include the Scanner class, the Random class, and other miscellaneous classes java.io | classes for reading from and writing to files

Wrapper Classes for Primitive Data Types

Primitive Data Type | Wrapper Class double | Double float | Float long | Long int | Integer short | Short byte | Byte char | Character boolean | Boolean - these classes are part of the java.lang package; they do not require import statements - Java will automatically provide the conversion through autoboxing

String Class Method Summary

Return Value | Method Name + Argument List int | length( ) returns the length of the string String | toUpperCase( ) returns a copy of the String with all letters in uppercase String | toLowerCase( ) returns a copy of the String with all letters in lowercase char | charAt( int index ) returns the character at the position specified by index int | indexOf( String searchString ) returns the index of the beginning of the first occurrence of searchString or −1 if searchString is not found int | indexOf( char searchChar ) returns the index of the first occurrence of searchChar in the String or −1 if searchChar is not found String | substring( int startIndex, int endIndex ) returns a substring of the String object beginning at the character at index startIndex and ending at the character at index endIndex − 1 String | substring( int startIndex ) returns a substring of the String object beginning at the character at index startIndex and continuing to the end of the String

NumberFormat Methods

Return Value | Method Name and Argument List NumberFormat | getCurrencyInstance( ) static method that creates a format object for money NumberFormat | getPercentInstance( ) static method that creates a format object for percentages String | format( double number ) returns a String representation of number formatted as a currency or percentage, depending on the object used to call the method - import java.text.NumberFormat; < example: double winningPercentage = .675; double price = 78.9; 15 16 // get a NumberFormat object for printing a percentage NumberFormat percentFormat = NumberFormat.getPercentInstance( ); // call format method using the NumberFormat object System.out.print( "The winning percentage is " ); System.out.println( percentFormat.format( winningPercentage ) ); // get a NumberFormat object for printing currency NumberFormat priceFormat = NumberFormat.getCurrencyInstance( ); // call format method using the NumberFormat object System.out.println( "\nThe price is: " 28 + priceFormat.format( price ) );

Integer and Double Wrapper Classes

Return Value | Method Name and Argument List int | parseInt( String s ) static method that converts the String s to an int and returns that value Integer | valueOf( String s ) static method that converts the String s to an Integer object and returns that object double | parseDouble( String s ) static method that converts the String s to a double and returns that value Double | valueOf( String s ) static method that converts the String s to a Double object and returns that object < example 1: int intPrimitive = 42; Integer integerObject = intPrimitive; System.out.println( "The int is " + intPrimitive ); System.out.println( "The Integer object is " + integerObject ); int sum = intPrimitive + integerObject; System.out.println( "Their sum is " + sum ); > < example 2: int i1 = Integer.parseInt( "76" ); // convert "76" to an int Integer i2 = Integer.valueOf( "76" ); // convert "76" to Integer System.out.println( "\nThe value of i1 is " + i1 ); System.out.println( "The value of i2 is " + i2 ); >

PrintStream Methods

Return Value | Method Name and Argument List void | print( argument ) prints argument to the standard output device; the argument can be any primitive data type, a String object, or another object reference void | println( argument ) prints argument to the standard output device, then prints a newline character.; the argument can be any primitive data type, a String, or another object reference void | println( ) prints a newline character; this method is useful for skipping a line in the program's output - can be used with various data types such as double, int, and char; variables and expressions can also be used instead of literals; can also print objects - all classes have a toString method, which converts the object data to a String for printing using this syntax: String toString( )

Math Class Method

Return Value | Method Name and Argument List dateTypeOfArg | abs( arg ) static method that returns the absolute value of the argument arg, which can be a double, float, int, or long double | log( double arg ) static method that returns the natural logarithm (in base e) of its argument, arg. For example, log(1) returns 0 and log(Math.E) returns 1 dataTypeOfArgs | min( argA, argB ) static method that returns the smaller of the two arguments; the arguments can be doubles, floats, ints, or longs dataTypeOfArgs | max( argA, argB ) static method that returns the larger of the two arguments; the arguments can be doubles, floats, ints, or longs double | pow( double base, double exp ) static method that returns the value of base raised to the exp power long | round( double arg ) static method that returns the closest integer to its argument, arg double | sqrt( double arg ) static method that returns the positive square root of arg. < examples: > double d2 = Math.log( 5 ); System.out.println( "\nThe log of 5 is " + d2 ); double d4 = Math.sqrt( 9 ); System.out.println( "\nThe square root of 9 is " + d4 ); double fourCubed = Math.pow( 4, 3 ); System.out.println( "\n4 to the power 3 is " + fourCubed ); ** the pow method takes two arguments; the first is the base and the second is the exponent **

Object Reference

- is the identifier of the object - specify the data type and an identifier syntax for declaring an object reference: ClassName objectReference1, objectReference2 instantiate the object using the following syntax: objectReference = newClassName ( argument list ); **argument list consists of a comma-separated list of initial data values to assign to the object**

Null

- it can no longer be used to call methods - it will generate either a compiler error or a NullPointerException at run time

Import Statement

- it is inserted at the top of the program after our introductory comments, but before the class statement that begins the program example: import java.text.DecimalFormat; if we're using more than one class from a package, we can import all those classes we use by replacing the class name with an asterisk, as in the following example: import java.text.*;

User Input

- methods created/used to receive data from a user - can be inputted through the: keyboard, from a file or through a Graphical User Interface (GUI)

Object

- objects of a class are created using the class as a template, or guide - when an object is instantiated, the JVM allocates memory to the new object

Pseudorandom

- pertaining to a sequence of numbers that appear to be random, but are generated by a deterministic program.

Static Method

- static methods are defined in an object but do not require instance data, therefore; they can be called directly with the class name, such as Math.random() - they can be called without instantiating an object - they are also called class methods - the API of these methods has the keyword static before the return type: static dataType methodName( arg1, arg2, . . . ) - class, or static, methods are invoked using the class name, rather than an object reference, as in the following syntax: ClassName.staticMethodName( argumentList ); < example: > absValue = Math.abs( someNumber ); the class name is Math, and the static method is abs, which returns the absolute value of the argument (someNumber) ** static methods cannot access the instance variables of the class (because instance variables are object data and exist only after an object has been instantiated) ** - like static methods, static constants are also accessed using the class name and dot operator, as in this syntax: ClassName.staticConstant Thus, the static constant representing the value of pi can be accessed this way: Math.PI

Commonly Used Java Classes

- string: which provides a data type for character sequences along with methods for searching and manipulating strings - random: which generates random numbers - scanner: which provides methods for reading input from the keyboard - system and PrintStream: which provide data members and methods for printing data on the Java console - DecimalFormat and NumberFormat: which allow us to format numbers for output - math: which provides methods for performing mathematical operations - object wrappers, which provide an object equivalent to primitive data types so they can be used in our program as if they were objects

toUpperCase and toLowerCase Method

- the toUpperCase method returns a copy of the String with all the letters in uppercase, while the toLowerCase method returns a copy of the String with all the letters in lowercase; digits and special characters are unchanged

Class

- they are composed of data and operations—or functions—that operate on the data - programs using the class, such as clients, must call the methods to set or retrieve the values of the instance variables - just as the primitive data types can be manipulated using arithmetic operators (+, −, *, /, and %), an object can be manipulated by calling the methods of its class - some of the most important benefits include reusability (not only in the current program but also in other programs), encapsulation, and reliability **tip** By convention, class names in Java start with a capital letter. Method names, instance variables, and object names start with a lowercase letter. In all of these names, embedded words begin with a capital letter.

Accessor Methods < Getters >

- they enable clients to access the value of the instance variables of an object

Random Class

- this class provided by Java is used to generate random numbers - part of the java.util package - the constructor generates a seed value, which determines where in that sequence the set of random numbers will begin

Deterministic

- this means that given a specific input to a specific set of instructions, a computer will always produce the same output

Random Numbers

- used for many operations in a program, such as rolling dice, dealing cards, timing the appearance of a nemesis in a game, or other simulations of seemingly random events

String Processing

- with the popularity of large search engines and Big Data, the ability to find, extract, and reformat information in a String of characters is becoming an important part of computer science <example: Assume we know that a String contains a name in this format: <lastname>, <firstname> that is, with the last name first, followed by a comma and a space, then the first name. Our job is to produce a String in this format: <Firstname> <Lastname>


Set pelajaran terkait

تُحْفَةُ الْأَطْفَالِ وَالْغِلْمَانِ فِي تَجْوِيْدِ الْقُرْآنِ

View Set

Topic 2 Test 2- Social Influence and Persuasion

View Set

Homeostasis - NSC 3361.HN1 - Introduction To Neuroscience - S24

View Set