MIS 3370 Ch. 1-3

Ace your homework & exams now with Quizwiz!

Relational Operators (Table)

Operator Description True EX) False EX) < Less than 3 < 8 8 < 3 > Greater than 4 > 2 2 > 4 == Equal to 7 == 7 3 == 9 <= Less than or equal to 5 <= 5 8 <= 6 >= Greater than or equal to 7 >= 3 1 >= 2 != Not equal to 5 != 6 3 != 3

float data type

Can hold a floating-point value of up to six or seven significant digits of accuracy Storing values as floats (rather than doubles) saves memory a value in a float is a single-precision floating-point number To indicate that a floating-point numeric constant is a float, you can type the letter F after the number (can type either a lowercase or an uppercase F) EX) float pocketChange = 4.87F;

Nondefault constructors

take parameters

clean build

when you make a change to a Java class and then recompile and execute it, the old version still runs. The simplest solution is to delete the .class file and compile again --> Programmers call this creating a clean build.

Operand

A value used on either side of an operator

exceptions

Errors that occur while an application is running

Parenthesis ( )

Follows method names as in print() Parentheses can be called round brackets, but such usage is unusual

Chapter 1 Review Practice

Starts on txtbook page 41

Java programming statements

all statements end with a semicolon

final modifier

1) Non-access modifier 2) Can use with classes, variables, methods 3) Cannot use with interfaces because interface is abstract by default declaring a parameter as final means it cannot be altered within the method --> other users of program would know that the parameter is not intended to change makes a method's parameter constant

Angle brackets < > - NOT NEEDED FOR CLASS

Angle brackets are used with generic arguments in parameterized classes When angle brackets appear with nothing between them, they are called a chevron

Chaining methods

Any method might call any number of other methods (refer to word doc for example) can chain method calls in a single statement

Understanding Data Hiding

Data fields (attributes) usually should be private, and a client application should be able to access them only through the public interfaces—that is, through the class's public methods.

Semantic Errors (ie. Logic error)

EX) if you misspell a programming language word, you commit a syntax error, but if you use a correct word in the wrong context, you commit a semantic error.

String Variable (a string in a variable)

EX) the expression that stores the name Audrey as a string in a variable named firstName is as follows: String firstName = "Audrey";

High level programming language

Ex) Java, Visual Basic, C++, or C# allows you to use English-like, easy-to-remember terms such as read, write, and add

Some illegal class names in Java

Inventory Item = Space character is illegal in an identifier class = class is a reserved word 2019Budget = Class names cannot begin with a digit phone# = The number symbol (#) is illegal in an identifier

example of an executed statement that displays a confirm dialog box using 5 arguments (Confirm dialog box with title, Yes and No buttons, and error icon displayed)

JOptionPane.showConfirmDialog(null, "A data input error has occurred. Continue?", "Data input error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);

Example of 4 arguments within showInputDialog() (when the statement executes, it displays the input dialog box shown in example)

JOptionPane.showInputDialog(null, "What is your area code?", "Area code information", JOptionPane.QUESTION_MESSAGE); **Note that the title bar displays Area code information, and the dialog box shows a question mark icon**

Shell Code for any java program needed to execute

Java code shown in Figure 1-8 as a shell (basic template), in which you replace AnyClassName with a class name you choose and the line /******/ with any statements that you want to execute Figure 1-8 Shell code)) public class AnyClassName { public static void main(String[] args) { /******/ } }

Java primitive data types

Java consistently specifies the size and format of its primitive data types --> In other programming languages, the format and size of primitive data types might depend on the platform on which a program is running

Strongly typed language

Java is a strongly typed language --> one in which each variable has a well-defined data type that limits the operations you can perform with it; strong typing implies that all variables must be declared before they can be used

implicit conversion (promotions)

Java performs an implicit conversion that automatically converts nonconforming operands to the unifying type

java advantages (provided by JVM)

Java program is isolated from the operating system, it is also insulated from the particular hardware on which it is run b/c of that insulation --> JVM provides security against intruders accessing your computer's hardware through the operating system --> making Java more secure than other languages JVM makes less work for programmers --> one Java program version runs correctly on all/multiple platforms (like Windows version, Macintosh version, UNIX version, Linux version, etc.) - "Write once, run anywhere" (WORA) Java is simpler than many other object-oriented programming languages --> its modeled after C++ - Java eliminates some of the most difficult-to-understand features in C++, such as pointers and multiple inheritance

mutator methods (setters)

Methods that set or change field values (attributes) - setters - set() - does not employ static modifier EX) public void setEmpNum(int emp) { empNum = emp; }

instantiation

Process of creating an object, an instance of a class; creates space in memory for the new object and binds a name for the object with the object's data in memory An object is an instantiation of a class, or one tangible example of a class. Objects can be members of more than one class (referring to inheritance)

Source code

Programming statements written in a high-level programming language When creating Java program: 1) first construct the source code using a plain text editor such as Notepad, or use a development environment such as Eclipse, NetBeans, or jGRASP 2) Java source code statements written are saved in a file; then, the Java compiler converts the source code into a binary program of bytecode 3) program called Java interpreter then checks the bytecode and communicates with the operating system, executing the bytecode instructions line by line within the JVM

JOptionPane class (dialog boxes include: InputDialog & ConfirmDialog)

Provides a method for displaying message dialogs and constants for displaying icons in those dialogs can accept input in a GUI dialog box 2 dialog boxes that can be used to accept user input: 1) InputDialog — Prompts the user for text input 2) ConfirmDialog — Asks the user a question, providing buttons that the user can click for Yes, No, and Cancel responses

new operator

To allocate the needed memory for an object, you must use the new operator --> this is for objects declared as an instance of a class Two statements that actually complete the process by setting aside enough memory to hold a class [in this instance: Employee] are as follows: Employee someEmployee; someEmployee = new Employee(); CAN ALSO declare and reserve memory for someEmployee in one statement, instead of using two statements [like above] in the following: Employee someEmployee = new Employee(); ***In this statement, Employee is the object's type (as well as its class), and someEmployee is the name of the object - someEmployee becomes a reference to the object—the name for a memory address where the object is held - class such as Employee is a reference type - The value that the statement is assigning to someEmployee is a memory address at which someEmployee is to be located - The final portion of the statement after the new operator, Employee(), with its parentheses, is the name of a method that constructs an Employee object ----> the Employee() method is a constructor new operator is allocating a new, unused portion of computer memory for newly declared objects

Limits on integer values by type (Using headers from left2right: Data Type, Minimum Value, Maximum Value, and Size in Bytes)

Type Min-Value Max-Value Size-in-Bytes byte -128 127 1 short -32,768 32,767 2 int -2,147,483,648 2,147,483,647 4 long -9,223,372,036,854,775,808 9,223,372,036,854,775,807 8

Limits on floating-point values (the minimum and maximum values for each floating-point data type: float & double)

Type Minimum Maximum Size in Bytes float -3.4 * 10^38 3.4 * 10^38 4 double -1.7 * 10^308 1.7 * 10^308 8

Legal but unconventional and nonrecommended class names in Java

Undergradstudent = New words are not indicated with initial uppercase letters, making this identifier difficult to read Inventory_Item = Underscore is not commonly used to indicate new words BUDGET2019 = Using all uppercase letters for class identifiers is not conventional budget2019 = Conventionally, class names do not begin with a lowercase letter

Unicode decimal values and their character equivalents

Unicode values 0 through 127 and their character equivalents pg. 70 textbook table 2-5 ch. 2

Abstraction

Using a method name to contain or encapsulate a series of statements is an example of abstraction (basically capturing the essence of an object w/out focusing on the details) when programmers employ abstraction, they use a general method name in a module rather than list all the detailed activities that will be carried out by the method

when a variable goes out of scope

When a variable ceases to exist at the end of a method

Comment out

When you comment out a statement, you turn it into a comment so the compiler does not translate it, and the JVM does not execute its command. makes a statement nonexecuting This can help you pinpoint the location of errant statements in malfunctioning programs

Unitialized Variable

When you declare a variable within a method but do not assign a value to it, the unknown value contained w/n becomes a garbage value EX) the following variable declaration declares a variable of type int named myAge, but no value is assigned at the time of creation: int myAge;

Programmer-defined data type

a [data] type that is not built into the language

fully-qualified identifier

a complete name that includes the class do not need to use the fully qualified name when using a method WITHIN ITS OWN CLASS (although you can - but simple method name alone is enough) However, if you want to use a method IN ANOTHER CLASS, the compiler does not recognize the method unless you use the full name. when using the same named method (ex: displayAddress() method) for TWO DIFFERENT CLASSES - Such a method in the second class would be entirely distinct from the identically named method in the first class - could use both methods in a third class by using their fully qualified identifiers - Two classes in an application cannot have the same name

blank final

a constant that is not initialized at its declaration --> can assign a value later

lossless conversion

a conversion in which no data is lost The opposite of a lossy conversion

lossy conversion

a conversion in which some data is lost

computer program

a set of instructions that you write to tell a computer what to do

Development Environment

a set of tools that help you write programs by providing such features as displaying a language's keywords in color

object

a specific, concrete instance of a class can create objects from classes that you write and from classes written by other programmers, including Java's creators classes can't do work, only objects can do work Objects gain their attributes from their classes, and all objects have predictable attributes because they are members of certain classes objects have methods associated with them, and every object that is an instance of a class is assumed to possess the same methods values contained in an object's properties often differentiate instances of the same class from one another - EX) the class 'Automobile' describes what 'Automobile' objects are like. - Some properties of the 'Automobile' class are make, model, year, and color. - Each 'Automobile' object possesses the same attributes, but not necessarily the same values for those attributes. - One 'Automobile' might be a 2014 white Ford Taurus and another might be a 2018 red Chevrolet Camaro.

integer variable

a variable that stores an integer (whole number) value can hold millions of different values (at different times)

escape sequence

always begins with a backslash followed by a character—the pair represents a single character and give new meaning than original 'plain' character value EX) '\n' = \n = Newline or linefeed; moves the cursor to the beginning of the next line

object-oriented programming

an extension of procedural programming in which you take a slightly different approach to writing computer programs originally most used for 2 major applications (computer simulations, Graphical user interfaces) Within any object-oriented program, you are continuously making requests to objects' methods and often including arguments as part of those requests involves: • Creating classes, which are blueprints for objects • Creating objects, which are specific instances of those classes • Creating applications that manipulate or use those objects

