ITCS 1213

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

creating an object is called instantiation

creating an object is called instantiation

An object is an instance of a class

An object is an instance of a class

String concat(String str)

concat(String str) Concatenates the specified string to the end of this string.

What is the use of Javadoc comments?

/** */ - Using Javadoc comments allows the comments to be used in the generation of html documentation.

How many versions of indexOf() are available in the String class?

4

A Java project is made up of class definitions.

A Java project is made up of class definitions.

Class Definition File

A class definition file is a file composed of fields and methods.

A class is a template for an object

A class is a template for an object

Where a Program Begins Executing

A program begins executing at a method named main() in a public class. i.e.: public static void main (String [] args)

Runtime Errors

A runtime error is an error that occurs during the execution of a program either due to user error or logic errors. The code will compile, but some error occurs while the program is running (i.e. not a syntax error).

What parameter type does the contains() method require?

CharSequence (String)

Classes

Classes are templates (blueprints) from which objects are created. The public class name must match the file name exactly.

Constants

Constants are fields only, use the keyword final, and are named in ALL_CAPS

Constructor Methods

Constructor methods must have the exact same name as the class which contains them. They have no return type. Their purpose is to construct/make objects by giving fields their starting values. Like most methods, they are generally public access. Default constructor methods take in no parameters and set all fields (not including constants) to a zero value. If you do not create a constructor method, Java will create one for you, which will be a default constructor.

Reading Input with the Scanner Class

Create a Scanner object and use the Scanner class methods to read input. System.in reads input from the keyboard. Here are some of the Scanner class methods used to read input: nextInt() - reads integer data nextDouble() - reads floating-point (double) data next() - reads a string up until the first space nextLine() - reads a string including spaces next().charAt(int) - reads a character at the specified index

Fields

Fields are a part of the class definition file which constitute the attributes of the object to be created. Fields are generally private access.

Fields vs Local Variables

Fields are declared above/outside of any methods. Local variables are contained within methods and are limited to the method in which they are declared. Local variables do not require an access type.

Where are fields declared?

Fields are declared outside of any methods.

Encapsulation

Fields within a class definition file are hidden from the rest of the program and can only be accessed by methods within the same class definition file. This protects the field values from being accidentally, or unnecessarily, altered by external files/sources.

Get Methods

Get (accessor) methods are used to return the values of the fields. Remember that these methods can only return one value.

What is the purpose of accessor (getter) methods?

Get methods return a value from an object.

What is the starting point for the execution of a Java project?

In a method named main() within a public class; i.e. public static void main()

What data type does the constructor method return?

It has no return type?

What is the purpose of the constructor method?

It is used to create an object by giving the fields their starting values.

What is the purpose of the trim() method?

It removes leading and trailing whitespace.

Where are local variables declared?

Local variables are declared within methods.

Method Overloading

Method overloading is the use of multiple methods with the same name, but with different parameter lists. Parameter lists are made up of the sequence of data types, not their parameter names. Two methods with the same name may NOT have the same sequence of data types in their parameter lists.

Methods

Methods are a part of the class definition file which constitute the actions available to the object to be created from the template. Methods are generally public access.

boolean contains(CharSequence s)

contains(CharSequence s) Returns true if and only if this string contains the specified sequence of char values.

Can a field declared as type boolean hold a value of 1?

No. A boolean can only hold true or false.

Objects

Objects are instances of a class. The creation of an object is also called instantiation.

Parameters

Parameters are declared within the method header. They are only known within that method.

Putting the data for an object and the methods that can access and change this data together in the same file is called encapsulation.

Putting the data for an object and the methods that can access and change this data together in the same file is called encapsulation.

Why do we declare fields of a class using private access?

This ensures that only methods within the same class can access the fields and cannot be accidentally/unnecessarily altered.

Set Methods

Set (mutator) methods are used to change/assign values of fields. Note that set methods should not return any values and are generally void methods.

What is the purpose of mutator (setter) methods?

Set methods assign/change the values of fields.

What data type do the valueOf() methods return?

String

Suppose you have written a class definition for a Student class. Write the line of code you would use to declare a reference to a Student object.

Student referenceName;

Suppose in the Student class there is a method that returns the student's ID. Write the line of code to print the student's ID to the screen using this getter method.

