Java-A2
Errajae Abdellah
Scope
Definition:
Scope determines where a variable can be accessed in your code. Variables exist only
inside the block ({}) where they are declared.
Types of scope:
• Local scope: inside a method or block — accessible only there.
• Global scope (class scope): declared outside methods but inside a class —
accessible to all methods in that class (e.g., static Scanner scanner = new
Scanner([Link]);).
Example:
public class Example {
static int globalVar = 10; // class scope
public static void main(String[] args) {
int localVar = 5; // local scope
[Link](globalVar + localVar);
}
Method Overloading
Definition:
Method overloading means defining multiple methods with the same name but different
parameters (different types or number of arguments).
It’s a form of compile-time polymorphism.
Example:
static int add(int a, int b) {
return a + b;
static double add(double a, double b) {
return a + b;
Both methods are named add, but Java decides which one to use depending on the
argument types.
Arrays
Definition:
An array stores multiple values of the same type in a single variable, accessible by index.
Example:
String[] fruits = {"apple", "banana", "orange"};
[Link](fruits[0]); // apple
[Link]([Link]); // 3
You can use a loop to iterate:
for (String fruit : fruits) {
[Link](fruit);
Enhanced for-loop
Definition:
A simplified loop is used to iterate through arrays or collections without managing indices
manually.
Example:
for (String item : fruits) {
[Link](item);
Equivalent to:
for (int i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}
Searching in Arrays
Definition:
You can manually loop through an array to find an element.
Example:
String[] fruits = {"apple", "orange", "banana"};
String target = "orange";
boolean found = false;
for (int i = 0; i < [Link]; i++) {
if (fruits[i].equals(target)) {
[Link]("Found at index " + i);
found = true;
break;
if (!found) [Link]("Not found");
Varargs (...)
Definition:
Varargs (variable arguments) let a method take a variable number of parameters of the
same type. It acts like an array inside the method.
Example:
static int add(int... numbers) {
int sum = 0;
for (int n : numbers) sum += n;
return sum;
[Link](add(1, 2, 3, 4)); // 10
Varargs can even be used for averaging:
static double avg(double... numbers) {
if ([Link] == 0) return 0;
double sum = 0;
for (double n : numbers) sum += n;
return sum / [Link];
Switch Statements (Enhanced Switch)
Definition:
A switch chooses one of many code blocks to execute based on a variable’s value.
The enhanced switch (Java 14+) allows cleaner syntax.
Example:
int choice = 2;
switch (choice) {
case 1 -> [Link]("Option 1");
case 2 -> [Link]("Option 2");
case 3 -> [Link]("Option 3");
default -> [Link]("Invalid choice");