Allman style

an indent style in which curly braces are aligned and each occupies its own line

K&R style

an indent style in which opening braces do not stand alone on separate lines

method body (implementation)

between a pair of curly braces contains the statements that carry out the work

Method name

can be any legal identifier (similar to identifiers for variables & classes) a method's identifier (name) must be: - one word with no embedded spaces - cannot be a Java keyword The method that executes first when you run an application must be named main() - Other methods you write in a class can have any legal identifier methods are actions --> therefore method names frequently contain a verb, i.e. print or compute EX) in method statement: public static void main(String[] args) - args is a traditional identifier within its parenthesis

return statement

causes a value to be sent from the called method back to the calling method method ends when it reaches a return statement, program's logic returns back to calling statement

Relational Operator (comparison operator)

compares two items Java supports 6 relational operators that are used to make comparisons The value of an expression that contains a relational operator is always true or false When you use any of the operators (see table in term below) that have two symbols (55, ,5, .5, or !5), you cannot place any whitespace between the two symbols cannot reverse the order of the symbols =<, =>, and =! are all invalid operators

byte (bytecode) (binary code)

constructed from eight 1s and 0s, or binary digits The first binary digit, or bit, holds a 0 or 1 to represent positive or negative The remaining seven bits store the actual value

type-wrapper classes

contained in the java.lang package, include methods that can process primitive type values --> corresponding classes for each primitive data type EX) To convert Strings to numeric values using methods belonging to type-wrapper classes Double and Integer: for Double --> use Double.parseDouble() method for Integer --> use Integer.parseInt() method

floating point numbers

contains decimal positions Java supports two floating-point data types: float and double floating-point numbers frequently are only approximations No matter how many decimal places you can store, the result is only an approximation. Even values that don't repeat indefinitely, such as 0.1, cannot be represented precisely in the binary format used by computers this binary Imprecision (of storage representation) leads to several problems: 1) produced floating-point output, it might not look like what's expected 2) comparisons with floating-point numbers may not look like expected fractional values cannot be represented accurately in java --> the result may be a calculated value that is higher than the original fractional value --> would result in incorrect calculations and inaccurate true/false comparisons Don't attempt to assign a literal constant floating-point number (such as 2.5) to a float without following the constant with an uppercase or lowercase F. By default, constant floating-point values are doubles

Low level programming language

correspond closely to a computer's circuitry and are not as easily read or understood must be customized for every type of machine on which a program runs

method variables

declared inside of methods

conventionally named constants

each of the following defines a conventionally named constant: final int NUMBER_OF_DEPTS = 20; final double PI = 3.14159; final double TAX_RATE = 0.015; final string COMPANY = "ABC Manufacturing"; can use each of these named constants anywhere you use a variable of the same type, except on the left side of an assignment statement after the first value has been assigned a named constant is an lvalue when it receives a value a named constant is an rvalue after its assignment

parenthesis in method header

every method header contains a set of parentheses that follow the identifier The parentheses might contain data to be sent to the method (regardless of main method or other methods) - EX)) the parenthesis for the main() method header in a class surround String[] args Parenthesis can also be empty in a method that require no outside data

main() method

executes automatically when you run a program, A program's main() method can execute additional methods, and those methods can execute others. - Any class can contain an unlimited number of methods, and each method can be called an unlimited number of times composed of method header & method body made up of the four total lines between the curly braces of the named class --> method body begins with the 2nd curly brace types underneath the main() method header First set of curly braces defines the class body --> 2nd set of curly braces --> the inner curly braces placed underneath main() method header = main method body Even though you pass no arguments, the main() method must contain String[] and a legal identifier (such as args) within its parentheses

Structured walkthrough

finding logic errors by carefully examining the structure of your program (when a group of programmers do this together)

Class header

first line --> types above curly braces indicating start of scope public --> the specifier placed in class header to define the type of access used --> written before class identifier keyword --> then the name of the class written

Debugging

freeing the program of all flaws or errors, also known as bugs When a syntax error is detected, the programmer can correct the error and attempt another translation. Repairing all syntax errors is the first part of the process of debugging a program

standard input device

normally is the keyboard

Curly braces

placement/layout of the opening and closing curly braces is not important to the compiler

private data/public method arrangement

provides a means for you to control outside access to your data—only a class's nonprivate methods can be used to access a class's private data

significant digits

refers to the mathematical accuracy of a value EX) a float given the value 0.324616777 is displayed as 0.324617 because the value is accurate only to the 6th decimal position

Syntax

rules about how language elements are combined correctly to produce usable statements Every programming language has its own syntax All languages have a specific, limited vocabulary (the language's keywords) and a specific set of rules for using that vocabulary

Java Reserved primitive values

true, false, null = reserved words that represent values

Concept requirements of object-oriented programming

• Encapsulation as it applies to classes as objects • Inheritance • Polymorphism

Braces and brackets used in Java

Parenthesis Curly braces square brackets angle brackets (not used in class)

"System.out.println()"

System in "System.out.println()" is the name of an object (made from the System class) "out" is the name of an object that is created in the System class

println()

a method that produces output --> after the output is displayed, the insertion point moves to the following line so that subsequent output appears on a new line

print()

a method that produces output --> the insertion point does not advance to a new line, so subsequent output appears at the end of the current line

actual parameters & formal parameters

arguments in a method call = actual parameters variables in the method declaration that accept the values from the actual parameters = formal parameters

method variable

is known only within the boundaries of the method

Unicode values

unexpected values are unicode values Every computer stores every character it uses as a number; every character is assigned a unique numeric code using Unicode.

token

a set of characters that is separated from the next set by whitespace

assignment

an assignment made later

Arguments

pieces of information that are sent into a method

integer division

(2 types of division in java) occurs when both of the operands are integers. result is an integer, any fractional part of the result is lost. EX) the result of 45 / 2 is 22 39 / 5 is 7 because 5 goes into 39 seven whole times; 38 / 5, 37 / 5, 36 / 5, and 35 / 5 all evaluate to 7

Floating-point division

(2 types of division in java) occurs when either or both of the operands are floating-point values. EX) 45.0 / 2 is 22.5

Choosing appropriate data types for variables

(example): If an application uses a literal constant integer, such as 932, the number is an int by default. If you need to use a constant higher than 2,147,483,647, the letter L must follow the number to indicate long. EX) the following statement stores a number that is greater than the maximum limit for the int type. long mosquitosInTheNorthWoods = 2444555888L; Can type either an uppercase or a lowercase L after the digits to indicate the long type (as seen in example above) uppercase L is preferred!!! to avoid confusion with the number 1. NO special notation needed to store a numeric constant in an int, a byte, or a short.

Relative precedence of arithmetic operators

* / % --> Multiplication, division, remainder (Higher precedence) + - --> Addition, subtraction (Lower preference) can override normal operator precedence by putting the operation to perform first in parentheses When multiple pairs of parentheses are used in a statement, the innermost expression surrounded by parentheses is evaluated first.

Encapsulation

1) the enclosure of data and methods within an object, allows you to treat all of an object's methods and data as a single entity 2) the concealment of an object's data and methods from outside sources (information hiding/implementation hiding) - encapsulation lets you hide specific object attributes and methods from outside sources & provides the security that keeps data and methods safe from inadvertent changes In object-oriented classes, attributes and methods are encapsulated into objects

reasons to use the named constant rather than the literal one:

1) to make values more easily recognizable w/ identifiers, using named constants makes your programs easier to read and understand, to more clearly describe the values purpose as it an ambiguous variable holder (a magic number) without distinguishing with named constants, Avoiding magic numbers helps provide internal documentation for your programs EX) a program that uses the value 7 for several purposes, so you might use constants such as DAYS_IN_WEEK and NUM_RETAIL_OUTLETS that both hold the value 7 but more clearly describe the purposes 2) the ability to make a change at one memory location in order to save time, preventing missing a reference to the changed named constant EX) If the number of departments in your organization changes, you would change the value of NUMBER_OF_DEPTS at one location within your program—where the constant is defined—rather than searching for every use of 20 to change it to a different number. EX) Even if you are willing to search for every instance of 20 in a program to change it to the new department number value, you might inadvertently change the value of one instance of 20 that is being used for something else, such as a payroll deduction value. 3) Using named constants reduces typographical errors EX) if you must include 20 at several places within a program, you might inadvertently type 10 or 200 for one of the instances, and the compiler will not recognize the mistake. However, if you use the identifier NUMBER_OF_DEPTS, the compiler will ensure that you spell it correctly 4) When you use a named constant in an expression, it stands out as different from a variable EX) , in the following arithmetic statement, it is easy to see which elements are variable and which are constant because the constants have been named conventionally using all uppercase letters and underscores to separate words: double payAmount = hoursWorked * STD_PAY_RATE - numDependents * DEDUCTION; **Although many programmers use named constants to stand for most of the constant values in their programs, many make an exception when using 0 or 1.

Declaring Objects and Using Their Methods

2-step process creates an object that is an instance of a class: 1) supply a type 2) supply an identifier—just as when you declare any variable—and then you allocate computer memory for that object objects conventionally start with a lowercase letter. EX) declare an integer as int someValue; declare an Employee as: Employee someEmployee When you declare an integer as int someValue;, you notify the compiler that an integer named someValue will exist, and you reserve computer memory for it at the same time. When you declare the someEmployee instance of the Employee CLASS, you are notifying the compiler that you will use the identifier someEmployee. - However, you are not yet setting aside computer memory in which the Employee named someEmployee might be stored— that is done automatically only for primitive type variables - To allocate the needed memory for an object, you must use the new operator --> this is for objects declared as an instance of a class

Boolean Expressions

A boolean expression often uses one of Java's equality operators or relational operators, which all return boolean results: Note the difference between the equality operator (==) and the assignment operator (=) more meaningful when a variable is used for one or both of the operands in a comparison EXAMPLES) a variable is compared to a literal constant (40) boolean isOvertimePay = (hours > 40); a variable is compared to a named constant (HIGH_CUTOFF) boolean isTaxBracketHigh = (income > HIGH_CUTOFF); and two variables are compared boolean isFirstScoreHigher = (score1 > score2);

Executing

A compiler translating an entire program before carrying out any statements

Constant

