JAVA Final Exam Reviewer
JAVA Final Exam Reviewer
1. if Statement
The if statement is the simplest form of conditional statement. It executes a block of code if the
condition inside the if statement is true.
Syntax:
if (condition)
{
// Code to be executed if the condition is true
}
Example:
int age = 20;
if (age >= 18)
{
System.out.println("You are eligible to vote.");
}
Use Case:
Checking if a user meets a specific condition, such as age eligibility.
Validating user input before processing.
2. if-else Statement
The if-else statement provides an alternative path of execution if the condition is false.
Syntax:
if (condition)
{
// Code to be executed if the condition is true
}
else
{
// Code to be executed if the condition is false
}
Example:
int number = 10;
if (number % 2 == 0)
{
System.out.println("The number is even.");
}
else
{
System.out.println("The number is odd.");
}
Use Case:
Providing alternative actions when a condition is not met.
Handling success and failure scenarios.
3. if-else-if Ladder
The if-else-if ladder allows checking multiple conditions sequentially. As soon as one condition is true,
the corresponding block of code is executed.
Syntax:
if (condition1)
{
// Code to be executed if condition1 is true
}
else if (condition2)
{
// Code to be executed if condition2 is true
}
else
{
// Code to be executed if none of the conditions are true
}
Example:
int marks = 85;
if (marks >= 90)
{
System.out.println("Grade: A");
}
else if (marks >= 80)
{
System.out.println("Grade: B");
}
else if (marks >= 70)
{
System.out.println("Grade: C");
}
else
{
System.out.println("Grade: F");
}
Use Case:
Grading systems based on scores.
Handling multiple conditions in a structured way.
4. switch Statement
The switch statement is used to execute one block of code from multiple options based on the value of
a variable or expression.
Syntax:
switch (expression)
{
case value1:
// Code to be executed if expression == value1
break;
case value2:
// Code to be executed if expression == value2
break;
default:
// Code to be executed if none of the cases match
}
Example:
int day = 3;
switch (day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
Use Case:
Replacing multiple if-else statements when checking for specific values.
Building menu-driven programs.
5. Ternary Operator
The ternary operator is a shorthand version of the if-else statement. It is used to assign a value
based on a condition in a single line.
Syntax:
variable = (condition) ? valueIfTrue : valueIfFalse;
Example:
int number = 5;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println("The number is " + result);
Use Case:
Simplifying if-else statements when assigning values to variables.
Writing concise and readable code.
Incorrect: if (x = 5)
Correct: if (x == 5)
2. Unreachable Code: Ensure that all possible conditions are covered to avoid unreachable code.
3. Missing Break Statements in switch: Forgetting to use break in a switch statement can
cause the code to fall through to the next case.
Conclusion
Conditional statements are crucial in Java for controlling the flow of execution in a program.
Understanding the different types of conditional statements and their appropriate use cases is essential
for writing efficient and maintainable code. By mastering conditional statements, developers can create
more flexible, dynamic, and responsive applications.
Lecture: Conditional Statements (if) in Java
Introduction to Conditional Statements
Conditional statements allow a program to make decisions based on certain conditions. In Java, the if
statement is one of the most fundamental conditional constructs. It allows code to be executed only
when a specific condition is true.
Java provides several types of conditional if statements:
1. Simple if Statement
2. if-else Statement
3. if-else-if Ladder
4. Nested if Statement
5. Ternary Operator
1. Simple if Statement
The simple if statement checks a condition and executes the block of code inside the if statement if
the condition is true.
Syntax:
if (condition) {
// Code to be executed if condition is true
}
Example:
int age = 18;
if (age >= 18)
{
System.out.println("You are eligible to vote.");
}
Use Case:
Checking whether a user meets a specific condition, such as age eligibility.
Validating inputs before processing further.
2. if-else Statement
The if-else statement provides an alternative path of execution when the if condition is false.
Syntax:
if (condition)
{
// Code to be executed if condition is true
}
else
{
// Code to be executed if condition is false
}
Example:
int number = 10;
if (number % 2 == 0)
{
System.out.println("The number is even.");
}
else
{
System.out.println("The number is odd.");
}
Use Case:
Providing a fallback action if the primary condition is not met.
Handling success and failure scenarios.
3. if-else-if Ladder
The if-else-if ladder allows multiple conditions to be checked sequentially. As soon as one condition is
true, the corresponding block of code is executed, and the remaining conditions are skipped.
Syntax:
if (condition1)
{
// Code to be executed if condition1 is true
}
else if (condition2)
{
// Code to be executed if condition2 is true
}
else
{
// Code to be executed if none of the conditions are true
}
Example:
int marks = 85;
if (marks >= 90)
{
System.out.println("Grade: A");
}
else if (marks >= 80)
{
System.out.println("Grade: B");
}
else if (marks >= 70)
{
System.out.println("Grade: C");
}
else
{
System.out.println("Grade: F");
}
Use Case:
Grading systems based on marks.
Handling multiple conditions in a structured way.
4. Nested if Statement
A nested if statement is an if statement inside another if statement. It allows more complex
conditions to be checked.
Syntax:
if (condition1)
{
if (condition2)
{
// Code to be executed if both conditions are true
}
}
Example:
int age = 20;
int income = 50000;
if (age > 18)
{
if (income > 40000)
{
System.out.println("You are eligible for a loan.");
}
}
Use Case:
Handling dependent conditions.
Validating multiple criteria before proceeding.
5. Ternary Operator
The ternary operator is a shorthand for the if-else statement. It uses the ? and : symbols to
perform conditional checks in a single line.
Syntax:
variable = (condition) ? valueIfTrue : valueIfFalse;
Example:
int number = 5;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println("The number is " + result);
Use Case:
Simplifying if-else statements when assigning values to variables.
Writing concise and readable code.
Incorrect: if (x = 5)
Correct: if (x == 5)
2. Unreachable Code: Ensuring that all possible conditions are covered to avoid unreachable
code.
3. Missing Braces: Although optional for single-line statements, always use braces {} for clarity.
Conclusion
Conditional statements are crucial for making decisions in Java programs. Understanding the different
types of if statements and their appropriate use cases is essential for writing dynamic and responsive
code. By mastering conditional statements, developers can create more flexible, efficient, and
maintainable applications.
Lecture: Loops in Java
Introduction to Loops
Loops are essential constructs in Java that allow developers to execute a block of code repeatedly based
on a condition. They help in reducing code duplication and make programs more efficient by
automating repetitive tasks.
Java provides three main types of loops:
1. For Loop
2. While Loop
3. Do-While Loop
Each type of loop serves a specific purpose and can be used depending on the scenario.
1. For Loop
The for loop is used when the number of iterations is known beforehand. It consists of three parts:
initialization, condition, and update.
Syntax:
for (initialization; condition; update)
{
// Code to be executed
}
Example:
for (int i = 0; i < 5; i++)
{
System.out.println("Iteration: " + i);
}
Use Cases:
Iterating over arrays or collections.
Repeating a task a fixed number of times.
Performing mathematical operations, like calculating the sum of numbers.
2. While Loop condition b4 execution
The while loop is used when the number of iterations is not known in advance. It checks the condition
before executing the loop body.
Syntax:
while (condition)
{
// Code to be executed
}
Example:
int count = 0;
while (count < 5)
{
System.out.println("Count: " + count);
count++;
}
Use Cases:
Taking user input until a certain condition is met.
Reading data from files or databases until the end is reached.
Implementing complex loops where the exit condition depends on dynamic values.
3. Do-While Loop execution before condition
The do-while loop is similar to the while loop but ensures that the loop body executes at least once,
regardless of the condition.
Syntax:
do
{
// Code to be executed
} while (condition);
Example:
int count = 0;
do
{
System.out.println("Count: " + count);
count++;
} while (count < 5);
Use Cases:
Taking input until a valid input is provided.
Menu-driven programs where a user selects options repeatedly.
Ensuring a task is executed at least once before checking the condition.
Special Types of Loops
1. Enhanced For Loop (for-each Loop)
The enhanced for loop is used to iterate over arrays and collections without using an index variable. It
simplifies the syntax and reduces the chance of errors.
Syntax:
for (dataType item : array)
{
// Code to be executed
}
Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers)
{
System.out.println(number);
}
Use Cases:
Iterating over arrays or lists.
Simplifying code when working with collections.
Common Mistakes with Loops
1. Infinite Loops: Occur when the loop condition never becomes false.
Example:
while (true)
{
// Ensure there is a break condition
}
2. Off-by-One Errors: Occur when loops run one iteration too many or too few.
Example:
for (int i = 0; i <= 5; i++)
{ // Ensure correct condition
System.out.println(i);
}
3. Failing to Update Loop Variables: Ensure that the loop variable is updated correctly to avoid
infinite loops.
Uses of Loops
Loops are used in a wide variety of programming scenarios:
1. Processing Collections: Iterating through arrays, lists, and other collections.
2. Performing Repetitive Tasks: Automating repetitive tasks like calculations, data processing,
and file handling.
3. Building User Interfaces: Displaying menus and handling repeated user inputs.
4. Game Development: Managing game loops and updating game states.
5. Data Structures: Implementing data structures like linked lists, stacks, and queues.
6. Algorithms: Implementing algorithms such as sorting, searching, and dynamic programming.
Best Practices for Using Loops
1. Choose the Right Loop Type: Use the most appropriate loop based on the problem.
2. Avoid Infinite Loops: Ensure the loop has a clear exit condition.
3. Keep It Simple: Keep the loop logic simple and easy to understand.
4. Use Descriptive Variable Names: Use meaningful names for loop variables.
5. Test Edge Cases: Ensure the loop handles edge cases correctly.
Conclusion
Loops are powerful constructs in Java that allow developers to automate repetitive tasks, process
collections, and handle dynamic scenarios. Understanding the different types of loops and their
appropriate use cases is essential for writing efficient and maintainable code.
Lecture: Multidimensional Arrays in Java
Introduction to Multidimensional Arrays
A multidimensional array is an array that contains other arrays as its elements. In Java,
multidimensional arrays can have more than one dimension, with the most common being two-
dimensional arrays (2D arrays) and three-dimensional arrays (3D arrays).
Multidimensional arrays are useful when working with data that can be represented in a grid, matrix, or
table-like structure, such as images, spreadsheets, and game boards.
Example:
int[][] matrix = new int[3][3];
Initialization Example:
int[][] matrix =
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing Elements:
System.out.println(matrix[0][1]); // Output: 2
2. Three-Dimensional Array (3D Array)
A 3D array is an array of 2D arrays. It can be visualized as a cube or a collection of matrices.
Syntax:
dataType[][][] arrayName = new dataType[x][y][z];
Example:
int[][][] cube = new int[2][3][4];
Initialization Example:
int[][][] cube =
{
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
Accessing Elements:
System.out.println(cube[1][2][3]); // Output: 24
3. Jagged Array
A jagged array is a multidimensional array where the inner arrays can have different lengths. It is also
called a ragged array.
Syntax:
dataType[][] arrayName = new dataType[rows][];
Example:
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[2];
jaggedArray[1] = new int[3];
jaggedArray[2] = new int[1];
Initialization Example:
int[][] jaggedArray =
{
{1, 2},
{3, 4, 5},
{6}
};
Accessing Elements:
System.out.println(jaggedArray[1][2]); // Output: 5
Conclusion
Multidimensional arrays are powerful tools for handling complex data structures in Java.
Understanding how to declare, initialize, and use them effectively is essential for working with grid-
like data, matrices, and dynamic datasets. By mastering multidimensional arrays, you can efficiently
solve problems that involve tabular or multi-layered data.
Lecture: Methods in Java
Introduction to Methods
Methods are blocks of code designed to perform a specific task in a Java program. They help improve
code reusability, readability, and maintainability by encapsulating behavior within a named unit that
can be invoked multiple times.
A method in Java consists of a declaration (or signature) and a body. The declaration includes the
method name, return type, and parameters (if any), while the body contains the code to be executed
when the method is called.
Syntax of a Method
returnType methodName(parameters)
{
// Method body
}
returnType: The data type of the value the method returns. Use void if no value is returned.
methodName: A descriptive name that follows Java naming conventions.
parameters: Input values that the method can accept (optional).
Method body: The code to be executed when the method is called.
Example:
public int addNumbers(int a, int b)
{
return a + b;
}
Example:
int number = 9;
double result = Math.sqrt(number);
System.out.println("Square root: " + result);
2. User-Defined Methods
These are methods created by the programmer to perform specific tasks. They can be further classified
into several types based on their functionality and return type.
Example:
public void displayMessage()
{
System.out.println("Hello, World!");
}
Example:
public void greetUser(String name)
{
System.out.println("Hello, " + name);
}
3. Methods with No Parameters but a Return Value
These methods do not accept any input parameters but return a value to the caller.
Syntax:
returnType methodName()
{
// Code to execute
return value;
}
Example:
public int getNumber()
{
return 42;
}
Example:
public int addNumbers(int a, int b)
{
return a + b;
}
Usage:
ClassName.printMessage();
2. Instance Methods
Belong to an instance of a class.
Require creating an object of the class to be invoked.
Example:
public void showDetails()
{
System.out.println("This is an instance method.");
}
Usage:
ClassName obj = new ClassName();
obj.showDetails();
3. Constructor Methods
Special methods that are called when an object is instantiated.
Have the same name as the class and no return type.
Example:
public class Person
{
public Person()
{
System.out.println("Person object created.");
}
}
Usage:
Person person1 = new Person();
Method Overloading
Method overloading allows multiple methods to have the same name but with different parameter lists.
Example:
public int add(int a, int b)
{
return a + b;
}
Conclusion
Methods are essential building blocks in Java programming. They improve code structure, reusability,
and maintainability. Understanding the different types of methods and how to use them effectively is
crucial for writing clean, efficient Java programs.
Lecture on JOptionPane in Java: Types and Uses
Introduction to JOptionPane
The JOptionPane class in Java is a part of the javax.swing package. It provides a simple way to
display standard dialog boxes for getting input, showing messages, or confirming actions in a GUI
application. This class is commonly used for creating pop-up windows that interact with users.
The main types of dialogs provided by JOptionPane are:
Syntax:
JOptionPane.showMessageDialog(Component parentComponent, Object message, String
title, int messageType);
Message Types:
• JOptionPane.PLAIN_MESSAGE – No icon.
• JOptionPane.INFORMATION_MESSAGE – Information icon.
• JOptionPane.WARNING_MESSAGE – Warning icon.
• JOptionPane.ERROR_MESSAGE – Error icon.
• JOptionPane.QUESTION_MESSAGE – Question icon.
Example:
import javax.swing.*;
Syntax:
int response = JOptionPane.showConfirmDialog(Component parentComponent, Object
message, String title, int optionType, int messageType);
Option Types:
• JOptionPane.YES_NO_OPTION – Yes and No buttons.
• JOptionPane.YES_NO_CANCEL_OPTION – Yes, No, and Cancel buttons.
• JOptionPane.OK_CANCEL_OPTION – OK and Cancel buttons.
Example:
import javax.swing.*;
Syntax:
String input = JOptionPane.showInputDialog(Component parentComponent, Object
message, String title, int messageType);
Example:
import javax.swing.*;
Syntax:
int response = JoptionPane.showOptionDialog
(
Component parentComponent,
Object message,
String title,
int optionType,
int messageType,
Icon icon,
Object[] options,
Object initialValue
);
Example:
import javax.swing.*;