JAVA 1-8, 11

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

modulus

%, returns the remainder of a division

method header

(ex. public static void main(String [ ] args)

associativity

(mathematical operators) either left to right or right to left

Checked and Unchecked Exceptions

- In Java, there are two categories of exceptions: unchecked and checked. - Unchecked exceptions are those that inherit from the Error class or the RuntimeException class. So, you should not handle unchecked exceptions. - All of the remaining exceptions (that is, those that do not inherit from Error or RuntimeException) are checked exceptions.

Exception Classes

- an exception is an object. - all of the classes in the hierarchy inherit from the Throwable class. - Just below the Throwable class are the classes Error and Exception. - An EOFException object is thrown when an application attempts to read beyond the end of a file, and a FileNotFoundException object is thrown when an application tries to open a file that does not exist.

Java automatically stores this value in all uninitialized static member variables:

0

Look at the following declaration: enum Tree { OAK, MAPLE, PINE } What is the ordinal value of the MAPLE enum constant?

1

What are the parts of the while loop?

1. a boolean expression that is tested for a true or false value 2. a statement or block of statements that is repeated as long as the expression is true

while loop

1. boolean expression that is tested for a true or false value 2. statement or block of statements that is repeated as long as the expression is true (repeats until boolean expression is false) pretest loop, which means that it tests its expression before each iteration

has parts that serve specific purposes

A Java program

You cannot use the fully-qualified name of an enum constant for this.

A case expression

If the this variable is used to call a constructor:

A compiler error will result, if it is not the first statement of the constructor

Statement

A complete instruction that causes the computer to perform some action

Variable

A named storage location in the computer's memory

When a method's return type is a class, what is actually returned to the calling program?

A reference to an object of that class

Procedure

A set of programming statements that, together, perform a specific task

Portable

A term used to describe a program that can be ran on a wide variety of computers

parameter variable

A variable that holds the value of an argument that is passed to a method

In Java, it is possible to write a method that will return:

All of the above (A whole number, A monetary value, A string of characters, A reference to an object)

exception handler

An exception handler is a section of code that gracefully responds to exceptions when they are thrown.

Disadvantages of writing in assembly code

Assembly code is very hard to read, and it takes more lines of code to set up an operation than a simple System.out.println() function. Assembly language is also machine dependent, and it's hard to maintain and debug.

Central Processing Unit (CPU)

At the heart of the computer, it is the CPU's job to fetch instructions, follow the instructions, and produce some resulting data.

CRC stands for:

Class, Responsibilities, Collaborations

Machine Language

Computer instructions

Java Virtual Machine is platform independent.

False

TRUE/FALSE: If a class has a method named finalize, it is called automatically just before a data member that has been identified as final of the class is destroyed by the garbage collector.

False

Handle each exception only once in a try statement

For example, the following try statement will cause the compiler to issue an error message because it handles a NumberFormatException object with two catch clauses

The JVM periodically performs this process to remove unreferenced objects from memory.

Garbage collection

The term for the relationship created by object aggregation is:

Has a

\t

Horizontal tab (skip to next tab stop)

Serializing Aggregate objects

If a class implements the Serializable interface, then all of the fields in that class must be serializable This means that the object's class should also implement the Serializable interface. If it doesn't, then the transient key word should be used in the reference variable's declaration. private transient SomeClass refVar;

A stream of binary numbers

If i were to look at a machine language program, you would see what?

A deep copy of an object:

Is an operation that copies an aggregate object, and all the objects it references.

Operand

Is usually an item of data, such as a number

When the this variable is used to call a constructor:

It must be the first statement in the constructor making the call.

garbage collector

JVM periodically runs a garbage collector which removes unreferenced objects from memory

public

Java key word, must be lowercase, access specifier (means access to the class is unrestricted)

class

Java key word, must be lowercase, indicates the beginning of a class definition

.java

Java source code file

Punctuation

Mark the beginning and ending of a statement

The Java API provides a class named ______, which contains numerous methods that are useful for performing complex mathematical operations

Math

Assuming the following declaration exists: enum Tree { OAK, MAPLE, PINE } What will the following code display? System.out.println(Tree.OAK);

OAK

You cannot use the == operator to compare the contents of:

Objects

When a field is declared static, there will be:

Only one copy of the field in memory

Enumerated types have this method, which returns the position of an enum constant in the declaration list.

Ordinal

Control Unit

Part of the CPU that coordinates all of the computers operations.

Arithmetic Logic Unit

Part of the CPU that is designed to perform mathematical operations

Software

Programs that run on a computer

Application Software

Programs that solve specific problems or perform general operations that satisfy the needs of the user

what is pseudocode and why is it useful?

Pseudocode is not a programming language, but it is an informal description of the operation of a computer program. For example, in Lab #4, you were given Pseudocode on how to implement the Dice Rolls. It gives you an idea on how the program or an algorithm should flow.

What does RAM stand for?

Random Access Memory

Main Memory

Random Access Memory (RAM) holds the sequence of instructions in the programs that are running and the data those programs use.

\r

Return (cursor goes to the beginning of the current line)

Syntax

Rules that must be followed when writing a program

If you have defined a class SavingsAccount with a public static method getNumberOfAccounts(), and created a SavingsAccount object referenced by the variable account20, which of the following will call the getNumberOfAccounts()method?

SavingsAccount.getNumberOfAccounts();

An object's ____________ is simply the data that is stored in the object's fields at any given moment.

State

Static methods can only operate on ____________ fields.

Static

Operators

Symbols or words that perform operations on one or more operands.

Fetch

The CPU's control unit fetches, from main memory, the next instructions in the sequence of program instructions

Appending Data to an existing binary file

The FileOutputStream constructor takes an optional second argument, which must be a boolean value. (true/false) true: If the argument is true, the file will not be erased if it already exists and new data will be written to the end of the file. false: If the argument is false, the file will be erased if it already exists. FileOutputStream fstream = new FileOutputStream("MyInfo.dat", true); DataOutputStream outputFile = new DataOutputStream(fstream);

Source Code

The Java programming statements written by the programmer

The File Pointer

The RandomAccessFile class treats a file as a stream of bytes. The bytes are numbered, with the first byte being byte 0. The last byte's number is one less than the number of bytes in the file. The file pointer holds the byte number of a location in the file If the file pointer refers to a byte number that is beyond the end of the file, an EOFException is thrown when a read operation is performed To move the file pointer, you use the seek method. void seek(long position)

Assume the class BankAccount has been created, and the following statement correctly creates an instance of the class: BankAccount account = new BankAccount(5000.0); What is true about the following statement? System.out.println(account);

The account object's toString method will be implicitly called

Encapsulation

The action of combining data and code into a single object

What will be returned from a method, if the following is the method header? public Rectangle getRectangle()

The address of an object of the class Rectangle

Attributes

The data contained in an object

Source File

The file the source code is saved under

Decode

The instruction is encoded in the form of a number. The control unit decodes the instruction and generates an electronic signal.

A static field is created by placing:

The key word static after the access field specifier and before the field's data type

When a reference variable is passed as an argument to a method:

The method has access to the object that the variable references

When an object is passed as an argument to a method what is actually passed?

The object's memory address

exception handling

The process of intercepting and responding to exceptions

Deserialization

The process of reading a serialized object's bytes and constructing an object from them is known as deserialization. To deserialize an object you use an ObjectInputStream object, along with a FileInputStream object. FileInputStream inStream = new FileInputStream("Objects.dat"); ObjectInputStream objectInputFile = new ObjectInputStream(inStream);

The only limitation that static methods have is:

They cannot refer to non-static members of the class

RAM

This holds the computers main memory is a device that holds information. This specifically holds sequences of instructions in the programs that are running and the data those programs are using

If the following is from the method section of a UML diagram, which of the following statements is true? + equals(object2:Stock) : boolean

This is a public method that accepts a Stock object as its argument and returns a boolean value

Writing and Reading Strings

To write a string to a binary file you should use the DataOutputStream class's writeUTF method.

Writing data to a binary file

To write data to a binary file you must create objects from the following classes: 1) FileOutputStream 2) DataOutputStream You wrap a DataOutputStream object around a FileOutputStream object to write data to a binary file. The following code shows how a file named MyInfo.dat can be opened for binary output: FileOutputStream fstream = new FileOutputStream("MyInfo.dat"); DataOutputStream outputFile = new DataOutputStream(fstream); or DataOutputStream outputFile = new DataOutputStream(new FileOutputStream("MyInfo.dat"));