A data item whose value cannot be changed while a program is running EX) printing the number 459 --> a 'hard-coded' value System.out.println(459);

Creating a Method that Requires Multiple Parameters

A method can require more than one parameter, for purpose of passing more than one value a declaration for a method that receives two or more parameters must list the type for each parameter separately, even if the parameters have the same type (like double) can pass multiple arguments to a method by listing the arguments within the call to the method and separating them with commas EX)) example of a method that uses two such parameters rather than creating a calculateGross() method that uses a standard hourly rate of $13.75 for every employee, you might prefer to create a method to which you can pass two values—the hours worked as well as an hourly rate public static void calculateGross(double hours, double rate) { double gross; gross = hours * rate; System.out.println(hours + " hours at $" + rate + " per hour is $" + gross); } ****Each parameter (in method declaration for calculateGross) requires a data type and an identifier - double = data type - hours & rate = identifiers The parameters are separated with a comma (double hours, double rate) - the 2 parameters are referred to - in general - as double hours and double rate - located in the parenthesis of the method header each parameter requires its own declared (data) type (in this case, both are double) as well as its own identifier

When a method ends..

A method ends when any of the following events occur: • The method completes all of its statements • The method throws an exception. Exceptions are errors • The method reaches a return statement. A return statement causes a method to end and the program's logic to return to the calling method. A return statement frequently sends a value back to the calling method

method header (declaration)

A method's header provides information about how other methods can interact with it the FIRST line of a header, contains the following: • Optional access specifiers • A return type • An identifier (method name) • Parentheses a method's return type precedes the method's name

square brackets [ ]

A pair signifies an array Square brackets might be called box brackets or square braces

Curly braces { }

A pair surrounds a class body, a method body, and a block of code; curly braces also surround lists of array values Curly braces might also be called curly brackets

Application Software

A program that performs a task for a user (such as calculating and producing paychecks, word processing, or playing a game)

lvalue & rvalue

A variable can be used as an lvalue or an rvalue, but a literal constant can only be an rvalue

Class body

After the class header, you enclose the contents of a class within curly braces ({ and }); any data items and methods between the curly braces make up the class body can be composed of any number of data items and methods Everything between the curly braces is the class body.

Java reserved keywords

Although const and goto are reserved as keywords, they are not used in Java programs, and they have no function public = access specifier --> defines the circumstances under which a class can be accessed and the other classes that have the right to use a class --> public access = the most liberal type of access in java public --> the specifier placed in class header to define the type of access used --> written before class identifier keyword --> then class name written

initialization

An assignment made when you declare a variable Some programmers prefer to initialize all variables. Others prefer to initialize a variable only if it can be given a meaningful value at the start of a program. EX) if an age will be entered by the user, many programmers would not assign the age a value when it is first declared

lvalue

An identifier that can appear on the left side of an assignment operator

Data type

An item's data type describes the type of data that can be stored there, how much memory the item occupies, and what types of operations can be performed on the data (regardless if the item is a constant or a variable)

Saving a Java Class

Any java class written must be saved using a writable storage medium such as a disk, DVD, or USB device if a class is public (that is, if you use the public access specifier before the class name), you must save the class in a file with exactly the same name and a .java extension EX) the First class must be stored in a file named First.java Class name & file name must match exactly

Assignment Operator

Any value to the right of the assignment operator is assigned to the memory location named on the left EX) equal sign (=) --> has right-to-left associativity only an expression with a literal to the left of the assignment operator (such as 25 = myAge) is illegal

rounding techniques used to eliminate fractional value imprecisions generated when you use floating-point numbers

Appendix C contains directions on how to round numbers and how to format a floating-point number so it displays the desired number of decimal positions

private access

Assigning private access to a field means that no other classes can access the attribute's values, and only methods of the same class are allowed to set, get, or otherwise use private variables.

Camel casing

Beginning an identifier with a lowercase letter and capitalizing subsequent words within the identifier EX) identifier such as 'lastName' EX) the following declaration creates a conventionally named int variable, myAge, and assigns it an initial value of 25: int myAge = 25; This declaration is a complete, executable statement, so it ends with a semicolon. The equal sign ( = ) is the assignment operator the first statement that follows is an initialization, and the second is an assignment: int myAge = 25; myAge = 42;

Creating a Java Application that Produces GUI Output

Besides allowing you to use the System class to produce command window output, Java provides built-in classes that produce GUI output

Using the boolean Data Type

Boolean logic is based on true or false comparisons can hold only one of two values—true or false EX) The following statements declare and assign appropriate values to Boolean variables: boolean isItPayday = false; boolean areYouBroke = true; Can use any legal identifier for Boolean variables, but they are easily identified as Boolean if you use a form of to be (such as is or are) as part of the variable name, as in "isItPayday". Besides assigning true and false, can also assign a value to a Boolean variable based on the result of a comparison. Java data type boolean, however, begins with a lowercase b --> in written program

Java API (Application Programming Interface)

Collection of existing classes provided as part of the Java programming language the Java application programming interface, the java class library contains information about how to use every prewritten Java class, including lists of all the methods you can use with the classes helpful material exists at the Java website, www.oracle.com/technetwork/ java/index.html

syntax error

Compilers and interpreters issue one or more error messages each time they encounter an invalid program statement a misuse of the language, discovered by the language translator when programs are compiled EX) misspelling a keyword or omitting a word that a statement requires

2 Types of Java Applications

Console applications - which support character or text output to a computer screen (easier to create) Windowed applications - which create a GUI with elements such as menus, toolbars, and dialog boxes

get() method

Controls how a value is retrieved [controlling data accessibility] ***Even when a field has no data value requirements or restrictions, making data private and providing public set and get methods establishes a framework that makes such modifications easier in the future

Instantiation

Creating an instance of an object an object is an instantiation of a class, or one tangible example of a class

example of application using a confirm dialog box --> and following showConfirmDialog() method

EX of an application that uses a dialog box to ask a user a question and to store the user's response in the integer variable named selection import javax.swing.JOptionPane; public class AirlineDialog { public static void main(String[] args) { int selection; boolean isYes; selection = JOptionPane.showConfirmDialog(null, "Do you want to upgrade to first class?"); isYes = (selection == JOptionPane.YES_OPTION); JOptionPane.showMessageDialog(null, "You responded " + isYes); } } **After a value is stored in selection, a Boolean variable named 'isYes' is set to the result when selection and JOptionPane.YES_OPTION are compared. - If the user has selected the Yes button in the dialog box, this variable is set to true; - The message output being --> "You responded true" otherwise, the variable is set to false. Finally, the true or false result is displayed**

Anatomy of a Java Statement

EX of printing a string statement) class --> property of the class --> method(followed by parenthesis for input) --> input literal string inside parenthesis --> end w/ semicolon The string First Java application (in picture added to the right) appears within parentheses because the string is an argument to a method, and arguments to methods always appear within parentheses following the method name System.out.println("First Java application");, out is an object that is a property of the System class, one that refers to the standard output device for a system, normally the monitor System is a class. Therefore, System defines attributes for System objects, --> one of the System attributes is out in EX to the right) statement that displays the string "First Java application" contains a class, an object reference, a method call, a method argument, and a statement-ending semicolon, but the statement cannot stand alone; it is embedded within a class

Creating instance methods (methods contained w/n classes)

EX) one method you need for an Employee class that contains an empNum is the method to retrieve (or return) any Employee's empNum for use by another class. - A reasonable name for this method is getEmpNum(), and its declaration is public int getEmpNum() ---> because it will have public access, return an integer (the employee number), and possess the identifier getEmpNum() EX) need a method with which to set the empNum field. - A reasonable name for this method is setEmpNum(), and its declaration is public void setEmpNum(int emp) ---> because it will have public access, return nothing, possess the identifier setEmpNum(), and require a parameter that represents the employee's ID number, which is type int

Adding parameters to methods (example)

EX))) The calculateGross() method with a parameter public static void calculateGross(double hours) { final double STD_RATE = 13.75; double gross; gross = hours * STD_RATE; System.out.println(hours + " hours at $" + STD_RATE + "per hour is $" + gross); } ** IN THIS EXAMPLE)) - the parameter identifier is hours --> meaning calculateGross() method can be called any # of times w/ a different argument each time --> but each argument will be known as HOURS inside the method - identifier hours represents a variable that holds a copy of the value of any double value passed into the method - The calculateGross() method is a void method b/c it does not need to return a value to any other method that calls it—its only function is to receive the hours value, multiply it by the STD_RATE constant, and then display the result - the calculateGross() method's parameter data type is double --> must call it using any argument that can be promoted to a double --> it can accept all listed below - a variable that is a double, float, long, int, short, or byte - a constant that is a double, float, long, int, short, or byte - an expression that is a double, float, long, int, short, or byte - Each time the method is called (even w/ varying arguments), the parameter hours receives a copy of the value that was passed EXAMPLE OF VALID METHOD CALLS W/ DATA)) • calculateGross(10);—This call uses an unnamed int constant that is promoted to a double • calculateGross(28.5);—This call uses an unnamed double constant • calculateGross(7.5 * 5);—This call uses an arithmetic expression • calculateGross(STANDARD_WORK_WEEK);—This call uses a named constant that might be a double, float, long, int, short, or byte • calculateGross(myHours);—This call uses a variable that might be a double, float, long, int, short, or byte • calculateGross(getGross());—This call assumes that the getGross() method returns a double, float, long, int, short, or byte

do not need to perform a cast when assigning a value to a higher unifying type

EXAMPLE below provides written statement of code - and can be applied to others like this Java automatically promotes the integer constant 10 to be a double so that it can be stored in the payRate variable: double payRate = 10; However, for clarity, if you want to assign 10 to payRate, you might prefer to write the following: double payRate = 10.0; The result is identical whether you assign the literal double 10.0 or the literal int 10 to the double variable.

Automatic type conversion example

