Java Flashcards
Assignment operator:
The = (the equals sign). Assigns a value to an identifier.
Binary operator:
An operator that has two operands.
Cast operator:
Used for explicit type conversion
Computer program:
A sequence of statements whose objective is to accomplish a task.
Data type:
A set of values together with a set of operations.
Identifier:
A Java identifier consists of letters, digits, the underscore character ( _), and the dollar sign ($), and must begin with a letter, underscore, or the dollar sign.
Implicit type coercion:
When a value of one data type is automatically changed to another data type.
Mixed expression:
An expression that has operands of different data types.
Named constant:
A memory location whose content is not allowed to change during program execution.
Operator precedence rules:
Determine the order in which operations are performed to evaluate an expression.
Programming:
A process of planning and creating a program.
Programming language:
A set of rules, symbols, and special words.
Semantic rules:
determine the meaning of instructions in a programming language.
Source code:
The combination of the import statements and the program statements
Source file:
A file containing the source code, having the file extension .java.
Syntax rules:
determine the validity of instructions in a programming language.
Token:
The smallest individual unit of a program written in any programming language.
Unary operator:
An operator that has only one operand.
Variable:
A memory location whose content may change during program execution.
console.nextDouble():
retrieves that floating-point number, if the value of this expression is that floating-point number.
Arithmetic expressions
a sequence of operands and operators that computes a value
Comments
explanatory sentences inserted in a program in such a manner that the compiler ignores them
Coordinate system
a grid that allows a programmer to specify positions of points in a plane or of pixels on a computer screen
Exception
an abnormal state or error that occurs during runtime and is signaled by the operating system
Graphics context
in java, an object associated with a component where the images for that component are drawn
Logic error
an error such that a program runs, but unexpected results are produced. Also referred to as a design error
Origin
the point (0,0) in a coordinate system
Package
a group of related classes in a named directory
Pseudocode
A stylized half-English, half-code language written in English but suggestion Java code
Reserved words
Words that have predefined meanings that cannot be changed
Run-time error
An error that occurs when a program asks the computer to do something that it considers illegal, such as dividing by 0
Screen coordinate system
A coordinate system used by most programming languages in which the origin is in the upper-left corner of the screen, window, or panel, and the y values increase toward the bottom of the drawing area
Semantics
Rules for interpreting the meaning of statements
Syntax
Rules for combining words into sentences
Virus
a program that can enter a computer and perhaps destroy information
Java vocabulary
Set of all words and symbols in the language
Primitive data types
numbers, characters, and Booleans. combined in expression with operators
Objects
sent messages
Name the 6 numeric data types
int, double, short, long, byte, and float
Literals
items whose values do not change, like the number 5.0 or the string "Java"
What does /* suggest
a comment
Variable declaration statement
declares the identifier and data type for a variable
Constants
variables whose values cannot change
Arithemetic overflow
assigning a value to a variable that is outside of the ranges of values that the data type can represent
Mixed-mode arithmetic
expressions imvolving integers and floating-point values
Type casting
allows one data type to be explicitly converted to another
String concatenation
append a string or value to another string
Escape character (\)
used in codes to represent characters that cannot be directly typed into a program
How do you print something in the output?
System.out.print("Something to print"); or System.out.println("Something to print with a line (LiNe)");
Why is there a semicolon (;) at the end of each statement?
So Java knows that it is the end of a statement.
What are variables?
Things that store information.
How do you create variables?
(A kind of variable) (name of the variable) = (value of variable);For example, String var = "Hello, World";
How do you make a comment?
//Comment/*Multi-LineComment*//**JavaDoc Comment*Describes Program or *Method**/
What is a main method for?
For letting your program run.
How do you make a main method?
public static main(String[] args) { //Your program goes here!}
How do you start a program?
class (name of program) { //Your program goes here!!}
How do you make a Hello World program?
class helloWorld { public static main (String[] args) { String hw = "Hello, World!"; System.out.println(hw); }}
What's a method?
A mini-program that is referred to by the program and others.
How do you create a method?
public void (method name)((arguments)) { }For example,public void greetYou(String greeting) { //Your program here!}
How do you make if...else statements?
if (arg) {}else {}if (arg) {}if (arg) {}else if (arg) {}else {}For exampleif (e < 10) {//What happens if e < 10}else {//What happens otherwise}Switch statements are better for if...else if...else.
How do you make a Switch statement?
switch (var) {case 1://if var = 1//What happensbreak;case 2://if var = 2//What happensbreak;default://Otherwise//What happensbreak;}
How do you make loops?
for (int i; i < 10; i++) {//Program}
What is a primitive type in Java?
In java, we have primitive types & objects.Primitive types hold the actual value in memory.Object hold references in memory.
Describe 2 classes can have.
1. Is a - inheritance 2. Has a - composition / aggregationV47
Name 9 primitive types
BSILF DB CSbyteshortintlongfloatdoublebooleancharString
Name 3 reasons why favor composition over inheritance
1. Almost all inheritance can be rewritten2. Less about modeling the real world and more about modeling interactions in a system and roles and responsibilities3. Inheritance is difficult to maintainV52
What is this "x+=3" the equivalent of?
x = x + 3;
What are 6 assignment operators?
=+=-=*=/=%=-----------------v20
Name to things about strings in Java.
1. Treated like a primitive type (can be assigned w/o the New keyword) but it's an object2. They're immutable (can't be changed). If you give a string a different value, it create an new string in memory. Java Fundamentals - v22
Given: String firstName = "reynald";Writhe the line of code to out the index of letter 'a'
System.out.println(firstName.indexOf('e'));v23
1. Create an Array called 'number' w/ 3 slots2. Write out the 2nd number
int[] numbers = new int[3];
What does the 'new' key word do here when creating an instance?Printer myPrinter = new Printer();
Calls the default constructor on the Printer class.
Create an array called 'colors' and add to it :"red","blue", "Green" 2. 1. Create a foreach loop the writes out the contents of the arra
1. String[] colors = new String[] {"red","blue", "Green"};2. for (String c : colors){ System.out.println(c); }v42
1. Define a variable that = to ten.2. Create a while loop that prints you name tens time.
int ten = 10; while(copies > ten) { System.out.println("Reynald"); copies --; }
Given this method below, implements 'continue' or 'break' statement if color is 'green' public void printColors() { String[] colors = new String[] {"red","blue", "green","yellow"}; for (String c : colors) { System.out.println(c); } }
public void printColors() { String[] colors = new String[] {"red","blue", "green","yellow"}; for (String c : colors) { if("green".equals(c)) continue; System.out.println(c); } }
In OOP, describe is-a or has-relationships?
Classes in OOP, are related to each other & they're going to be related through an "IS-A" relationship or "HAS-A" relationship.> IS-A relationship result from inheritance> HAS-A relationship result from compositionThis comes from the need to reuse code.v47
Create an example of composition. Create a car class that HAS a gas tank. After the car runs 200miles, make it request to add gas.
TODOinspired by v49 (paper tray example)
Create an example of changing inheritance to composition by using interfaces. See exampled in v54.
TODO
What are bounded types in Java?
Allows you to restrict the types that can be used in generics based on a class or interface.v60
What is erasure?
TODOv62
Create an IllegalAurgumentException (with some error message) in a method & on the calling method, add a try / catch block to display your error.
TODO - video on Excepions -->Try / Catch
What's the purpose of the Finally Block
It's useful to force code to execute whether or not an exception is thrown. It's useful for IO operations to close files.
What are checked & unchecked exceptions.
1) Checked Exception is required to be handled by compile time while Unchecked Exception doesn't.2) Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.
What's the equivalent of a dictionary in Java? Please create an example.
Map - Look in module about collections.
What's a list in Java?
A grouping that is ordered, sequential & can have duplicates.
What is a 'set' in Java?
A grouping like a LIST but all the items are unique. There are no duplicates.
What is a 'Queue' in Java?
TODO: Create a queue
Access Control
Public or Private; Determines how other objects made from other classes can use the variable, or if at all.
Applet
A program that runs on a web page.
appletviewer
A tool included in the JDK that's supported in NetBeans, which will test applets.
Application
A program that runs locally, on your own computer.
Argument
Extra information sent to a program.
Argument Storage
An Array.
Array
A group of related variables that share the same type and are being arranged.
Attribute
The information that describe the object and show how it is different than other objects.
Attributes and Behaviors
An object contains these two things.
Autoboxing
Casts a simple variable value to the corresponding class.
Behavior
What an object does.
Boolean Values
Type of variable that cannot be used in any Casting.
Casting
Converting information from one form to another.
char
Any character.Surrounded by single quotation marks.
Class
A master copy of the object that determines the attributes and behavior an object should have.
Class Statement
The way you give your computer program a name.
Comma
Used to separate things within a section.
Concatenating
Joining one string to another string. Also known as pasting.
Constants
Variables that do not change in value; typed in all-caps.
Destination
The converted version of the source in a new form.
Differences in String
S is Capitalized. Type of Object.
Do While Execution
This loop will always execute at least once, even if the conditions are not met.
Do While Loop
Tests the condition at the end of each repetition of a section of a program.
Double "
Quotation type used for string values.
Element
An item in an Array.
Engaging in OOP
Breaking down computer programs in the same way a pie chart is broken down.
For Loop
Repeats a section of a program a fixed amount of times.
Inheritance
Enables one object to inherit behavior and attributes from another object.
Iteration
A single trip through a loop.
Iterator
The counter variable used to control a loop.
Loop
This causes a computer program to return to the same place more than once.
main()
Block statement statement in which all of the program's work gets done.
Method
A group of Attributes and Behaviors.
Method
A way to accomplish a task in a Java program.
Methods
Part of an Object's behavior.
Multi-thread
A way for the computer to do more than one thing at the same time.
Object
A way of organizing a program so that it has everything it needs to accomplish a task.
Objects
Programs that you create. These can be thought of as physical items that exist in the real world.
OOP Program
A group of objects that work together to get something done.
Platform Independent
A program that does not have to be written for a specific operating system.
Programs
A class that can be used as a template for the creation of new objects.
Public int
Makes it possible to modify the variable from another program that is using the object.
Reason Brackets are missing
Not required for single statement IF statements or Loops.
Semicolon
Used to separate sections.
Single '
Quotation type used for character values.
Source
Information in it's original form.
Statement
An instruction you give a computer.
String
A collection of characters.Surrounded by double quotation marks.
String
A line of text that can include letters, numbers, punctuation, and other characters.
Subclass
A class that inherits from another class.
Superclass
A class that is inherited from.
Ternary Operator
Used to assign a value or display a value based on a condition.
Thread
Each part of a program which takes care of a different task.
Three types of Loops
For, While, and Do-While.
Unboxing
Casts an object to the corresponding simple value.
Variable
A storage place that can hold information, which may change.
While Loop
Tests the condition at the beginning of each repetition of a section of a program.
Expressions
Statements that involve a mathematical equation and produce a result.
println
Starts a new line after displaying the text.
Object reference
a value that denotes the location of the object in memory
toUpperCase
Method which converts any String to uppercase equivalent by creating a new String object
Assignment operator
an operator (=) that changes the value of the variable to the left of the operator
length() method
method which counts the number of characters in a String
*
operator for multiplication
API documentation
lists the classes and methods of the Java library
New operator
An operator that constructs new objects
int
a primitive data type, integer
JFrame
used to show a frame(window)
Accessor
Extracts information from an object without changing it. Usually prefixed with 'get'.
The RGB values of Color.RED
255, 0, 0
Package
Java classes grouped together in order to be imported by other programs
Variables
Used to store values that can be used repeatedly in a class
Mutator
Method that alters the attributes of an object.
Applet
Graphical Java program that runs in a web browser or viewer. To run one must have an HTML file with an applet tag.
Objects
belong to classes
overloaded
a class having more than one method with the same name
Object references
stored in Object variables and denotes the memory location of an Object
-
operator for subtraction
trim() method
method which removes leading and trailing spaces from a String
Public Interface
specifies what you can do with its objects
Identifier
name of a variable, method or class
Identifiers may contain ...
letters, digits and the underscore character
primitive
data such as numbers and characters, NOT objects
Method
a sequence of instructions that accesses the data of an object
Declare a variable
int n;
Initialize a variable
n = 5;
Declare & Initialize a variable
int n = 5;
import java.util.Scanner;
Import the ability to use a scanner from database
public class{
Opens and names your program
public static void main(String[] args){
Line 2 of program, opens programming block
Scanner input = new Scanner(System.in);
Adds scanner to program
System.out.print(" ");
Prints a string of text
Double var = input.nextDouble();
Establishes value inputed into scanner as a variable
long totalMilliseconds = System.currentTimeMillis();
Sets total number of milliseconds since midnight, January 1, 1970, as a variable
Method call
object.methodName(parameters);
Variable definition
typeName variableName = value;
Assignment
variableName = value;
Object Construction
ClassName objectName = new ClassName(parameters);
Importing a Class from a Package
import packageName.ClassName;
Method Definition
accessSpecifier returnType methodName(parameterType parameterName, . . .){ method body}
Constructor Definition
accessSpecifier ClassName(parameterType paramterName, ...){constuctor body}
Class Definition
accessSpecifier class ClassName{constructorsmethodsfields}
Instance Field Declaration
accessSpecifier class ClassName{accessSpecifer fieldType fieldName;}
The return Statement
return expression;
Cast
(typeName) expression
Constant definition
final typeName variableName = expression;
Static method call
ClassName.methodName(parameters);
The if Statement
if (condition) statement;else statement;
Block statement
{statement;statement;}
The while Statement
while (condition) statement;
The for Statement
for (initialization; condition; update) statement;
Array Construction
new tymeName[length];
Array Element Access
arrayReference[index]
The "for each" loop
for (Type variable: collection) statement;
ArrayList<String>: Instantiation
ArrayList <String> myArr = new ArrayList<String>();
ArrayList: add "hi"
myArr.add("hi");
ArrayList: add "hi" to ArrayList at index i
myArr.add(i,"hi");
ArrayList: grab item at index i
myArr.get(i);
ArrayList: delete item at index i
myArr.remove(i);
ArrayList: get size
myArr.size();
ArrayList: get first index of item
myArr.indexOf(item);
ArrayList: get last index of item
myArr.lastIndexOf(item);
ArrayList: check if list contains item
myArr.contains(item);
ArrayList: replace item at index i with new item
myArr.set(i, newItem);
What is a Vector?
Similar to ArrayList, but synchronized
LinkedList<String>: Instantiation
LinkedList<String> myList = new LinkedList<String>();
LinkedList: add item to beginning of list
-addFirst(item);
LinkedList: peek methods
list.peek(); //peeks headlist.peekLast(); // peeks last element
LinkedList: remove methods
same as arraylist remove methods, but also:remove(); // removes first item from listremoveLast(); //removes last item from list
LinkedList: iterate through list of strings and print each one
Iterator<String> iter = list.iterator();while(iter.hasNext()){ System.out.println(iter.next());}don't forget: iterators have a remove() function!
HashMap<String, String>: Instantiation
HashMap<String, String> myMap = new HashMap<String,String>();
HashMap: insert a key string and a value string
myMap.put("key","value");
HashMap: get value string from key string
myMap.get("key");
HashMap: see if map contains a key
myMap.contains("key");
HashMap: get a Set of the keys
myMap.keySet();
HashMap: get a Collection of the values
myMap.values();
HashMap<String,String>: iterate and print keys/values
for (String key : loans.keySet()) {System.out.println("key: " + key + " value: " + loans.get(key));}
Array: convert from Collection strs to Array
String[] arr = new String[strs.size()];strs.toArray(arr);
string Array: Instantiation
String[] myArr = new String[numberOfItems];String[] myArr = {"a","b","c"};
String: concatenate two strings
str1.concat(str2);str1 + str2;
String: get char at index i
str.charAt(i);
String: compare two strings
str1.equals(str2)
String: get first index of substring
str.indexOf(char); // returns -1 if doesn't exist
String: get last index of substring
str.lastIndexOf(char); // returns -1 if doesn't exist
String: remove whitespace
str.trim();
String: get substring "He" from "Hello"
str.subString(0,2); // begin index is inclusive, end index is exclusive
Enum: Instantiate Enum for days of the week
public enum Day{ Monday(0),Tuesday(1), Wednesday(2), Thursday(3),Friday(4),Saturday(5),Sunday(6); private int value; private Day(int v){value = v;} public int getValue(){return this.value;}}//values() returns array of all constants defined in enum// valueOf() returns Enum with name matching to String passed to valueOf// Day.name() returns string name of enum
&&
"And" operator
||
"Or" operator
!=
Boolean not equal to
~
Bitwise Not operator
&
Bitwise And operator
|
Bitwise Or operator
//
comment
()
used to surround perimeters
{}
Defines a block of code
[]
Declares arrays
;
End of a statement
.
separates package names / adds folders
byte
8 bit integer
short
16 bit integer
int
32 bit integer
long
64 bit integer
float
32 bit real number
double
64 bit real number
char
A single character
boolean
true or false
+
add operator
+=
Add and assign operator
-
Subtraction operator
-=
subtract and assign operator
*
Multiplication operator
*=
Multiply and assign operator
/
Division operator
/=
divide and assign operator
%
Take remainder operator
%=
Take remainder and assign operator
++
Increment by one
--
Decrement by one
>
Greater than
>=
Greater than or equal to
<
Less than
<=
Less than or equal to
!
Boolean not
==
Boolean equals
=
Assignment
public static void main(String args[])
Main Method
for(i=10; i > 5; i++){System.out.println(i);}
Write an endless for loop where i=10
int i = 10;while(i > 5){ i = i + 5; System.out.print(i);}
Write an endless while loop where i=10
int i = 10;do{ i = i + 5; System.out.print(i);}while (i > 5);
Write an endless do loop where i=10
if(i=10){//do stuff}
Write an if then statement where i=10
if (i=10) { //do something } else { //do something else }
Write an if then else statement where i=10
i
What is the standard convention for un-named variables?
Abstract is assigned when you want to prevent an instance of a class from being created.
Define the keyword "abstract"
Used to catch exceptions and tell the application to do something else.
Define the keyword "catch"
used to create a subclass for an existing class.
Define the keyword "extends"
used to implement an interface.
Define the keyword "implements"
Null means nothing. It's a place holder.
Define "Null"
Able to be modified by the class, package, subclass, and world.
Define the keyword "public"
Only able to be modified inside the class.
Define the keyword "private"
Able to be modified by the class, package, and subclass. But not the world.
Define the keyword "protected"
Does not change. Cannot make an instance of.
Define the keyword "static"
Method that does not return.
Define the keyword "void"
Method that returns.
Define the keyword "return"
System.out.println
prints statement and creates new line
System.out.print
prints statement
import java.util.Scanner
imports Scanner library
Scanner in = new Scanner(System.in);
declares Scanner "in"
int i = in.nextInt();
declares and inputs integer value
double d = in.nextDouble();
declares and inputs a real value (floating point #)
String s = in.nextLine();
declares and inputs a line (a string of characters)
char answer = 'y'
variable answer = y (*single quotes!)
string Var = "Hello"
variable Var = Hello (*double quotes!)
//comment
short comments
/* */
long comments
final int VOLUME = 8
names constant integer
++/--
increment/decrement; add 1 to/subtract 1 from the variable
Math.sqrt(x)
square root of x
Math.pow(x,y)
x^y (x>0, or x=0 and y>0, or x<0 and y is an integer)
Math.sin(x)
sine of x (x in radians)
Math.cos(x)
cosine of x
Math.tan(x)
tangent of x
Math.toRadians(x)
convert x degrees to radians (ie, returns x* p/180)
Math.toDegrees(x)
convert x radians to degrees (ie, returns x*180/p)
Math.exp(x)
e^x
str.length()
returns the number of characters in the given string (int)
str.charAt(pos)
returns the character (char) at position pos (int) in the given string
str.substring(start, end)
returns the string starting at position (start) and ending at position (end-1) in the given string
str.indexOf(text)
returns the position (int) of the first occurrence of string (text) in string str (output -1 if not found)
str.equals("test")
(boolean) returns true if the string "test" matches string str, false otherwise
double blah = (int) (blah + 3)
typecast; change variable type
\
char that comes after is exempted from compiler (ie printing "")
==,!=,>,<,>=,<=
relational operators; equal, not equal, greater than, less than, greater than/equal to, less than/equal to
&&, ||, !
boolean operators; and, or, not
if (condition){ statements1}else{ statements2}
if statement (else not required in all cases)
if (string1.equals(string2))...
compares equality of 2 strings
string1.compareTo (string2) < 0
The compareTo method compares strings in lexicographic order.
Character.isDigit(ch)
statement (boolean), ch (char); allows you to check if ch is a digit or not
Character.isLetter(ch);Character.isUpperCase(ch);Character.isLowerCase(ch);Character.isWhiteSpace(ch);
statement (boolean), ch (char); allows you to check if ch is a letter/uppercase/lowercase/whitespace
while (condition) { statements }
statements = body of while loop; braces not needed for a single statement
in.hasNextDouble()
checks for numerical input; false if the next input is not a floating-point number
java SentinelDemo < numbers.txt
redirects input
for (initialization; condition; update){ statements}
terminating loop
System.out.Printf("%3d", i*j)
% /number of spaces taken up/ Integer, variable
return volume;
return statement that returns the result of a method and terminates the method call
public static double cubeVolume (double sideLength)
header for method
/** Computes the volume of a cube. @param sideLength the side length of the cube @return the volume*/
structure for commenting before methods (javadoc)
public static void boxString(String contents)
void methods return no value, but can produce output
do { i++; //more code}while (i<max)
do/while loop
char newChar = (char)(mychr + x)
shift character by x numbers (use ASCII table values)
double[] values = new double[10];double[] moreValues = {32, 54, 67.5};
array declaration and initialization
values[i] = 0;
access element of array at position i (count starts from 0)
array.length
gives the length of the array (no parentheses!)
for (typeName variable: array/collection){ sum = sum + variable;}
enhanced for loop for arrays; adds each element of array to sum (declared before loop)
Arrays.toString(values) = [4,7,9...]
elements separated by commas with brackets
Arrays.copyOf(values, n)
The call Arrays.copyOf(values, n) allocates an array of length n, copies the frst n elements of values (or the entire values array if n > values.length) into it, and returns the new array.
ArrayList<String> friends = new ArrayList<String>();
ArrayList<typeParameter> variableName = new ArrayList<typeParameter>(); typeParameter cannot be a primitive type
friends.add (i, "Cindy");String name = friends.get(i);friends.set(i, "Harry");friends.remove(0);
adds element to arrayList at pos i (w/out i will add element to end);obtains element at i;redefines element at i as "Harry";removes element
Scanner in = new Scanner(new File("input.txt");
reads input from a file (also declared in same line)
PrintWriter out = new PrintWriter("output.txt");
writes output to a file "output.txt"
throws FileNotFoundException
terminates main if FileNotFoundException occurs
in.useDelimiter("[^A-Za-z]+");
restricts input to only letters, removes punctuation and numbers
String input = in.next();
next() reads the next string; returns any charas that are not white space
countryName = countryName.trim();
The trim method returns the string with all white space at the beginning and end removed.
Integer.parseInt or Double.parseDouble
obtains the integer value of a string containing the digits
- Left alignment0 show leading zeroes+ show a plus sign for positive numbers( enclose negative numbers in parentheses, show decimal separators^ convert letters to uppercase
Format flags (printf)
d decimal integerf fixed floating-pointe exponential floating-point (very large or very small values)g general floating-points string
Format types (printf)
;
Like a period in English. Marks the end of a statement or command
{ }
(Curly braces). Marks the beginning and end of a unit, including a class or method description.
b()
A method called b
a.b()
Execute a method b which belongs to object a
void
Means that the method does something but does not return any value at the end
Object
An instance of a class.
Attribute
A value an object stores internally.
Method
A group of programming statements given a name.
Class
The data type of an object
Encapsulation
When each object protects its own information.
Inheritance
How one class can be created from another.
Polymorphism
The idea that we can refer to objects of different but related types in the same way.
String Literal
Anything within double quotation marks.
Concatenation
Adding one string to another.
Escape Sequence
A sequence used to represent special characters.
Variable
A location in memory used to hold a data value.
Assignment Statement
A statement assigning a value to a variable.
Constants
Identifiers that always have the same value.
Primitive Data Types
Eight commonly used data types.
int
A data type that represents whole numbers.
double
A data type that represents decimals.
boolean
A data type that represents a true or false value.
Boolean Literal
The words true and false.
Operator Precedence
The rules that govern the order in which operations are done.
Conversion
Changing one type of primitive data to another.
Instantiation
Creating an object.
Void
When a method does not return a value.
type[] [] name
Declare a 2D array
int [] [] matrixPixel [] [] pixels
Examples of 2D array declarations
new type [nRows] [nCols]
Create a 2D array
new int [5] [8]new Pixel [numRows] [numCols]
Examples of creation of 2D arrays
name [row] [col]
Access an element
int value = matrix [3] [2];Pixel pixel = pixels[r] [c];
Example: Accessing two elements
name [row] [col] = value
Set the value of an element
matrix[3] [2] = 8;pixels[r] [c] = aPixel;
Example of setting the value of elements
name.length
Get the number of rows
matrix.lengthpixels.length
Example of getting the number of rows
name[0].length
Get the number of columns
matrix[0].lengthpixels[0].length
Example: get the number of columns
In Java, every program statement ends with what?
; (a semicolon)
What System.out method moves the cursor to the next line?
System.out.println()
How could you define a String variable named wrd and initialize it to the word cats?
String wrd = "cats";
How could you define a real number named numero and initialize it to 867.5?
double numero = 867.5
What must every method and class have an open and closed of?
{ } (braces, or curly brackets)
A ________ is used to terminate all java
a semi colon ;
Work with Java Arrays
Chapter 6 Objective 1
Are there standard Java arrays built into the Java language?
Yeah, hell Yeah lol there standard Java arrays are built into the Java language.
What can standard Java arrays store?
Standard Java arrays can store both objects and primitives.
How many dimensions can standard Java arrays have?
Standard Java arrays can have one or many dimensions.
What are standard Java arrays and when must they be initialized?
Standard Java arrays are objects and must be initialized after they are declared.
....
Standard Java arrays can be declared with square brackets after the type or variable name. Example: int[] myArray or int my Array[]
...
Standard Java arrays can be initialized with the new operator and their size in square brackets after the type. Example: int[ ] myArray = new int[4]
...
Standard Java arrays can be initialized by placing the values that will populate the array in curly brackets. Example: int[ ] myArray = {1,2,3,4}
Can standard Java arrays be multi-dimensional?
Yes, standard Java arrays can be multi-dimensional; each set of square brackets represents a dimension.
.....How would a three dimensional array be declared as? (How would it look like?)
A three dimensional array would be declared as int[ ][ ][ ] threeDArray.
...
Multi-dimensional arrays can declared with the new operator by placing the size of each dimension in square brackets. Example: int[ ][ ][ ] threeDArray = new int[3][2][2]
...
Multi-dimensional arrays can be initialized by placing the values that will populate the array in curly brackets. Each dimension is represented by a nested set of curly brackets. Example: int[ ][ ][ ] threeDArray = {{{1,2}, {3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}
...
Multi-dimensional arrays do not have to have the same size sub arrays. Example: int[ ][ ] oddSizes = {{1,2,3,4},{3 },{6,7}}
...
Multi-dimensional arrays do not have to declare the size of every dimension when initialized. Example: int[ ][ ][ ] array5 = new int[3][ ][ ]
What is the ArrayList class a representation of?
The ArrayList class is an object-orientated representation of a standard Java array.
What package is the ArrayList part of?
" java.util package "The ArrayList class is part of the java.util package.
If the ArrayList object capacity is exceeded what will it automatically do?
"It will automaticallly resize"An ArrayList object will automatically resize if its capacity is exceeded.
...
An ArrayList object can have its internal capacity adjusted manually to improve efficiency.
What will automatically happen if you add elements at any index in the ArrayList object?
"It will automatically move the other elements"[Orginal below]An ArrayList object can have elements added at any index in the array and will automatically move the other elements.
...
An ArrayList object can have any element in it removed and will automatically move the other elements.
What is the perferred method of storing datat in an array?
In most cases, the ArrayList is the preferred method of storing data in an array.
Capital Letter
All java file names must have this at the beginning.
.java
All Java file names have to have this extension.
How to define a class?
public class "class name" (no extension)
Standard Starting, to start code block?
public static void main(String[] args) {//code goes here}
Command to print to the console? (what letter is capitalized)
System.out.println("Hello");
Set of print commands to print to the console on two different lines?
System.out.print("Hello"); //no "ln"System.out.print("World"); //Has the "ln"
Surround all String text with?
Double Quotes
4 Java Data Types?
Numeric, String, Character, Boolean.
Numeric Data Sub-Types
int, long, float, double
Reasons to use "int"
Numbers -2 billion to, 2 billion
Reasons to use "long"
Numbers greater then ±2 billion
Reasons to use "float"
127 digits after the decimal point
Reasons to use "double"
1023 digits after the decimal point
0 or more characters surrounded by double quotes?
String (always capital "S")
True False data type
boolean
What must variable names have/not have?
Have: Starts with a lower case letter.Not Have: after initial letter cannot have a symbol other than the underscore (no spaces).
What must a class name always start with?
A capital letter then camel case with no spaces.
Example of variable declaration and explanation.
String firstName; Start with data type then variable name. Must end with the ";".
How to declare variables with the same data type on the same line?
Separate them with commas. ex. int number, salary, hoursWorked; (end with semi-colon)
What is camel casing?
Each time a new word begins start it with a capital letter
How do you assign data to a variable?
"=". ex. int number = 100
Insert a comment? On multiple lines?
double slash ex. //commentedslash asterisk ex. /* one linetwo lines */ (its the back slash for both)
Define how java classes are connected.
Loosely connected objects that interact with each other.
Define the Java related "object" and what is it interchangeable with?
Object and class define state (data_ and behavior (operations). Classes define an object's behavior.
What could a object be compared to for similarity?
like base blocks that are interchangeable in how they can be used in other programs.
Private variable declaration?
Only applies to that class. ex. private String first;
Methods?
Are always public. They return data. Methods are made so that you can call on them so that you can use its functionality.
Naming Methods?
Begins with public then is whatever data is going to be returned. ex. public String displayname()
What does empty Parenthesis at the end of a method declaration mean?
That the data for the method will be put in later.
return function?
Returns and expression. ex. return first + " " + middle + " " + last;
vocabulary
the set of all of the words and symbols in a given language
syntax
the rules for combining words into sentences
statements
lines of code in java
semantics
define the rules for interpreting the meaning of statements
programming vs natural languages
size, rigidity, literalness
primitive data types
first category of Java variables such as numbers, characters, and Booleans
objects
second category of Java variables such as scanners and strings
concatenation operator
allows strings to be combined in Java
numeric data types
another name for primitive data types; most commonly int and double
int
4 bytes, stores integer values
double
8 bytes, stores floating-point numbers
short
2 bytes, stores integer values
long
4 bytes, stores long integer values
byte
1 byte, stores an integer
float
4 bytes, stores less precise floating-point numbers
literals
items in programs whose values do not change; restricted to the primitive data types and strings
variable declaration statement
when a program declares the type of a variable
arithmetic expression
consists of operands and operators combined in a manner familiar from algebra
grouping operator
( ), highest precedence
method selector operator
., second highest precedence, left to right association
unary plus operator
+, third highest precedence
unary minus operator
-, third highest precedence
instantiation operator
new, third highest precedence, right to left association
cast operator
(double),(int), third highest precedence, right to left association
multiplication operator
*, fourth highest precedence, left to right association
division operator
/, fourth highest precedence, left to right association
remainder or modulus operator
%, fourth highest precedence, left to right association
addition operator
+, fifth highest precedence, left to right association
subtraction operator
-, fifth highest precedence, left to right association
assignment operator
=, lowest precedence, right to left association
escape character
used when including 'special characters' in string literals
\t
indicates a tab character
\n
indicates a newline character
\\
escape character for backslash
keywords
words in java that cannot be used as user-defined symbols
import x.y.z
x - overall name of package, y - name of package subsection, z - name of particular class in subsection
syntax errors
when a syntax rule is violated
run-time errors
when a computer is asked to do something that is considered illegal
logic errors
when the computer is unable to express an answer accruately
Objects have both _______ and _______.
Instance Variables && Methods
All objects in a class have the same _______ and same types of _______.
Methods && Instance Variables
The two main kinds of methods:
methods that return a value / void methods
Private instance variables can be accessed from outside their class through ______ methods and changed with _________ methods
Accessor methods && Mutator methods
A local variable disappears when...
a method invocation ends.
T or F: The name of a local variable can be reused outside of the method in which it is declared ?
True
A parameter is a local variable initialized to....
the value of the corresponding argument. (Known as Call-by-value)
*** If a variable is used as an argument...
ONLY the value of the the argument is plugged into the parameter, NOT the variable itself
Encapsulation?
Data and actions combined into a class whose implementation details are hidden
Overloading the method?
Creating multiple definitions for the same method name, using different parameter types
Constructor?
A special type of method that is called when an object is created to initialize variables.
A no-argument constructor has....
No parameters.
What is the method signature of public void setDate(int month, int day);?
setDate(int, int);
What is assumed to be true when a method is called
Precondition
Post Condition?
What will be true after a method is called
Helper methods should be
marked as private
An object is this type of variable
A reference variable
What are the TWO types of data contained by classes?
Characteristics and Behavior
Naming standard for mutator method?
setXYZ();
Naming standard for accessor method?
getABC();
-All must have one (except apps)-Follows the class, where execution begins-Must h ave { and }
Main method
-Must end with a ; (semicolon)
Statements
Prints x on the same line
print(x)
-Begins with a \-Always comes in pairs
Escape sequences
New line
\n
Tab
\t
Backspace
\b
\
\\
"
\"
'
\'
Stores (points to) the memory address of an object
Reference variable
Stores a specific type of value
Primitive data types
Name the variableNOTE: starts with lower case, new word starts with capital letter (numDays)
Identity
=
Assignment Operator
blank.
Value
;
Semicolon
-Must start with a letter-Can contain letters, numbers, and underscore character-Cannot contain spaces-Cannot contain reserved (key) words
Identifiers (name) Rules
-64 bitsRange: -big to big
double
Value: true/false
boolean
-Cannot put a bigger box into a smaller box-Data type on RIGHT side of = has to be less than the type on the LEFT sideEX: 64bits = 32bits <---CORRECTEX: 32bits = 64bits <--- WRONG
Mixing Data Types Rules
-Cannot put a decimal into an integer-Integers cannot hold decimal values EX: int = double <---WRONGEX: double = int <--- CORRECT
Mixing Data Types Rules
-short and char are not interchangeable -char is unsigned (only positive values), short has both positives and negatives
Mixing Data Types Rules
to convert data type
Casting
int input
nextInt()
byte input
nextByte()
short input
nextShort()
float input
nextFloat()
double input
nextDouble()
String input
next()nextLine()
next()
One word String
nextLine()
String of words
Instantiating an object
class name object name = classname();
static
One copy and everyone can see it
Build a void method
public void main
Build a return method
public return
Instance variables
Set to 0a = 0;b = 0;c = 0;
Print statement
System.out.println("");
Print format statement to get 3.14 of pi
System.out.printf("%.2f", pi);
Initialize scanner
Scanner keyboard= new Scanner (System.in);
Constants declaration
public static final NAME = value;
String declaration
String name = "";
Length method
name.length()
Comparison operators: Equal to, Not equal to, greater than, greater than or equal to, less than, less than or equal to
== != > >= < <=
Logical Operators
&& ||
Conditional operator
condition?truepath:falsepath; (hours<12 ? "AM" : "PM";)
Emergency exit
Sytem.exit(value);
String comparing a to b
a.compareTo("b");
Keyboard integer input
keyboard.nextInt();
Switch statement
switch (variable you're check against) { case label: code; break; default:
Loop count to 10
for(count = 0; count<11: count++);
Method call/actual and formal for method name; No return value, no parameters
methodName(); public static void methodName():
Method call/actual and formal for method name; Return value, no parameters
variableName = methodName();public static int methodName():
Method call/actual and formal for method name; No value, send parameters
variableName = methodName();
/***/
opening comments
public class _____
class header; indicates a publicly accessible class named "_____"
public static void main(String [ ] args)
method header;
method
a group of one or more programming statemetnts that collectively has a name
//
double slash; marks the beginning of a comment (a statement ignored by the computer)
( )
opening/closing parentheses; used in a method header
{ }
opening/closing braces; encloses a group of statements, such as the contents of a class or a method
" "
quotation marks; encloses a string of characters, such as a message that is to be printed on the screen
;
semicolon; marks the end of a complete programming statement
System
a class that holds objects/methods to perform system-level operations, like output
out
an object that provides a way to send output to the screen
a method that prints characters to the screen and remains on the same line
println
a method that prints characters to the screen and moves to the next line
System.out.print( _____ );
prints the content in the parentheses ( _____) and remains on the same line
System.out.println( _____ );
prints the content in the parentheses ( _____ ) and moves to the next line
/n
newline; advances the curson to the next line for subsequent printing
/t
horizontal tab; causes the curson to skip over to the next tab stop
/b
causes the cursor to back up, or move left, one position
/r
return; causes the cursor to go to the beginning of the current line, not the next line
\\
backslash; causes a backslash to be printed
When an array is created, all elements are initialized with ___.A) zeroB) array elements are not initialized when an array is createdC) nullD) a fixed value that depends on the element type
Ans: DSection Ref: Section 7.1 Arrays
What is the type of a variable that references an array of integers?A) int[]B) integer()C) integer[]D) int()
Ans: ASection Ref: Section 7.1 Arrays
Fill in the if condition that will only access the array when the index variable i is within thelegal bounds.if (____________________)data[i] = value;A) 0 <= i < data.length()B) 0 <= i && i < data.lengthC) 0 <= i < data.lengthD) 0 <= i && i < data.length()
Ans: BSection Ref: Section 7.1 Arrays
What is the error in this array code fragment?double[] data;data[0] = 15.25;A) The array referenced by data has not been initialized.B) A two-dimensional array is required.C) An out-of-bounds error occurs.D) A cast is required.
Ans: ASection Ref: Section 7.1 Arrays
Which class manages a sequence of objects whose size can change?A) ArrayB) ObjectC) SequenceD) ArrayList
Ans: DSection Ref: Section 7.2 Array Lists
What is the type of a variable that references an array list of strings?A) ArrayList[String]()B) ArrayList<String>()C) ArrayList<String>D) ArrayList[String]
Ans: CSection Ref: Section 7.2 Array Lists
You access array list elements with an integer index, using the __________.A) () operatorB) [] operatorC) get methodD) element method
Ans: CSection Ref: Section 7.2 Array Lists
The wrapper class for the primitive type double is ____________________.A) There is no wrapper class.B) DoubleC) doubleObjectD) Doub
Ans: BSection Ref: Section 7.3 Wrappers and Auto-boxing
Wrapper objects can be used anywhere that objects are required instead of ____.A) primitive data typesB) clone methodsC) array listsD) generic classes
Ans: ASection Ref: Section 7.3 Wrappers and Auto-boxing
Rewrite the following traditional for loop header as an enhanced for loop, assuming thatArrayList<String> names has been initialized.for (int i = 0; i < names.size(); i++){// process name}A) for (String s : names)B) for (int i = 0; i < names.size(); i++)C) for (s : names)D) for (names : String s)
Ans: ASection Ref: Section 7.4 The Enhanced for Loop
What is the purpose of this algorithm?for (int i = 0; i < data.size(); i++){data.set(i, i );}A) Filling in initial values for an array.B) Counting matches in an array.C) Filling in initial values for an array list.D) Counting matches in an array list.
Ans: CSection Ref: Section 7.6 Common Array Algorithms
What is the purpose of this algorithm?double total = 0;for (double element : data){total = total + element;}A) Computing the sum.B) Finding a value.C) Locating an element.D) Counting matches.
Ans: ASection Ref: Section 7.6 Common Array Algorithms
What is the purpose of this algorithm?int m = 0;for (BankAccount a : accounts){if (a.getBalance() >= atLeast)m++;}A) Counting matches.B) Finding a value.C) Computing the sum.D) Locating an element.
Ans: ASection Ref: Section 7.6 Common Array Algorithms
What is the purpose of this algorithm?for (BankAccount a : accounts){if (a.getAccountNumber() == accountNumber)return a;}return null;A) Finding a value.B) Counting matches.C) Computing the sum.D) Inserting an element.
Ans: ASection Ref: Section 7.6 Common Array Algorithms
A static method can have which of the following types of parameters?A) Only implicit parameters.B) Only explicit parameters.C) Both implicit and explicit parameters.D) A static method cannot have parameters.
Ans: BSection Ref: 8.6
A method that has no implementation is called a/an ____ method.A) interfaceB) implementationC) overloadedD) abstract
Ans: DSection Ref: 9.1
____ are generated when the user presses a key, clicks a button, or selects a menu item.A) ListenersB) Interfaces.C) Events.D) Errors.
Ans: CSection Ref: 9.7
Which of the following is an event source?A) A JButton object.B) An event listener.C) An inner class.D) An event adapter.
Ans: ASection Ref: 9.7
When you use a timer, you need to define a class that implements the ____ interface.A) TimerListenerB) TimerActionListenerC) ActionListenerD) StartTimerListener
Ans: CSection Ref: 9.10
A class that represents the most general entity in an inheritance hierarchy is called a/an ____.A) Default class.B) Superclass.C) Subclass.D) Inheritance class.
Ans: BSection Ref: 10.1
When designing a hierarchy of classes, features and behaviors that are common to all classesare placed in ____.A) every class in the hierarchyB) the superclassC) a single subclassD) all subclasses
Ans: BSection Ref: 10.1
To create a subclass, use the ____ keyword.A) inheritsB) implementsC) interfaceD) extends
Ans: DSection Ref: 10.2
The ____reserved word is used to deactivate polymorphism and invoke a method of thesuperclass.A) thisB) myC) parentD) super
Ans: DSection Ref: 10.3
A class that cannot be instantiated is called a/an ____.A) Abstract class.B) Anonymous class.C) Concrete class.D) Non-inheritable.
Ans: ASection Ref: Special Topic 10.1
The ____ reserved word in a method definition ensures that subclasses cannot override thismethod.A) abstractB) anonymousC) finalD) static
Ans: CSection Ref: Special Topic 10.2
In Java, every class declared without an extends clause automatically extends which class?A) thisB) ObjectC) superD) root
Ans: BSection Ref: 10.7
int
Used to declare and initialize a non fraction interagerEx: int canVolume = 5;
double
Used to declare and initialize a fraction interager.Ex: double canVolume = 0.335;
final
variable is defined with the reserved word its value can never change.Ex: final double .canVolume = 0.335;
//
Used to comment out a line.
/ /
Used to comment out a paragraph or longer
==
Used to equal a value
&&
Boolean operator meaning both sides have to be true. A Short circuiting logical operator.
||
Boolean operator meaning only one side has to be true. A Short circuiting logical operator.
java.awt.*;
To paint basic graphics and images.
javax.swing.*;
To create lightwieght components for a GUI.
java.io.*;
To utilize data streams.
java.net.*;
To develop a networking application.
java.util.*;
To work with collections framework, event model, and date/time facilities.
java.lang.*;
To utilize the core java classes and interfaces.
byte
Used to define a primitive variable as an integer with 1 byte of storage. Also a corresponding wrapper class.
classpath
An enviroment variable that includes an argument set telling the Java virtual machine where to look for user defined classes/packages.
Error
This Class indicates issues that an application should not try to catch. Subclass of the class Throwable.
Exception
This class indicates issues that an application may want to catch. A subclass of the class Throwable.
J2EE
Acronym for Java 2 Platform, Enterprise Edition.
J2ME
Acronym for Java 2 Platform, Micro Edition.
J2SE
Acronym for Java 2 Platform, Standard Edition.
JDK
A bundled set of development utilities for compiling, debugging, and interpreting Java Applications.
JRE
An environment used to run Java Applications. Contains basic client and server JVM, core classes and supporting files.
Literal
A value represented as an integer, floating point, or character value that can be stored in a variable.
Relative Path
A path that is not anchored to the root of a drive. Its resolution depends upon the current path. Example ../usr/bin.
RuntimeException
Class is the superclass of those exceptions that can be thrown during normal runtime of the Java virtual machine.
Scope
Block of code in which a variable is in existence and may be used.
String
Can use +, ., and +=
b
b
b
b
b
b
b
b
b
b
b
b
b
bb
main loop
public static void main (String[] args)
print(return)
System.out.println();
print (return) a command line input
System.out.println (args[0]);
declare and define command line integer argument, a
int a = Integer.parseInt (args[0]);
declare a as an int
int a;
declare a boolean variable, isAscending
boolean isAscending;
and
&&
not equal
!=
to swap values of integers you need a...
place holder
double b = a / b, but a is an int. Cast int to double
double b = (double) a / b;
Declare and define integer a from double, b.
int a = (int) b;
Ï
Math.PI;
x^y
Math.pow (x, y);
square root of a
Math.sqrt (a);
find the max
Math.max (x, y);
find the min
Math.min (x, y);
radians to degrees
Math.toDegrees();
degrees to radians
Math.toRadians();
declare and define a double, a, from command line argument
double a = Double.parseDouble(args[0]);
first line of program, HelloWorld
public class HelloWorld
if statement (many commands)
if (true) {}
if / else
if (true) {}else {}
while
while (true) {}
for loop (use i and N)
for (int i = 0; i < N; i++) {}
random number between 0 and 1
Math.random();
random number between 1 and n
1 + Math.random() * n;
random number between 0 and n
Math.random() * (n + 1);
short hand a = a + n;
a += n;
short hand a = a - n;
a -= n;
short hand a = a * n
a *= n;
std print
StdOut.println();
read an integer
StdIn.readInt();
read double
StdIn.readDouble();
set pen color
StdDraw.setPenColor();
draw a filled rectangle centered at (x, y)width = wheight = h
StdDraw.filledRectangle(x, y, w, h);
draw "text" at (x, y)
StdDraw.text(x, y, "text");
draw circle at (x, y)radius = r
StdDraw.circle(x, y, r);
draw filled circle at (x, y)radius = r
StdDraw.filledCircle(x, y, r);
set x and y window scale to -R , R
StdDraw.setXscale(-R , R);StdDraw.setYscale(-R, R);
declare and initial double array, points, with length N
double[] points = new double [N];
declare and initial int array, number, with length N
int[] number = new int [N];
declare and initial string array, names, with length N
String[] names = new String [N];
play 2001.mid
StdAudio.play("2001.mid");
draw an image, starfield.jpg at (0, 0)
StdDraw.picture(0, 0, "starfield.jpg");
absolute value of x - y
Math.abs(x - y);
boolean for empty
StdIn.isEmpty()
sin x
Math.sin(x);
cos x
Math.cos(x);
arc cos x
Math.acos(x);
arc sin x
Math.asin(x);
pen size to 0.05
StdDraw.setPenRadius(0.05);
draw line from (x, y) to (q, s)
StdDraw.line(x, y, q, s);
draw point at (x, y)
StdDraw.point(x, y);
Strongly Typed
Whereby, in a language (Java), every variable and expression has a type when the program is compiled. You cannot arbitrarily assign the value of one type to another.
Java Type Categories
Primitive Types & Reference Types. It is possible for the user to create further reference types but there is a limited number of pre-defined Java primitive types.
Primitive Variables
Can store data values.
Reference Variables
Can't store data values, but refer to objects that do.
Literals
Have a fixed value, as opposed to a variable. Each primitive type has an associated set of literal values and a literal value can be assigned to a primitive variable of the same type.
Declaration
Creating a variable of the type that you want to use, reserves a memory location for that variable.
Initialization
When you first store something in a variables memory location.
Integral Types
Primitive types, all signed : byte, short, int, long. Fixed length, regardless of platform. Can all take integer literals. An integer variable can hold the result of an arithmetic expression.
Data Type Sizes
Fixed in Java, to ensure portability across implementations.
Char Type
Store single unicode characters (international character set) and can be initialised with character literals enclosed in '. E.g. 'a'.
Escape Sequence
characters marked by a backslash \ that represent special information such as non-standard unicode characters, e.g. '\u00A9'. Also non-printable characters, e.g. newline '\n'.
Floating Point Types
Those that contain fractional parts using significand digits and an exponent which represents its magnitude. Includes floats and doubles (32 and 64 bits respectively).
Floating Point Literals
Either written with a whole and fractional part separated by a dot '45.98' or with scientific notation which allows significant digits that are multiplied by a power of 10 specified after the character 'e'. 'double speedOfLight = 2.998e8'. It seems that both double and float use the same literals, unlike C++.
Logical Type
boolean, with literals 'true' and 'false'. A logical variable can hold the result of a logical expression.
Casting
The process of explicitly converting one primitive type to another. Involves writing the desired type of an expression in parentheses e.g. '(int)'. This can result in the loss of information and therefore is worth avoiding by choosing appropriate types.
Casting Float Types to Integral Types
Always requires a cast. Will result in the loss of the fractional part of the number.
Promotion
Term used when casting a smaller memory type to a larger memory type and therefore a cast is not needed (in the reverse case, a cast is needed).
Statement
A unit of executable code, terminated by a semi-colon.
Code Block
Delimited by curly-brackets, enables a set of statements to be treated as a single statement.
Local Variables
variables declared within a method or, more accurately, within a code block. These variables can only be used within the code block scope. They aren't initialised by default, so should be initialised by hand !.
Operators
Sets of which are associated with primitive datatypes, can be either unary or binary, depending on whether they require one variable or two (operands). E.g. addition, multiplication or increment.
Arithmetic Operators
Can be applied to integral or floating point types, includes multiplication(*), division(/), remainder(%), addition(+), subtraction(-).
Modulus
Represented by the character %, gives the remainder of a division between integral or fractional numbers (note that the result can also be fractional).
Arithmetic Expression Type
Depends on the types of the variables or literals used in the expression. E.g 3/4 would be 0, integral, and the fractional part discarded. However if an expression mixes integrals and floating points, the expression will return a floating point type.
Prefix Operator
Unary operator that appears before it's operand. E.g. the negation operator '-' which negates the value to it's right. e.g. 'int negative speed = -speed;'
Operator Precedence
When an expression includes one or more operators, this governs in what order the operations are carried out. For example, multiplication has a higher precedence than addition and so is carried out first. Each language has rules of precedence for all of it's operators.
Precedence and Parentheses
Operations in parentheses are carried out first and can therefore be used by the programmer to control the order in which an expression is evaluated. This is preferable so that anyone using the code doesn't have to remember orders of precedence and it helps avoid obfuscation.
Increment and Decrement Unary Operators
Operators available in postfix and prefix forms. The postfix version returns the old value of the variable before applying the addition or subtraction of 1. Note that these operators do change the variable that the y operate on, as well as returning values for the expression to use. E.g. 'int a = myInt++;' where a will be assigned the old value of the variable and the variable will also be incremented.
Data Type 'String'
Sequence of characters, a reference data type.
String Literal
Enclosed in double quotation marks. E.g. "Jonathan withey". This actually creates a String object to be referenced, for example 'String aString = "Character Sequence";'.
Empty String
A special string literal, denoted by "".
Strings and escape sequences
Can be included in a string as if they were another character using the backslash \. E.g. "\"This is a string\"" uses \" to include double quotation marks as characters in the sequence.
Reference Variable
An identifier that represents a location in memory which itself has a reference to another location in memory where an object resides. Multiple reference variables can reference the same object and so affect its reference count. An object with no references can be garbage collected.
String method length()
Returns the number of characters in a string, counting from 1. E.g. "12345".length() would return 5. An empty String has length 0.
Operator Overloading
Where the user can define the behaviour of an operator depending on the types of its operands. This isn't possible in Java, although the '+' operator is overloaded by the system to concatenate String objects.
String operator '+'
Used for concatenation. If either operand is a String type, both operands will be turned into strings, concatenated and then added to a newly created String object. E.g. String aString = "Jon" + 2; would output 'Jon2'.
Conditional Processing
Whereby a program can respond to changes due to the data on which it operates.
flow control structures
Allow different segments of code to be executed under different circumstances. Keywords : if...else, switch..case (all selection statements).
Logical Expression
Evaluates to either 'true' or 'false' (boolean literals). Can be used for conditional processing in flow control structures.
Relational Operators
Check relationships between values of the same type and will be part of a logical expression. Can be used with floating points, integers and characters (including >, <, <=, >=). booleans only use '==' and '!=' which can also be used with other types.
Relational Operators and Floating Points
Floating point values have limited precision, they are approximations, therefore using relational operators requires care (e.g. might be best to check within a precision range).
Selection Statements
Flow control structures that allow us to select which segments of code are executed depending on conditions. Includes 'if...else' and 'switch...case'.
'if' statement
Of the form 'if( [logical_expression] ) { statements; }'. where the statements in the body are executed if the logical expression argument in the header parentheses evaluates to true. Note that the entire structure is considered a single statement.
curly brackets and ;
In general, Java doesn't require code blocks delimited by '{..}' to be followed by a ';' as would normally be the case for a statement.
Demarcation and indentation
Good programming style in Java includes clearly showing the body of an if statement by creating a boundary around it with '{..}' curly-brackets. Segments of code can also all start with tabbed whitespace to highlight the structure of a program.
Caching truth or falsity
Rather than constantly checking the truth of a logical expression, sometimes it is better to store the result in a boolean and use that subsequently. For example 'boolean isFlying = height > 0.5f; if(isFlying == true) { flapWings(); }'
if...else statement
The if statement can be extended to include an alternative code block to be executed if the header argument evaluates to false. For example 'if(isFlying) { flapWings(); } else { closeWings(); }'.
if...else if... statement
Possible to chain many if..else statements by using 'else if...' statements. In the form 'if(logical_expression) { statements; } else if (logical_expression) { statements; } else { statements; }'. Note that you can have as many 'else if' statements as you like, and you don't have to end with an else code block.
Nesting Conditional Constructs
Within a code block, additional flow control structures can be nested. For example an if statement could be nested within the code block of another if statement, or a switch statement within the case of another switch statement. Note that stylistically, nesting results in further indentation so that flow can be followed easily.
Logical Operators
Operate on boolean values and can be unary or binary. Often used to combines logical expressions with relational operators.
&&
logical AND operator returns true if both its operands are true. E.g. 'boolean isCup = hasHandle && holdsTea;'. Otherwise returns false.
||
logical OR operator returns if any of its its operands are true (including both). E.g. 'boolean isCool = hasCar || hasBand'.
!
logical NOT operator is unary and returns the opposite of its operand. Ie. if operand is true, returns false and vice-versa. E.g. 'boolean isWoman = !hasBeard;' where isWoman would equal false if hasBeard is true.
^
logical XOR, effectively returns true if both its operands are different (ie. a mix of true and false) but returns false if they are the same. E.g. 'boolean isHetero = likesWomen ^ likesMen;'.
switch....case use-age
Multi-coniditional branching. Used instead of the 'if' statement when a large number of outcomes need to be tested. Each case contains code that is executed if the switch argument takes on a particular value.
switch...case form
'switch ([argument]) { case [selector]: [statements;] break; default: [statements;] break; }'. Where many cases can be written and the 'default' case is selected if none of the other cases are selected.
switch argument
Has to be an expression of type int, char, short or byte. Notably not float, double and long (too imprecise or large).
switch selector value
Has to be a constant value (usually a literal) that is compatible with the argument type. The statements within the case are executed if it is logically equivalent to the argument '=='.
switch break
Causes the switch to terminate by transferring control to the end of the statement. Note that it can be used in a similar way in any statement.
switch fall-through
If a 'break' keyword is missing after a case, processing will continue through to the next case and until it reaches a break statement or the end of the switch statement.
switch default case
Can be included to perform some processing if none of the other cases in the switch statement are selected, such as throwing an exception. It isn't a requirement but is good style.
switch example
'char control = 'a'; switch (control) { case 'a': invokeA(); break; default: invokeError(); break; }' Note that because 'a' is logically equivalent to the switch argument 'control', that case would be selected and, once the statements executed, break would transfer control to the end of the switch statement, skipping the default: case.
Truncation
When casting a larger type to a smaller type there may be a loss of information due to the truncation of additional bits or the fractional part of the number when casting from a floating point number to an integral number.
What are the two subclasses of the throwable class?
Error & Exception
exceptions that usually occur because of code that isn't very robust.
Runtime Exceptions
exceptions happen when you try to use a variable that doesn'trefer to an object yet.
NullPointerException
exception that is thrown when your not properly checking to make sure that your code always stays within the bounds of an array
ArrayIndexOutofBounds
Exception that occurs when you're reading from a file and the file ends before you expected it to end.
EOFException
Exception that occurs when a URLisn't in the right format (perhaps a user typed it incorrectly)
MalformedURLException
What try and catch effectively mean is:What try and catch effectively mean is:
"Try this bit of code that might cause an exception.If it executes okay, go on with the program. If the code doesn't execute, catch the exception and deal with it."
This method is presentin all exceptions, and it displays a detailed error message describing what happened.
.getMessage() method
displays the sequence of methodcalls that led to the statement that generated the exception.
printStackTrace()
when writting multiple catch clauses you should always start with ______
more specific subclass exceptions and end with more general superclass exception catches (because if you start with a superclass exception catch you wont know what the specific exception was.
How does the substring() method of the String class work ?
the first argument specifies the index of the first character to include, the second argument indicates the index of the last character plus 1. A call to substring(2, 5) for a string would return the charactersfrom index position 2 to index position 4.
In particular, exceptions of either the ______or ____________ class or any of their subclasses do not have to be listed in your throws clause.
Error & RuntimeExceptions
subclasses of the RuntimeException and Error classes andare usually thrown by the Java runtime itself.
Unchecked exceptions
if your method has been declared with a throws clause, don't forget to:
actually throw the exception in the body of your method using the throw statement.
The assert keyword must be followed by one of three things:
an expression that is trueor false, a boolean variable, or a method that returns a boolean.
How can you specify a string to make a assert statement more meaningful
assert price > 0 : "Price less than 0.";
parts of a program set up to run on their own while the rest of the programdoes something else.
Threads
A thread can be created in two ways:
by subclassing the Thread class or implementingthe Runnable interface in another class.
To run a thread what method must be callled?
start() method
What are the two subclasses of the throwable class?
Error & Exception
exceptions that usually occur because of code that isn't very robust.
Runtime Exceptions
exceptions happen when you try to use a variable that doesn'trefer to an object yet.
NullPointerException
exception that is thrown when your not properly checking to make sure that your code always stays within the bounds of an array
ArrayIndexOutofBounds
Exception that occurs when you're reading from a file and the file ends before you expected it to end.
EOFException
Exception that occurs when a URLisn't in the right format (perhaps a user typed it incorrectly)
MalformedURLException
What try and catch effectively mean is:What try and catch effectively mean is:
"Try this bit of code that might cause an exception.If it executes okay, go on with the program. If the code doesn't execute, catch the exception and deal with it."
This method is presentin all exceptions, and it displays a detailed error message describing what happened.
.getMessage() method
displays the sequence of methodcalls that led to the statement that generated the exception.
printStackTrace()
when writting multiple catch clauses you should always start with ______
more specific subclass exceptions and end with more general superclass exception catches (because if you start with a superclass exception catch you wont know what the specific exception was.
How does the substring() method of the String class work ?
the first argument specifies the index of the first character to include, the second argument indicates the index of the last character plus 1. A call to substring(2, 5) for a string would return the charactersfrom index position 2 to index position 4.
In particular, exceptions of either the ______or ____________ class or any of their subclasses do not have to be listed in your throws clause.
Error & RuntimeExceptions
subclasses of the RuntimeException and Error classes andare usually thrown by the Java runtime itself.
Unchecked exceptions
if your method has been declared with a throws clause, don't forget to:
actually throw the exception in the body of your method using the throw statement.
The assert keyword must be followed by one of three things:
an expression that is trueor false, a boolean variable, or a method that returns a boolean.
How can you specify a string to make a assert statement more meaningful
assert price > 0 : "Price less than 0.";
parts of a program set up to run on their own while the rest of the programdoes something else.
Threads
A thread can be created in two ways:
by subclassing the Thread class or implementingthe Runnable interface in another class.
To run a thread what method must be callled?
start() method
JSEJEEJMEJava Card
Java Standard Edition - Contains the core functionality of the Java language; used to develop desktop applications.Java Enterprise Edition - Provides additional functionality required of enterprise applications, including web applications.Java Micro Edition - A scaled-down version used for mobile phones and other handheld devices.Java Card - The smallest Java footprint used for integrated circuits (e.g., memory and microprocessor cards).
Java bytecode
A platform independent instruction set that's produced when Java source code is compiled.
Java Virtual Machine (JVM)
A platform-targeted runtime environment that knows how to execute Java bytecode.
The Java Runtime Environment (JRE)
A set of libraries that define the application programming interface (API) of the Java language. The JRE also contains the JVM application.
The Java Software Development Kit (JDK)
A set of command line tools (e.g., compilers, de-compilers, debuggers) used to develop Java programs. The JDK also contains the JRE, which contains the JVM.
8 primitive data types
All of Java's numeric primitive data types are signed.Boolean (1 bit): true, falsechar (2 bytes): Unicode characters, ranging from 0 TO 65,535byte (1 byte): -128 to 127short (2 bytes): -32,768 TO 32,767int (4 bytes): -2,147,483,648 TO 2,147,483,647long (8 bytes): -9,223,372,036,854,775,808 TO +9,223,372,036,854,775,807float (4 bytes): 1.40129846432481707e-45 TO 3.40282346638528860e+38 (+ or -)double (8 bytes): 4.94065645841246544e-324d TO 1.79769313486231570e+308d (+ or -)
Declare the data type of a variable.
Primitive types are used to declare the data types of variables where a variable is a named memory location. datatype variableName = initialvalue;The following statements illustrate the use of Java's eight primitive data types in variable declarations:char c = 'a';Boolean succeeded = false;byte age = 0;short index = 0;int ssn = 0;long length = 0;float pi = 3.14159f;double d = 0.0;floating point literals are defaulted to a "double" data type. To compile certain types, such as float, add a suffix to the literal: float pi = 3.14159f;
How do you declare a CONSTANT in Java?
Using the keyword "final":final float pi = 3.14159f;
Are primitive data types considered objects in Java?
No, primitive types are the only elements of the Java language that are not modeled as objects.
What is the syntax of a sequence control flow example?
base = rate * hours; taxes = base * taxRate; net = base - taxes; count++; count--;
What is the syntax of a decision control flow example?
if (x == y) { ... } else { ... } switch (index) { case 0: {...} case 1: {...} default: {...}}
What is the syntax of a looping control flow example?
for (int i=1; i<10; i++) { ... }while (x < y) { ... }do { ... } while (x<y)
Definition of class
Describes the properties and behavior of a prototypical object. During runtime, the application creates individual instances of classes where the instances are called objects.For example:class - Bookproperties - title, authorbehaviors - checkOut(), checkIn()Then at runtime, the application creates a separate object for each book as they are requested by users.
Syntax to define a class
public class SomeClassName { // class properties and behaviors (methods) go here }keyword "public" is an access modifier, keyword "class" identifies the construct (i.e., the item) as a class definition, class name may contain alpha numeric characters, underscore, and $ (last two are rarely used). By convention, class names always start with an upper case letter, using CamelCase if there are more than one word.
Basic definition of class for Book (library program)
public class Book { // properties private String title = null; private String author = null; private boolean isCheckedOut = false; // behavior public void checkOut () { isCheckedOut = true; } public void checkIn () { isCheckedOut = false; }}
Syntax to define a method (behavior (function in C++))
returntype methodName(optional_list_of_arguments){...}Names of properties (variables) and methods should start with a lower case letter, using camelCase if multiple words.
UML Diagrams - list the structure diagrams
Structure Diagrams - CCCODPPComposite StructureClassComponentObjectDeploymentProfilePackage
UML Diagrams - list the behavior diagrams
Behavior Diagrams - STIACUSSequenceTimingInteractiveActivityCommunicationUse CaseState
UML Class diagram w/ general syntax
ClassNameProperties HereBehaviors HereBooktitle: Stringauthor: StringisCheckedOut: booleancheckOut(): voidcheckIn(): voidEach property name is followed by its data type (e.g., String, boolean).Each method name is followed by its return type (e.g., void).
Objects...
are instances (instantiations) of classes, as objects are created, the properties that are defined in the class template are copied to each object instance and assigned values. Thus, each object has its own copy of the class properties
Objects example illustrated
CLASSBooktitle: Stringauthor: StringisCheckedOut: booleancheckOut(): voidcheckIn(): voidIf a user checks out 2 books, each of them are assigned the class properties:Book Booktitle: Call of the Wild title: Gone with the Windauthor: J. London author: M. MitchellisCheckedOut: true isCheckedOut: trueclass is a type, and objects are instances of those types
Constructors are special methods defined in a class that are used to initialize ___ ___.
Answer: object instancesConstructors must have the same name as the class name; the class Book will have constructors named Book (must be identical).Constructs are not allowed to explicitly declare that they return a type; rather, the implicit type they return is the enclosing class type in which they're defined.
Constructor syntax
public class Book { // properties private String title = null; private String author = null; private boolean isCheckedout = false; // constructors public Book() { } public Book(String title, String author, boolean isCheckedout) { this.title = title; this.author = author; this.isCheckedout = isCheckedout; }} Two constructors:Book(), which is known as the default constructorBook(String title, String author, boolean isCheckedout)Default constructor - typically used to initialize properties to their "null" values, unless it is done when they are declared, then there is no need to have the first constructor.The 2nd constructor above, takes the passed parameters and assigns them to the class's properties (i.e., data members) using the keyword "this".
Keyword: this
this - used to disambiguate the overloaded use of variable names; in particular, "this" can be used to reference a data member (defined in the class) when that name is identical to a passed parameter. assigns the input parameter, title, to the data member, title:private String title = "";public void setTitle(String title) { this.title = title; }inside the method setTitle(String title), the passed parameter, title, hides the data member, title, defined in the class. To access to the title data member, the keyword "this" is used to indicate a data member of the object is being referenced (and not a local variable inside the method).
Keyword: new
new - creates Class objects and a constructor as shown below:Book book1 = new Book();Book book2 = new Book("SomeTitle", "SomeAuthor", false); Constructors are invoked with the "new" keyword as shown below:Book book1 = new Book();Book book2 = new Book(1);Book book3 = new Book(1, "Gone with the Wind", "Margaret Mitchell"); Using a constructor that allows you to initialize the object with passed-in parameters. Using the default constructor, followed by the invocation of set(...) methods.
Predefined Java classes
Example of 2:Object class & String class
Object class
Object is base class of all Java classes. All Java classes extend (inherit) class Object either directly or indirectly. these 2 definitions are exactly the same:public class Book {...} public class Book extends Object {...}
The comparing method: equals(Object)
Using equals(Object):boolean areEqual = book1.equals(book2);It compares object references, compares to see if book1 and book2 reference the same Book object in memory. In the example above, book1 and book2 reference different Book objects, so the boolean variable areEqual is set to false.This one would be true:Book book1 = new Book();Book book2 = book1; boolean areEqual = book1.equals(book2);
String class
Java's String class is used to represent a sequence (i.e., string) of characters. A simplified class diagram of String is shown below:STRINGcount : intvalue : char[]String()String(orig:String)length : intcharAt(index:int) : charconcat(st : String) : Stringequals(obj : String) : booleanindexOf(str : String) : intisEmpty() : booleanlastIndexOf(str : String) : intlength() : intreplace(oldChar : char , newChar : char) : Stringsubstring(beginIndex : int, endIndex : int) : StringtoLowerCase() : StringtoUpperCase() : StringtoString : String* Extends class Object and thus inherits Object's properties and behavior, including method equals(Object);* Encapsulates private fields (e.g., count and value), prevents direct access to these fields by other objects; indirect access is provided through public methods; e.g., the method length() provides access to the count field;* Has two overloaded constructors, String() and String(String s). The first constructor takes no parameters, and the second takes a String object that is copied into the new String object;* Overrides methods toString() and equals() inherited from class Object by providing its own implementations;* Exhibits polymorphism (one interface, multiple behaviors) with methods toString() and equals();
method toString()
default behavior is to return the object's fully qualified name followed by the object's hash code.book1.toString(); //returns: Book@1ea2df3book2.toString(); //returns: Book@1ea2df3this information is typically not useful, it's common to override toString().
Syntax to create a String
String s1 = new String("Hello World");Can be created and initialized without using new:String s2 = "Hello World";Can be concatenated with the + operator:String s3 = "Hello " + "World";Operator == compares object references (and not the object's state), and since s1, s2 and s3 reference different String objects, == returns false:(s1 == s2); // returns false(s2 == s3); // returns false(s1 == s3); // returns falseString's implementation of equals(Object) examines the values of the strings, this is true:s1.equals(s2);s2.equals(s3);s1.equals(s3);Strings objects created with the "new" operator that have the same value (the same string of characters) are always "equals()" to each other, but since they are different objects, they are never "==" to each other.One last subtle point: strings created using the double quote syntax with the same value without the new operator are always = = to each other. String s4 = "Hello World";String s5 = "Hello World";(s4 == s5); // returns true
Application defined classes
classes that you create for your specific applicationLogin-username : String-password : String+setUsername : (username : String)+getUsername () : String+setPassword : (password : String)+getPassword () : String+validate() : boolean+equals(Login Login) : booleantwo private data members: username and password; the minus sign means the properties are hidden in the class, cannot access them outside of class.When a class does not explicitly provide a constructor, Java implicitly provides a default constructor (one that takes no arguments). The default constructor is available for use even though it's not shown.
Software Layers and responsibilities
* Presentation Layer - rendering the user interface, responding to user event, creating and populating domain objects, and invoking the business layer.* The Business Layer - managing workflow by coordinating the execution of services located in the service layer.* The Service Layer - service interfaces and implementations, the movement of objects in and out of the application, and the hiding of technology choices.* The Domain Layer - abstracting domain objects (i.e., the nouns) as they appear in the problem space.Data types for:user interface ->> Presentation Layer;manage use case workflow ->>Business Layer;move objects in and out of application ->>Service Layer;abstract the "nouns" of problem space ->> Domain Layer
Package
Items of related functionality, each item in the package has a unique name. Thus, a package is a namespace, where a namespace is a collection of uniquely named items. One of main packages is "java", does not contain any data types, it's used to aggregate other packages that are nested within it.java.appletjava.awtjava.beansjava.iojava.utilnested package example:java.util.concurrent.locksother nested packages do contain type definitions:- java.util contains the Date class (and other classes)- java.util.concurrent contains the Semaphore class (and other classes)- java.util.concurrent.locks contains the LockSupport (and other classes)
Declaring a class to a package
class is declared to belong to a package by including a package statement at the beginning of the source file, it must be the first statement in the file:package mypackage;public class MyClass{ ...}If package is not declared, the class will belong to the "default package". Not recommended for larger programs.
Importing packages
when classes are in defined in different packages. In order for ClassA, in packageA, to have visibility to ClassB, in packageB, one of three things must happen; either:- the fully qualified name of ClassB must be used,- fully qualified name of ClassB be must be imported with an import statement,- entire contents of packageB must be imported with an import statement. first technique is to use the FQN of the class. The FQN of ClassB is packageb.ClassB. to declare:package packagea;public class ClassA { packageb.ClassB b = new packageb.ClassB();}better technique is to use an "import" statement:package packagea; import packageb.ClassB;public class A { ClassB b = new ClassB();}import statements must appear after the package statement, and before the data type (class, interface) definitionmore efficient technique is to import all the data types from a given package using the * notation:import packageb.*;if multiple packages have classes with the same name, use long way (FQN) of importing package:package1.ClassXYZ xyz = new package1.ClassXYZ()
Access Modifiers
Information hiding is achieved through the use of access modifiers, which are keywords that are used to augment the visibility of various constructs. PublicDefault (no modifier)ProtectedPrivate
Public modifier
Can be applied to a class and/or individual data members and methods within a class; indicates that the given item is accessible across package boundaries, the following class and method are both accessible outside the package in which they're defined.package domain;public class Book { public void checkOut() { }}
Default (no modifier)
Can be applied to a class and/or individual data members and methods within a class; indicates that the given item is not accessible across package boundaries (i.e., it limits access to members of the same package) e.g., the following class and method are NOT accessible outside the package in which they're defined.package domain;class Book { void checkout() { }}
Protected modifier
Can be applied to individual data members and methods (but cannot be applied to a class); when applied, it restricts access to members of the same class and any derived class; e.g., the following method, setHashCode, is only accessible to members of the LibraryItem class and any derived classes (e.g., Book).package domain;public class LibraryItem { protected void setHashCode() { }}package domain;public class Book extends LibraryItem { public LibraryItem () { setHashCode(); }}
Private
Can be applied to individual data members and methods (but cannot be applied to a class); when applied, it restricts access to members of the same class; e.g., the following data member, isbn, is only accessible to members of the Book class, and nowhere else.package domain;public class Book { private String isbn; public void getIsbn() { return isbn }}
Method overloading
occurs when a class contains more than one method with the same name. Within a class, methods can have the same name if there's difference:The number of parameters.And/or the type parameters.And/or order of parameters.The determination of which overloaded method to invoke is a compile-time decision; hence, it is sometimes referred to as static binding. Library library = new Library();Book book = new Book(); library.add(book);User user = new User();library.add(user);Notice that the statement library.add (book) is clearly targeting the add (Book) method because of the parameter data type, Book. Similarly, the statement library.add(user) is clearly targeting the add(User) method because of the parameter data type, User. Since these decisions can be determined at compile time, the binding is said to be static.
polymorphism
Method overloading is an example of polymorphism. polymorphism can be defined as "one interface with multiple behaviors." Another form of polymorphism is method overriding, which is an example of dynamic binding. Method overriding is discussed later in this topic.
static fields and methods
By default, data members and methods are "instance" members and are said to be "non static." Non static instance data members are copied to each object instance of the class, so each object has its own copy. Non static methods can reference these copied data members through an implicit object reference (but you can access it via "this" when necessary). The concept of non static instance members is illustrated below.public class Book { private String title = ""; public void setTitle(String title) { this.title = title; }}When there's a need to not copy data members to each object instance, such as constants. They can remain in the class definition. Data members and methods that are not associated with object instances are call "class" members; they are local to the class and are not affiliated with the objects. Annotated with the keyword "static":public static final int CHECKOUT_DURATION = 21;Because the above data member is a class variable, it can be accessed through the class name as follows:int duration = Book.CHECKOUT_DURATION;Methods can also be designated as static:private static int nextId = 1;public static int getNextId() {return nextId++;}Above, method getNextId() provides access to the static data member and manages its next value.IMPORTANT:"static only sees static" but "non-static sees everything"static members can only access other static members; in particular, static members cannot access non-static members. Non-static members have access to all members (both static and non-static).
Inheritance
One of the 3 main pinnacles of object-oriented programming (the others being encapsulation and polymorphism). Inheritance is a means by which a class extends another class, it acquires the properties and behavior of the class that's being extended. Sometimes called generalization/specialization, also called an "is a" relationship.For example, the class declarations of Book, Audio, and Periodical are shown below:package domain;public class Book extends LibraryItem { // properties and behavior of Book go here}package domain;public class Audio extends LibraryItem { // properties and behavior of Audio go here}package domain;public class Periodical extends LibraryItem { // properties and behavior of Periodical go here}class can only extend one other class -- cannot extend multiple classes
Class Constructors
special methods that are called when a class is created. Must have the same name as the enclosing class, and are declared with no return value (the implied return type of the constructor is the enclosing class type).public Book() {...} public Book(int id) {...} public Book(int id, String title) {...} public Book(int id, String title, String author) {...} public Book(int id, String title, String author, int pages) {...}Constructors can be overloaded. Once you define at least one constructor (whether default or not), the implicit, hidden default constructor is not provided for you.used to initialize the data members of the newly created object either by assigning default values or by using the passed-in parameters. Constructors can also invoke other constructors either in the same class or in a base class.public Book(int id) { super(id); }Above uses "super" keyword to invoke a constructor in the base class LibraryItem. Constructors are invoked with the "new" keyword
Method Overriding
when a method in a base class is repeated (redefined) in a derived classsignature of both methods must match identicallyoverride its behavior in the LibraryItem to output the item's id and title as shown below:public class LibraryItem { ... public String toString() { return "LibraryItem, id=" + id + ", title: " + title; }}can invoke toString() to get a meaningful description of the object. Also true if the object is a Book, Audio, or Periodical because they inherit LibraryItem. Object obj = new Book(1, "Catch-22", "Joseph Heller", 485);String s = obj.toString();actual instance is a Book and Book "is a" LibraryItem which overrides toString(), the LibraryItem's toString() method is called. Example of polymorphic dynamic binding; dynamic because it's not known until runtime which toString() method is invoked; it depends on whether the method is overridden, and if so, where.Can override toString in each of the more specialized classes: Book, Audio, and Periodical:public class Book extends LibraryItem {public String toString() { return super.toString() + ", Author, =" + author; } }super.toString() in the above return statement; its purpose is to invoke the toString() method in the base class LibraryItem. So the Book's overridden toString() method calls the LibraryItem's toString() method and then appends to it the author information that's contained in the Book.This time, since Book has overridden toString(), which overrides LibraryItem.toString(), which overrides Object.toString(), it's Book.toString() that gets called, and not the ones declared in Object or LibraryItem:Object obj = new Book(1, "Catch-22", "Joseph Heller"); String s = obj.toString();another example of method overriding, consider the method equals(Object obj) defined by the Object class.to compare the state of two objects, overriding equals(Object obj) as shown below for LibraryItem:public class LibraryItem {public boolean equals(Object obj) { if (this == obj) return true; if ( ! (obj instanceof LibraryItem)) return false; LibraryItem item = (LibraryItem)obj; if ( this.id != item.id ) return false; if ( ! this.title.equals(item.title)) return false; return true; } }@override annotation - applied to methods that are intended to override behavior defined in a base class. annotation forces the compiler to check that the annotated method truly overrides a base class method. package domain;public class LibraryItem { @Override public String equals(Object obj) { ... } @Override public String toString() { ... }}
Abstract Classes & Interfaces
abstract class - class that is never intended to be instantiated as an object. Its purpose is to serve as a base class that provides a set of methods that together form an API. classes that inherit the abstract class can override its base behavior as necessary.Because the derived classes can be instantiated, they are referred to as concrete classes. This combination of an abstract base class and one or more concrete derived classes is widely used in industry and is known as the "Template" design pattern.class is identified as being abstract by pre-pending the keyword "abstract" to the class definition.package domain; public abstract class LibraryItem {}abstract keyword prohibits a LibraryItem from being instantiated with the "new" keyword. When a class is denoted as abstract, it typically means that one or more of its methods are also abstract, which implies they have no implementation.method is declared to be abstract by using the "abstract" keyword:public abstract boolean validate();there's no {...} following the signature; rather, a semicolon is present. method must not have an implementation following its signature, the enclosing class must be declared to be abstract.implementation of validate() in one of the concrete derived classes: Book.package domain;public class Book extends LibrarayItem { public boolean validate() { if (id <= 0) return false; if (title == null || title.equals("")) return false; if (author == null || author.equals("")) return false; if (pages <= 0) return false; return true; }}another technique for declaring "abstract" interfaces by way of the "interface" keyword:package domain;public interface IValidator { public boolean validate();}interface construct is used to capture zero or more method signatures without specifying their implementation details. methods enclosed within an interface definition must be "abstract" in the sense that they must not provide an implementation (i.e., {...}), but the abstract keyword is not necessary.interfaces are implemented in classes with the "implements" keyword. User and Login are not defined as abstract since implementations are provided for the validate() method.package domain; public abstract class LibraryItem implements IValidator { public abstract boolean validate();}uniform interface for validating objects.package domain;public class User implements IValidator { public boolean validate() { }}package domain;public class Login implements IValidator { public boolean validate() { }}while Java does not support multiple class inheritance , it does support the implementation of multiple interfaces in a single class.To serialize Login objects across a secure network Login class needs to implement the Serializable interface. package domain;public class Login implements IValidator, Serializable {...} Serializable does not contain any methods, known as a Marker Interface. Marker interfaces, used to "mark" classes (and hence their objects) as "one of those," but without any additional methods. In summary, interface constructs are used to separate interface abstractions from implementation details.
Inner & Anonymous Classes
Inner classes are defined within the context of another class.package domain; public class Book extends LibraryItem implements AuthorableItem, PrintedMaterial { BookReader reader = new BookReader(); // .rest of Book definition public String nextLine() { return reader.readNextLine(); } // Note that this is not a "public" class- //only an instance of Book can access the BookReader class BookReader { public BookReader() { } public String readNextLine() { // Implementation of this method. } } // BookReader } // BookAnonymous classes are also inner classes that are defined within the context of another class, but these classes do not have a name, hence the name anonymous. Anonymous inner classes are often used as event handlers in the implementation of graphical user interfaces.
Associations
allow classes (and their objects) to form relationships with one another. These relationships facilitate object collaboration. two types of associations:"Has a" relationships: Abstracts/models the concept of containment (e.g., a Customer has an Account; or in other words, the Customer contains an Account)."Uses a" relationships: Abstracts/models the concept of using (e.g., a Workflow manager uses various services to accomplish a task [to get some work done])."has a" relationship with another class if it has a data member of that particular type. package domain;public class User { private Account account = new Account();}abstracting a Login class that contains the user's credentials (username, password) and associating it with the User by declaring Login data member:package domain;public class User { private Login login = new Login(); private Account account = new Account();}Once you declare a data member as an object type, you have essentially created a "has a" relationship between the two objects."uses a" relationship, only difference between a "has a" and "uses a" relationship is where the declaration is made. "uses a" relationships are defined within method declarations (and not as data members of the enclosing class). So for instance, suppose a particular method needs to use a Date object to timestamp a message:package domain;public class Logger { public generateLogMessage(String message) { Date date = new Date(); }}The above method instantiates a Date object locally within the scope of the method, not as a data member (at the class/object level). "uses a" relationship. So we can summarize "has a" and "uses a" relationships as follows:"Has a" relationships are realized as object declarations located at the class level (i.e., as data members)."Uses a" relationships are realized as object declarations located within the scope of a method.
Arrays
Group (or collection) of items that are the same type. declares an array object, daysOfWeek, as an array of seven String objects: String [ ] daysOfWeek = new String[7];assign the seven elements as follows:daysOfWeek[0] = "Sunday";daysOfWeek[1] = "Monday";daysOfWeek[2] = "Tuesday";daysOfWeek[3] = "Wednesday";daysOfWeek[4] = "Thursday";daysOfWeek[5] = "Friday";daysOfWeek[6] = "Saturday";values could be initialized at the point of declaration:private String [ ] daysOfWeek ={"Sunday", "Monday", "Tuesday", "Wednesday" , "Thursday", "Friday", "Saturday"};The size of the array is available via the length property (e.g., daysOfWeek.length), allowing you to iterate through its values in a "for loop":for (int i = 0; i<daysOfWeek.length; i++) { System.out.println(daysOfWeek[i]);}Array downside, once declared, their size is fixed. Can create a new, larger array and move the contents of the first array into the second, but that is clumsy. Typically used only for grouping items whose size is fixed.
Java Collection Framework
Group of interfaces, classes, and algorithms that together provide a rich set of abstractions for grouping objects. Maps - A collection whose entries are accessed by some unique identifier.Lists - A collection whose entries can be accessed with an index.Sets - A collection whose entries are guaranteed to be unique.Queues - A collection whose entries are ordered, based on some scheme.
Maps
supports the ability to add and retrieve items from a collection using a key value pair. The key (K) is the lookup identifier and the value (V) is the item being looked up. The methods for inserting/retrieving items in/out of the Map are put(...) and get(...). General accounts - For general public use.Business accounts - For commercial organizations.Nonprofit accounts - For nonprofit organizations.The above account types can be abstracted as a Java enum (enumerator):enum AccountType {general, business, nonprofit};Each user is allowed to have one account of each type. Accounts for a given user could be contained in a Map data structure where the key for each account is one of the above enum values (general, business, or nonprofit) as shown below:Account generalAccount = new Account();Account businessAccount = new Account();Account nonprofitAccount = new Account();//...Map<AccountType, Account> accountsMap = new HashMap<AccountType, Account>();accountMap.put(AccountType.general, generalAccount);accountMap.put(AccountType.business , businessAccount);accountMap.put(AccountType.nonprofit , nonprofitAccount);Retrieval of the accounts from the map is then achieved with the key:Account generalAccount = accountMap.get(AccountType.general);Account businessAccount = accountMap.get(AccountType.business);Account nonprofitAccount = accountMap.get(AccountType.nonprofit);In summary, the key is used to place values in the map and also to retrieve values from the same map. advantage, code readily accommodates additional account types. simply add to the enum type:enum AccountType {general, business, nonprofit, government, education};
Iterable Interface
base interface for all interfaces of the Java collection framework (excluding Map). Iterable defines exactly one method, namely:Iterator iterator();This allows you to get an Iterator for iterating over the elements of a collection. Since all other collection interfaces extend Iterable (either directly or indirectly), they all inherit the above method; that is, they all provide an iterator for iterating over their elements. For example, the Collection interface directly extends Iterable, and hence, if you have a Collection, you can get an iterator to iterate over its elements:Collection<Book> coll = getOverdueBooks();Iterator<Book> iter = coll.iterator();while (iter.hasNext()) { Book book = iter.next();}Because the need to iterate over all items in a collection is a common practice, the method iterator() is placed in the base interface Iterable, and then through inheritance, it's made available to all collections that extend Collection (because Collection extends Iterable). The extension of Iterable by Collection (and then List, Set, and Queue) is known as interface inheritance.
Collection Interface
general abstraction for a collection of objects. It provides a handful of methods that operate over all interfaces that extend Collection. <<interface>>Collection+add(E) : boolean+addAll(Collection) : boolean+clear() : void+contains(Object) : boolean+containAll(Collection) : boolean+isEmpty() : boolean+remove(Object) : boolean+size() : intJava API does not provide any direct class implementations of interface Collection. Instead, implementations are provided for interfaces that extend Collection, namely, List, Set, and Queue. Nevertheless, the Collection interface is often used to pass collections around since it represents the base behavior of all collections. We'll now take a look at List, Set, and Queue and see how they might be used in our Library application.
List Interface
represents an ordered sequence of objects. That is, elements are added to the list in a particular order, and the list maintains that order.suppose we have a List, booksCheckedIn, which contains all the books that are checked-in on a given day. Then, if we add books to the list as they are checked-in, the list will maintain the order in which they were checked-in.private List booksCheckedIn = new ArrayList();public void checkin(Book book) { booksCheckedIn.add(book);}Implementations of the List interface include ArrayList, LinkedList, Stack, and Vector. List collections do not check for duplicate entries, so if an object is added multiple times, it will appear in the list multiple times (i.e., have multiple entries). Therefore, if it's important for a given object to appear only once in the collection, the Set interface should be used as explained below.
Set Interface
represents a collection of objects with no duplicates. By default, duplicates are identified by their equals(Object) method whose default behavior is defined in the root class Object. In other words, if equals(Object) is not overridden, object references will be used to determine if list entries are equal. If this behavior is not desired, equals(Object) needs to be overridden in the class for which objects are added to the set. A portion of the Set API is shown below.<<interface>>set+add(E) : boolean+addAll(Collection) : boolean+clear() : void+contains(Object) : boolean+containAll(Collection) : boolean+isEmpty() : boolean+remove(Object) : boolean+size() : intsuppose the Library system has a business rule that prevents users from checking out more than one copy of a given book. During the checkout process, the user's books could be added to a Set collection where duplicate books are not added to the set.private Set booksCheckedOut = new HashSet();public boolean checkout(Book book) { return booksCheckedOut.add(book); }The above method returns true if the book is not already in the set; otherwise, it returns false. If false is returned, the user would be notified that the duplicate book could not be checked out.Implementations of the Set interface include HashSet and TreeSet. The order of elements in a Set depends on the underlying implementation, and thus, will vary across implementations. If order is important, the interface SortedList should be used.
Queue Interface
represents an ordered collection based on some known order: e.g., first in first out (FIFO), last in first out (LIFO, a.k.a. a stack), priority. A subset of the Queue API is shown below (not including the methods inherited from interface Collection).<<interface>>Queue+element() : E+offer(E) : boolean+peek() : E+poll() : E+remove() : Eorder of the queue is determined by the implementing class. Classes that implement the Queue interface include LinkedList and PriorityQueue.As an example, suppose the Library system solicits user suggestions, and these suggestions need to be processed in a FIFO basis. private Queue suggestions = new LinkedList(); public void addSuggestion(Suggestion suggestion) { suggestions.add(suggestion); }The above method adds the new Suggestion to the Queue. Because the implementing class is a LinkedList, each suggestion is added to the end of the queue.
Exception Handling
events (e.g., errors) that disrupt the normal flow of execution. Examples of software exceptions:- Dividing by zero.- Using an unassigned object reference (that points to null) to invoke a method.- Failure to open/read/write/close a file.- Failure to open/read/write/close a socket connection.- Database errors.when a program executes, described as a call stack, ordered list of the active methods called up to the current point in time. stack starts with the main entry point and documents the active methods that are currently under call.once an exception occurs, it must be handled, or the program aborts. the JVM marches through the call stack looking for the nearest handler for the exception. If one is found, control is transferred. Otherwise, the program terminates.
Defining Exceptions
exceptions are classes that extend the class Exception either directly or indirectly. For example, just a few of the many exceptions defined by the Java API.public class ClassNotFoundException extends Exception {...}public class IOException extends Exception {...}public class NullPointerException extends Exception {...}public class NumberFormatException extends Exception {...}The Exception class, most of its behavior is inherited from a base class named Throwable, which defines a message (String) property and a corresponding accessor, getMessage(). defining a custom exception that denotes a failed login:public class LoginFailedException extends Exception { public LoginFailedException() { super(); } public LoginFailedException(String msg) { super(msg); }}when defining your own exceptions, provide at least two constructors, default constructor and a constructor that takes a message string as a parameter. In both cases, the base constructor of Exception is invoked using the keyword super.
Declaring Exceptions
required that if a method throws an exception without catching it, the exception must be declared in the method signature to notify users. method that authenticates logins, throws an exception named LoginFailedException without catching it:public bool authenticate(Login login) throws LoginFailedException {...}Any exception that occurs in a method must either be handled (caught) by that method or be declared in its signature as "throws" (see above). method throws (and does not handle) multiple exception types, instead of listing all the exceptions in the method signature, the base exception class Exception can be listed:public bool authenticate(Login login) throws Exception {...}declaration covers all possible exception types, and thus prevents you from having to list the individual exceptions when multiple exceptions can be thrown.
Throwing & Catching Exceptions
Exceptions can be thrown either by the Java API or by your code. To throw an exception examples:throw new Exception();throw new Exception("Some message goes here");throw new LoginFailedException("User not authenticated");Once an exception is thrown, the JVM starts looking for a handler in the call stack to transfer execution of the program. Exception handlers are declared in the context of a try/catch block.Catching ExceptionsJava supports the catching of exceptions in what's known as a try/catch block or also known as a try/catch/finally block. Syntax for a try/catch block:try { ...} catch (SomeException e) { ...}The interpretation of the try/catch block is the following: the statements between the try and catch are executed sequentially, and if no exception occurs, then execution continues with the first statement that follows the try/catch block. On the other hand, if an exception occurs while executing the statements between the try/catch, execution transfers to the catch block, and then once the catch block finishes executing, execution continues with the first statement after the try/catch block.
JSEJEEJMEJava Card
Java Standard Edition - Contains the core functionality of the Java language; used to develop desktop applications.Java Enterprise Edition - Provides additional functionality required of enterprise applications, including web applications.Java Micro Edition - A scaled-down version used for mobile phones and other handheld devices.Java Card - The smallest Java footprint used for integrated circuits (e.g., memory and microprocessor cards).
Java bytecode
A platform independent instruction set that's produced when Java source code is compiled.
Java Virtual Machine (JVM)
A platform-targeted runtime environment that knows how to execute Java bytecode.
The Java Runtime Environment (JRE)
A set of libraries that define the application programming interface (API) of the Java language. The JRE also contains the JVM application.
The Java Software Development Kit (JDK)
A set of command line tools (e.g., compilers, de-compilers, debuggers) used to develop Java programs. The JDK also contains the JRE, which contains the JVM.