Look at the following declaration: enum Tree { OAK, MAPLE, PINE } What is the fully-qualified name of the PINE enum constant?

Tree.PINE

Every CPU has their own machine language

True

TRUE/FALSE: A class's static methods do not operate on the fields that belong to any instance of the class.

True

TRUE/FALSE: A single copy of a class's static field is shared by all instances of the class.

True

TRUE/FALSE: An enumerated data type is actually a special type of class.

True

TRUE/FALSE: An instance of a class does not have to exist in order for values to be stored in a class's static fields.

True

TRUE/FALSE: Both instance fields and instance methods are associated with a specific instance of a class, and they cannot be used until an instance of the class is created.

True

TRUE/FALSE: Enum constants have a toString method.

True

TRUE/FALSE: If a class has a method named finalize, it is called automatically just before an instance of the class is destroyed by the garbage collector.

True

TRUE/FALSE: If you write a toString method for a class, Java will automatically call the method any time you concatenate an object of the class with a string.

True

TRUE/FALSE: If you write a toString method to display the contents of an object, object1, for a class, Class1, then the following two statements are equivalent: System.out.println(object1); System.out.println(object1.toString());

True

TRUE/FALSE: The key word this is the name of a reference variable that an object can use to refer to itself.

True

TRUE/FALSE: When an object is passed as an argument, it is actually a reference to the object that is passed.