EXAMPLE of successful type conversion))) assume that an int, hoursWorked, and a double, payRate, are defined and then multiplied as follows: int hoursWorked = 37; double payRate = 16.73; double grossPay = hoursWorked * payRate; result of the multiplication is a double b/c when a double and an int are multiplied, the int is promoted to the higher-ranking unifying type double—the type that is higher in the list (term #191 in quizlet) EXAMPLE of unsuccessful type conversion)) following code will not compile because hoursWorked times payRate is a double, and Java does not allow the loss of precision that occurs if you try to store the calculated double result in an int int hoursWorked = 37; double payRate = 16.73; int grossPay = hoursWorked * payRate;

input dialog box example

EXAMPLE) shows an application that creates an input dialog box containing a prompt for a first name import javax.swing.JOptionPane; public class HelloNameDialog { public static void main(String[] args) { String result; result = JOptionPane.showInputDialog(null, "What is your name?"); JOptionPane.showMessageDialog(null, "Hello, " + result + "!"); } } ***For example above to work correctly --> user must execute the application, input the name 'William' (by typing), then click the OK button or press enter on keyboard - The result String will contain William --> this is called the resulting output message box ***In example above: the response is concatenated with a welcoming message and displayed in a message dialog box

nonstatic attribute (instance variable)

Each object gets its own copy of each nonstatic attribute in its class - each object gets its own unique attribute instance variable for the class (a nonstatic attribute) because one copy exists for each object instantiation a class's data fields are most often private and not static - The exception (static attributes) occurs when you want to use a nonchanging value without being required to create an object—in that case you make the field both static and final if you are creating a class from which objects will be instantiated, most methods probably will be nonstatic because you will associate the methods with individual objects When creating a class with a nonstatic attribute and instantiate 100 objects, then 100 copies of that attribute exist in memory. When creating a nonstatic method in a class and instantiate 100 objects, only one copy of the method exists in memory, but the method receives a 'this' reference that contains the address of the object currently using it The system allocates a separate memory location for each nonstatic attribute in each instance When using a nonstatic attribute or method, you must use an object; for example: System.out.println();

Valid class names in Java

Employee = Begins with an uppercase letter UnderGradStudent = Begins with an uppercase letter, contains no spaces, and emphasizes each new word with an initial uppercase letter InventoryItem = Begins with an uppercase letter, contains no spaces, and emphasizes the second word with an initial uppercase letter Budget2019 = Begins with an uppercase letter and contains no spaces

Requirements for defining a Java Class

Everything that used within a Java program must be part of a class. EX) 'public class First' --> defines a class for which you have chosen the name First can define a Java class using any name or identifier as long as it meets the requirements listed below: 1) A Java identifier must begin with a letter of the English alphabet, a non-English letter (such as α or π), an underscore, or a dollar sign. A class name CANNOT begin with a digit. 2) A Java identifier can contain only letters, digits, underscores, or dollar signs. 3) A Java identifier cannot be a reserved keyword, such as public or class. (See Table 1-1 for a list of reserved keywords.) 4) A Java identifier cannot be one of the following values: true, false, or null. These are not keywords (they are primitive values), but they are reserved and cannot be used ****DON'T try to use a Java keyword as an identifier for a variable or constant.

Calling a method that returns a value

If a method returns a value, then when you call the method, you normally use the returned value (the method's value)

EXAMPLE (from txtbook) of Concatenated String: import javax.swing.JOptionPane; public class NumbersDialog { public static void main(String[] args) { int creditDays = 30; JOptionPane.showMessageDialog(null, "" + creditDays); JOptionPane.showMessageDialog (null, "Every bill is due in " + creditDays + " days"); } }

In this example))) - shows a NumbersDialog class that uses the showMessageDialog() method twice to display an integer declared as creditDays and initialized to 30 - In each method call, the numeric variable is concatenated to a String, making the ENTIRE SECOND ARGUMENT a String - In 1st call to method showMessageDialog(), the concatenated String is a null String created by typing a set of quotes with nothing between them a null String is NOT the same thing as an empty string. An empty (or zero-length) String, which can be created by typing a set of quotes with nothing between them, exists in memory. This outputs --> 2 dialog boxes, the 1st dialog box shows just the value 30; after it is dismissed by clicking OK, the second dialog box appears. given the class name = NumbersDialog --> we say that the 2 dialog boxes were created by the NumbersDialog application

Java's primitive data types

Made of 8 built-in primitive data types (EX: int and double) Java's primitive data types are also called SCALAR types Java's primitive data types are not composite (of composite type)

method declaration (header) syntax

Method name syntax: (including a class name, dot, and method name) Method declaration (method header) syntax - includes: optional access specifiers, the return type for the method, the method name, and a set of parentheses - a method's declaration contains these same elements regardless of whether or not they accept parameters - 2 additional elements required if method DOES receive parameters (required within the parenthesis of method) 1) The parameter type 2) A local name for the parameter - EX)) The declaration (method header) for a public method named calculateGross() that accepts a value for an employee's hours worked could be written as follows: public static void calculateGross(double hours) Parentheses in a method declaration acts as a funnel into the method— parameters listed there contain data that is "dropped into" the method Method Syntax: access specifier(public or private) -> return type of variable -> method name -> list of incoming variables including their type { method body }

accessor methods (getters)

Methods that retrieve values - getters - get() - does not employ static modifier the getEmpNum() method must be nonstatic because it returns a different empNum value for every Employee object you ever create EX) public int getEmpNum() { return empNum; }

Organizing attributes/method variables/methods

PRIMARY KEY = attribute used as a unique identifier, organized at top of list [of attributes listed for a class] lots of flexibility in how you position your data fields within any class if a class has multiple attributes of the same data type [like string for ex:] --> , they might be declared within the same statement, such as private String empLastName, empFirstName;

Example of parsing strings for numeric conversion

Refer to page 85-86 in txtbook, Figure 2-30: 'The SalaryDialog class'

Arguments

Some methods require that data items be sent to them when they are called --> arguments are data items you use in a call to a method EXAMPLE for purpose of arguments in a method)) - designing a square() method that you can supply with an argument that represents the value to be squared - rather than having to develop a square1() method (that squares the value 1), a square2() method (that squares the value 2), etc. - To call a square() method that takes an argument, you might write a statement like square(17); or square(86); - Similarly, any time it is called, the println() method can receive any one of an infinite number of arguments and print that string out

magic number

Some programmers refer to the use of a literal numeric constant, such as 20, as using a magic number—a value that does not have immediate, intuitive meaning or a number that cannot be explained without additional knowledge

method overloading

The ability to define two or more different methods with the same name but different method signatures (diff parameters) The ability to execute different method implementations by altering the argument used with the method name

Object's state

The alues of the properties of an object

main method header

The method header is public static void main(String[] args) located in the first line within the curly brace scope under the FIRST curly brace (of the class body) --> the 2nd written line in an executed program Components of the main() method header: 1) The keyword public is an access specifier, just as it is when you use it to define the First class. public = is an access specifier 2) The keyword static does NOT mean that a method works without being in an object / without instantiating an object of the class Java just creates the object for us when static method is used 3) The keyword void indicates that the main() method does not return any value when it is called. This doesn't mean that main() doesn't produce output—in fact, the method does. It only means that the main() method does not send any value back to any other method that might use it void = the method's return type 4) The name of the method is main(). As is the convention with Java methods, its identifier begins with a lowercase letter. Not all classes have a main() method; in fact, many do not. All Java applications, however, must include a class containing a public method named main(), and most Java applications have additional classes and methods. When you execute a Java application, the JVM always executes the main() method first. 5) In the method header, the contents between the parentheses, String[] args, represent the type of argument that can be passed to the main() method, just as the string "First Java application" is an argument passed to the println() method. String is a Java class that can be used to hold character strings (according to Java convention, it begins with an uppercase letter, like other classes). The brackets following String mean that argument is a list of Strings. The identifier args is used to hold any String objects that might be sent to the main() method. The main() method could do something with those arguments, such as display them, but in Figure 1-4, the main() method does not actually use the args identifier. Nevertheless, you must place an identifier within the main() method's parentheses. The identifier does not need to be named args—it could be any legal Java identifier—but the name args is traditional String is a class. Any arguments to this method must be String objects. The square brackets mean the argument to this method is an array of Strings --> (String[] args) args = the identifier of the array of Strings that is the argument to this method

Modifying a compiled java class (execution of modified class)

To produce the new output, first you must modify the text file that contains the existing class. You need to change the existing literal string, and then add an output statement for another text string The changes to the First class include the addition of the statement System.out.println("My new and improved"); and the removal of the word First from the string in the other println() statement the old compiled version of the class with the same name is still stored on your computer STEPS: 1) save the new file --> 2) recompile (ctrl + 1) --> 3) Interpret the class bytecode and execute the class using the java command (ctrl + 2) When you recompile a class, the original version of the compiled file with the .class extension is replaced, and the original version no longer exists. When you modify a class, you must decide whether you want to retain the original version. If you do, you must give the new version a new class name and a new filename, or you must save it in a different folder

scientific notation format

When a number is in scientific notation --> the value to the left of the decimal point is always greater than or equal to 1 and less than 10 The e in the displayed value stands for exponent; the 8 means the true decimal point is eight positions to the right of where it is displayed, indicating a very large number (A negative number following the e would mean that the true decimal point belongs to the left, indicating a very small number.) EX)) a float given the value 324616777 is displayed using a decimal point after the 3 and only six or seven digits followed by e+008 or E8 means that the value is approximately 3.24617 times 10 to the 8th power, or 324617000

When declaring objects

When declaring a primitive type object, or when declaring an object from one of your classes, - you provide its type and an identifier. After each exists, you can use them in similar ways. EX)) suppose you declare an int named myInt and an Employee named myEmployee - each can be passed into a method, returned from a method, or assigned to another object of the same data type Objects created can be accepted as parameters in methods, object must be declared first - EX) Employee myEmployee; myEmployee = getEmployeeData(); displayEmployee(myEmployee); *** - Employee is declared - Value returned from getEmployeeData() method is assigned to myEmployee object. - myEmployee object is passed to displayEmployee() method. -EX) public static void displayEmployee(Employee anEmp) *****Parameter is Employee type Objects created can be returned as a return type within a method, object must be declared first - EX) public static Employee getEmployeeData() ****Return type is Employee -EX) return tempEmp; ****Employee object is returned (Employee is passed into and out of methods just like a primitive object would be)

Using a constructor [general info]

