Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Java Fundamentals

This document provides guidance and materials for studying for the AP Computer Science A exam. It recommends partially completing an online Java course and focusing on topics listed in the course description. It also lists several topics that are important to study and understand for the exam.

Uploaded by

Arda Güler
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java Fundamentals

This document provides guidance and materials for studying for the AP Computer Science A exam. It recommends partially completing an online Java course and focusing on topics listed in the course description. It also lists several topics that are important to study and understand for the exam.

Uploaded by

Arda Güler
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

← back to Study Materials for Various APs

Preface
This is based on my learning style. Projects and practice problems are recommended.

If you’re taking AP CS A, I recommend partially doing Codecademy’s free Java course.


Pick the topics that are listed in the AP Course Description.

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.

● “Objects” are also sometimes called “instances”


● “Instance variables” are also called “member variables” or “fields”
● “Class variables” are also called “global/static variables”
In-Code Commenting
● Help show thinking and organize code
● //single line
● /*multiple
● lines*/
Numeric Primitive Data Types
● Integral
○ int
■ Integers
■ Size: 32 bits
○ Note: other types of integral data types include byte, char (unicode), short, and long (e.g. 10L)
■ Differ in bit size
● Floating-point
○ double
■ Can have decimals
■ Size: 64 bits
○ float (e.g. 3.14f)
■ Can have decimals
■ Size: 32 bits
○ Note: bit size with integral and floating-point data types do not determine the limits the same way
Other Primitive Data Types
● Primitive type boolean (not numeric)
○ true or false
● Note: char is technically an integral data type (unicode) but you will probably use
it for single characters like ‘a’ when interacting with strings
● Note: All primitive data types are predefined, not user-defined (the names “int”,
“boolean”, etc. are not created by the user)
Non-Primitive/Reference Data Types
● Non-primitive types (aka reference types): refer to objects, used to call methods, user-defined, fall under
three categories
○ Note: “class”, “array”, and “interface” are NOT the names of the data types, only categories of
non-primitive data types
○ class
■ String - special class that is predefined, not user-defined
■ Other than String, data type name is imported/created by user
○ array
■ Examples: int[], String[], MyClass[], etc.
○ interface
○ Names of the data types are user-defined (except for String)
■ Convention: all words capitalized
Declaring and Initializing Variables w/ Primitive Data Types
● Declaration (data type)
○ int i;
○ Multiple declarations in one line:
■ int a, b, c;
○ Convention: 1st word of variable name lowercase, subsequent words capitalized
● Initialization (must declare first, then apply value)
○ i = 0;
● Both in one line (declaration, then initialization):
○ int i = 0;
● Changing values (must initialize first):
○ int i = 0;
○ i = 1;
● Note: you can declare multiple variables in one line using only commas, but you cannot initialize multiple
variables in one line only using one equal sign
Data Type Conversion from Numeric to Numeric
● Use declaration and initialization:
○ int i = 1;
○ double d = i;
Data Type Conversion between String and Primitive
● Each primitive data type has a corresponding class
○ Integer, Float, Boolean, etc. (capitalized)
○ Each class wraps the value of a primitive type into an object (wrapper classes)
● To convert String to primitive types, use this method: Class.parseClass() (exception: Integer.parseInt())
● To convert primitive to String, add empty string
○ String str = (“”+9);
○ int i = Integer.parseInt(str);
○ double d = Double.parseDouble(str);
Arithmetic Operators
● + add (also used for Strings)
● - subtract
● * multiplication
● / division
○ integer division (rounds down) vs. double division (decimals)
■ Double division example: double d1 = (double) 5/7; //typecasting
● % remainder
○ int i = 6 % 5;
○ i=1
● Increment/decrement operators
○ i++;
○ i--;
● Compound assignment operators
○ basic operator w/ =
○ i += 1;
Comparison Operators
● == equals (notice the double equal signs; this is necessary)
● != not equals
● < less than
● > greater than
● <= less than or equal to
● >= greater than or equal to
● Return boolean
Logical Operators
● && and (true if both statements are true)
● || or (true if at least one statement is true)
● Note: && and || evaluate statements in left-to-right order.
● ! not (negates boolean after it, e.g. !(x>5) is false if x=6)
● All evaluate true or false
Dot/Member Operator
● . is used to access package/class members
● Example: System.out.println(“No.”);
○ The first dot operator accesses a class member (field) from System
○ The second accesses a class member (method) from System.out
Print
● System.out.print(“text”);
○ Prints and leaves the cursor at the end of the text
● System.out.println(“text”);
○ Prints and then moves cursor to the next line
● Exercise 1: Print the following, with each line of code corresponding to one sentence of text:
○ I am on Earth. I am a human being.
○ I eat food.
● Exercise 2: What will the following lines of code print?
○ System.out.print(“Bob”);
○ System.out.println(“ is about”);
○ System.out.print(“1092 feet”);
○ System.out.print(“ tall.”);
String Concatenation
● Use + operator
● String bob = “Bob”;
● String joe = “Joe”;
● String bobjoe = bob + “G. ” + joe;
● System.out.print(“My name is ” + bobjoe + “.”);
● Can also add char, such as ‘c’.
● Note: Basically never need the concat() method
Conditional Statements
● if tests condition
● else if tests different condition if “if” condition is false
● else is executed if all of the above are false
● Note: can have multiple comparison operators in a condition by using logical operators; in that case each
statement is evaluated one by one in left-to-right order
● if (x<5 && x>0) { //will first evaluate x<5, then x>0 if and only if x<5 is true (otherwise logical operator
evaluates as false)
○ //stuff
● } else if (x>5) {
○ //stuff
● } else {
○ //stuff
● }
For Loops
● If you know how many times you will loop, use for
● for (int i = 0; i < b; i++) { //don’t forget semicolons
● }
● In this case, the loop iterates b times (doesn’t iterate when i==b)
○ Not all for loops will look like this (different initial value, different direction, different operators,
etc.)
● Example:
● for (int i = 0; i < num; i++) {
○ System.out.println(i);
● }
● Exercise: Print out “12345678910” using a for loop.
While Loops
● If you don’t know how many times you will loop, use while
● while (condition) {
● }
● Keeps iterating as long as the condition is true
● Note: If you use && or ||, statements will be evaluated in left-to-right order.
● Logical operator to negate condition:
● while (!condition) { //keeps iterating as long as condition is false
● }
● Example:
● while (num % 7 != 0) num++; //since the body here is only one line, the whole loop can be written on one
line
● Convention: Don’t write one-line loops. Even if you don’t use curly brackets, hit “enter” and indent to
make it two lines so it is easier to read.
The Math Class
Math Class Presentation (not mine)
Importing Classes
● Only if the class you need is not already included
○ java.lang and the package you are working in are automatically imported
● import java.util.Scanner;
○ java.util is a package: named group of related classes (Scanner is a class in the package)
● import java.util.*; //imports all classes from the java.util package
Creating Variables of the Data Type Class (Object References)
● Class variableName = new Class(arg1, arg2);

Data type Creates instance Arguments


(object)

Declaration Initializes object by calling


constructor method

● 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

● no return value, just value

for longer code:

(parameters) -> {codeblock}

● return statement needed


The Stack Class
import java.util.stack

Stack<E> stack = new Stack<E>();

● 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.

first-in-first-out (think waiting line)

Can be implemented by LinkedList or PriorityQueue


Useful Websites
● Repl.it for free in-browser coding
● Codecademy has a free course for a good introduction to Java + cheatsheet summaries
● CodingBat for practice problems sorted by topic and difficulty
● Java Documentation for finding methods of classes
○ click most recent version, go to API Documentation, use the search bar for quick navigation
● Stack Overflow for coding questions (Google and then try to find Stack Overflow results)
● Java in VSCode
Learning Python from Java
Big Difference Between Java/Python and C++
In C++ VARIABLES ARE ASSIGNED WITH VALUE/SHALLOW COPY by default
(without extra operators), unlike Java/Python where variables holding objects (not
primitive types) are REFERENCE VARIABLES by default (assigning new variable to a
variable holding an object just makes the new variable with the same “reference value”
(address of same object), i.e. both variables are aliases for the SAME OBJECT).

You might also like