True

TRUE/FALSE: When an object reference is passed to a method, the method may change the values in the object.

True

UML

Unified Modeling Language

What does USB drive stand for?

Universal Serial Bus drives

Programmer-defined Names

Used to identify storage locations in memory and parts of the program that are created by the programmer.

Key Words

Words that have a special meaning in the programming language.

Throwing Exceptions

You can write code that throws one of the standard Java exceptions, or an instance of a custom exception class that you have designed. -> throw new ExceptionType(MessageString); E.g. throw new Exception("Out of fuel"); - Don't confuse the throw statement with the throws clause. The throw statement causes an exception to be thrown. The throws clause informs the compiler that a method throws one or more exceptions.

System (Java)

a class that is part of the Java API, contains objects and methods that perform system-level operations

Java API

a collection of prewritten classes and methods for performing specific operations

loop

a control structure that causes a statement or group of statements to repeat

A double value is not compatible with a float variable because ...

a double can be much larger or much smaller than the allowable range for a float

nested loop

a loop inside another loop

nested loop

a loop that is inside another loop

count-controlled loop

a loop that repeats a specific number of times

Unicode

a set of numbers that are used as codes for representing characters, each Unicode number requires two bytes of memory

buffer

a small "holding section" of memory

sentinel value

a special value that cannot be mistaken as a member of the list and signals that there are no more values to be entered

running total

a sum of numbers that accumulates with each iteration of a loop

literal

a value that is written into the code of the program

user-controlled loop

allows the user to decide he number of iterations

boolean data type

allows you to create variables that may hold one of two possible values: true or false

Bounds Checking

array indexes always start at 0 and continue to the array length -1

initialization

assigning values to variables as part of the declaration statement

value = 5 (example)

assignment statement

class's members

attributes and methods that belong to a class are referred to as the class's members

\b

backspace (cursors moves left one position)

static class member

belongs to the class, not objects instantiated from the class

method

can be thought of as a group of one or more programming statements that collectively has a name

A Java program must have at least one _____

class definition

public class Simple (example)

class header

class

class is code that describes a particular type of object

field

class member that holds data

java (ex: java Simple)

command to execute Java .class file

loop header

consists of the key word while followed by a boolean expression enclosed in parentheses

method's signature

consists of the method's name and the data types of the method's parameters

text file

contains data that has been encoded as text may be opened and viewed in a text editor

binary file

contains data that has not been converted to text

ArrayList<String> nameList = new ArrayList<>(); (example)

creating an ArrayList

attributes

data stored in an object (also known as fields)

self-documenting program

designed to give an understanding of what the program is doing just by reading its code

The print and println methods are used to ______

display text output, members of the out object, perform the work of writing characters on the screen

static fields and static methods..

do not belong to any instance of a class an instance of the class does not have to exist for values to be stored in the class's static fields

double

double precision data type, can store floating point number with 15 digits of accuracy, uses 8 bytes of memory

subscript

each element is assigned a number; it is used as an index to identify a specific element in the array

instance

each object is considered an ___________ of the class

iteration

each repetition of a loop

A declaration for an enumerated type begins with this key word:

enum

conditional loop

executes as a long as a particular condition exists

update expression

executes at the end of each iteration

input file