When you create a class ( EX: Employee ) and instantiate an object with a statement such as the following, Employee chauffeur = new Employee(); you are calling the Employee class constructor that is provided by default by the Java compiler When the default constructor for the Employee class is called, it establishes one Employee object with the identifier provided Any constructor you write must have the same name as the class it constructs constructors cannot have a return type—not even void Normally constructors are declared to be public so that other classes can instantiate objects that belong to the class. When you write a constructor for a class, you no longer have access to the automatically created version Even though you might want a field to hold the default value for its data type, you still might prefer to explicitly initialize the field for clarity. - can write any Java statement in a constructor - not for default ones tho Can place a constructor anywhere inside the class, outside of any other method. Typically, a constructor is placed with the other methods. Often, programmers list the constructor method first because it is the first method used when an object is created constructors are NOT required to make classes that compile without error

Declaring a variable

You declare a variable just once in a method, but you might assign new values to it any number of times You can declare multiple variables of the same type in separate statements. You also can declare 2 or more variables of the same type in a single statement by separating the variable declarations with a comma, as shown in the following statement: int height = 70, weight = 190; many programmers declare each variable in its own separate statement for convention --> but if the variable's purposes are closely related then you can follow the convention of declaring multiple variables in the same statement - can declare as many variables in a statement as you want, as long as the variables are the same data type - to declare variables of different types, you must use a separate statement for each type A compiler error message will be displayed when there is a conflict between two variables with the same name variables declared in a class, but outside any method, are automatically initialized for you NOTE that even if a statement occupies multiple lines, the statement is not complete until the semicolon is reached

default constructor

[for class purposes] default constructor is the ONLY constructor provided to us by Java [by java compiler]. prewritten by java a constructor that requires no arguments The automatically supplied default constructor provides the following specific initial values to an object's data fields: (fields are ATTRIBUTES) • Numeric fields are set to 0 (zero) • Character fields are set to Unicode '\u0000' • Boolean fields are set to false • Fields that are object references (for example, String fields) are set to null (or empty)

common escape sequences to use in java

\b --> Backspace; moves the cursor one space to the left \t --> Tab; moves the cursor to the next tab stop \n --> Newline or linefeed; moves the cursor to the beginning of the next line \r --> Carriage return; moves the cursor to the beginning of the current line \" --> Double quotation mark; displays a double quotation mark \' --> Single quotation mark; displays a single quotation mark \\ --> Backslash; displays a backslash character **When you display values within JOptionPane dialog boxes rather than in a command window, the escape sequences '\n' (newline), '\"' (double quote), and '\\' (backslash) operate as expected within a JOptionPane object, but '\t', '\b', and '\r' do not work in the GUI environment**

dialog box

a GUI object resembling a window in which you can place messages you want to display

Abstract Data Type (ADT)

a [data] type whose implementation is hidden and accessed through its public methods

Logic error

a bug that allows a program to run, but that causes it to operate incorrectly (even if all syntax errors are corrected) --> more difficult than syntax error corrections Logic error = a type of run-time error when the syntax of the program is correct and the program compiles but produces incorrect results when you execute it --> must be detected by carefully examining the program output EX) multiplying two values when you meant to divide them or producing output prior to obtaining the appropriate input Correct logic requires that all the right commands be issued in the appropriate order. when developing programs of significant size, logic must be planned before writing program statements can identify logic errors only when you examine a program's output EX) discovering an incorrect calculation was performed

JOptionPane class

a class that allows you to produce dialog boxes can accept INPUT using JOptionPane class To use the JOptionPane class, you must import the package named javax. swing.JOptionPane EXAMPLE) using import statement in 1st line import javax.swing.JOptionPane; public class FirstDialog { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "First Java dialog"); } {

Class

a group or collection of objects with common properties (object-oriented terminology) Classes define properties and methods their objects can use classes can't do work, only objects can do work concept of a class is useful because of its reusability Objects gain their attributes from their classes, and all objects have predictable attributes because they are members of certain classes concept of a class is useful because of its reusability - Objects gain their attributes from their classes - all objects have predictable attributes because they are members of certain classes - objects have methods associated with them, and every object that is an instance of a class is assumed to possess the same methods

prompt

a message displayed for the user that requests and describes input

constructor

a method that initializes a newly instantiated object [its sole purpose is to create new objects]

showMessageDialog()

a method that requires 2 arguments inputting 'null' as one of the 2 arguments in this method indicates that the box should appear in the center of the screen inputting the argument 'string' as an additional argument to null in this method --> indicates the typed string to be displayed in the output dialog box whenever a method contains more than one argument, the arguments are separated by commas

return type void

a method that returns no data, when a method does not send any information back to the method that calls it The main() method in an application must have a return type of void void method and method of type void both refer to a method that has a void return type

method's type

a method's return type; can be any data type used in Java includes primitive data types: int, double, char, etc. also includes class types (including class types you create) method can also return no value --> so then the return type is void - if a method produces output but does NOT return any value --> it's return type is void A method's declared return type must be compatible with the type of the value used in the return statement - meaning the return value must match the return type or be promotable to the return type - If the returned value is not compatible with the method's return type, the class does not compile All methods except void methods require a return statement that returns a value of the appropriate type - CANNOT place any statements after a method's return statement --> these are unreachable statements b/c the logical flow leaves the method at the return statement EXAMPLE) of a method that prompts a user for an age and returns the age to the calling method might be declared as: public static int getAge() - The method returns an int, so it is type int EXAMPLE) of a method that returns true or false depending on whether an employee worked overtime hours might be declared as: public static boolean didWorkOvertime() - This method returns a Boolean value, so it is type boolean

variable

a named memory location that can store a value can hold only one value at a time, but the value it holds can change (can be altered)

keyword static (aka class attributes & class methods)

a nonchanging value that doesn't require the creation of new objects (per say) keyword static is used for classwide methods, but not for methods that "belong" to objects - If you are creating a program with a main() method that you will execute to perform some task, ----> many of your methods will be static so you can call them from within main() without creating objects When creating a class with a static attribute and instantiate 100 objects, only one copy of that attribute exists in memory. When creating a static method in a class and instantiate 100 objects, only one copy of the method exists in memory and the method does not receive a this reference When using a static attribute or method, you do not need to use an object; for example: JOptionPane.showDialog(); Static class variables are not instance variables. - The system allocates memory to hold class variables once per class, no matter how many instances of the class you instantiate. - The system allocates memory for class variables the first time it encounters a class, and every instance of a class shares the same copy of any static class variables EX, the Java Math class contains a final, public, static field named PI that you can use without instantiating a Math object

Numeric constant

a number whose value is taken literally at each use as opposed to a character or string constant

implementation hiding

a principle of object-oriented programming that describes the encapsulation of method details within a class Meaning - a client does not have to know how a method works internally, but only needs to know the name of the called method and what type of information to send (and any data returned by the method) the calling method needs to understand only the interface to the called method Additionally - if you substitute a new or revised method implementation, as long as the interface to the method does not change, you won't need to make any changes in any methods that call the altered method Hidden implementation methods are often referred to as existing in a black box --> understanding how they work but not understanding the internal mechanisms

System Software

a program that manages the computer itself (such as Windows or Linux)

Method

a self-contained block of program code that carries out some action, similar to a procedure in a procedural program a program module that contains a series of statements that carry out a task Any class can contain an unlimited number of methods, and each method can be called an unlimited number of times To execute a method, you invoke or call it - a calling method (i.e. the client method) invokes a called method

Literal string (of characters)

a series of characters that will appear in output exactly as entered Any literal string in Java is written between double quotation marks (not single ones) In Java, String is a built-in class that provides you with the means for storing and manipulating character strings In Java, a literal string cannot be broken and placed on multiple lines.

Primitive data type

a simple data type, they serve as the building blocks for more complex data types (reference types) Each primitive type in Java has a corresponding class (type-wrapper classes) contained in the java.lang package; like most classes, the names of these classes begin with uppercase letters Java provides for 8 primitive types of data --> called primitive because they are simple and uncomplicated

documentation comments / javadoc comments NOT USED IN CLASS

a special case of block comments called documentation comments because they are used to automatically generate nicely formatted program documentation with a program named javadoc Javadoc comments begin with a forward slash and two asterisks ( /** ) and end with an asterisk and a forward slash ( */ )

constructor

a special type of method that creates and initializes objects the name of the constructor is always the same as the name of the class whose objects it constructs

variable declaration statement

a statement that reserves a named memory location and includes the following: • A data type that identifies the type of data that the variable will store • An identifier that is the variable's name • An optional assignment operator and assigned value, if you want a variable to contain an initial value • An ending semicolon

Procedural Programming

a style of programming in which operations are executed one after another in sequence typical procedural program defines and uses named computer memory locations (variables)

literal constant

a value that is taken literally at each use

uninitialized variable

a variable that has not been assigned a value in Java, you cannot display an uninitialized variable Therefore, Error messages generate when variables are not initialized EX) correct usage --> int aWholeNumber = 315; incorrect usage --> int aWholeNumber; the aWholeNumber declaration must be modified (from incorrect usage above) so that the variable is again initialized to 315 (correct usage above)

integer

a whole number without decimal places Integer values are exact int data type is the most commonly used integer type, a variable of type int can hold any whole number value from - 2,147,483,648 to + 2,147,483,647 do not type commas or periods when assigning values to int variables Java allows underscores in numbers; typically used to make long numbers easier to read EX) corporateBudget = 8_435_000; when typing a number, most people only use digits and optional plus or minus signs (to indicate a positive or negative integer) Don't attempt to assign a constant decimal value to an integer using a leading 0. EX) if you declare int num = 021; and then display num, you will see 17. The leading 0 indicates that the value is in base 8 (octal), so its value is two 8s plus one 1. In the decimal system, 21 and 021 mean the same thing, but not in Java.

class client or class user

an application or class that instantiates objects of another (prewritten) class ***You can identify a class that is an application because it contains a public static void main() method. The main() method is the starting point for any application. You will write and use many classes that do not contain a main() method—these classes can be used by other classes that are applications A Java application can contain only one method with the header public static void main(String[] args). If you write a class that imports another class, and both classes have a public main() method, your application will not compile

stub

an empty method that acts as a placeholder to fill for implementation later

run-time error

an error not detected until the program asks the computer to do something wrong, or even illegal, while executing. Logic error = type of run-time error Not all run-time errors are the fault of the programmer EX) a computer's hardware failing while a program is executing Good programming practices help to minimize run-time errors

rvalue

an item that can appear only on the right side of an assignment operator

unnamed constant

an unnamed constant b/c it has no identifier associated with it

Whitespace

