Java Basics 1

  1. 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.
  2. Exceptions
    • if (n<0)
    • {
    • throw new IllegalArgumentException("negative n");
    • }
    • // ^Text Displayed to User
  3. 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
  4. 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;
  5. Java Bytecode
    • -What Java programs are compiled into.
    • -Can run on many different platforms.
    • -Executed in Java Runtimes
  6. 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;
    • }
  7. 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

    • public class Hello
    • {
    • }

    Saved as Hello.java
  8. Object Oriented Programming (OOP)
    -Program is a set of objects rather than a set of actions.
  9. 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
  10. 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
  11. State
    Set of values stored in an object (internal data).
  12. Behavior
    A set of actions an object can perform.
  13. 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 ^
  14. Comments
    -Document every class, method, constant, and variable.

    • /* Comment */
    • // Comment

    • /*
    • * Multiline Comment
    • */

    • /**
    • * JavaDoc
    • * Comment
    • */
  15. Statement
    • -Executable snippet of code representing a complete command
    • -Ends with ";" // Statement Terminator
  16. Main Method
    • public static void main(String[] args)
    • {
    • }
  17. Print to Screen
    System.out.println(); // Prints line with carriage return

    System.out.print(); // No carriage return, continues on same line
  18. Syntax Error
    "Grammar" errors such as forgetting a ";"
  19. Logic Error
    Code does not perform task as intended.
  20. Runtime Error
    Crashes program, such as divide by zero error.
  21. Expression
    Simple value (literal) or set of operations that produces a value.
  22. Evaluation
    Process of obtaining a result (value).
  23. Result
    A value obtained.
  24. 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
  25. String Literal
    • -Regular text enclosed by quotation marks.
    • -Must not span more than 1 line.
  26. Escape Sequences
    • \t Tab
    • \n New Line
    • \" Quotation Mark
    • \\ Backslash
  27. 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
  28. 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
  29. 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";
  30. Scope
    -For variables, extends from right curly brace to the left curly brace.
  31. Local Variable
    • -Declaring variable in the innermost scope.
    • -Declared in method and only accessible to that method.
  32. Declaration
    -Request to set aside a new variable with a given type and name (case sensitive).

    • double x;
    • int a, b, c;
  33. Assignment
    -Expression on right is evaluated and is stored in the variable.

    • x = 3 + 5;
    • x = y + z;

    -Variables can be declared and assigned in one statement.

    • int x = 15 / 3;
    • int a = 3, b = 5, c = 10;
  34. Relational Operators
    • == Equal to
    • != Not Equal to
    • < Less Than
    • > Greater Than
    • <= Less Than or Equal
    • >= Greater Than or Equal
  35. 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
  36. 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
  37. Precondition
    -Must be true before a method executes to guarantee it can perform a task.

    -Document such as //pre: n>=0
  38. 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
  39. Nested if/else
    • if(<test>)
    • {
    • <statement>;
    • }else if(<test>)
    • {
    • <statement>;
    • }
    • else
    • {
    • <statement>;
    • }
  40. 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
    • {
    • }
  41. 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
  42. switch
    int x = 3;

    • switch (x)
    • {
    • case 1: y=5;
    • break;
    • case 2: y=3;
    • break;
    • default: y=1;
    • break;
    • }
  43. 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-
  44. Control Structure
    A Syntactic structure that controls other statements. (For, While, Etc)
  45. 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!");
    • }
  46. 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.
  47. 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
    • }
  48. 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
    • }
  49. 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
  50. 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++)
  51. Exception
    • -Runtime error that prevents a program from continuing normal execution.
    • -These are "thrown" when the error occurs.
  52. Immutable
    -Once strings are constructed, their values cannot be changed.
  53. 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);
  54. 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
  55. Package
    • -Collection of related Java classes
    • -java.awt, java.util, etc.
  56. 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
  57. Value Semantics/Types
    Values stored directly and copying creates independent copies of the values.
  58. 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.
  59. 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.
  60. Whitespace
    Spaces, Tabs, Newline Characters
  61. 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
    • }
  62. Sentinel
    Special value that signals the end of input (ie -1, q, defined by programmer)
  63. 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)
  64. 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
  65. 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)
    • {
    • }
  66. 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);
  67. 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);
  68. Forever Loop
    • while (true)
    • {
    • <statement>
    • // Use break
    • }

    -OR-

    • for (;;)
    • {
    • <statement>
    • // Use break
    • }
  69. Client Code
    Code that interacts with a class or objects of that class.
  70. Instance Of A Class
    • -Created Objects by using a constructor.
    • -One Class can create multiple objects
  71. 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;
  72. Encapsulation
    • -Protecting an object's data from outside access.
    • -Hiding the implementation details of an object from the clients of the object.
  73. 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
    • {
    • }
    • }
  74. Record / Struct
    Object that contains state, but no behavior.
  75. 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.
  76. 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);
  77. Accessor
    • -Instance method that provides information about the state of an object without modifying it.
    • -Generally return values.
    • -Read Only
    • -IE. p1.distanceFromOrigin();
  78. 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;
    • }
  79. Abstraction
    Focusing on essential properties rather than inner details.
  80. 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();
  81. 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.
Author
cmrjets
ID
11532
Card Set
Java Basics 1
Description
Basic Java Definitions & Examples
Updated