System.out.print (referenceName.getStudentID());

Write the code to extract and print "Miss" from the following String object: String river = new String("Mississippi");

System.out.print (river.substring(0,4));

Do the same as above, except print a String object that holds "miss". String river = new String("Mississippi");

System.out.print (river.substring(0,4).toLowerCase());

Generating Output

System.out.print() - leaves the cursor on the same line System.out.println() - moves the cursor to the next line (i.e. uses the newline character '\n') Include + between data (e.g. literals, variables, get methods)

The Java Language

The JDK (Java Development Kit) is the platform released by Oracle. Java is a translated language: the Java compiler (javac) produces byte code which is translated by the Java Virtual Machine (JVM). Java source code is contained in a file with the extension .java.

The Java API (Application Programming Interface)

The Java API is a collection (library) of pre-written code/classes. A package is a namespace for organizing classes (i.e. folders). Importing the code packages allows the use of the classes it contains and their methods (e.g. java.util.Scanner, java.lang.String). The import statement imports the package/class/methods. If left out, you must declare the location of the class at each instance of the class in your code.

The String Class

The String class is found in the java.lang package, which is included and does not need to be imported. String Class Methods

Access Specifiers

The access specifier determines what can access fields and methods. Private access allows only elements within the same class definition file access (e.g. fields). They are hidden from the rest of the program (i.e. external files). Public access allows elements outside of the class definition file access (e.g. methods). They are not hidden from the rest of the program.

What is the name of the constructor method?

The constructor method has the same name as the class that contains it.

The . (dot) Operator

The dot operator allows access to public (i.e. non-private) methods in a class.

Creating an Object

The new keyword is used to create an object from a class. Once the object is created, a method other than the constructor method is needed to modify it (e.g. setter/mutator methods).

The Ternary Operator

The ternary operator can be used as shorthand for an if/else statement. They are set up as follows: (test expression) ? (execute this if true) : (execute this if false); // Example: boolean eligible; int age = 35; eligible = age >= 21 ? true : false; // This is the same as: if (age >= 21) eligible = true; else eligible = false;

Java Data Types

There are two general data types in Java: primitive and reference. Primitive data types are subdivided into numeric and non-numeric data types. Numeric data types include integer (i.e. int, byte, short, long) and floating-point (i.e. float, double). Non-numeric data types include char and boolean. Note that boolean data types hold only "true" or "false"; they cannot be 0 or 1 as they can be in C++. Reference data types hold the memory address of an object (like pointers in C++). This includes String, Scanner, and other object classes. Note that primitive data types are lowercase, while reference data types start with an uppercase letter.

Documentation

Three types of comments: /* */ // /** */ Javadoc tags: @author Name @version Version/Date @param paramName description of the parameter (used above methods) @return description of the value returned (used above methods) Documentation also includes the use of white space, case conventions (e.g. camel case, uppercase), variable names, etc.

The constructor method is only called when an object is created. True or False?

True

Usually fields have private access and methods have public access

Usually fields have private access and methods have public access

What are two String methods you can use to determine if the two strings have the same value: "Charlotte" is the same as "Charlotte": equals() "Charlotte" is the same as "charlotte": equalsIgnoreCase()

What are two String methods you can use to determine if the two strings have the same value: "Charlotte" is the same as "Charlotte": equals() "Charlotte" is the same as "charlotte": equalsIgnoreCase()

Using the Debugger

You can set a stop point by clicking in the margin in BlueJ. To open the debugger, click view > debugger. Then run the program. The step tool allows you to run the code line-by-line. Each line will execute. The step into tool allows you to jump into a method call to run that method's code line-by-line, rather than simply executing the line's code. Continue will cause the program to execute as normal until the next stop point. Terminate will stop the debugger end the program's execution. In the debugger, local variables reference variables within e.g. the main() method, while instance variables reference the fields in the class definition file. Double-clicking reference variables in the debugger will show their values.

Write the line(s) of code to get a version of this String in all uppercase letters: String city = new String("Charlotte"); String capCity;

capCity = city.toUpperCase();

char charAt(int index)

charAt(int index) Returns the char value at the specified index.

Write this if statement using the ternary operator: if (age > 21) { eligible = true; } else { eligible = false; }