any combination of nonprinting characters, optional in java used to organize program code and make it easier to read CAN insert whitespace between words or lines in program codes by typing spaces, tabs, or blank lines because the compiler ignores these extra spaces CANNOT use whitespace within an identifier or keyword, or surrounding the dots in any class-object-method combination

integer constants

are int by default, when the variable's purpose is to hold a whole number --> the variable will then almost always be declared as type int **though an integer numeric constant is declared by Java as int, you don't have to cast it when you assign it to a variable declared as byte or short. Though this is true sometimes, for the purposes of our class, you MUST always cast it when assigning to a byte or short** EX) 18 = int If you are writing an application in which saving memory is important, you might choose to declare the same variable as a byte. Saving memory is seldom an issue for an application that runs on a PC. when you write applications for small devices with limited memory, such as phones, conserving memory becomes more important.

input dialog box

asks a question and provides a text field in which the user can enter a response created using the showInputDialog() method --> single argument input of what you want to be displayed in dialog box - returns a String that represents a user's response; - meaning you can assign the showInputDialog() method to a String variable and the variable will hold the value that the user enters

showConfirmDialog() method

belongs to JOptionPane class the simplest version of the method (out of 4 versions) requires a parent component (which can be null) and the String prompt that is displayed in the box showConfirmDialog() method returns an integer containing one of three possible values: JOptionPane.YES_OPTION JOptionPane.NO_OPTION JOption Pane.CANCEL_OPTION

Java's 8 primitive data types (keywords & their descriptions)

byte = Byte-length integer short = Short integer int = Integer long = Long integer float = Single-precision floating point double = Double-precision floating point char = A single character boolean = A Boolean value (true or false)

classes without a main() method

can be compiled but not executed classes w/out a main() method are intended to be used as a data type for objects within other applications,

When creating classes

can create a class with fields and methods long before you instantiate any objects that are members of that class

char variable (a variable of type char)

can hold only one character To store a string of characters, (ex: person's name) you must use a data structure called a String single characters use single quotation marks You can store any character—including nonprinting characters such as a backspace or a tab—in a char variable using an escape sequence EX) the following code stores a newline character and a tab character in the char variables aNewLine and aTabChar: char aNewLine = '\n'; char aTabChar = '\t'; - In the declarations of aNewLine and aTabChar, the backslash and character pair acts as a single character; the escape sequence serves to give a new meaning to the character. - the literal characters in the preceding code ('\n' and '\t') have different values from the "plain" characters 'n' or 't'.

When calling additional methods to a method in a class

can place additional methods to call within a class, but it must be outside of any other methods --> CANNOT place a method within another method only 2 locations where you can place additional calling methods within an existing class --> - within the curly braces of the class, but outside of (either before or after) any other methods. Methods can never overlap 1) can place additional methods before (above) main() method body (the inner, 2nd set of curly braces) --> below 2nd set of curly braces that close off the main() method body & above the curly brace that encapsulates the class scope (the 1st set of curly braces) 2) can place additional methods after (below) main() method header, above main() method body (the inner, 2nd set of curly braces) --> below 1st set of curly braces under class name The order in which methods appear in a class has no bearing on the order in which the methods are called or execute - main() method is always executed first (no matter where it's placed - it might call any other methods in any order and any number of times - An application will execute based on the order that methods are called --> not their physical placement METHODS (other than the main() method) MUST BE CALLED IN ORDER TO EXECUTE --> they do not execute if they are simply just placed in a class (where additional calling methods are placed: mentioned above) - ONLY main () method executes automatically when a program is run --> and any method within main() method - classes can contain methods that are never called from particular applications The main() method can call a method that resides in its own class When a main() method contains a method within its body scope --> - the main() method can then contain its own statements and execute its contained method's own statements (statements belonging to the method that the main() method executes)'

to produce console output on multiple lines

can use the newline escape sequence (\n), more efficient OR use the println() method multiple times

Parameters/arguments & their order in a method call

can write a method with any # of parameters in any order BUT when you call a method, the arguments you send to a method must MATCH in ORDER the parameters listed in the method declaration (both in number and in type) arguments to a method passed in the wrong order can/will result in the following: • If the method can still accept all the arguments, the result is a logical error (program compiles and executes, but it probably produces incorrect results) • If the method cannot accept the arguments, passing arguments in the wrong order constitutes a syntax error, and the program does not compile. EX) if you try to pass a double value to a method that accepts an int parameter, the program fails to compile

classes ARE data types

classes that you create become data types a class is sometimes referred to as an abstract data type (ADT) --> which is a data type whose implementation is hidden and accessed through its public methods a class that you create can also be referred to as programmer-defined data type --> which is a [data] type that is not built into the language A class is a composite type—that is, a class is composed from smaller parts - Java's primitive data types are NOT COMPOSITE

Concatenated Strings

combination of strings --> the action of combining the strings In Java, when a numeric variable is concatenated to a String using the plus sign, the entire expression becomes a String. plus (+) sign creates concatenation of 2 strings --> when you place a string on one or both sides of a plus sign When you concatenate Strings with numbers, the entire expression is a String. EX) the expression "A" + 3 + 4 results in the String "A34" EX) If the intention is to create the String "A7" then you could add parentheses to write "A" + (3 + 4) so that the numeric expression is evaluated first. when a String and a numeric value are concatenated, the resulting expression is a string another EX))) "X" + 2 + 4 results in "X24", not "X6" If you want the result to be "X6", you can use the expression "X" + (2 + 4)

Running java application

ctrl + 2 to run java program after compiling (w/ ctrl +1)

Parameters

data items received by a method Methods that receive data (parameters) are flexible because they can produce different results depending on what data they receive the parentheses in a method declaration as a funnel into the method— parameters listed there contain data that is "dropped into" the method A parameter accepted by a method can be any data type, including: - primitive data types: such as int, double, and char - built-in class type such as String or PrintStream - or a class type you create EX)) The declaration (method header) for a public method named calculateGross() - the parameter double hours within the parentheses indicates that the method will receive a value of type double, and that within the method, the passed value will be known as hours public static void calculateGross(double hours) EACH PARAMETER WRITTEN REQUIRES its own declared type as well as its own identifier

attributes (data fields)

declared outside of methods (but within classes) attributes are usually private / most class methods are public

return type

describes the type of data the method sends back to its calling method Not all methods return a value to their calling methods - the return type void is a method that returns no data

Class definition

describes what attributes its objects will have and what those objects will be able to do a class definition exists before any objects are created from it

Logic

determines the exact order of instructions needed to produce desired results behind any computer program, whether it is an application or system program

Java Program

developed by Sun Microsystems (later acquired by Oracle) as an object-oriented language for general-purpose business applications and for interactive, World Wide Web-based Internet applications Java's popularity as a language stems from its advantages of its security features and the fact that it is architecturally neutral --> meaning java can be used to write a program that runs on any operating system or device can be run on a wide variety of computers and devices because it does not execute instructions on a computer directly --> Java runs on a hypothetical computer known as the Java Virtual Machine (JVM). - JVM = not physical entity created from hardware, it is composed only of software

easy to lose data when performing a (type) cast

distorted results occur when data is lost EX) the largest byte value is 127 and the largest int value is 2,147,483,647, so the following statements produce distorted results: int anOkayInt 5 200; byte aBadByte 5 (byte)anOkayInt; makes the 'aBadByte' variable above (2nd line) appear to hold the value -72, which is inaccurate and misleading

order for establishing unifying data types (between values) highest to lowest in descending order from top to bottom

double = Highest float long int = Lowest (short and byte are automatically converted to int when used in expressions) When two unlike types are used in an expression, the unifying type is the one that is higher in the list when an operand that is a type lower on the list is combined with a type that is higher, the lower-type operand is converted to the higher one EX)))) the addition of a double and an int results in a double the subtraction of a long from a float results in a float Boolean values cannot be converted to another type in java data types char, short, and byte all are promoted to int when used in statements with unlike types calculations performed with any combination of char, short, and byte values, results in an int by default. EX) adding two bytes results in an int type, not a byte

Semicolon usage

end every statement with a semicolon, do not end any class or method headers with a semicolon

Variables

hold the data a program uses EX) data might be read from an input device and stored in a location the programmer has named variable values may be used in arithmetic statements, as the basis for a decision, sent to an output device, or have other operations performed with it The data stored in a variable can change, or vary, during a program's execution Don't try to use a variable or named constant that has not yet been assigned a value

associativity & precedence

important to know when combining mathematical operations in a single statement associativity of arithmetic operators with the same precedence is left to right EX) in statement --> answer = x + y + z;, - the x and y are added first, producing a temporary result - then z is added to the temporary sum - After the sum is computed, the result is assigned to answer an arithmetic expression is evaluated from left to right, and any multiplication, division, and remainder operations take place. - Then, the expression is evaluated from left to right again, and any addition and subtraction operations execute

Polymorphism (meaning many forms)

it describes the feature of languages that allows the same word or symbol to be interpreted correctly in different situations based on the context EX) a plus sign for addition EX) although the classes Automobile, Sailboat, and Airplane all inherit from Vehicle, methods such as turn and stop work differently for instances of those classes. important concept in object-oriented terminology (that does not exist in procedural programming terminology)

After an object has been instantiated

its methods can be accessed using the object's identifier, a dot, and a method call EX))) Employee clerk = new Employee(); Employee driver = new Employee(); clerk.setEmpNum(345); driver.setEmpNum(567); ******ABOVE IN EXAMPLE an application that instantiates two Employee objects. The two objects, clerk and driver, each use the setEmpNum() and getEmpNum() method one time - application can use these methods because they are public, and it must use each of them with an Employee object because the methods are not static - must use the public methods setEmpNum() and getEmpNum() to be able to set and retrieve the value of the empNum field for each Employee because you cannot access the private empNum field directly. - EX)) the following statement would not be allowed: clerk.empNum = 789; - This statement generates the error message empNum has private access in Employee, meaning you cannot access empNum from the DeclareTwoEmployees class - If you made empNum public instead of private, a direct assignment statement would work, but you would violate an important principle of object-oriented programming—that of data hiding using encapsulation

3 types of comments in Java

line comments, block comments, documentation comments

null (keyword)

means that no value has been assigned. It is not the same as a space or a 0; it literally is nothing

parse

means to break into component parts Parsing a String converts it to its numeric equivalent EX) methods: Double.parseDouble(), Integer.parseInt()

nonstatic methods (instance methods)

