Java Fundamentals
Java Fundamentals
Preface
This is based on my learning style. Projects and practice problems are recommended.
Note: If you are planning to use this document AFTER Spring 2023, please make a
copy of it before then; I can’t guarantee that it won’t be deleted after that point.
Missing Topics (in no specific order):
● Wrapper classes (parse, MAX/MIN, ArrayLists) Extra (not AP CS A)
● for-each loops (and when not to use them) ● try/catch blocks
● == vs equals(), reference (address comparison) vs object (content comparison) ● Escape sequences
○ Literal vs. Constructor (both String and arrays) ● ternary operator (condensed if-else)
○ reference type diagrams ● clone()
○ floating-point error w/ == ● interface vs abstract class
● ArrayLists ● sorting algorithms (selection, insertion, merge, quick, etc.)
● 2D Arrays/Lists ● time complexity: Big O Notation
● common errors (Index, Null, param, etc.) ● Hashing, Linked Lists, Trees, Graphs
● superclasses & subclasses ● VarArgs
○ abstract & protected
■ subclass inherits but cannot directly access private members
○ calling methods (+super())
○ polymorphism
○ The first line of every constructor is a call to the superclass’ constructor
○ Cannot typecast to type that the object is not an instance of
○ declaration determines whether it CAN use a method, but the constructor used
determines WHICH method it uses (overridden)
■ e.g. Bird birb = new Parrot(...), where Parrot is subclass of Bird; Parrot methods
will override Bird methods that have the same name
○ “The rule of thumb is: When super is used, find the method in the superclass. But if that
method calls a method that’s been overridden in the subclass, go back there for the
overridden method.”
● scope (changing a parameter won’t change an argument if the argument is of an immutable type)
Helpful Comparisons for Teaching
variables - labels for values
syntax - grammar
semicolon - period
class - basically designing your own non-primitive data type; instantiating a class by
making an object effectively creates a variable whose behavior is defined by the class
(blueprint, fill-in-the-blank template)
Distinguishing Vocabulary
● class - blueprint for objects determining how they behave and their characteristics
● object - instance of a class (thing defined by the class)
○ Note: arrays are also objects, objects aren’t only class instances
● method: functions in a class
○ constructor: method used to create objects
● parameter: type of data than can be referred to in a method (variable used to define value used in
method)
● argument: values plugged into parameters when method is called
● variable: containers that store a value
○ “data type” (regarding value stored by variable): type of value a variable can hold
○ “variable type” (regarding scope of access to the variable): local variable (declared in class, in
method), instance variable (declared in class, not in method, aka member/field), class variable
(declared in class, not in method, also has static modifier)
○ field: variable that is a class member
○ Convention: variable names should be named appropriately based on purpose
Distinguishing Vocabulary (continued)
Note: This is just to clear up confusion as you come across other sources. Don’t stress
about drilling this vocabulary into your head. Keep in mind that these terms may not
be precisely interchangeable in the context of other programming languages.
● Note: variableName refers to the object, it is not the object itself (but it may just be called the object for
easier understanding)
● String is an object but can be initialized two ways
○ Note: Generally, use string literals (String str = “bob”;). Using object references will lead to different
properties (see “Comparing Objects”).
The Scanner Class
● Scanner class contains methods that allow you to take user input and store it into variables
● import java.util.Scanner;
● Scanner sc = new Scanner(System.in); //initialization, argument is an object
● sc.nextInt(); //returns user input as int
● sc.nextLine(); //returns user input as String
● Note: If you switch between the two, you have to use sc.nextLine() for a pause.
The String Class
● String is a unique class (initialization using String literal), but variables of String data type are still
referring to objects
● Each character of a String has an index, starting from 0
○ Example: “bob” has char ‘b’ at index 0
● variable1.equals(variable2) //where variable1 and variable2 both refer to an instance of the same class
○ for comparing any two objects of the same type, not just String
● substring(int a, int b) returns a String that includes characters of indices a to (b-1) of the original String
● substring(int a) returns a String that includes all indices from a to the end of the original String
● charAt(int a) returns a char at the specified index of the original String
● length() returns the number of characters in a given String
● Other useful methods: indexOf, toUpperCase, compareTo, split, etc.
● Exercise: CodingBat practice! Check out String-1 questions.
Comparing Objects
● == compares references, while equals() compares objects
● Example with String object (special, can initialize 2 ways):
○ String str1 = “bob”;
○ String str2 = new String(“bob”);
○ System.out.println(str1 == str2); //returns false, two separate objects (this has to do with how Java’s
storage works)
○ System.out.println(str1.equals(str2)); //returns true, objects are equivalent
● TLDR: Generally, you want to use equals() when comparing objects. Don’t try using ==, as you will get
confused.
Declaring Classes
● class ClassName {
○ //class members here
● }
● Typically, the class with the main method in it must have the same name as the
java file
○ Note: This is not true if you have two classes each with their own main
methods, and you have compiled the java file to create their class files.
● If the class is public (at most one per java file), it must have a main method and
the file name must be same
Class Members
● Instance Variables/Fields
○ copied by all objects of the class
● Class Variables/Fields (static, global)
○ only one copy used by all objects
● Methods (can be static)
○ functions that can be called by objects
● Constants (static + final)
○ variables that cannot be reassigned (also only one copy)
Important Keywords for Classes and Class Members
● Access Modifiers
○ public: visible to the world
■ Note: Generally, use public unless you specifically don’t want the method to be accessible
outside the class
■ Note: Each source file can only have at most one public class, of which the name must be the
same as that of the file
○ private: visible to only the class
○ none = defaults to package-private: visible to the package (named group of related classes)
■ Note: No package declaration = default/unnamed package
○ other: protected
● Non-Access Modifiers
○ static: same for all objects, class level (used for variables, methods, nested classes, and blocks)
○ final: cannot reassign a variable, override a method, or extend a class
○ other: abstract, synchronized, volatile
● Convention: Access Modifiers, then Non-Access Modifiers in declaration
Declaring Methods
● public static int myMethod(String param1, int param2) {
○ //method body here
● }
● Modifiers + Return Type + Method Name + Parameters
● Note: Generally, use public unless you specifically don’t want the method to be
accessible outside the class
● Note: No parameters = does same thing to any given object
● Note: No static = default non-static
Return Types
● Return types can be primitive type, reference type, or void
● Method body must end with return statement with proper data type unless return
type is void
● Note: Can have return statements in the middle of the body, but return statement
at end is always required if not void
Static vs. Non-Static Methods
● static method = class method, class-level
● non-static method = instance method, instance-level
Calling Methods
● Calling a class method in the same class
○ No instance/class name needed
● Calling a instance method in the same class
○ In instance method: no instance/class name needed (object defaults to this)
○ In static method: need instance
● Calling a class method from a different class
○ Need class name that contains the static method
○ Note: You can technically use an instance instead, but you typically won’t
● Calling a instance method from a different class
○ Need instance
● Note: When calling a static method, you generally need a class name (class-level). When calling an
instance method, you generally need an instance (instance-level).
● Note: The main method is a special static method. You can technically call it, but you typically won’t.
Calling Methods (continued)
● Flowchart
● With instance example:
○ ClassA placeholder = new ClassA(arg1, arg2);
○ placerholder.myMethod(arg3, arg4);
● With class name example:
○ ClassA.myMethod(arg1, arg2); //myMethod is in ClassA
● Note: When calling any method with reference type arguments, you need an
instance to pass as an argument (if you are calling an instance method from a
different class that has reference type arguments, you can create an instance and
use it both to call the method AND to pass as an argument)
The “this” Keyword
● this serves as a placeholder for an object
● Used to distinguish instance variables and parameters with the same name
● Default object when you call an instance method within an instance method in
the same class (so you don’t need an initialized instance)
● Note: Also used to emphasize use of instance variables in instance methods, even
if not technically needed.
Instance Variables and Constructor Methods
● Constructors are called to create class instances (objects) and/or initialize instance variables
○ Note: Can have multiple in a class - different initial states of objects
● private int age; //instance variable
● private int height; //instance variable
● public Class(int age, int height) { //constructor and class name are same
○ this.age = age;
○ this.height = height;
● }
● Note: Instance variables are typically private so they can only be directly accessed from the class
● Note: No parameters = cannot reassign initial values of instance variables when initializing object
● Note: You could alternatively just have different parameter names instead of using this
● See “Creating Variables of the Data Type Class” for how to call the constructor method
Omitting the Constructor Method
● No constructor = default constructor containing no code
● You may use no constructor if you just want to use the object to call methods
other than the constructor
● If desired, you can still initialize the instance variables using other methods
Accessors and Mutators
● Accessors are methods for giving public access to private instance variables (get)
● Mutators are methods for modifying instance variables that have been initiated
(set)
Class Variables (Static/Global Variables/Fields)
● public static int variableName = 0;
● Only one copy used for all objects (each object does not have its own copy)
● Call using Class.variableName after making an object of Class
○ Note: Don’t need class instance or class name if you are calling the static
variable in a static method that is in the same class (similar to “Calling
Methods”)
Constant Variables
● public static final int VARIABLE_NAME = 0;
● Class variable that cannot be reassigned
● Convention: Variable names for constants are fully capitalized
with underscores to separate words.
Overloading and Overriding (WIP)
● Overloading is writing a method with the same name as another method but is
differentiated by different parameters (both can be used depending on arguments
passed)
● Overriding is writing a method with the same name and the same parameters as a
predefined method to redefine it (only overriding method is used by default)
Arrays (WIP)
● Arrays are a category of non-primitive data types (see “Non-Primitive/Reference Data Types”).
● datatype[] arrayName = new datatype[length]; //length is an int
● datatype can be primitive or non-primitive (e.g. int, String, etc.)
● length is how many indices the array will have
○ Note: Array length cannot be changed after initialization.
● Like a String’s characters, the index numbers start from 0
● Array elements have a default value
○
● Arrays.toString()
Beyond AP CS A
Lambda Expressions (Anonymous Functions)
(parameters) -> expression
● where E is non-primitive datatype. You can exclude <E> to allow stack to hold different
datatypes
● last-in-first-out (think deck of cards; also defines sequential order)
● push(element) add appends element to top of stack
● peek() returns top element
● pop() removes/returns top element
● search(element) returns position from end (last/top element is 1) or -1 if not in stack
● empty()
The Queue Interface
Note: Interface is abstract blueprint of class.