file from which a program reads data

input file

file that a program reads data from

output file

file that a program writes data to

output file

file to which program writes data called an output file because the program stores output in the file

floating point numbers

fractional values ex: 1.7, -45.316

What does an inner loop do?

goes through all iterations for each iteration of an outer loop

for loop

ideal for performing a known number of iterations pretest loop, tests its boolean expression before it performs an iteration

access specifier

indicates how the class may be accessed (ex. private, public)

array's size declarator

indicates the number of elements, or values, the array can hold

int[] days = {31, 28, ... , 31};

initialization list; values stored in the array elements in the order they appear in the list

delimiter

item that separates other items

counter variable

keeps a count of the number of iterations

{

left brace/opening brace, associated with the beginning of a class definition

Every Java application must have a method named _______

main

cast operator

manually converts a value even if it means a narrowing conversion ex: x = (int)number; (int is cast operator)

; (semicolon)

marks the end of a statement in Java

public class name must ______

match the name of the save file

Math.pow

method for raising a number to a power, takes two double arguments

toString

method returns a string representing the state of the object. string will be appropriate for displaying on the screen.

method overloading (overloaded methods)

multiple methods have the same name, but use different parameters

"this" keyword

name of a reference variable that an objet can use to refer to itself can only be used to call a constructor from another constructor in the same class must be the first statement in the constructor that is making the call otherwise a compiler error will result

\n

newline

initialization expression

normally used to initialize a control variable to its starting value

If you have defined a class named SavingsAccount with a public static data member named numberOfAccounts, and created a SavingsAccount object referenced by the variable account20, which of the following will assign numberOfAccounts to numAccounts?

numAccounts = SavingsAccount.numberOfAccounts;

data hiding

object hides its internal data from a code that is outside the class of which the object is an instance

reference copy

object's address is copied

out (Java)

object, member of the System class, provides methods for sending output to the screen

console

old computer term, a terminal consisting of a simple screen and keyboard was called a console

strongly typed language

only allows you to store values of compatible data types in variables

What does the PrintWriter class allow you to do?

open a file for writing, write data to a file using the same print and println methods already used to display data on screen

methods

operations that an object can perform

postfix mode

operator is placed after the variable

prefix mode

operator is placed before the variable name

loop

part of a program that repeats control structure that causes a statement or group of statements to repeat

constructor

performs initialization or setup operations such as storing initial values in instance fields.

console output

plain text, usually appears in a window with a system that has a GUI

the do-while loop

posttest loop ideal in situations where you always want the loop to iterate at least once

do-while loop

posttest loop, which means its boolean expression is tested after each iteration must be terminated with a semicolon

Math.PI

predefined named constant, assigned the value 3.14159265358979323846

the while loop

pretest loop ideal in situation where you do not want the loop to iterate if the condition is false from the beginning. ideal if you want to use a sentinel value to terminate the loop

the for loop

pretest loop that has built-in expressions for initializing, testing, and updating these expressions make it very convenient to use a loop control variable as a counter. for loop is ideal in situations where the exact number of iterations is known

input validation

process of inspecting data given to a program by the user and determining if its valid

How does a continue statement effect a do-while loop?

program jumps to the boolean expression at the bottom of the loop

Java API

provides several classes that you can use for writing data to a file and reading data from a file

priming read

read operation that takes place just before the loop

standard output device

refers to the device that displays console output.

unary operator

require only a single operand, (ex: negation operator '-number')

problem domain

set of real-world objects, parties and major events related to the problem

buffer

small holding section of memory

object

software component that exists in the computer's memory and performs a specific task

read position

special value is internally maintained for that file

Body

statement repeated in a loop

In programming terms, the group of characters inside quotation marks is called a _______

string literal

running total

sum of numbers that accumulates with each iteration

variable declaration

tells the compiler the variable's name and the type of data it will hold, variables must be declared before they can be used

pretest loop

tests it expression before each iteration

binding

the process of matching a method call with the correct method

How does a continue statement effect a while loop?

the program jumps to the next boolean expression at the top of the loop

data type

the type of data that the variable can hold

argument

the value that is to be displayed on the screen and placed inside parentheses

when a field is static

there will only be one copy of the field in the memory regardless of the number of instances of the class that might exist

.length (public field array "length")

this field contains the number of elements in the array

any method that uses a PrintWriter object must have a

throws IOException clause in its header

nameList.get(index);

to access items in an ArrayList

numbers = new int[6]; (example)

to create an array and assign its address to a variable

nameList.size();

to get current size of ArrayList

nameList.add("");

to populate the ArrayList

Java compiler

translates a java source file into a file that contains byte code instructions

a method can return a reference to an object

true

java automatically stores 0 in all uninitialized numeric static member variables

true

more than one constructor may be defined for a class

true

Handling an exception

try { (try block statements . . .) } catch (ExceptionType parameterName) { (catch block statements . . .) } - To handle an exception, you use a try statement - A try block is one or more statements that are executed and can potentially throw an exception.

instance fields and instance method cannot be used...

until an instance of the class is created

char data type

used to store characters, can hold one character at a time, enclosed in single quotation marks

Accessing an array

using the reference name and a subscript that identifies which element to access; array subscripts can be accessed using variables

argument

value that is passed into a method

sentinel

value that signals when the end of a list of values has been reached

accumulator

variable that is initialized with a starting value and then accumulates a sum of numbers by having the numbers added to it

int

variable type, integer (value will be used to hold integer numbers)

accumulator

variable used to keep the running total variable initialized with a starting value

E notation

what Java uses to represent values in scientific notation

aggregation

when an instance of a class is a field in another class

"has a" relationship is sometimes called a..

whole-part relationship - because one object is part of a greater whole

What does the close method do?

writes any unsaved data remaining in the file buffer

to pass an object as a method argument,

you pass an object referee

string concatenation operator

+ (to append, attach one string to another)

Input Devices

A device used to collect data from the outside world/user

Output devices

A device used to send information to the outside world/user

javac (ex: javac Simple.java)

Java compiling command

If you attempt to perform an operation with a null reference variable:

The program will terminate

Execute

The signal is routed to the appropriate component of the computer (such as the ALU, a disk drive, or some other device). The signal causes the component to perform an operation

variable

a named storage location in the computer's memory

identifier

a programmer-defined name that represents some element of a program (variable names, class names, etc)

instance fields

belong to an instance of a class

//

comment

Handling Exceptions

- An exception is an object that is generated as the result of an error or an unexpected event. To prevent exceptions from crashing your program, you must write code that detects and handles them. - You can think of the code in the try block as being "protected" because the application will not halt if the try block throws an exception.

Retrieving the Default Error Message

- Each exception object has a method named getMessage that can be used to retrieve the default error message for the exception. - This is the same message that is displayed when the exception is not handled and the application halts. try { file = new File(fileName); 26 inputFile = new Scanner(file); 27 JOptionPane.showMessageDialog(null, 28 "The file was found."); 29 } 30 catch (FileNotFoundException e) 31 { 32 JOptionPane.showMessageDialog(null, e.getMessage()); 33 }

default exception handler

- If your code does not handle an exception when it is thrown, the default exception handler deals with it. - The default exception handler prints an error message and crashes the program.

Secondary Storage

A disk drive typically known as a hard drive that can hold data even when there is no power.

Binary Files

A file that contains raw binary data is known as a binary file. The content of a binary file is not formatted as text, and not meant to be opened in a text editor. - raw binary format.

Reading and Writing with the RandomAccessFile Class

A file that is opened or created with the RandomAccessFile class is treated as a binary file.

The whole-part relationship created by object aggregation is more often called:

A has a relationship

Program

A series of instructions that contains variables (which store information) and statements (which are single program steps). It is a source code made up of Keywords, Operators punctuation, and programmer-defined names

Operating Systems

A set of programs that manages the computer's hardware devices and controls their processes.

Algorithm

A set of well-defined steps for performing a task or solving a problem.

Line

A single line as it appears in the body of a program

The Strack Trace

A stack trace is a list of all the methods in the call stack The call stack is an internal list of all the methods that are currently executing All exception objects have a printStackTrace method, inherited from the Throwable class, which can be used to print a stack trace.

Data Hiding

An object's ability to hide its data from code that is outside the object

API

Application Programmer Interface (a standard library of prewritten classes for performing specific operations. These classes and their methods are available to all Java programs)

TRUE/FALSE: The names of the enum constants in an enumerated data type must be enclosed in quotation marks.

False

TRUE/FALSE: The this key word is the name of a reference variable that is available to all static methods.

False

TRUE/FALSE: You can declare an enumerated data type inside of a method.

False

Object Serialization

Java allows you to serialize objects, which is a simpler way of saving objects to a file. When an object is serialized, it is converted into a series of bytes that contain the object's data. In order for an object to be serialized, its class must implement the Serializable interface The Serializable interface, which is in the java.io package, has no methods or fields To write a serialized object to a file, you use an ObjectOutputStream object. The ObjectOutputStream class is designed to perform the serialization process (converting an object to a series of bytes). FileOutputStream outStream = new FileOutputStream("Objects.dat"); ObjectOutputStream objectOutputFile = new ObjectOutputStream(outStream);

When you write an integer literal in your program code...

Java assumes it to be of the int data type

widening conversion

Java automatically converts the lower-ranked value to the higher-ranked type

array elements

Java initializes these within 0, where values of a data type are stored

Is Java Portable and why?

Java is a portable language because every other Operating System has their own Java Virtual Machine. We only need to write the program once on any machine, and we can run it using JVM on any other platform/machine.

The finally clause

The try statement may have an optional finally clause, which must appear after all of the catch clauses. The finally block is one or more statements that are always executed after the try block has executed and after any catch blocks have executed if an exception was thrown. The statements in the finally block execute whether an exception occurs or not

Random File Access

To create and work with random access files in Java, you use the RandomAccessFile class, which is in the java.io package. RandomAccessFile(String filename, String mode) String mode: The two modes are "r" for reading, and "rw" for reading and writing. When a file is opened with "r" as the mode, the program can only read from the file. When a file is opened with "rw" as the mode, the program can read from the file and write to it. * Here are some important points to remember about the two modes: • If you open a file in "r" mode and the file does not exist, a FileNotFoundException will be thrown. • If you open a file in "r" mode and try to write to it, an IOException will be thrown. • If you open an existing file in "rw" mode, it will not be deleted. The file's existing contents will be preserved. • If you open a file in "rw" mode and the file does not exist, it will be created.

Creating your own exception classes

To meet the needs of a specific class or application, you can create your own exception classes by extending the Exception class or one of its subclasses. public class NegativeStartingBalance 8 extends Exception //Constructor public NegativeStartingBalance() 16 { 17 super("Error: Negative starting balance"); 18 } Program code public BankAccount(double startBalance) throws NegativeStartingBalance { if (startBalance < 0) throw new NegativeStartingBalance(startBalance); balance = startBalance; }

Reading data from a binary file

To open a binary file for input, you use the following classes: 1) FileInputStream 2) DataInputStream To open a binary file for input, you wrap a DataInputStream object around a FileInputStream object. FileInputStream fstream = new FileInputStream("MyInfo.dat"); DataInputStream inputFile = new DataInputStream(fstream); or DataInputStream inputFile = new DataInputStream(new FileInputStream("MyInfo.dat"));