methods used with object instantiations only nonstatic methods behave uniquely for each object, cannot use a nonstatic method without an object

Reference types

more complex data types which hold memory addresses EX) system class, scanner class

% remainder operator (modulus operator), (mod)

most often used with two integers, and the result is an integer with the value of the remainder after division takes place EX) the result of 45 % 2 is 1 because 2 "goes into" 45 twenty-two times with a remainder of 1 In Java --> no division operation needed before performing remainder operation a remainder operation can stand alone remainder operator is most often used with integers - legal but less often useful to use the operator with floating-point values - using the % operator with floating-point values results in a remainder from rounded division in Java, the result of using the remainder operator can be negative

Creating a class

must assign a name to the class, and you must determine what data and methods will be part of the class To begin, you create a class header with three parts: • An optional access specifier (ex: public --> is a class modifier) • The keyword class • Any legal identifier you choose for the name of your class—starting with an uppercase letter is conventional

Variable names

must be legal Java identifiers (refer back to ch.1 legal identifier requirements) variable name must start with a letter, cannot contain spaces, and cannot be a reserved keyword must declare a variable before you can use it can declare a variable at any point before using it, but it is common practice to declare variables first in a method and to place executable statements after the declarations Variable names conventionally begin with lowercase letters to distinguish them from class names --> but programs can compile without error even if names are constructed unconventionally (just like class names can)

program comments

nonexecuting statements added to a program for the purpose of documentation --> designed for people reading the source code and not for the computer executing the program best practice dictates that you also include a brief comment to describe the purpose of each method you create within a class Turning some program statements into comments = useful for program application development If a program is not performing as expected, you can "comment out" various statements and subsequently run the program to observe the effect

access specifiers (aka access modifiers)

optional, can be any of the following modifiers: public, private, protected, or, if left unspecified, package by default. Most often, methods are given public access; a method with public access means that any other class can use it, not just the class in which the method resides EX)) public static void main(String[] args) - The main() method (shown in example statement above) in an application must specify public access - static modifier does NOT mean that methods do not require an object to be created EX)) public static void displayAddress() - not main() method --> this method written within main() method scope -The displayAddress() method is not required to specify public access. if access is public, the method can be used by other, outside classes - again, static modifier does NOT mean that methods do not require an object to be created The main() method in an application must use the keyword static, but other methods, like displayAddress(), can use it too.

showMessageDialog() method

part of the JOptionPane class --> when executed a dialog box is displayed to user used for console output, the showMessageDialog() method starts with a lowercase letter and is followed by a set of parentheses --> similar to println() method showMessageDialog() method requires 2 arguments --> println() method only requires 1 argument between its parentheses to produce an output string When a method requires multiple arguments, they are separated by commas When the first argument to showMessageDialog() is null, it means the output message box should be placed in the center of the screen --> The second argument, after the comma, is the literal string that is displayed ****NOTE!!!!! showInputDialog() method returns a String, which must be converted to a number using a type-wrapper class before you can use it as a numeric value****

information hiding (encapsulation)

principle used in creating private access, an important component of object-oriented programs A class's private data can be changed or manipulated only by a class's own methods and not by methods that belong to other classes.

type conversion

process of converting one data type to another Automatic type conversion: Java performs some conversions for you automatically or implicitly, but other conversions must be requested explicitly by the programmer performing arithmetic operations with operands of unlike types, Java chooses a unifying type for the result Java performs an implicit conversion --> which automatically converts nonconforming operands to the unifying type

Writing Arithmetic Statements Efficiently

programs operate more efficiently if you avoid unnecessary repetition of arithmetic statements, avoid duplication of operations EX))) instead of writing 2 statements using "hours * rate" twice stateWithholding = hours * rate * STATE_RATE; federalWithholding = hours * rate * FED_RATE; it would be more efficient to perform the calculation once like this grossPay = hours * rate; stateWithholding = grossPay * STATE_RATE; federalWithholding = grossPay * FED_RATE;

set() method

provides a value for does accept any integer value you send into it, - however, one could rewrite the set() method to prevent invalid data from being assigned to an object's attributes - in that case --> any statements [that you write] that enforce these requirements [that you expect] would be part of the set() method ***Even when a field has no data value requirements or restrictions, making data private and providing public set and get methods establishes a framework that makes such modifications easier in the future

Example of main() method calling another method (additional method) - check back to method location terms for more context *** main() method public static void main(String[] args) calls for another method "public static void calculateGross(double hours)" (this method is outside main method body but within class body)

public class DemoGrossPay { public static void main(String[] args) { double hours = 25; double yourHoursWorked = 37.5; calculateGross(10); calculateGross(hours); calculateGross(yourHoursWorked); } public static void calculateGross(double hours) { final double STD_RATE = 13.75; double gross; gross = hours * STD_RATE; System.out.println(hours + " hours at $" + STD_RATE + " per hour is $" + gross); } } ** THE FINAL MODIFIER IN "final double STD_RATE = 13.75;" --> makes STD_RATE constant. B/c hours is not altered within the calculateGross() method - could also make the method's parameter constant by declaring the method header as public static void calculateGross(final double hours) - but declaring a parameter as final means it cannot be altered within the method --> other users of program would know that the parameter is not intended to change **THE HOURS IDENTIFIER - METHOD VARIABLE** - the identifier hours in the main() method that is used as an argument in one of the method calls refers to a different memory location than hours in calculateGross() method - The parameter hours is simply a placeholder while it is being used within the method, no matter what name its value "goes by" in the calling method -The parameter hours is a method variable to the calculateGross() method; it is known only within the boundaries of the method. The variable and constant declared within the method are also local (only known) to the method - b/c of method variable --> Each time the calculateGross() method in example above executes, an hours variable is declared as a brand new variable and a new memory location large enough to hold a double is set up and named hours - Within the method, hours holds a copy of whatever value is passed into the method by the main() method - When the calculateGross() method ends at the closing curly brace, the method (local) hours variable ceases to exist - if you change the value of hours after you have used it in the calculation within calculateGross(), it affects nothing else. - The memory location that holds hours is released at the end of the method, and any changes to its value within the method do not affect any value in the calling method. - NO CHANGE in the variable named hours in the main() method; that variable, {even though it has the same name as the method variable (local variable) declared parameter in the calculateGross() method}, is a different variable with its own memory address

example of written method's type in program (A version of the calculateGross() method that returns a double)

public static double calculateGross(double hours, double rate) { double gross; gross = hours * rate; return gross; } *** in method declaration "public static double calculateGross(double hours, double rate)" --> the first double (b/w static and calculateGross) is the method's return type --> this is its location in a method header *** "return gross;" is the VALUE that is returned --> this is where it is written (the method's value) EXAMPLE of a assigning method's value (return value) to a variable)) when invoking the calculateGross() method (in previous example above), one can assign the returned value (the method's value) to a double variable named myPay, as in the following statement: myPay = calculateGross(myHoursWorked, myRate); ****CAN ALSO use a method's returned value directly, without storing it in any variable - use the method's value in the same way any variable of the same type would be used EXAMPLE)) can display a method's returned value from within a println() method call as in the following: - Because calculateGross() returns a double, you can use the method call in the same way that you would use any simple double value. System.out.println("My pay is " + calculateGross(myHoursWorked, myRate)); ** 2 closing parenthesis at end of statement, b/c first one completes the call to the calculateGross() method, the second one completes the call to the println() method CAN USE use a method's return value directly in an arithmetic expression, as in the following statement: EX))) double spendingMoney =calculateGross(myHoursWorked, myRate) - expenses;

Type Casting

purposely overriding the unifying type imposed by Java forces a value of one data type to be used as a value of another type uses a cast operator to perform, cast operator is followed by the variable or constant to be cast EXAMPLE of a type cast performed in a code)) In this example below, the double value bankBalance is divided by the integer 4, and the result is a double (data type) Then, the double result is converted to a float BEFORE it is stored in weeklyBudget. Without the conversion, the statement that assigns the result to weeklyBudget would NOT compile double bankBalance = 189.66; float weeklyBudget = (float) (bankBalance / 4); // weeklyBudget is 47.415, one-fourth of bankBalance ANOTHER EXAMPLE of a type cast conversion) a cast from a float to an int occurs in this code segment: In this example, the float value myMoney is converted to an int before it is stored in the integer variable named dollars When the float value is converted to an int, the decimal place values are lost - b/c cast operators do not permanently alter variables' data types, only temporarily for duration for the current operation --> - SO if myMoney was used again in the example below, it would still be a float and its value would still be 47.82 float myMoney = 47.82f; int dollars = (int) myMoney; // dollars is 47, the integer part of myMoney

is-a relationships

relationships in which the object "is a" concrete example of the class Expressing an is-a relationship is correct only when you refer to the object and the class in the proper order - correct order = object is a part of class The difference between a class and an object parallels the difference between abstract and concrete programmers use the phrase is-a when talking about inheritance relationships

A variable holds one value at a time

remember from compsci class if x = 2 and y = 3 --> if you then assign x = y --> Then x will no longer = 2 and will = 3 now z, is used as a temporary holding spot for one of the original values of x and y --> b/c The extra variable is used because as soon as you assign a value to a variable, any value that was previously in the memory location is gone

binary operators

require two operands, arithmetic operators are binary operators

double data type

requires more memory than a float, can hold 14 or 15 significant digits of accuracy A value stored in a double is a double-precision floating-point number a floating-point constant, such as 18.23, is a double by default (just like how an integer constant, such as 18, is a value of type int by default) Doubles are chosen (over floats) when higher levels of accuracy are needed (rather than saved memory) --> such as in graphics-intensive software can type D (or d) after a floating-point constant to indicate it is a double, but even without the D, the value will be stored as a double by default

showInputDialog() method

returns a String object that holds the combination of keystrokes a user types into the dialog box - used to display an input dialog if user enters a value meant to be used as a number (like an arithmetic statement) then the returned String must be converted to the correct numeric type - To convert a String to an int or double, you must use methods from the built-in Java classes Integer and Double requires 4 arguments that allows flexibility in controlling the appearance of the input dialog box the 4 arguments for showInputDialog() include: 1) The parent component (a.k.a the screen component, ex: a frame) in front of which the dialog box will appear. - If argument is null, the dialog box is centered on the screen. 2) The message the user will see before entering a value, a String 3) The title to be displayed in the title bar of the input dialog box. 4) A class field describing the type of dialog box; it can be one of the following: - ERROR_MESSAGE - INFORMATION_MESSAGE - PLAIN_MESSAGE - QUESTION_MESSAGE - WARNING_MESSAGE

