-
Scanner
import java.util.Scanner; // Put on top line
- Scanner console = new Scanner(System.in); //"console" can be any name desired
- int n = console.nextInt();
- double n = console.nextDouble();
- String name = console.next(); //Next Token
- String fullName = console.nextLine(); //Next Whole Line
// Scanner uses whitespace to separate tokens.
-
Exceptions
- if (n<0)
- {
- throw new IllegalArgumentException("negative n");
- }
- // ^Text Displayed to User
-
Construct Object
- public class Point
- {
- int x,y; //Two Integers Declared (Fields)
- }
- Point origin = new Point(); //origin may be any name
- origin.x = 7; // First Field
- origin.y = 5; // Second Field
-
Class Constant
- - Named value that cannot be changed and whose scope is the entire class.
- - All uppercase
- - Use keyword "final"
public static final int WIDTH = 20;
-
Java Bytecode
- -What Java programs are compiled into.
- -Can run on many different platforms.
- -Executed in Java Runtimes
-
Return
- -Send a value out as the result of a method that can be used in an expression.
- -Void methods do not return any value.
- -Must be last statement in method.
- public static double cost(double price, int quantity)
- {
- double subtotal = price * quantity;
- return subtotal;
- }
- public static boolean state(int x, double y, char z)
- {
- if ...
- return true;
- }
-
Class
- -Basic unit of code
- -Nothing can exist outside of this
- -Name must match filename
- -Name begins with a capital letter
- -A category or type of object
Saved as Hello.java
-
Object Oriented Programming (OOP)
-Program is a set of objects rather than a set of actions.
-
Short Circuited Evaluation
-Property of && (and) and || (or) that prevents the second operand from being evaluated if the overall result is obvious from the value of the first operand.
if (5>10 && 6==6)...
-5 is not greater than 10, so the evaluation stops here, since both have to be true
if (5==5 || 6>7 || 4==4)...
-5 equals 5, so the evaluation stops here, since any have to be true
-
Object
- -Programming entity that contains state and behavior.
- -Also known as an instance of a class
- -Capitalized name
- -To call a method (behavior), you write the variable (state), a period, and then the name of the method
- Point p = new Point(5, 10); // Point contains two variables x & y
- p.translate (-1,+3); // Subtracts 1 from x coordinate & adds 3 to y coordinate
- p.x = 35; // Changes x coordinate of Point to 35
-
State
Set of values stored in an object (internal data).
-
Behavior
A set of actions an object can perform.
-
Operator Precedence
- -Evaluated from Left to Right
- -Listed below from highest precedence to lowest:
- Unary !, ++, --, +, - // Not, Increment, Decrement, +5, -2
- Multiplicative *, /, % //% is Mod AKA Remainder
- Additive +, -
- Relational <, >, <=, >=
- Equality ==, !=
- Assignment =, +=, -=, *=, /=, %=
- Logical AND &&
- Logical OR || XOR ^
-
Comments
-Document every class, method, constant, and variable.
-
Statement
- -Executable snippet of code representing a complete command
- -Ends with ";" // Statement Terminator
-
Main Method
- public static void main(String[] args)
- {
- }
-
Print to Screen
System.out.println(); // Prints line with carriage return
System.out.print(); // No carriage return, continues on same line
-
Syntax Error
"Grammar" errors such as forgetting a ";"
-
Logic Error
Code does not perform task as intended.
-
Runtime Error
Crashes program, such as divide by zero error.
-
Expression
Simple value (literal) or set of operations that produces a value.
-
Evaluation
Process of obtaining a result (value).
-
-
Casting
- -If java expects a double & gets an int, it adds a decimal to the int automatically.
- -If java expects an int & gets a double, it truncates the decimal.
- -To cast, put the desired type in parenthesis
- double v = 4.75;
- (int) v * 3; // Evaluates to 12
(int) 4.75; // Evaluates to 4
-
String Literal
- -Regular text enclosed by quotation marks.
- -Must not span more than 1 line.
-
Escape Sequences
- \t Tab
- \n New Line
- \" Quotation Mark
- \\ Backslash
-
Method Overloading
- -Two or more different methods with the same name, but different parameters
- -Both in class, but will be called based on actual parameter.
- public static void printName(String fName, String lName)
- {}
- public static void printName(String fName)
- {}
- printName("John", "Doe"); //Calls first version
- printName("John"); // Calls second version
-
Identifier
- -Name given to entity in a program such as a class or method.
- -Must start with a letter or underscore, or $
- -Case SeNsItIvE!
- -Classes begin with uppercase - "GeometricCalculator"
- -Methods begin with lowercase and subsequent words capitalized - "calculateArea"
- -Variables begin with lowercase and subsequent words capitalized - "circleDiameter"
- -Constants are all uppercase - PI
-
Primitive Types
- int x = 3;
- double y = 7.625;
- char a = 'a', b = 'B', c = '!'; // Use single quotes
- boolean on = true, off = false;
**String is not actually a primitive type, but an object. String name = "Bob";
-
Scope
-For variables, extends from right curly brace to the left curly brace.
-
Local Variable
- -Declaring variable in the innermost scope.
- -Declared in method and only accessible to that method.
-
Declaration
-Request to set aside a new variable with a given type and name (case sensitive).
-
Assignment
-Expression on right is evaluated and is stored in the variable.
-Variables can be declared and assigned in one statement.
- int x = 15 / 3;
- int a = 3, b = 5, c = 10;
-
Relational Operators
- == Equal to
- != Not Equal to
- < Less Than
- > Greater Than
- <= Less Than or Equal
- >= Greater Than or Equal
-
Method
- -Program unit representing one particular action/computation.
- -Behavior each object can execute.
public static void drawCircle(int radius)
- public - available to all
- static - procedural rather than object oriented
- void - returns nothing (return type - ie. double, int, boolean)
- int Radius - formal parameter & is local to method
drawCircle(5); // Calls method drawCircle with an Actual Parameter (Argument) of 5
-
Boolean
-Primitive whose only value is true or false.
- boolean test1 = true;
- boolean test2 = false;
- test1 = test2; // test1 now set to false
- test1 = (2+2 == 4); //test1 now set to true
- test2 = (3*100 < 250); //test2 set to false
-
Precondition
-Must be true before a method executes to guarantee it can perform a task.
-Document such as //pre: n>=0
-
Postcondition
-Condition that method guarantees will be true after it finishes executing, as long as preconditions are true.
-Document such as //post: returns n factorial
-
Nested if/else
- if(<test>)
- {
- <statement>;
- }else if(<test>)
- {
- <statement>;
- }
- else
- {
- <statement>;
- }
-
Exclusive OR
-One or the other is true, but not both.
^ XOR
- true ^ true // false
- true ^ false // true
- false ^ true // true
- false ^ false // false
- if((x>y)^(x>z)) // Only x>y OR x>z for this test to evaluate to true
- {
- }
-
Field
- -Variable inside an object that makes up part of its internal state.
- -Declared inside of {} for class
- -Every object of that class contains this variable
-
switch
int x = 3;
- switch (x)
- {
- case 1: y=5;
- break;
- case 2: y=3;
- break;
- default: y=1;
- break;
- }
-
Logical Operators
- ! // Not operator reverses truth value of operand
- != // Not Equal
- !(2==2) // false
- && // AND
- (2==2) && (3<4) //True
- || // OR
- (1<2) || (2==3) //True
- p---q---p&&q---p||q
- T---T-----T--------T-
- T---F-----F--------T- //Truth Table
- F---T-----F--------T-
- F---F-----F--------F-
-
Control Structure
A Syntactic structure that controls other statements. (For, While, Etc)
-
For Loop
- -Used when you know exactly how many times the loop should iterate (definite loop)
- -Evaluated at the "top" of the control structure
- for (<initialization>; <continuation test>; <update>)
- {
- statement; // Body Of Loop
- }
- for (int i = 1; i <= 5; i++)
- {
- System.out.println("Hi There!");
- }
-
Control Variable
- -Variable in a loop that controls the number of iterations.
- -Can be declared outside of the loop to extend scope.
- -If declared in the loop, the scope is limited to the loop only.
- -Should not use the same control variable for nested loops.
-
Nested For Loop
- for (int i = 1; i <= 5; i++) // Iterates 5 times & prints a line of *s
- {
- for (int j = 1; j <= 5; j++)
- {
- System.out.print("*"); // Iterates 5 times & prints out a *
- }
- System.out.println(); // Carriage Return
- }
-
Pseudocode
- -Using description of a desired action rather than the code itself
- -Can be used to design/organize a program
- -Is replaced by java when program is actually written
- for (each of 20 lines)
- {
- draw a line of 5 asterisks
- }
-
Useful Methods of String Objects
String s = "Hello"
- charAt(index) s.charAt(1) returns "e" //Index starts at 0
- endsWith(text) s.endsWith("llo") returns "true"
- indexOf(text) s.indexOf("o") returns "4"
- length() s.length() returns "5"
- startsWith(text) s.startsWith("hi") returns "false"
- substring(start,stop) s.substring(1,3) returns "el" // returns from start to just before stop index
- toLowerCase() s.toLowerCase() returns "hello" // creates new string with all lower case
- toUpperCase() s.toUpperCase() returns "HELLO" //creates new string with all upper case
-
Index
- -Integer used to specify a location in a sequence of values
- -Usually begins at 0
- -When used to specify a substring, the first index is the character you wish to start with & the last index is ONE PAST the character you wish to end with. (i.e. i = first ; i < last; i++)
-
Exception
- -Runtime error that prevents a program from continuing normal execution.
- -These are "thrown" when the error occurs.
-
Immutable
-Once strings are constructed, their values cannot be changed.
-
Constructor
- -Method that creates and initializes an object.
- -Use keyword "new" followed by the object's type and any necessary parameters.
- -Always have the same name as the class
- Point p = new Point(2, 6);
- Point p2 = new Point(4, 10);
-
Useful Methods Of Point Objects
- translate (dx, dy) // translates x & y by given amounts (d) [p.translate(-3, +4);]
- setLocation(x, y) // sets the coordinates to the given values) [p.setLocation(16, 32);]
- distance(p2) // returns the distance from this point to point p2
-
Package
- -Collection of related Java classes
- -java.awt, java.util, etc.
-
Import Declaration
- -Request to access a specific Java package
- - * is a wildcard and will allow you to import all classes in a package
- import java.awt.*; // Grants access to all classes in .awt
- import java.util.Scanner; // Grants access to util.Scanner only
-
Value Semantics/Types
Values stored directly and copying creates independent copies of the values.
-
Reference Semantics/Types
- -References to values are stored and copying only copies the reference, not the values.
- -Objects work with references to data rather than the data itself.
-
Parameter
- - Becomes copy of whatever is passed in the call to the method.
- method (int x){ change x}
- y=5;
- method(y); // the value of y is copied into x, x is changed but y is not
- method (Point p) { manipulates p}
- Point test = new Point(2,3);
- method (test); // test refers to the coordinates (values) 2,3 but what is passed to method is test, a
- --------------// reference to 2,3 not the actual values. p becomes a COPY of test. Now when
- --------------// p is manipulated, those values are changed. Since test is a reference to those
- --------------// values, it refers to the new values as well.
-When you pass an object as a parameter, you can change the object itself, but you can't change the variable that points to the object.
-
Whitespace
Spaces, Tabs, Newline Characters
-
While Loop
- -Used for when you do not know how many times a loop should iterate, if at all (indefinite loop).
- -Terminates when test evaluates to "false"
- -Variable is declared outside of loop
- -Tests at the top of the loop
- while (<test>)
- {
- <statement>;
- }
- int count = 1;
- while (count < 100)
- {
- System.out.println(count);
- count ++; // Be careful to include this or you'll get an infinite loop
- }
-
Sentinel
Special value that signals the end of input (ie -1, q, defined by programmer)
-
Pseudorandom Number
Number generated from predictable & well-defined algorithms, but mimic the properties of numbers chosen at random.
- 0.0 <= Math.random() < 1.0
- or
- java.util.Random
- Random r = new Random();
- result = r.nextInt(10) // Generates random number between 0 & 9 (one less than 10)
-
Useful Methods Of Random Objects
- nextInt() // return integer between -231 and (231-1)
- nextInt(max) // return integer between 0 and (max-1)
- nextDouble() // return real number between 0.0 (inclusive) and 1.0 (exclusive)
- nextBoolean() // return logical value of true or false
-
Priming A Loop
- -Initializing variables before a loop to guarantee that the loop is entered.
- -Often set to a "dummy" value so that it does not affect processing
- int count = 0;
- while (count < 10)
- {
- }
-
Do While Loop
- -Used when you do not know how many iterations are needed (indefinite loop), but it should run at least once.
- -Tests at the bottom of the loop, therefore always runs at least once
- do
- {
- <statement>;
- } while (<test>); // Do Not Forget This Semicolon!
- int number = 0;
- do
- {
- number++;
- System.out.println(number);
- } while (number <= 10);
-
Using break To Exit A Loop
- Scanner console = new Scanner(System.in);
- int sum = 0;
- while (true)
- {
- System.out.println("Next integer (-1 to quit)?"); // -1 is a Sentinal
- int number = console.nextInt();
- if (number == -1) {
- break;
- }
- sum = sum + number;
- }
- System.out.println(sum);
-
Forever Loop
- while (true)
- {
- <statement>
- // Use break
- }
-OR-
- for (;;)
- {
- <statement>
- // Use break
- }
-
Client Code
Code that interacts with a class or objects of that class.
-
Instance Of A Class
- -Created Objects by using a constructor.
- -One Class can create multiple objects
-
Field
- -Data stored in an object
- -Declared the same as a normal variable, but in the {} of the class
- -Scope is entire class
- -Every object of this class contains this variable (Field)
- -AKA instance variable, data member, attribute
- public class Point
- {
- int x; // Field
- int y; // Field
- }
- Point origin = new Point (); //defaults to 0,0
- Point destination = new Point(87, 100);
- int a = origin.x;
- int b = origin.y;
- int c = destination.x;
- int d = destination.y;
-
Encapsulation
- -Protecting an object's data from outside access.
- -Hiding the implementation details of an object from the clients of the object.
-
Instance Method
- -A method inside an object that operates on that object.
- -Do not have "static" keyword
- public <type> <name> (param)
- {
- <statement>;
- }
- public class Point
- {
- int x;
- int y;
- public void translate (int dx, int dy) // Instance Method
- {
- }
- }
-
Record / Struct
Object that contains state, but no behavior.
-
Implicit Parameter
- -Object being referenced during an instance method call
- -IE. if you define two Point objects p1 and p2 and then call p1.translate(5,4) it translates the parameters referenced by p1 implicitly.
-
Mutator
- -Instance method that modifies an object's internal state
- -Generally assigns a new value to one or more of the object's fields
- -Read/Write
- -IE. p1.translate(5,3);
-
Accessor
- -Instance method that provides information about the state of an object without modifying it.
- -Generally return values.
- -Read Only
- -IE. p1.distanceFromOrigin();
-
Constructor Syntax
- -When a class does not have a constructor, it is supplied with a "default" constructor with no parameters.
- -Header begins with keyword "public" followed by the class name & parameters.
- public <class name> (params)
- {
- }
- public Point (int initialX, int initialY)
- {
- x = initialX;
- y = initialY;
- }
-
Abstraction
Focusing on essential properties rather than inner details.
-
Private Fields
- -Use keyword "private"
- -Visible to all code inside the class but not outside, so you cannot directly refer to these fields from client code.
- -The only way to pass these values to the client is through accessors (Read Only).
private <type> <name>;
- private int y;
- private int x = 3;
- public int getX() // This accessor is public. It reads x (private) and passes to client.
- {
- return x;
- }
- Client obtains value by calling method getX()
- firstPoint = p1.getX();
-
Class Invariant
- -Assertion about an object's state that is true for the lifetime of that object.
- -Should be treated as an implicit postcondition of every instance method of the class.
- -May also add proconditions to constructors and mutator methods of the class.
|
|