Polymorphic References to Exceptions

When handling exceptions, you can use a polymorphic reference as a parameter in the catch clause. For example, all of the exceptions that we have dealt with inherit from the Exception class. So, a catch clause that uses a parameter variable of the Exception type is capable of catching any exception that inherits from the Exception class try { number = Integer.parseInt(str); } catch (Exception e) { System.out.println("Conversion error: " + e.getMessage()); }

Using the @exception Tag in Documentation Comments

When writing the documentation comments for a method, you can document the exceptions thrown by the method by using an @exception tag. @exception ExceptionName Description Example: @exception NegativeStartingBalance When startBalance is negative.

If object1 and object2 are objects of the same class, to make object2 a copy of object1:

Write a copy method that will make a field by field copy of object1 data members into obejct2 data members

To compare two objects in a class:

Write an equals method that will make a field by field compare of the two objects

aggregate

a whole that is made of constituent parts

Math.sqrt

accepts a double value as its argument and returns the square root of the value

Class

blueprint for an object specifies the attributes and methods that an object has one or more objects may be created in the class

test expression

boolean expression that controls the execution of the loop

array

can hold multiple values of the same data type simultaneously; once it is created, its size cannot change

Primitive Data Types

can not be used to create objects, can only create variables (PAGE 45 , see chart)