Program statements (commands)

similar to English sentences; they carry out the tasks that programs perform orders to the computer, such as Output this word or Add these two numbers

Named Constants (symbolic constant)

similar to a variable in that it has a data type, a name, and a value If a named location's value should not change during the execution of a program, you can create it to be a named constant Don't try to use a variable or named constant that has not yet been assigned a value How it differs from a variable: 1) In its declaration statement, the data type of a named constant is preceded by the keyword final. 2) A named constant can be assigned a value only once and cannot be changed later in the program. Usually you initialize a named constant when you declare it; if you do not initialize the constant at declaration, it is known as a blank final, and you can assign a value later. Either way, you must assign a value to a constant before it is used. 3) Although it is not a requirement, named constants conventionally are given identifiers using all uppercase letters, using underscores as needed to separate words

block comments

start with a forward slash and an asterisk ( /* ) and end with an asterisk and a forward slash ( */ ) block comment can appear on a line by itself, on a line before executable code, or on a line after executable code can extend across as many lines as needed Every /* must have a corresponding */, even if it is several lines later

line comments

start with two forward slashes ( // ) and continue to the end of the current line line comment can appear on a line by itself or at the end (and to the right) of a line following executable code they do not require an ending symbol.

unreachable statements (dead code)

statements that cannot be executed because the logical path can never encounter them; these statements cause compiler errors

Pascal casing (upper camel casing)

style that joins words in which each word begins with an uppercase letter

Inheritance

the ability to create classes that share the attributes and methods of existing classes, but with more specific features - EX) 'Automobile' is a class, and all 'Automobile' objects share many traits and abilities. 'Convertible' is a class that inherits from the Automobile class; a Convertible is a type of Automobile that has and can do everything a "plain" Automobile does—but with an added ability to lower its top. (In turn, Automobile inherits from the Vehicle class.) Convertible is not an object—it is a class. A specific Convertible is an object—for example, my1967BlueMustangConvertible Inheritance an important feature of object-oriented program design that differentiates it from procedural program design

passing arguments

the act of sending arguments to a method

scope

the area in which a data item is visible to a program and in which can be referred to using its simple identifier A variable or constant is in scope from the point it is declared until the end of the block of code in which the declaration lies

Attributes

the characteristics that define an object; they are properties of the object properties

block of code

the code contained between a set of curly braces EX)) if you declare a variable or constant within a method, it can be used from its declaration until the end of the method... unless the method contains MULTIPLE sets of curly braces. Then, a data item is usable only until the end of the block that holds the declaration

A method's signature

the combination of the method name and the number, types, and order of arguments a method call must match the called method's signature

compile-time error

the compiler detects a violation of language syntax rules and is unable to translate the source code to machine code

Procedures (methods - java)

the individual operations used in a computer program are often grouped into logical units EX) a series of four or five comparisons and calculations that together determine a person's federal withholding tax value might be grouped as a procedure named calculateFederalWithholding() BOOK WILL show parenthesis () after every procedure name When a program calls a procedure calls a procedure, the current logic is temporarily suspended so that the procedure's commands can execute a single procedural program might contain any number of procedure calls some methods used in an application must return a message or value - within object-oriented programs, methods are often called upon to return a piece of information to the source of the request.

Machine Language (Machine Code)

the most basic set of instructions that a computer can execute All computer programs ultimately are converted to the lowest level language Each type of processor (the internal hardware that handles computer instructions) has its own set of machine language instructions machine language uses 1s and 0s (binary numbering system) to represent the on-and-off circuitry of computer systems

reference to the object

the name for a memory address where the object is held Every object name is also a reference—that is, a computer memory location - the class being referred to in the new operator statement is the reference type

interface

the only part of a method that the method's client sees or with which it interacts

associativity

the order in which values are used with operators The associativity of every operator is either right-to-left or left-to-right

a variable's scope

the part of a program in which a variable exists and can be accessed using its unqualified name.

Hardware

the physical parts of a computer Ex) computer equipment: keyboard, monitor, etc.

Software

the programs and other operating information used by a computer.

performing arithmetic with variables or constants of the same type

the result of the operation retains the same type (data type) EX) dividing two ints results in an int (data type) subtracting two doubles results in a double (data type) however, you might want to perform mathematical operations on operands with unlike types

method's value (a method's returned value)

the returned value of a method that's called to return a value

operator precedence

the rules for the order in which parts of a mathematical expression are evaluated The multiplication, division, and remainder operators have the same precedence - it is higher than the precedence of the addition and subtraction operators

unifying type

the type to which all operands in an expression are converted so that they are compatible with each other

data types byte, short, and long

these data types are all variations of the integer type byte and short types = occupy less memory and can only hold smaller values long type = occupies more memory and can hold larger values Don't attempt to assign a constant value less than -2,147,483,648 or greater than +2,147,483,647 to a long variable without following the constant with an uppercase or lowercase L. By default, constant integers are ints, and a value less than -2,147,483,648 or greater than 2,147,483,647 is too large to be an int.

Legal declaration statements

those that compare 2 values directly EX) boolean isSixBigger = (6 > 5); // Value stored would be true boolean isSevenSmallerOrEqual = (7 <= 4); // Value stored would be false

Compiler/Interpreter

translates a high-level language into machine language and tells you if you have used a programming language incorrectly

forward slash ( / ) and the backslash ( \ ) characters

two distinct characters, cannot use them interchangeably

garbage value

unknown value stored in an uninitialized variable Java protects you from inadvertently using the garbage value that is stored in an uninitialized variable. EX) if you attempt to display garbage or use it as part of a calculation, you receive an error message stating that the variable might not have been initialized, and the program will not compile

Compiling a java class

use ctrl + 1 goal is for output to receive no messages, which means that the application compiled successfully compiler finds all errors and syntax errors

extended

used as a basis for any other class --> Each new class can become an extension of the original, inheriting its data and methods public classes can be extended

Confirm Dialog Boxes

used for presenting simple options to a user to confirm a choice - instead of typing input on keyboard A confirm dialog box that displays the options Yes, No, and Cancel can be created using the showConfirmDialog() method in the JOptionPane class Confirm dialog boxes provide more practical uses when applications can make decisions based on the users' responses

print() or println() statement

used to create console output the println() statement starts a new line after output (the only diff b/w the 2 statements) can display a variable or a constant in a print() or println() statement alone or in combination with a string --> combination of strings = concatenating strings print() and println() method calls are used to display different data types, including simple Strings, an int, and a concatenated String EX)) *in line containing "System.out.print(billingDate);" -- billingDate is used alone *in line containing "System.out.println("Next bill: October " + billingDate);" --> billingDate is concatenated with a string public class NumbersPrintln { public static void main(String[] args) { int billingDate = 5; System.out.print("Bills are sent on day "); System.out.print(billingDate); System.out.println(" of the month") System.out.println("Next bill: October " + billingDate); } }

char data type

used to hold any single character place constant character values within single quotation marks because the computer stores characters and integers differently. EX)) the following are typical character declarations: char middleInitial = 'M'; char gradeInChemistry = 'A'; char aStar = '*'; A character can be any letter—uppercase or lowercase- or can be a punctuation mark or digit A character that is a digit is represented in computer memory differently from a numeric value represented by the same digit. EX) the following two statements are legal: displaying each of these values using println() statement results in --> 9 BUT ONLY the numeric value, 'aNumValue,' below can be used to represent the value 9 in arithmetic statements char aCharValue = '9'; int aNumValue = 9;

cast operator (unary cast operator)

used to perform a type cast, using cast operator is an explicit conversion created by placing the desired result type in parentheses. Using a cast operator is an explicit conversion In a Java arithmetic cast, a value is "molded" into a different type The cast operator is followed by the variable or constant to be cast (when type casting operation performed) Unlike a binary operator that requires two operands, a unary operator uses only one operand unary cast operator is followed by its - one - operand cast operators do not permanently alter any variable's data type --> the alteration is only for the duration of the current operation

5 standard arithmetic operators

used to perform calculations with values in programs + Addition 45 + 2, the result is 47 - Subtraction 45 - 2, the result is 43 * Multiplication 45 * 2, the result is 90 / Division(floating-point division) 45.0 / 2, the result is 22.5 / Division(integer division) 45 / 2, the result is 22 (not 22.5) % Remainder (modulus) 45 % 2, the result is 1 (that is, 45/2 = 22 with a remainder of 1)

dots(periods)

used to separate the names of the components in the statement

variables of data types byte, short, int, and long

used to store (or hold) integers

import statement

used when you want to access a built-in Java class that is contained in a group of classes called a package To use the JOptionPane class, you must import the package named javax. swing.JOptionPane Any import statement used must be placed outside of any class you write in a file Import statement not needed/required when using the System class (as with the System.out.println() method) because the System class is contained in the package java.lang, which is automatically imported in every Java program

Java keywords (also: true, false, and null) are blue, and all other program elements are black

written in blue in textpad --> all other program elements are black colored

can create a confirm dialog box with 5 arguments

• The parent component (which can be null) • The prompt message • The title to be displayed in the title bar • An integer that indicates which option button will be shown; it should be one of the constants YES_NO_CANCEL_OPTION or YES_NO_OPTION • An integer that describes the kind of dialog box; it should be one of the constants ERROR_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE, or WARNING_MESSAGE

major advantages of including a method call (creating a separate method w/ intended purpose for program)

• main() method remains short and easy to follow EX) calling a method to execute 3 statements of addresses needed with 'displayAddress();' method rather than including three separate println() statements • A method is easily reusable, once method is written it can be used many times EX) after creating the displayAddress() method (example from above), it can be used in any application that needs the company's name and address.


Related study sets

AP Euro- Chapter 15 Absolutism, Constitutionalism AP Exam Review Quiz

View Set

Chapter 25 & 18 of Bushong/ASRT Article (Fluoroscopy & photometric quantities)

View Set

IS232 Pre Exam 2-Chapter 4-6 part 1

View Set

bar and pie charts intro to stats

View Set

Nutrition Consultant Exam Chp. 12-13

View Set

REPHRASING: DESPITE/IN SPITE OF - ALTHOUGH

View Set