💻AP Computer Science A
9 min read•Last Updated on June 18, 2024
Avanish Gupta
Kashvi Panjolia
Avanish Gupta
Kashvi Panjolia
The Big Takeaway Of This Unit
💡**Objects** Objects are instances of classes and we can write methods to manipulate these objects.
Java is what is known as an object-orientated programming language, or OOP for short. What is this object-orientated programming, and why is it so important to Java? This is the first of three units emphasizing object-orientated programming (the others are Units 5 and 9, covering classes and inheritance respectively). This unit, we will be learning about objects, the cornerstone of object-orientated programming, and what they are. There are four principles of object-orientated programming: abstraction (partly covered in this unit, also in Unit 5), encapsulation (covered in Unit 5), inheritance, and polymorphism (both covered in Unit 9).
In this unit, you'll learn how to write your first methods (functions in other programming languages), which perform a specific class. You'll also learn how to use methods from the Math and String classes, which will allow us to work more with numbers and text. These will make the foundations of all future units. Finally, you'll learn about objects, which are reference types: combinations of other data types that allow us to represent actual items and situations.
Java is an object-orientated programming language, which means that most major programs in Java are about the manipulation of objects. What are objects? Objects are a reference type, which refers to how they are combinations of other primitive and reference data types. When you refer to them, you are not referring to the actual object itself, but where it is stored in data.
How do we know what combination of primitive and reference types each object has? This is due to the help of a class. A class is like a template that defines what an object is like and what the object can do. A class is basically the guidelines for a type of object, and an object is a particular instance of that class. We can think of a class as a blueprint for a house, and the object is a particular house. Different houses are different objects. The different houses may look different, but they have the same general features and functions. This is how classes and objects work.
2.2 Creating and Storing Objects (Initialization)
To create an object, we call the object's constructor. Every class must have a constructor, and if you do not create one, it will have a default constructor that is empty. If we use the analogy that a class is like a blueprint for an object, the constructor, when called, is the architect that makes the blueprint come to life. The constructor takes in parameters, which are the attributes of the object (name, age, etc), and when called, those parameters can be assigned specific values to create the object. Here is an example constructor and initialization of a car object:
Car(String brand, String model, int year) Car flash = new Car("BMW", "X7", 2023);
Creating an object is similar to creating a variable: you start with the type, then enter the name of the object, and use the equals sign (assignment operator) to assign the object to a value. With objects, however, the "new" keyword is used to create a new object. It is important you include this keyword when you initialize objects; otherwise, you will simply point the object you created to another object.
Notice how the brand, model, and year were provided in the order they were written in the constructor. When calling methods and constructors, the order of the parameters matters. An IllegalArgumentException will arise if you enter the order of the parameters differently than they were provided in the constructor. In this case, the constructor stated the order needs to be (String, String, int), so if you entered (String, int, String), the program would crash, and this exception will display. The computer will not know what to do if you enter the parameters in a different order.
A class can have multiple constructors. This is called overloading a constructor. Each constructor must be different than the others. Since the constructor must only be named the name of the class, the constructors should be differentiated based on their parameters.
Null is another keyword in Java. You can instantiate an object as null, meaning there is no reference created and the object contains nothing. Here's how to do it:
Car lightning = null;
Be careful when you instantiate an object as null, because if you try to call a method on it or use it anywhere else, you will get a NullPointerException. This is an important exception, and it states that the computer cannot do anything with this object because, well, there is no reference to the object.
A method is made up of five main parts: the scope, the return type, the name, the parameters, and the body. This may sound like a lot, but it's very formulaic. We'll tackle methods with this example:
public void study(int hoursStudied) {
totalHours += hoursStudied;
}
The first word, public, defines the scope of the method. Public means that anyone that accesses your code after it has been published can see this method. The next word, void, defines the return type of the method. Void means the method returns nothing. The name of the method is study, and it is case-sensitive.
This method only has one parameter: hoursStudied, which is an int. When this method is called, the user will have to enter an integer defining the number of hours they studied for. Finally, the body of the method is the statement totalHours++; and it tells the computer what the method does. There may be a variable elsewhere in the class called totalHours that is being incremented by the amount of hoursStudied every time the method is called.
This method can be called on an object. Person bob = new Person("bob");
bob.study(2);
In this snippet, a new object of type Person was created, and the name parameter was passed in as "bob." Then, the study method was called on bob using dot notation. Dot notation is the usage of a period, or dot, to call a method on an object. The number of hours bob studied was 2 hours, so 2 was passed in as an argument to the study method.
Methods, like constructors, can be overloaded. This means the parameter list for each method that is overloaded must be different.
public void waterTracker(int numberOfGlasses)
public void waterTracker(String typeOfDrink)
The method waterTracker is overloaded because there are two methods with the same name. However, these two methods are still different because the first one takes an integer as a parameter and the second one takes a String as a parameter. Depending on what you pass in as the argument when called the waterTracker method, one of these two methods will be called. Remember to stay hydrated.🚰
2.5 Calling a Non-Void Method
In the study(int hoursStudied) method defined above, the return type was void, so nothing was returned. However, there are many different return types for methods in Java, and they can be both primitive and reference types. A method can return an int, String, boolean, double, Object, and other types of data. Implementing a non-void return type in a method is useful when we want to store the result of the method for later.
Each method that has a non-void return type must have a return statement at the end of the method. A return statement will tell the computer what is being returned by that method and will be the data we will store for later. The return statement must always be the last line in the method.
public double degreesToRadians(double degrees) {
double radians = degrees * (3.141 / 180);
return radians;
} In this method, the return type of the degreesToRadians method is a double, so we return the variable radians because it is a double. We can now store the value returned by this method in a variable like this:
double result = degreesToRadians(34.5);
The right side of the expression will evaluate to approximately 0.602, which will then become the value of the variable result. Pretty useful!
2.6 String Objects: Concatenation, Literals, and More
In Java, a String object is a sequence of characters. You can create a String object by using the String class's constructor.
String greeting = new String("What's up?");
However, the more efficient version is to use a string literal, which you learned about in the previous unit.
String greeting = "What's up?";
Since a String is an object, you can call methods on Strings like you would for any other object. Some common methods are .length() and .toLowerCase(). One special attribute of Strings is string concatenation. String concatenation is the process of combining two or more strings into a single string. You can concatenate strings using the + operator. Be sure to add a space between words because Java will not do that for you.
String greeting = "What's " + "up?";
Escape characters are characters that are used to represent certain special characters in a string. For example, the \n escape character is used to represent a new line in a string. Here is an example of a string with an escape character:
String greeting = "Hello,\nworld!";
This will output: Hello,
world!
2.7 String Methods
In Java, the String class has several methods that can be used to perform operations on strings. Some common String methods are:
2.8 Using the Math Class
The Math class is a class in Java that provides various mathematical functions and constants. You do not need to import this class; it is already included in the standard Java package. Some common methods of the Math class are:
abs(int a): This method returns the absolute value of the argument as an int or double, depending on whether you put in an int or double into the argument.
pow(double a, double b): This method returns the value of a raised to the power of b as a double.
sqrt(double a): This method returns the square root of the argument as a double.
random(): This method returns a random number between 0 (inclusive) and 1 (exclusive) as a double. The Math class also has constants you can use to increase your efficiency, such as Math.PI (approximately 3.14159).
5-7.5% of the AP exam
Roughly 2 to 3 multiple-choice questions
Making/Initializing Objects
Writing/Calling Methods
String Class
String Methods
Wrapper Classes
Math Class
length(): This method returns the length of the string.
indexOf(String str): This method returns the index of the first occurrence of the specified string in this string.
substring(int beginIndex): This method returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the end of the string.
substring(int beginIndex, int endIndex): This method returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
abs(int a): This method returns the absolute value of the argument as an int or double, depending on whether you put in an int or double into the argument.
pow(double a, double b): This method returns the value of a raised to the power of b.
sqrt(double a): This method returns the square root of the argument as a double.
random(): This method returns a random number between 0 (inclusive) and 1 (exclusive) as a double.
The abs() function is used to find and return the absolute value (magnitude) of an integer. It disregards any negative sign attached to it and always gives back its positive equivalent.
Term 1 of 27
The abs() function is used to find and return the absolute value (magnitude) of an integer. It disregards any negative sign attached to it and always gives back its positive equivalent.
Term 1 of 27
The abs() function is used to find and return the absolute value (magnitude) of an integer. It disregards any negative sign attached to it and always gives back its positive equivalent.
Term 1 of 27
Objects are instances of a class that represent real-world entities or concepts. They encapsulate data (attributes) and behavior (methods) into a single entity.
Classes: Classes are user-defined data types in object-oriented programming. They serve as blueprints for creating objects by defining their attributes and methods.
Attributes: Attributes are variables within an object that store data specific to that object.
Methods: Methods are functions within an object that define its behavior and allow it to perform actions.
Classes are user-defined data types in object-oriented programming. They serve as blueprints for creating objects by defining their attributes and methods.
Objects: Objects are instances created from classes. They represent individual entities with their own unique characteristics.
Inheritance: Inheritance is a mechanism in which one class inherits properties (attributes and methods) from another class, allowing for code reuse.
Encapsulation: Encapsulation is the concept of bundling data (attributes) and methods together within a class to hide implementation details from outside access.
Methods are functions defined within a class that perform specific tasks or actions when called upon by an object. They can manipulate data, interact with other objects, or return values.
Parameters: Parameters are variables used in method declarations to receive input values when the method is called. They allow methods to accept and work with different data.
Return Type: The return type of a method specifies the type of value that the method will return after its execution. It can be void (no return value) or any other data type.
Overloading: Method overloading is a feature that allows multiple methods within a class to have the same name but different parameters, enabling flexibility and code reusability.
Inheritance is a concept in object-oriented programming where a class inherits the properties and behaviors of another class. It allows for code reuse and promotes the creation of hierarchical relationships between classes.
Encapsulation: Encapsulation is the practice of hiding internal details and providing access to only necessary information through methods. It helps maintain data integrity and protects sensitive information.
Superclass: A superclass is the parent class in an inheritance hierarchy. It serves as a blueprint for creating subclasses that inherit its properties and behaviors.
Subclass: A subclass is a child class that inherits properties and behaviors from its superclass. It can add additional features or override existing ones inherited from the superclass.
Abstraction is the process of simplifying complex systems by focusing on essential features while hiding unnecessary details. It allows programmers to work with high-level concepts without worrying about implementation specifics.
Object-oriented programming (OOP): OOP is a programming paradigm that uses abstraction as one of its core principles. It enables developers to model real-world entities as objects with well-defined behaviors and attributes.
Interface: An interface defines a contract for how a class should behave, specifying a set of methods that must be implemented. It allows for abstraction by separating the definition from the implementation, enabling different classes to provide their own implementations.
Polymorphism: Polymorphism refers to the ability of an object to take on many forms. In programming, it allows objects of different classes to be treated as instances of a common superclass or interface, providing flexibility and extensibility.
Encapsulation refers to the bundling of data and methods within a class, where the data is hidden from external access. It ensures that an object's internal state remains consistent by controlling how it can be accessed or modified.
Object-oriented programming (OOP): OOP promotes encapsulation as one of its fundamental principles. It allows for modular design by grouping related data and behaviors together within classes.
Access modifiers: Access modifiers control the visibility and accessibility of members (variables or methods) in a class. They determine whether other parts of the program can access or modify those members directly.
Information hiding: Information hiding is closely related to encapsulation and involves restricting direct access to internal details of an object. By hiding information, we protect it from being accidentally modified or misused outside its intended scope.
Polymorphism refers to the ability of objects to take on multiple forms or have multiple types. In programming, it allows different objects to be treated as instances of a common superclass, enabling flexibility and extensibility.
Method Overriding: Method overriding occurs when a subclass provides its own implementation for a method that is already defined in its superclass. This allows for customization of behavior specific to each subclass.
Dynamic Binding: Dynamic binding refers to determining which implementation of an overridden method should be called at runtime based on the actual type of the object rather than its declared type. It allows for flexibility in method invocation.
Interface: An interface is a collection of abstract methods that define a contract for classes to implement. It enables polymorphism by providing a common set of methods that different classes can implement.
Reference types are data types in programming that store references or memory addresses rather than the actual values themselves. They include objects, arrays, and strings, and allow for dynamic memory allocation and manipulation.
Value Types: Value types are data types that directly store their values instead of referencing memory addresses. They include primitive data types like integers, booleans, and characters.
Null: Null is a special value that represents the absence of an object or no value assigned to a reference type variable. It indicates that the variable does not currently refer to any valid object.
Garbage Collection: Garbage collection is an automatic process performed by programming languages' runtime environments to reclaim memory occupied by objects that are no longer needed or referenced. It helps manage memory efficiently and prevent memory leaks.
The Math class in Java provides various mathematical operations and functions that can be performed on numeric data types. It includes methods for basic arithmetic operations, trigonometry, logarithms, random numbers generation, etc.
ceil(double d): This method returns the smallest integer greater than or equal to a given number.
pow(double base, double exponent): This method raises a number to the power of another number.
sqrt(double d): This method calculates and returns the square root of a given number.
A constructor is a special method within a class that is used to initialize objects of that class. It is called automatically when an object is created and helps set initial values for its attributes.
Class: A class is a blueprint or template for creating objects in object-oriented programming. Constructors belong to classes and define how objects of that class should be initialized.
Instance variables: Instance variables are attributes or properties associated with each instance (object) of a class. Constructors often assign initial values to these instance variables.
Overloading: Constructor overloading allows multiple constructors within the same class, but with different parameter lists. This provides flexibility in creating objects with varying initialization options.
Parameters are variables declared in a method or function that receive values when the method is called. They allow data to be passed into a method, enabling it to perform actions or calculations based on those values.
Arguments: Arguments are actual values passed into a method when it is called. They correspond to the parameters defined in the method's declaration.
Return type: The return type specifies the type of value that a method will return after its execution. Parameters help determine what inputs are needed for the method, while return types define what output can be expected.
Method signature: A method signature consists of its name and parameter list. It uniquely identifies a specific method within a class and helps differentiate it from other methods with similar names but different parameters.
The assignment operator is used to assign a value to a variable. It is represented by the equals sign (=) and it assigns the value on the right side of the equals sign to the variable on the left side.
Arithmetic operators: These are operators used for mathematical calculations such as addition (+), subtraction (-), multiplication (*), and division (/).
Comparison operators: These are operators used to compare two values or variables, such as greater than (>), less than (<), equal to (==), not equal to (!=).
Compound assignment operators: These are shorthand versions of assignment operators combined with other arithmetic or bitwise operations, such as +=, -=, *=, /=.
An IllegalArgumentException is an exception that occurs when a method receives an argument that is inappropriate or invalid for its intended purpose. It usually indicates that there was an error in how arguments were passed into a method.
NullPointerException: This is an exception that occurs when you try to use/access an object reference that points to null (no object). It's like trying to use an empty box without putting anything inside.
IndexOutOfBoundsException: This exception occurs when you try to access elements outside the valid range of indexes in arrays or collections. It's similar to trying to reach for something beyond the boundaries of your reach.
ArrayIndexOutOfBoundsException: This is a specific type of IndexOutOfBoundsException that occurs when you try to access an array element with an index that is outside the valid range of indexes for that array.
The length() method is used to find the number of characters in a string.
charAt(int index): This method returns the character at the specified index position in a string.
isEmpty(): This method checks if a string is empty or not and returns true or false accordingly.
trim(): This method removes any leading and trailing white spaces from a string.
The indexOf(String str) method is used to find the index position of the first occurrence of a specified substring within a larger string.
lastIndexOf(String str): This method finds the index position of the last occurrence of a specified substring within a larger string.
contains(CharSequence sequence): This method checks if a sequence of characters exists within another string and returns true or false accordingly.
replace(CharSequence target, CharSequence replacement): This method replaces all occurrences of one sequence with another sequence within a given string.
The substring(int beginIndex) method is used to extract part of an existing string starting from the specified beginning index up to (but not including) the end of the original string.
substring(int beginIndex, int endIndex): This method is used to extract part of a string starting from the specified beginning index up to (but not including) the specified ending index.
concat(String str): This method concatenates two strings together and returns a new string.
toLowerCase(): This method converts all characters in a string to lowercase.
The substring() method is used to extract a portion of a string based on the specified beginning and ending indexes. It returns a new string that contains the characters from the original string within the given range.
length(): This method returns the length of a string.
indexOf(String str): This method returns the index within this string of the first occurrence of the specified substring.
replace(char oldChar, char newChar): This method replaces all occurrences of a specified character in a string with another character.
The abs() function is used to find and return the absolute value (magnitude) of an integer. It disregards any negative sign attached to it and always gives back its positive equivalent.
max(int a, int b): This method returns the larger of two given integers.
min(int a, int b): This method returns the smaller of two given integers.
random(): This method generates a random number between 0.0 (inclusive) and 1.0 (exclusive).
The pow() function is used to raise a number (a) to the power of another number (b). It returns the result of a raised to the power of b.
Math.pow(a,b): This is the actual method call for using the pow() function in Java.
Exponentiation: Exponentiation refers to raising a base number to an exponent.
Logarithm: A logarithm is the inverse operation of exponentiation. It helps us find the exponent needed to obtain a certain value from a given base.
The sqrt() function calculates and returns the square root of a given number (a).
Math.sqrt(a): This is the actual method call for using the sqrt() function in Java.
Square root symbol (√): The square root symbol represents finding the value that, when multiplied by itself, gives us our original number.
Cube root: Similar to square roots, cube roots involve finding the value that, when multiplied by itself twice, gives us our original number.
The random() function generates and returns a pseudo-random decimal value between 0.0 (inclusive) and 1.0 (exclusive).
Math.random(): This is the actual method call for using the random() function in Java.
Pseudo-random: Pseudo-random refers to a sequence of numbers that appears to be random but is actually generated by an algorithm.
Random number generator: A random number generator is a mathematical function or device that generates a sequence of numbers with no discernible pattern or predictability.
Math.PI is a constant in the Math object of JavaScript that represents the ratio of the circumference of a circle to its diameter. It is approximately equal to 3.14159.
Math.sqrt: This method returns the square root of a number.
Math.random: This function generates a random number between 0 (inclusive) and 1 (exclusive).
Math.floor: This function rounds down a decimal number to the nearest whole number.