Handling Multiple Exceptions with One catch Clause (Java 7)

catch(NumberFormatException | IOException ex) - The ability to catch multiple types of exceptions with a single catch clause is known as multi-catch

continue statement

causes a loop to stop its current iteration and begin the next one

What does a continue statement do to a loop?

causes a loop to stop its current iteration and start the next one

What does a break statement do to a loop?

causes a loop to terminate early

break statement

causes a loop to terminate early

How does a continue statement effect a for loop?

causes the update expression to be executed and then the test expression is evaluated

inner class

class that is defined inside another class definition

CRC

class, responsibilities, and collaborations

compound operators

combined assignment operators (ex: x+=5 or x = x +5)

enumerated data type

consists of a set of predefined values

constructor is named

constructor method has the same name as the class

copy constructor

constructor that accepts n object of the same class as an argument

does not have a return type

constructors

text file

contains plain text may be opened in a text editor such as Notepad

.class

contains the translated Java byte code

binary file

contains unformatted binary data, you cannot view its contents with a text editor

loop control variable

controls the number of times that the loop iterates

narrowing conversion

conversion of a value to a lower-ranked type, Java does not automatically perform them

deep copy

copies of the object the aggregate object references

key word "new"

creates an instance of an object in memory

public static void main(String[] args) is known as a ______

