Podcast
Questions and Answers
What is Java?
What is Java?
Java is a programming language created in 1995 and owned by Oracle. It runs on many devices and is used for mobile apps, desktop apps, web apps, servers, and databases.
Java is case-insensitive.
Java is case-insensitive.
False (B)
What is the main method in Java?
What is the main method in Java?
The main method is the entry point of a Java program.
Which of the following are examples of Java primitive data types?
Which of the following are examples of Java primitive data types?
What is object instantiation?
What is object instantiation?
What is type casting in Java?
What is type casting in Java?
What is the difference between widening and narrowing type casting?
What is the difference between widening and narrowing type casting?
The ____ statement executes a block of code if a condition is true.
The ____ statement executes a block of code if a condition is true.
What is the purpose of a switch
statement?
What is the purpose of a switch
statement?
The break
statement is not important to exit the switch block after a match.
The break
statement is not important to exit the switch block after a match.
Describe the purpose of a for
loop.
Describe the purpose of a for
loop.
What is a while
loop used for?
What is a while
loop used for?
What is the difference between a while
loop and a do-while
loop?
What is the difference between a while
loop and a do-while
loop?
What does the break
statement do in a loop?
What does the break
statement do in a loop?
What is the function of the continue
statement in a loop?
What is the function of the continue
statement in a loop?
Describe the use of an enhanced for
loop (for-each loop).
Describe the use of an enhanced for
loop (for-each loop).
What are arrays used for?
What are arrays used for?
What is a single-dimensional array?
What is a single-dimensional array?
What is a multi-dimensional array?
What is a multi-dimensional array?
What is a Java method?
What is a Java method?
The void
keyword indicates that the method returns a value.
The void
keyword indicates that the method returns a value.
What is a parameter in a Java method?
What is a parameter in a Java method?
What are arguments in a Java method?
What are arguments in a Java method?
What is Object-Oriented Programming (OOP)?
What is Object-Oriented Programming (OOP)?
What is a class in OOP?
What is a class in OOP?
What is an object in OOP?
What is an object in OOP?
What is inheritance in OOP?
What is inheritance in OOP?
What is polymorphism in OOP?
What is polymorphism in OOP?
What is abstraction in OOP?
What is abstraction in OOP?
What is encapsulation in OOP?
What is encapsulation in OOP?
Which of the following are key features of encapsulation?
Which of the following are key features of encapsulation?
Which of the following are examples of data structures for storing elements?
Which of the following are examples of data structures for storing elements?
ArrayList uses a doubly linked list to store elements?
ArrayList uses a doubly linked list to store elements?
LinkedList provides Random Access with O(1) time complexity to access elements using index?
LinkedList provides Random Access with O(1) time complexity to access elements using index?
Flashcards
What is Java?
What is Java?
A programming language created in 1995, used for mobile, desktop, and web applications.
Java Case Sensitivity
Java Case Sensitivity
Java distinguishes between uppercase and lowercase characters.
Class Declaration
Class Declaration
A Java program starts with a class definition.
Main Method
Main Method
Signup and view all the flashcards
Comments in Java
Comments in Java
Signup and view all the flashcards
Variables
Variables
Signup and view all the flashcards
Primitive Data Types
Primitive Data Types
Signup and view all the flashcards
Reference Data Types
Reference Data Types
Signup and view all the flashcards
Control Flow
Control Flow
Signup and view all the flashcards
Object Instantiation
Object Instantiation
Signup and view all the flashcards
Methods
Methods
Signup and view all the flashcards
Packages
Packages
Signup and view all the flashcards
Exception Handling
Exception Handling
Signup and view all the flashcards
Integral Types
Integral Types
Signup and view all the flashcards
Character Types
Character Types
Signup and view all the flashcards
Boolean Type
Boolean Type
Signup and view all the flashcards
Floating-Point Types
Floating-Point Types
Signup and view all the flashcards
Widening (Implicit) Casting
Widening (Implicit) Casting
Signup and view all the flashcards
Narrowing (Explicit) Casting
Narrowing (Explicit) Casting
Signup and view all the flashcards
If-Else Statement
If-Else Statement
Signup and view all the flashcards
Switch Statement
Switch Statement
Signup and view all the flashcards
For Loop
For Loop
Signup and view all the flashcards
While Loop
While Loop
Signup and view all the flashcards
Do-While Loop
Do-While Loop
Signup and view all the flashcards
Break Statement
Break Statement
Signup and view all the flashcards
Continue Statement
Continue Statement
Signup and view all the flashcards
Enhanced For Loop (for-each)
Enhanced For Loop (for-each)
Signup and view all the flashcards
Arrays
Arrays
Signup and view all the flashcards
Single-Dimensional Array
Single-Dimensional Array
Signup and view all the flashcards
Multi-Dimensional or 2D Array
Multi-Dimensional or 2D Array
Signup and view all the flashcards
Arrays Class
Arrays Class
Signup and view all the flashcards
Varargs
Varargs
Signup and view all the flashcards
Java Method
Java Method
Signup and view all the flashcards
Method Overloading
Method Overloading
Signup and view all the flashcards
Parameter
Parameter
Signup and view all the flashcards
Arguments
Arguments
Signup and view all the flashcards
Study Notes
Basic of Java
- Java was created in 1995 and is owned by Oracle
- Java runs on over 3 billion devices
- Java is used for mobile apps (Android), desktop apps, web apps, servers, databases, etc
Java Syntax
- Java is case-sensitive
- A Java program begins by the definition of a class using
class declaration
- The keyword
public
makes the class accessible outside its package - The
main method
is the point where the program starts executing
Core Elements
Comments
are single-line (//
) or multi-line (/* */
)Variables
hold data and needs to be declared with a type and an identifierData types
can be primitive (int, double, boolean, etc.) or reference types (String, custom classes)Control flow
statements includeif
,else
,for
,while
,switch
Object instantiation
uses thenew
keywordMethods
are declared in classes and can return valuesPackages
organize code and import classesException handling
usestry
,catch
,finally
, andthrow
statements
Data Types
Integral types
includebyte
,short
,int
, andlong
Characters
are represented bychar
andString
Boolean type
isboolean
Floating-point types
arefloat
anddouble
Type Casting
Widening (implicit) casting
automatically converts smaller data types to larger ones (e.g.,int
todouble
)Narrowing (explicit) casting
converts larger data types to smaller ones, which may lead to loss of precision.
Control Flow Statements
If statement
executes a block of code if a specified condition is true and can include an optional else block
Switch Statement
Switch statement
executes one of many code blocks based on the value of an expressionIf statements
are more flexible for complex logical conditionsSwitch statements
are useful for single variables with multiple possible valuesSwitch
requires constant values in cases (e.g., integers, characters, enums)Break
is important to exit the switch block after a match
Loops
For loop
is used when the number of iterations is knownWhile loop
continues as long as a condition is trueDo-while loop
executes at least once, then checks the condition
Loop Control Statements
Break statement
terminates a loop prematurelyContinue statement
skips the rest of the loop body for the current iterationEnhanced for loop
simplifies iteration over arrays and collections
Arrays
Arrays
store multiple values of the same data type in a single variable- Arrays are fixed in size once initialized
Single-dimensional array
example:int[] numbers = {1, 2, 3, 4, 5};
Multi-dimensional array
is an array of array and commonly used for matrices or tables
Accessing Elements
- Access the first element in a single-dimensional array:
numbers[0]
- Access an element in a 2D array:
matrix[1][2]
Length
- Get the length of a single-dimensional array:
numbers.length
- Get the number of rows in a 2D array:
matrix.length
- Get the number of columns in a 2D array:
matrix[0].length
Iterating Over Arrays
- Display all elements of an array using a for loop:
for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }
- Display all elements using a for-each loop:
for (int num : numbers) { System.out.println(num); }
Arrays Class
- Java provides a utility class called
Arrays
for common array operations - Importing Arrays:
import java.util.Arrays;
Sorting
- Sort the array in ascending order:
Arrays.sort(arr);
Notes on Arrays
- Arrays have a fixed size after initialization
- Array indices start at 0
- Arrays can store primitives or objects
- Multi-dimensional arrays are arrays of arrays
Varargs (Variable-Length Argument Lists)
- Declared using three dots (
...
) after the data type - A method can have only one varargs parameter, which must be the last parameter in the method signature
- Use varargs by passing zero or more arguments of the specified type, or an array of the specified type
- Java internally treats varargs as an array
Syntax
void methodName(DataType... variableName) { // Method body }
Intro to Array
- Arrays store multiple values in a single variable
- An array is a collection of similar data elements in contiguous memory locations
- Arrays have a fixed size sequential collection of elements of the same type
- Can be referred to as a collection of variables of the same type
Types of Arrays
- Single-dimensional array: a normal array with sequential elements, also known as a linear array where elements are stored in a single row or adjacent memory locations
- Two-dimensional array: stores data in rows and columns
- Multi-dimensional array: an array of arrays
Basic Operations on Arrays
- Visit each element of the array at least once is array traversal
- Add an element at a given index is insertion
- Delete an element at a given index is deletion
Array Traversal
int[] arr = {2, 3, 5, 7, 11, 13, 17, 19};
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
Array Insertion
int[] arr = new int[5];
arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; arr[4] = 5;
int pos = 3, x = 24;
for (int i = arr.length - 1; i >= pos - 1; i--) {
arr[i + 1] = arr[i];
}
arr[pos - 1] = x;
Array Deletion
int[] arr = {1, 2, 3, 4, 5};
int[] arr_new = new int[arr.length - 1];
int j = 3;
for (int i = 0, k = 0; i < arr.length; i++) {
if (i != j) {
arr_new[k] = arr[i];
k++;
}
}
Search
- To look for an element using its value or index is searching
Search code
int search_ele = 15;
int[] arr = {10, 15, 20, 25, 30};
for (int i = 0; i < arr.length; i++) {
if (arr[i] == search_ele) {
System.out.println("Element Found");
break;
}
}
Update
- update an element at a given index
Update code
int search_ele = 15;
int[] arr = {10, 15, 20, 25};
int x = 20;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == search_ele) {
arr[i] = x;
break;
}
}
10 Array Methods
String[] aArray = new String[5];
declares an arrayString[] bArray = {"a", "b", "c", "d", "e"};
declares an arrayString[] cArray = new String[]{"a", "b", "c", "d", "e"};
declares an array- Print Arrays
int[] intArray = {1, 2, 3, 4, 5};
String intArrayString = Arrays.toString(intArray);
System.out.println(intArrayString); // [1, 2, 3, 4, 5]
Checking Arrays
String[] stringArray = {"a", "b", "c", "d", "e"};
boolean b = Arrays.asList(stringArray).contains("a");
System.out.println(b); // true
Array Operations
- Concatenate Two Arrays:
int[] combinedIntArray = ArrayUtils.addAll(intArray1, intArray2);
- Declare an Array Inline:
method(new String[]{"a", "b", "c", "d", "e"});
- Join Array Elements into a String:
String j = StringUtils.join(new String[]{"a", "b", "c"}, ", ");
System.out.println(j); // a, b, c
- Create an ArrayList from an Array:
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(stringArray));
- Convert ArrayList to Array
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("a", "b", "c"));
String[] stringArr = new String[arrayList.size()];
arrayList.toArray(stringArr);
- Convert Array to Set:
Set<String> set = new HashSet<>(Arrays.asList(stringArray));
- Reverse an Array
int[] intArray = {1, 2, 3, 4, 5};
ArrayUtils.reverse(intArray);
System.out.println(Arrays.toString(intArray)); // [5, 4, 3, 2, 1]
Key Array Notes
- Arrays have a fixed size once initialized
- Array indices start from 0
- Arrays can store primitive data types or objects
- Multi-dimensional arrays are arrays of arrays
Java Method
- A method is a block of code that runs when called by name
- Data passed into a method are parameters
- Methods perform actions and are also known as functions
- Methods allow to reuse code: write ones, use many times
Return Values
- The
void
keyword states that the method will not return anything - For when a method should return a value, state a primitive data type and use the return keyword inside the method
Syntax guide
returnType methodName(parameterType1 parameterName1) {
// method body
// code to perform a specific task
return returnValue; // optional, depending on the returnType
}
returnType
: The returned type of value, else use voidmethodName
: The name of the method used to call itparameterType
: The data type the method accepts as inputparameterName
: The name assigned to each input parameter
public static String sayHello(String name) {
return "Hello, world! " + name;
}
Types of Methods
Instance methods
belong to an instance of a class, and needs an object to be createdReturn Type Methods
return a value
Key Terms for Methods
VarArgs
allows to accept a variable number of argumentsMethod Overloading
allows for methods to have the same name but differing parametersMethod Scope
: Variables declared inside a method are accessible anywhere in the method after their declarationBlock Scope
: Variables declared inside a block{}
are only accessible within that block
Recursion
- A method that calls itself to solve a problem
- Used for repetitive processes
Parameter vs Argument
Parameters
are placeholder variables declared in a method’s definitionArguments
are are the actual values that are passed to a new method- When the called method executes, the values replace their corresponding parameters
Introduction to Object Oriented Programming(OOP)
- OOP is focusses on creating obects that interract with each other
- OOP uses classes and objects to create real-world entities
- OPP models entities using objects and classes
Key Terms
Encapsulation
hides dataInheritance
inherets objects from annother classPolymorphism
has different multiple formsAbstraction
hids away unnessecary details and data
Why use OOP
- Code Reusability: Write once, reuse multiple times.
- Better Organization: Code is structured in logical components.
- Data Security: Private data is protected using encapsulation.
- Scalability: Makes it easier to manage and expand large programs.
Terminology
Class
is a blueprint for creating variablesObject
is a form of class, with its own attributes
Instance Variables and Methods
Instance Variables
: Each object gets its own copy of the variablesMethods
: Define what an object can do- Methods act on instance variables
Constructor
- A constructor is a method called at aumatically when a new object is created
- Names are the same as the class
- There is no return type
- Used to initialize objects
- Default Constructor
class Person {
Person() {
System.out.println("Default Constructor called");
}
}
- Parameterized Constructor
class Person {
String name;
Person(String personName) {
name = personName;
}
}
Encapsulation
- OOP principle that combines data and methods in a class
- Hides the internal details
Features of Encapsulation
- Data Hiding:: Prevents direct variable modifications
- Access Control: Getter and Setters
- Security: Protects data and modifications
- Maintainability: Changes to the class internals don’t affect external code
Code Example
- Using 'private' restrics access directly
- Public getter and setter methods allow controlled access
Practice of OOP
- Data Hiding: The name variable cannot be accessed directly.
- Controlled Access: Only setter/getter methods control modifications.
- Security & Flexibility: You can add validation inside setters
Understanding Inheritance
- OOP principles alongisde Encapsulation
- It allows a subclass to be inhereted by a superclass
- Code is more reusable
Important Terms
Superclass
also known as ParentSubclass
also known as Child
Why use Inheritance
- Code is morereusable, making common subclasses
- Method Overriding
Example on how to inherit
class DerivedClass extends BaseClass {
// methods and fields
}
Inheritance Types
- Can be Single, Mulitple and Hierachical
Code Example For Inheritance Types
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
Multilevel Inheritance:
- A class inherits from another class, which itself is inherited from another.
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Mammal extends Animal {
void walk() {
System.out.println("Mammals can walk.");
}
}
class Dog extends Mammal {
void bark() {
System.out.println("The dog barks.");
}
Hierarchical Inheritance:
- Multiple classes inherit from a single parent class.
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}
Important Note
- Java does not do multiple inheretence, insteasd uses INTERFACES
Polymorphism
- OOP that allows methods to perform different aspects based on the object calling them
- Can be acheived by way of Method Overloading or Method Overriding(Dynamic or Runtime)
Key terms
- Code to be reusable
Implementation
- Polymorphism allows methods to perform different tasks based on the object calling them
Compile-time Polymorphism
(Method Overloading)Runtime Polymorphism
(Method Overriding)- Compile-Time Polymorphism (Method Overloading); multiple methods in the same class have the same name but different parameters (method signature)
Method Executing
- determined at compile time
Example
class Calculator {
// Method Overloading
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Runtime Polymorphism
- subclass provides a specific implementation of a method
- method call is resolved at runtime
Example Code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Method Overriding
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Upcasting
myAnimal.sound(); // Output: Dog barks
}
}
Essential Notes
- Overloaded methods must have different method signatures
- Method overriding allows a subclass to provide a specific implementation of a method in the superclass
- the overridden method must have same signature
Abstraction
- Hides the data
- Abstract classes and Interfaces
Abstraction Rules
- Java must declare abstract class
- Not instantiated
- Methods are either abstract or nor abstract
- Constructors and Instance Variables
Java Best Practices
- Promote organizaiton
- Enforce common sctructure and subclass
Implementation
- Java provides 2 ways to achieve
- Abstract Classes
- Interfaces
Interfaces
- Anotheer way to do abstaction
o
Key Points:
oTo implement an interface, use the keyword implements with a class.
oAll methods in an interface are public and abstract by default.
oA class can implement multiple interfaces
oUsed when classes share some common behavior but have differences in specific implementations.
Key Notes on Abstraction
- interfaces are good to have
Arrays vs Lincked lists
- Both implement Java collection Framework for different data manipulaition
Array List Key Characteristics
- Data is allocated dynamically and assigned with an index
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println(list.get(1)); // Output: Banana
Array Proformance
- Easy Random Access thanks to use of index, O(1)
- Can resize quick, but costly at middle indexes O(n) memory
Linked List Characteristics
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
Data in Link List
- Data is stord in sequential order from start to finnish hence more overheads to read, uses refernce.
- Pro: Fast add and removal in middle indexes, con longer time to perform, O(n)
Summary
Array list
better for fast index reads at memoryLink list
better for queques or stacks
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.