1/54
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Accessor method
method that accesses an object, but does not change it
ex. getTotal and getCount
return the value of an instance (or static) variable to the user, method header should contain the return type in place of the keyword void
Actual parameter (actual arguments)
actual values or expressions that are passed to a method when it is called. Actual arguments should match the data type and order of the formal parameter
public class Example {
// Method definition with formal parameters x and y
public int add(int x, int y) {
return x + y;
}
public static void main(String[] args) {
Example obj = new Example();
int num1 = 10;
int num2 = 20;
// Method call with actual parameters num1 and num2
int sum = obj.add(num1, num2);
System.out.println("The sum is: " + sum); // Output: The sum is: 30
// Method call with literal values as actual parameters
int anotherSum = obj.add(5, 7);
System.out.println("The sum is: " + anotherSum); // Output: The sum is: 12
}
}
x and y are the formal parameters, while the actual digits are the actual parameters
API (Application programming interface)
a code library for building programs
API documentation: info about each class in the java library
Argument
a value supplied in a method call, or one of the values combined by an operator
any values the method needs to carry out its task
enclosed in parentheses, multiple arguments separated by commas
argument types
int, float, double, boolean, char, byte, short, long
Array
A collection of values of the same type stored in contingous memory locations, each of which can be accessed by an integer index
can hold primitive types like int, char, float, and objects
objects, indexing starts at 0
Declaration: specific element type followed by [] and array name
int[] intArray; // Declares an integer array
String[] stringArray; // Declares a String array
Instantiation: instantiated using new keyword, specifying the size of array
intArray = new int[10]; // Creates an integer array of size 10
stringArray = new String[5]; // Creates a String array of size 5
Initialization: arrays can be initialized at the time of declaration or after instantiation
// Initializing at the time of declaration
int[] initializedIntArray = {1, 2, 3, 4, 5};
// Initializing after instantiation
for (int i = 0; i < intArray.length; i++) {
intArray[i] = i * 2;
}
Accessing elements: array elements are accessed using their index within square brackets []
int firstElement = initializedIntArray[0]; // Accesses the first element (value: 1)
stringArray[2] = "Hello"; // Assigns "Hello" to the third element
Multi-dimensional arrays: java supports multi dimensional arrays, which are arrays of arrays
int[][] multiArray = new int[3][4]; // 3 rows, 4 columns
multiArray[1][2] = 10; // Assigns 10 to the element at row 1, column 2
Array List
a java class that implements a dynamically resizable array of objects, when you write a program that collects input, you don’t always know many inputs you will have. In this situation, an array list offers 2 advantages
can grow and shrink as needed
supplies method for common tasks, such as inserting and removing elements
just more flexible
ex. import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Creating an ArrayList of Strings
ArrayList<String> names = new ArrayList<>();
// Adding elements to the ArrayList
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Accessing elements
System.out.println("First name: " + names.get(0)); // Output: Alice
// Modifying elements
names.set(1, "David");
// Removing elements
names.remove(2);
// Iterating through the ArrayList
System.out.println("Current names:");
for (String name : names) {
System.out.println(name);
}
}
}
ASCII (American Standard code for information interchange)
a character encoding system used to represent text in computers and other devices. Assigns a unique numerical value to each character, including letters, numbers, punctuation marks, and other symbols. Each character is represented by a 7-bit binary code
Assignment
placing a new value into a variable. you use the assignment statement to place a new value into a variable
int age = 30; // Assigns the value 30 to the variable age String name = "John Doe"; // Assigns the string "John Doe" to the variable name double pi = 3.14159; // Assigns the value 3.14159 to the variable pi boolean isEmployed = true; // Assigns the value true to the variable isEmployed
Java also supports compound assignment operators, which combine an arithmetic or bitwise operation with assignment. For example:
Java
int x = 10;
x += 5; // Equivalent to x = x + 5, x is now 15
x -= 3; // Equivalent to x = x - 3, x is now 12
x *= 2; // Equivalent to x = x * 2, x is now 24
x /= 4; // Equivalent to x = x / 4, x is now 6
binary
numbering system using base-2 which means it uses only two digits: 0 and 1, important for how computer store data
bit
short for binary digit
smallest unit of data in computing 0 or 1
are stored within larger data types
a byte = 8 buts
short = 16 bits
int = 32 bits
long = 64 bits
boolean (java type)
primitive data type that can have true or false values
used in conditional statements like if, else if, and else and in loops like while or for to control execution flow based on certain conditions
boolean isRaining = true;
boolean isSunny = false;
if (isRaining) {
System.out.println("Take an umbrella.");
} else if (isSunny) {
System.out.println("Wear sunglasses.");
} else {
System.out.println("Enjoy the weather!");
}
Boolean expressions are expressions that evaluate to either true
or false
. They often use comparison operators (e.g., ==
, !=
, >
, <
, >=
, <=
) and logical operators (e.g., &&
(AND), ||
(OR), !
(NOT)
int x = 10;
int y = 5;
boolean isEqual = (x == y); // isEqual will be false
boolean isGreater = (x > y); // isGreater will be true
boolean expression
A boolean expression in Java is an expression that evaluates to a boolean value, which can be either true
or false
. These expressions are fundamental in programming for making decisions and controlling program flow. Boolean expressions often involve comparison operators, logical operators, and boolean variables.
Comparison Operators
Comparison operators compare two values and return a boolean result:
==
(equal to)
!=
(not equal to)
>
(greater than)
<
(less than)
>=
(greater than or equal to)
<=
(less than or equal to)
Java
int x = 10;
int y = 5;
boolean isEqual = x == y; // false
boolean isGreater = x > y; // true
Logical Operators
Logical operators combine or modify boolean expressions:
&&
(logical AND): Returns true
if both operands are true
.
||
(logical OR): Returns true
if at least one operand is true
.
!
(logical NOT): Returns the opposite of the operand's value.
Java
boolean a = true;
boolean b = false;
boolean andResult = a && b; // false
boolean orResult = a || b; // true
boolean notResult = !a; // false
Examples of Boolean Expressions
Java
int age = 20;
boolean isAdult = age >= 18; // true
int score = 75;
boolean isPassing = score > 60 && score <= 100; // true
String name = "Alice";
boolean isEmpty = name.isEmpty(); // false
boolean isEven = 10 % 2 == 0; // true
boolean isOdd = 7 % 2 != 0; // true
Boolean expressions are commonly used in control flow statements like if
, else if
, else
, while
, and for
loops to make decisions based on conditions.
Java
int temperature = 25;
if (temperature > 20) {
System.out.println("It's warm.");
} else {
System.out.println("It's cool.");
byte (java type)/byte
primitive data type representing a 8-bit signed two’s complement integer. It can store whole numbers ranging from -128 to 127 (inclusive). the byte type is useful for conserving memory in large arrays or when dealing with binary data or streams
cast
process of converting a variable’s data type from one type to another. its essential for situations where operations between different data types are necessary or when dealing with inheritance and polymorphism
implicit (widening) casting → automatic conversion
when smaller data type is converted to a larger data type, conversion is performed automatically by the complier w/o any explicit instruction from the programmer
int intValue = 10;
double doubleValue = intValue; // Implicit casting from int to double
System.out.println(doubleValue); // Output: 10.0
explicit (narrowing) casting → manual conversion
larger data type converted to smaller data type, requires explicit direction to not loose data
double doubleNum = 9.78;
int num = (int) doubleNum; // Explicit casting from double to int
System.out.println(num); // Output: 9
Casting can be done with objects, in the context of inheritance
upcasting
converting a subclass reference to a superclass reference, done implicitly
downcasting
converting a superclass reference to a subclass reference, requires explicit casting, can lead to ClassCastException if the object is not an instance of the target subclass
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting (implicit)
animal.eat(); // Output: Animal is eating
Dog dog = (Dog) animal; // Downcasting (explicit)
dog.bark(); // Output: Dog is barking
}
}
char (java type)
primitive data type that represents a single 16-bit unicode character. used to store characters including letters, numbers, symbols, and special characters
A char value must be enclosed in single quotes ‘K’
different from string!, string is sequence of characters
char is a primitive type, while string is a class
checked exception
checked at compile time usually out of program’s control, external to the program’s immediate logic
ex. i/o errors, file not found, network errors
must either be caught in a try catch or declared using throw
represent recoverable error conditions
class
blueprint for creating objects
it encapsulates data (fields or attributes) and methods (actions or behaviors) that define the characteristics and capabilities of objects of that class
keywords like public, private, or protect that control visibility and accessibility of the class and its members
class level variable
command line arguments
the line the user types to start a program in a terminal window. it consists of the program follow by an necessary arguments
allow users to provide input to the program directly from the command line → accessed within the main method of a java program as an array of strings
public static void main(String[] args) {
// Code to access and use command-line arguments
compiler
a program that translates code in a high level language (such as Java) to machine instructions (such as bytecode for the java virtual machine)
computer science
study of algorithms including 1) their formal and mathematical properties 2) their hardware realizations 3) their linguistic realizations 4) their applications
concatenation
place one string after another to form a new string → use + operator to concentrate 2 string
stringfN= “harry”
stringIN= “morgan”
string name = fN + IN
constructor
a sequence of statements for initializing a new instantiated object
many classes have more than one constructor, this allows you to declare objects in different ways
a constructor has no return type, not even void
block of codes similar to the method. called when an instance of the class is created, special type of method used to initializedo object
class MyClass {
int x;
String s;
// Default constructor
public MyClass() {
x = 0;
s = "default";
}
// Parameterized constructor
public MyClass(int x, String s) {
this.x = x;
this.s = s;
}
public static void main(String[] args) {
MyClass obj1 = new MyClass(); // Calls the default constructor
MyClass obj2 = new MyClass(10, "hello"); // Calls the parameterized constructor
}
}
data type
specify the type of value that a variable can hold
primitive and non primitive
prim: byte, short, int, long, float, double, char, boolean
nonprim: string, array, class, interface, enum
declare
statement that announces the existence and characteristics of a program entity, such as a variable, method, or class to the compiler
do not allocate memory or define the entity’s behavior, but rather establish it’s identity and properties
int age;
int add (int a, int b); // declares a method that add that takes 2 integers and returns a integer
double (java type)
prim data type used to represent double-precision
storing decimal w/ a higher degree of precision and a wider range of values compared to float
encapsulation
the hiding of implementation details: the process of providing a public interface, while hiding implementation details
integrating data (variables) and code (methods) into a single unit
declare class variable as private and providing public getter and setter methods to access and modify the variables
getters: retrieve the values of variable
setters: allow them to be changed
exception (java type)
a parameter of a method other than the object on which the method is invoked
explicit paramater
a parameter of a method other than the object on which the method is invoked
parameters explicitly mentioned in method declaration
parameter declared w/in the parentheses of a method definition. represents a value that must be provided as an argument when the method is called. parameters are explicit bc they’re clearly and directly specified in the method’s signature
file
a sequence of bytes that is stored on disk
float (java type)
a number that can have a fractional part
prim data type
floating point number
number is one where the position of the decimal point “float” rather than being in a fixed position in #
for loop
neatly groups the initialization condition, and update expressions together. however it is important that these expressions are not executed together
the initialization is executed once before the loop is entered
the condition is checked before each iteration, if it is true the loop body is executed, if condition is false, the loop terminates
the update is executed after each iteration
Types of for
Loops
Basic for
loop: The most common type, used when the number of iterations is known.
Enhanced for
loop (for-each loop): Used to iterate over elements in an array or collection.
Java
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
Nested for
loop: A for
loop inside another for
loop, often used for multi-dimensional arrays.
Java
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
When to use for
loop
When the number of iterations is known before the loop starts.
When iterating over arrays or collections with a known size.
When performing repetitive tasks with a defined number of repetitions.
formal parameter
declared in the method signature, defining the types and names of the data the method expects to receive. They are essentially variables within the scope of the method
public class Example {
// Method definition with formal parameters 'name' (String) and 'age' (int)
public static void printInfo(String name, int age) {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
String myName = "Alice";
int myAge = 30;
// Method call with actual parameters 'myName' and 'myAge'
printInfo(myName, myAge); // Output: Name: Alice, Age: 30
String anotherName = "Bob";
int anotherAge = 25;
printInfo(anotherName, anotherAge); // Output: Name: Bob, Age: 25
}
}
garbage collection
form of automatic memory management where the JVM reclaims memroy occupied by objects that are no longer in use
if else
control flow structure that allows the program to execute different blocks of code based on specified condition
it provides a way to make decisions in the code, enabling different actions depending on whether a condition is true or false
if statements evaluates a boolean expression. if the expression is true, the code block w/in statement is executed
the else block is option, if omitted and the condition is false, the program simply continues to the next statement after the if block
implicit parameter
the object on which a method is invoked
do not actually write the implicit parameter in the method declaration
refers to the object an which a non static method is called
implicitly passed as this → provides a reference to the current object, allowing the method to access its instance variables and other methods
immutable
object whose state cannot be modified after it is created
that once an instance of an immutable class is created, its data members values remain constant through its lifetime
cannot be subclassed
private and final keywords ensure that the fields cannot be modified after the object is created
inheritance (in java)
allows one class to inherit the properies and methods of another class
key OOP
refers to superclass and subclass
good for code reusability
child and parent relationship
initialize
assigning an initial value to a variable or object when its declared or created, setting a variable to a well-defined value when it is created
int CansPerPack = 6;
instance
variable defined in a class for which every object of the class has its own value, specify instance variables in the class declaration
instance variable
variable defined in a class for which every object of the class has its own value, specify instance variables in the class declaration
public class counter {
priv int value:
public class Car {
// Instance variables
public String model;
private int year;
protected String color;
// Constructor
public Car(String model, int year, String color) {
this.model = model;
this.year = year;
this.color = color;
}
// Method to display car details
public void displayDetails() {
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Color: " + color);
}
public static void main(String[] args) {
// Creating two Car objects
Car car1 = new Car("Sedan", 2023, "Red");
Car car2 = new Car("SUV", 2024, "Blue");
// Accessing and displaying instance variables
car1.displayDetails(); // Output: Model: Sedan, Year: 2023,
car2.displayDetails(); // Output: Model: SUV, Year: 2024,
}
}
instantiation
process of creating an object of an instance of a class
allocating memory for the new object and initializing its field using a constructor
new keyword is used to instantiate a class, when new is used, constructor of the class is called
instance method
method that requires an instance (object) of a class to be invoked. it operates on the specific instance it is called upon, allowing access and modification of the object’s attributes (instance variables). instance methods are defined w/o the static keyboard
method w/ an implicit parameter; that is, a methd that is invoked on an instance of a class
public void setName (String name)
this name = name;
int (java type)
long (java type)
main method
method signature
object
object (java type)
object reference
object oriented programming
overloading