method header

accessor method (getters)

method that gets a value from a class's fields but does not change it

constructor

method that is automatically called when a object is created

++ and --

operators that add and subtract one from their operands

++ and--

operators that add and subtract one from their operands

default instructor provided by Java

sets the class's numeric fields to 0, sets boolean fields to false, sets reference variables to the value "null"

exception

signal indicating that the program cannot continue until the unexpected event has been dealt with

float

single precision data type, can store floating point number with 7 digits of accuracy, uses 4 bytes of memory

When should you use the for loop?

situations where the exact number of iterations is known

When should you use a while loop?

situations where you do not want the loop to iterate if the condition is false from the beginning

When should you use the do-while loop?

situations where you want the loop to iterate at least once

escape sequence

starts with a backslash (\) and is followed by one or more control characters, embeds commands within the string itself

mutator methods (setters)

stores a value in a field or in some other way changes the value of a field

Scanner class and the File class

to read data from a file

int[] numbers;

to reference an array (object)

import java.util.ArrayList;

to use the ArrayList Class

PrintWriter class optionally FileWriter Class

to write data to a file

object's memory address

when a reference variable holds an object's memory address, it is said that the variable references the object.

assignment statement

when a value is put into a variable, = is assignment operator

"has a"

when an instance of one class is a member of another class, it is said that there is a "has a" relationship between the classes

null

when assigned to a variable means the variable "does not reference anything"

integer division

when both operands of the division operator are integers, if there is a remainder it will be discarded (truncated)

stale

when the value of an item is dependent on other data and that item is not updated when the other data is changed

can be used to create input routines that repeat until acceptable data is entered

while loop

Common Errors to Avoid

• Assuming that all statements inside a try block will execute. When an exception is thrown, the try block is exited immediately. This means that statements appearing in the try block after the offending statement will not be executed. • Getting the try, catch, and finally clauses out of order. In a try statement, the try clause must appear first, followed by all of the catch clauses, followed by the optional finally clause. • Writing two catch clauses that handle the same exception in the same try statement. You cannot have more than one catch clause per exception type in the same try statement. • When catching multiple exceptions that are related to one another through inheritance, listing the more general exceptions first. If you are handling multiple exceptions in the same try statement, and some of the exceptions are related to each other through inheritance, then you should handle the more specialized exception classes before the more general exception classes. Otherwise, an error will occur because the compiler thinks that you are handling the same exception more than once. • Forgetting to write a throws clause on a method that can throw a checked exception but does not handle the exception. If a method is capable of throwing a checked exception but does not handle the exception, it must have a throws clause in its header that specifies the exception. • Calling a method but not handling an exception that it might throw. You must either handle all of the checked exceptions that a method can throw, or list them in the calling method's throws clause. • In a custom exception class, forgetting to pass an error message to the superclass's constructor. If you do not pass an error message to the superclass's constructor, the exception object will have a null error message. • Serializing an object with members that are not serializable. If a class has fields that are objects of other classes, those classes must implement the Serializable interface in order to be serialized.


Ensembles d'études connexes

Constipation, diarrhoea, rectal bleeding

View Set

8.1: Gross Domestic Product Measures Total Production

View Set

Maternal Newborn ATI Practice 2019 A

View Set

Social Research Methods - Chapter 9 (Survey Research)

View Set

LÉXICO DE UNIDAD 2: COMPORTAMIENTOS Y LO SOCIALMENTE ACEPTABLE

View Set

Basic Terminology of Probability

View Set