eligible = age > 21 ? true : false;

boolean equals(Object anObject)

equals(Object anObject) Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)

equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations.

The public class name in a Java source code file must have the same name as the

file name

Write a loop to [read] integer values until the user enters a -999 to quit. When the user is done, print the sum of the numbers entered. // put your import statement here:

import java.util.Scanner; public static void main (String[]args) { int number; // declare a Scanner reference variable Scanner kb; // declare other needed variables intsum=0; number = 0; // create a Scanner object to read data from the keyboard kb = new Scanner(System.in); // write the code to perform the task while (number != -999) { sum += number; System.out.print("Enter a number or -999 to quit: "); number = kb.nextInt(); } System.out.print(sum); }

int indexOf(String str)

indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.

int indexOf(String str, int fromIndex)

indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

int indexOf(int ch)

indexOf(int ch) Returns the index within this string of the first occurrence of the specified character.

int indexOf(int ch, int fromIndex)

indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

What parameter type does the charAt() method require?

int

This one is more challenging and takes more than one line of code. Write the code to get and print how many times the letter 'a' occurs in this String object: String fruit = new String("banana");

int count = 0; for (int index = 0; index < fruit.length(); ) { if (fruit.indexOf('a', index) != -1) { count++; index = fruit.indexOf('a', index) + 1; } else index = fruit.length(); } System.out.print(count);

What numeric data type can hold an exact value?

integer (?)

What package is the String class located in?

java.lang

What is the name of the Java compiler?

javac

int lastIndexOf(String str)

lastIndexOf(String str) Returns the index within this string of the last occurrence of the specified substring.

int lastIndexOf(String str, int fromIndex)

lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

int lastIndexOf(int ch)

lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character.

int lastIndexOf(int ch, int fromIndex)

lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

Which String method returns how many characters are in a String object?

length()

int length()

length() Returns the length of this string.

What primitive Java data type can hold the largest integer value?

long

What keyword is used to create an object from the class definition?

new

Look up the Scanner class in the Java API documentation. Write four methods that belong to the Scanner class.

next(), nextBoolean(), nextDouble(), nextFloat(), nextInt(), nextLine(), etc.

What are the two categories of data types in Java?

primitive and reference

What are the two types of access to class members we have done?

public and private

Suppose you have already written the class for a Bowler. The Bowler class has two fields: a full name and a high score. Write the main() method to create two instances of this Bowler class. Get the input from the user and send the name and high score values to the constructor method of the Bowler class.

public static void main (String[]args) { Bowler player1, player2; String playerName; int playerHighScore; Scanner kb = new Scanner(System.in); System.out.print("Enter the first player's full name: "); playerName = kb.nextLine(); System.out.print("Enter the first player's high score: "); playerHighScore = kb.nextInt(); player1 = new Bowler(playerName, playerHighScore); // Repeat for player2... }

Write the line of code you would use to create a Student object and assign its address to the reference you declared [above]. You do not have to send any parameters to the Student class constructor.

referenceName = new Student();

String replace(CharSequence target, CharSequence replacement)

replace(CharSequence target, CharSequence replacement) Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

String replace(char oldChar, char newChar)

replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

The valueOf() method has another keyword next to the data type it returns. What is the keyword?

static

String substring(int beginIndex)

substring(int beginIndex) Returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex)

substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string.

Class definitions have two parts:

the fields and the methods.

String toLowerCase()

toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale.

String toUpperCase()

toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale.

String trim()

trim() Returns a copy of the string, with leading and trailing whitespace omitted.

Write the line(s) of code to find out if the String has the letter 'e' in it. String word = new String("apple");

word.contains("e");


Set pelajaran terkait

Chapter 4 Quiz Organizational Behavior

View Set

THEO1920 Religion and Secularity in the Modern World

View Set

Chapter 7 - Attitudes, Behaviour and Rationalisation

View Set

Managing Family Business Chapter 2

View Set

الملك حسين بن طلال

View Set

teamwork and collaboration prep u

View Set

Year 9 Science Semester 2 Exam Revision

View Set

Living With Art- Chapter 3 (Themes of Art)

View Set

Ripasso: capitolo 1 (Avanti con l'italiano)

View Set