0% found this document useful (0 votes)
1 views50 pages

Java for Beginners Course Level Coding Cheat Sheet

The document is a comprehensive course-level coding cheat sheet for Java, covering various topics such as data types, operators, arrays, and exception handling. It includes code examples and explanations for each topic, organized by video sections from the course. Additionally, it provides guidance on structuring Java code, creating packages, and organizing source files.

Uploaded by

pavan.tanuku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views50 pages

Java for Beginners Course Level Coding Cheat Sheet

The document is a comprehensive course-level coding cheat sheet for Java, covering various topics such as data types, operators, arrays, and exception handling. It includes code examples and explanations for each topic, organized by video sections from the course. Additionally, it provides guidance on structuring Java code, creating packages, and organizing source files.

Uploaded by

pavan.tanuku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

4/14/25, 9:26 AM about:blank

Course Level Coding Cheat Sheet


Welcome to this course-level coding sheet. This coding cheat sheet contains all of the code and explanations provide in the module-level cheat
sheets. Like the module-level coding cheat sheets, you'll find code and explanations for all videos in the course that presented code. Within
each video section, you'll find the code, organized by topics from within each video.

You can expand the hamburger menu in the upper left corner of this window to locate code by video name.

Here's list of the videos with code included in this reading.

Structuring Java Code and Comments


Exploring Data Types in Java
Introduction to Operators in Java
Using Advanced Operators in Java
Working with Arrays
Using Conditional Statements
Introduction to Loops in Java
Working with Strings in Java
Using Packages and Imports
Implementing Functions and Methods
An Introduction to Exceptions
Using Finally Block
Using Multiple Try Catch
Checked and Runtime Exceptions Compared

Structuring Java Code and Comments


Types of comments

Description Code Example

System.out.println("Hello, World!")
A Java
statement used
to print text or
other data to
the standard
output,
typically the
console.

// This is a single-line comment.</pre


Use two
forward
slashes to
precede a
single line
comment in
Java

int number = 10; // This variable stores the number 10

All text after


the two
forward slash
marks on this
line is treated
as a comment

These /* This is a multi-line comment It can be used to explain a block of code or provide detailed information
comments
start with /*

about:blank 1/50
4/14/25, 9:26 AM about:blank

Description Code Example


and end with
*/. They can
span multiple
lines.

This also is a */ int sum = 0;


multiline */ This variable will hold the sum of numbers */.
comment.
Multiline
comments
start with /*
and end with
*/. They can
span multiple
lines.

/*
This method calculates the square of a number.
The @param number The number to be squared
documentation @return The square of the input number
comments */
public int square(int number) {
start with /* return number * number;
and ends with }
*/ . These
comments are
used for
generating
documentation
using tools
like Javadoc.

Creating a package

Description Code Example

package com.example.myapp; // Declare a package


public class MyClass {
// Class code goes here
}

To create a package, use the package keyword at the top of your Java source
file.

Folder structure for a package

Description Folder Structure Example

The folder structure on your filesystem should match the package declaration. For instance, if your /src
package is com.example.myapp, your source file should be located in the following path example. └── com
└── example
└──>└──>
└──>└── └──>myapp
└──>└── └──>└── MyClass.java

about:blank 2/50
4/14/25, 9:26 AM about:blank

Description Folder Structure Example

Class and Methods Structure

Description Code Example

package com.example.library;
public class Library
{
private List <Book> books; // Private attribute to hold books
public Library()
{
books = new ArrayList<>(); // Initialize the list in the constructor
}
In Java, a class is a blueprint for creating objects and }public void addBook(Book book) {
can contain methods (functions) that define behaviors. books.add(book); // Method to add a book to the library
For instance, the second line of this code displays the } <br }
public class library, with methods like
calculatePrice() or applyDiscount().

Creating methods

Description Code Example

package com.example.library;

public class Main {

public static void main(String[] args) {

Library library = new Library(); // Create an instance of Library

// Add books to the library


library.addBook(new Book("1984", "George Orwell"));
library.addBook(new Book("To Kill a Mockingbird", "Harper Lee"));
Every Java application needs an entry point, which is
typically a main method within a public class. In this code, // Display all books
the second line of code identifies the method named Main library.displayBooks();
in the public class. }
}

Organizing source files in directories

Description Directory Structure

As your project grows, organizing your source files into MyProject/


directories can keep your code manageable. The following └── src/ # Source code goes here
└── lib/ # External libraries/JARs

about:blank 3/50
4/14/25, 9:26 AM about:blank

Description Directory Structure


example illustrates typical Java organizaton. └── resources/ # Configuration files, images, and others
└── doc/ # Documentation
└── test/ # Test files

Using imports

Description Code Example

import java.util.List;

When you need to use classes from


other packages, you need to import
them at the top of your source file.
These examples illustrate two import java.util.ArrayList; // Importing classes from Java's standard library </pre
examples of importing classes.

Exploring Data Types in Java


Primitive data types

Description Code Example

byte age = 25; // Age of a person

Use the byte data type when you need to save memory in large
arrays where the memory savings are critical, and the values are
between -128 and 127.

short temperature = -5; // Temperature in degrees

Use the short small integers data type for numbers from −32,768 to
32,767.

about:blank 4/50
4/14/25, 9:26 AM about:blank

Description Code Example

int population = 1000000; // Population of a city

Use the int integer data type to store whole numbers larger than
what byte and short can hold. This is the most commonly used
integer type.

long distanceToMoon = 384400000L; // Distance in meters

Use the long data type when you need to store very large integer
values that exceed the range of int.

float price = 19.99f; // Price of a product

Use the float when you need to store decimal numbers but do not
require high precision (for example, up to 7 decimal places).

double pi = 3.141592653589793; // Value of Pi

Use the double data type when you need to store decimal numbers
and require high precision (up to 15 decimal places).

char initial = 'A'; // Initial of a person's name

Use the char data type when you need to store a single character
such as a single letter or an initial.

boolean isLoggedIn = true; // User login status

Use boolean when you need to represent a true/false value. Boolean


is often used for conditions and decisions.

Reference data types

about:blank 5/50
4/14/25, 9:26 AM about:blank

Description Code Example

String greeting = "Hello, World!";

A string data type is a sequence of characters. The string


data type is very useful for handling text in your programs.

int[] scores = {85, 90, 78, 92};

An array is a collection of multiple values stored under a


single variable name. All the values in an array must be of
the same type. Arrays are great for storing lists of items, like
student scores or names. The following code defines an
integer array type of scores that include 85, 90, 78, and 92.

class Car {
String color;
int year;
void displayInfo() {
System.out.println("Color: " + color + ", Year: " + year);
}
}
The reference data type class is like a blueprint for creating
objects. You can see the class identified in the first line of
code.

public class Main {


public static void main(String[] args) {
Car myCar = new Car();
myCar.color = "Red";
myCar.year = 2026;
myCar.displayInfo(); // Output: Color: Red, Year: 2026
}
}
Objects are classes that contain both data and functions. In
this code, Car myCar = new Car(); is the object.

// The interface class


interface MyInterfaceClass {
void methodExampleOne();
void methodExampleTwo();
void methodExampleThree();
}
When you create an interface, you only declare the methods
without providing their actual code. All methods in an
interface are empty by default. Here's an example of an
interface called MyInterfaceClass with three methods.

about:blank 6/50
4/14/25, 9:26 AM about:blank

Description Code Example

enum DaysOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

An enum is a special data type that defines a list of named


values. An enum is useful for representing fixed sets of
options, such as days of the week or colors.

Introduction to Operators in Java


Arithemtic operators
The following operators perform basic mathematical functions.
In these code examples int a = 10; and int b = 5;

Description Example

System.out.println("Addition: " + (a + b)); // 15

The plus symbol + performs addition operations.

System.out.println("Subtraction: " + (a - b)); // 5

The minus symbol - performs subtraction operations.

System.out.println("Multiplication: " + (a * b)); // 50

The asterisk symbol * performs multiplication operations.

System.out.println("Division: " + (a / b)); // 2

The division symbol / performs division operations.

The percentage symbol % performs modulus (percentage) ystem.out.println("Modulus: " + (a % b)); // 0


operations.

about:blank 7/50
4/14/25, 9:26 AM about:blank

Description Example

Relational operators
You use relational operators to compare two values. These operators return a boolean result (true or false).

In the following examples int a = 10; and int b = 5;.

Description Example

System.out.println("Is a equal to b? " + (a == b)); // false

The double equal symbols == check for


equality.

System.out.println("Is a not equal to b? " + (a != b)); // true

The exclamation point and equal symbol


together != check for a not equal result.

System.out.println("Is a greater than b? " + (a > b)); // true 0

The greater than symbol > checks for the


greater than result.

System.out.println("Is a less than b? " + (a < b)); // false

The less than symbol < checks if the result for


a less than state.

The greater than equal symbols >= compares System.out.println("Is a greater than or equal to b? " + (a >= b)); // true
the values to check for a greater than or equal
to result.

about:blank 8/50
4/14/25, 9:26 AM about:blank

Description Example

System.out.println("Is a less than or equal to b? " + (a <= b)); // false

The less than equal symbols <= compares the


values to check for a less than or equal to
result.

Logical operators
You can use logical operators to combine boolean expressions. The following code examples use boolean x = true; and boolean y = false;.

Description Example

if (a > b && b < c) { ... }

The double ampersands && combines two boolean expressions (both must be true).

if (a > b || b < c) { ... }

The double vertical bar symbols || used with boolean values always evaluates both expressions,
even if the first one is true.

if (!(a > b)) { ... }

The single exclamation point symbol ! operator in Java is the logical NOT operator. This operator
is used to negate a boolean expression, meaning it reverses the truth value.

Using Advanced Operators in Java


Assignment operators
You can use assignment operators to assign values to a variable.

Description Example

The single equal symbol = assigns the right operand to left a = 10

about:blank 9/50
4/14/25, 9:26 AM about:blank

Description Example

a += 5

The plus sign and equal symbols combined += adds and assigns values to variables

a -= 2

The minus sign and equal symbols combined -= subtracts values to variables

a *= 3

The asterisk sign and equal symbols combined *= multipies and assigns values to variables

a /= 2

The forward slash sign and equal symbols combined /= divides and assigns values to variables

a %= 4

The percentage and equal symbols combined %= take the modulus (percentage) and assigns values to the variables

Unary operators
A unary operation is a mathematical or programming operation that uses only one operand or input. Developers use unary operations to
manipulate data and perform calculations. You would use the following assignment operators to assign values to variables.

Description Example

Use the plus symbol to indicate a positive value. int positive = +a;

about:blank 10/50
4/14/25, 9:26 AM about:blank

Description Example

int a = 10;
System.out.println("Unary plus: " + (+a)); // 10

Ternary operators
Ternary operators are a shorthand form of the conditional statement. They can use three operands.

Description Example

int a = 10;
int b = 20;
int max = (a > b) ? a : b; // If a is greater than b, assign a; otherwise assign b
System.out.println("Maximum value is: " + max); // 20

Ternary operators uses the Syntax:


condition ? expression1 : expression2;.
In the following code, int max = (a >
b) ? a : b;

Working with Arrays


Declaring an array

Description Example

int[] numbers;

To declare an array in Java, you use the following syntax: dataType[] arrayName;. The following doce displays the
data type of int and creates an array named numbers.

Initializing an array
After you declare an array, you need to initialize the array to allocate memory for it.

about:blank 11/50
4/14/25, 9:26 AM about:blank

Description Example

numbers = new int[5];

int[] numbers = new int[5];

These code samples display three methods used to create an array of 5 integers. You can
initialize an array using the new keyword. You can also declare and initialize an array in a single
line. Alternatively, you can create an array and directly assign values using curly braces.

int[] numbers = {1, 2, 3, 4, 5};

Accessing an array
You can access individual elements in an array by specifying the index inside square brackets.

Description Example

System.out.println(numbers[0]);System.out.println(numbers[0]); // Outputs: 1

Remember that indices start at zero. Here are


two examples: System.out.println(numbers[4]); // Outputs: 5

Modifying array elements

about:blank 12/50
4/14/25, 9:26 AM about:blank

Description Example

numbers[2] = 10; // Changing the third element to 10

Modify the array element value by accessing


it within its index.
System.out.println(numbers[2]);>System.out.println(numbers[2]); // Outputs: 10

Verify the array length

Description Example

System.out.println("The length of the array is: " + numbers.length);

Verify the array length by using the length property.

Using a for loop to iterate through an array

Description Example

for (int i = 0; i < numbers.length; i++) {


System.out.println(numbers[i]);
}

You can use a for loop for to iterarate through and array. Here's an example that
prints all elements in the numbers array. The for loop includes this code for (int i
= 0 in the following code snippet.

Using a for each loop to iterate through an array


Description Example

You can also use the enhanced for loop, known as the "for-each" loop. The enhanced for each for (int number : numbers) {
loop code include this portion, for (int of the following code snippet. System.out.println(number);
}

about:blank 13/50
4/14/25, 9:26 AM about:blank

Description Example

Declare and intialize a multidimensional array


Java supports multi-dimensional arrays, which are essentially arrays of arrays. The most common type is the two-dimensional array.

Description Example

int[][] matrix = {
{1,{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

Here's how to declare and initialize a 2D array. You will declare the integer
data type and create the matrix array.

System.out.println(matrix[0][1]); // Outputs: 2

You can access elements in a two-dimensional array by specifying both


indices, which are shown in this code inside of the square brackets.

Iterating Through a 2D Array

Description Example

for (int i = 0; i < matrix.length; i++) {


for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j]>System.out.print(matrix[i][j] + " ");
}
System.out.println(); // Move to the next line after each row

You can use nested loops to iterate through all


elements of a 2D array.

Using Conditional Statements


if statement
The if statement checks a condition. If the condition is true, it executes the code inside the block. If the condition is false, the program skips
the if block.

about:blank 14/50
4/14/25, 9:26 AM about:blank

Description Example

public class Main {

A Java class named Main with a main method. The main method is the
entry point of the program.

public static void main(String[] args) {

The main method is declared using public static void


main(String[] args). This method is required for execution in Java
programs.

int number = 10;

A variable number of type int is declared and initialized with the


value 10.

if (number > 5) {
System.out.println("The number is greater than 5.");
}

The if statement checks if number is greater than 5. If true, it prints


"The number is greater than 5."

}
}

Closing curly braces to end the main method and class definition.

Explanation: Since number is 10, which is greater than 5, the condition evaluates to true, and the program prints "The number is greater than
5.".

if-else statement
The if-else statement gives an alternative if the condition is false.

about:blank 15/50
4/14/25, 9:26 AM about:blank

Description Example

public class Main {

A Java class named Main with a main method. The main method
is the entry point of the program.

public static void main(String[] args) {

The main method is declared using public static void


main(String[] args). This method is required for execution in
Java programs.

int number = 3;

A variable number of type int is declared and initialized with the


value 3.

if (number > 5) {
System.out.println("The number is greater than 5.");
}

The if statement checks if number is greater than 5. If true, it


prints "The number is greater than 5.".

else {
System.out.println("The number is not greater than 5.");
}

The else block executes when the if condition is false, printing


"The number is not greater than 5.".

}
}

Closing curly braces to end the main method and class definition.

about:blank 16/50
4/14/25, 9:26 AM about:blank

else if statement
You can check multiple conditions using else if.

Description Example

public class Main {

A Java class named Main with a main method. The main method is the
entry point of the program.

public static void main(String[] args) {

The main method is declared using public static void


main(String[] args). This method is required for execution in Java
programs.

int number = 5;

A variable number of type int is declared and initialized with the


value 5.

if (number > 5) {
System.out.println("The number is greater than 5.");
}

The if statement checks if number is greater than 5. If true, it prints


"The number is greater than 5.".

else if (number == 5) {
System.out.println("The number is equal to 5.");
}

The else if statement checks if number is exactly 5. If true, it prints


"The number is equal to 5.".

The else block executes when none of the above conditions are met, else {
printing "The number is less than 5.". System.out.println("The number is less than 5.");
}

about:blank 17/50
4/14/25, 9:26 AM about:blank

Description Example

}
}

Closing curly braces to end the main method and class definition.

Explanation: Since number is exactly 5, the program prints "The number is equal to 5.".

switch statement
A switch statement checks a single variable against multiple values.

Description Example

public class Main {

A Java class named Main with a main method. The main method is the entry point of the
program.

public static void main(String[] args) {

The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.

int day = 3;

A variable day of type int is declared and initialized with the value 3.

The switch statement checks the value of day and compares it against the case labels. switch (day) {
If day is 3, it prints "Wednesday". case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;

about:blank 18/50
4/14/25, 9:26 AM about:blank

Description Example
case 5:
System.out.println("Friday");
break;
default:
System.out.println("Weekend");
}

}
}

Closing curly braces to end the main method and class definition.

default case in a switch statement


When using a switch statement, it's a good practice to specify a default case. This case runs if none of the specified cases match, acting as a
fallback option.

Description Example

switch (color) {

A switch statement checks the value of a variable color.

case "red":
System.out.println("Color is red.");
break;

A case checks if color is "red", printing "Color is red.".

about:blank 19/50
4/14/25, 9:26 AM about:blank

Description Example

case "blue":
System.out.println("Color is blue.");
break;

A case checks if color is "blue", printing "Color is blue.".

default:
System.out.println("Unknown color.");
}

The default case prints "Unknown color." if color doesn't match "red" or "blue".

Nested Conditional Statements


You can place conditional statements within each other to create more complex decisions. The process of placing conditional statements within
other conditional statements is called nesting.

Description Example

public class Main {

A Java class named Main with a main method. The main method is the
entry point of the program.

public static void main(String[] args) {

The main method is declared using public static void main(String[]


args). This method is required for execution in Java programs.

int age = 20;

A variable age of type int is declared and initialized with the value 20.

The if statement checks if age is greater than or equal to 18. If true, it if (age >= 18) {
prints "You are an adult.". System.out.println("You are an adult.");
}

about:blank 20/50
4/14/25, 9:26 AM about:blank

Description Example

if (age >= 65) {


System.out.println("You are a senior citizen.");
}

Another if statement checks if age is greater than or equal to 65, printing


"You are a senior citizen." if true.

else {
System.out.println("You are a minor.");
}

The else block executes if age is less than 18, printing "You are a
minor.".

}
}

Closing curly braces to end the main method and class definition.

Introduction to Loops in Java


for Loop
The for loop is used when the number of iterations is known beforehand. It consists of three parts:

Initialization: This sets a counter variable.


Condition: This checks if the loop should continue executing.
Increment/Decrement: This updates the counter variable after each iteration.

about:blank 21/50
4/14/25, 9:26 AM about:blank

Description Example

public class ForLoopExample {

A Java class named ForLoopExample with a main method. The main method is the entry
point of the program.

public static void main(String[] args) {

The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.

for (int i = 1; i <= 5; i++) {

A for loop is initialized with int i = 1, which starts the counter at 1. The counter
variable i is incremented by i++ after each iteration.

System.out.println(i);

The loop checks if i <= 5, and if true, it prints the value of i.

Close the for loop.

Close the main method.

Close the ForLoopExample class. }

about:blank 22/50
4/14/25, 9:26 AM about:blank

Description Example

while Loop
The while loop is used when the number of iterations is not known in advance. It continues executing as long as the specified condition
remains true.

Description Example

public class WhileLoopExample {

A Java class named WhileLoopExample with a main method. The main method is the
entry point of the program.

public static void main(String[] args) {

The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.

int i = 1;

A variable i is initialized to 1.

while (i <= 5) {

The while loop continues as long as i <= 5.

System.out.println(i);
i++;

Inside the loop, the value of i is printed, then incremented by i++.

The main method and class are closed with curly braces. }
}

about:blank 23/50
4/14/25, 9:26 AM about:blank

Description Example

do-while Loop
The do-while loop is similar to the while loop but guarantees that the code block executes at least once before checking the condition.

Description Example

public class DoWhileLoopExample {

A Java class named DoWhileLoopExample with a main method. The main method is the
entry point of the program.

public static void main(String[] args) {

The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.

int i = 1;

A variable i is initialized to 1.

do {

The do-while loop starts and executes at least once before checking if i <= 5.

System.out.println(i);
i++;

Inside the loop, the value of i is printed, then incremented by i++.

about:blank 24/50
4/14/25, 9:26 AM about:blank

Description Example

} while (i <= 5);

The condition i <= 5 is checked after each iteration.

}
}

The main method and class are closed with curly braces.

Nested loops
You can also use loops inside other loops, known as nested loops. This is useful for working with multi-dimensional data structures, like arrays
or matrices.

Description Example

public class NestedLoopsExample {

A Java class named NestedLoopsExample with a main method. The main method is the
entry point of the program.

public static void main(String[] args) {

The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.

for (int i = 1; i <= 10; i++) {

The outer loop controls the rows, running 10 times.

The inner loop controls the columns, also running 10 times for each row. for (int j = 1; j <= 10; j++) {

about:blank 25/50
4/14/25, 9:26 AM about:blank

Description Example

System.out.print(i * j + "\t");

The product of i * j is printed for each combination of rows and columns.

System.out.println();

After the inner loop, a newline is printed to separate the rows.

}
}

The main method and class are closed with curly braces.

break statement
The break statement is used to terminate a loop immediately, regardless of the loop's condition. This can be useful when you want to exit a loop
based on a specific condition that may occur during its execution.

Description Example

public class BreakExample {

A Java class named BreakExample with a main method. The main method is the entry
point of the program.

public static void main(String[] args) {

The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.

An array numbers is declared and initialized. int[] numbers = {1, 3, 5, 7, 9, 2, 4};

about:blank 26/50
4/14/25, 9:26 AM about:blank

Description Example

for (int num : numbers) {

The loop iterates through the array, checking if any number is greater than 5.

if (num > 5) {
break;

When a number greater than 5 is found, the loop exits with the break statement.

}
}

The main method and class are closed with curly braces.

continue statement
The continue statement is used to skip the current iteration of a loop and move to the next iteration. It's useful when you want to skip certain
conditions but continue executing the rest of the loop.

Description Example

public class ContinueExample {

A Java class named ContinueExample with a main method. The main method is the entry
point of the program.

The main method is declared using public static void main(String[] args). This public static void main(String[] args) {
method is required for execution in Java programs.

about:blank 27/50
4/14/25, 9:26 AM about:blank

Description Example

for (int i = 1; i <= 10; i++) {

The loop iterates through the numbers from 1 to 10.

if (i == 5) {
continue;

When i == 5, the continue statement is executed, skipping the


System.out.println(i); statement for that iteration.

System.out.println(i);

The value of i is printed for all numbers except 5.

}
}

The main method and class are closed with curly braces.

Working with Strings in Java


Creating strings
You can create a string in Java in two main ways:

Using string literals: This means writing the string directly inside double quotes.

Description Example

String greeting = "Hello, World!";

Create a string using string literal.

about:blank 28/50
4/14/25, 9:26 AM about:blank
In this example, we created a string called greeting that contains "Hello, World!".

Using the new Keyword: This method involves using the new keyword to create a string object.

Description Example

String message = new String("Hello, World!");

Create a string using the new keyword.

Although this works, it's more common to use string literals because it's simpler.

String length
To find out how many characters are in a string, you can use the length() method. This method tells you the total number of characters in the
string.

Description Example

String text = "Java Programming";

Create a string and use length() to get the number of


characters.

int length = text.length();

Use the length() method to find the string length.

System.out.println("Length of the string: " + length); // Output: 16

Print the length of the string.

Here, we created a string called text and then checked its length. The output tells us that there are 16 characters in "Java Programming".

Accessing characters
If you want to look at individual characters in a string, you can use the charAt() method. This method allows you to get a character at a specific
position in the string.

about:blank 29/50
4/14/25, 9:26 AM about:blank

Description Example

String word = "Java";

Create a string and access a character using charAt().

char firstChar = word.charAt(0);

Access the first character of the string.

System.out.println("First character: " + firstChar); // Output: J

Print the first character of the string.

In this example, we accessed the first character of the string "Java". Remember that counting starts at 0, so charAt(0) gives us 'J'.

Concatenating strings
Sometimes you might want to combine two or more strings together. You can do this easily using the + operator or the concat() method.

Description Example

String firstName = "John";

Combine two strings using the + operator.

String lastName = "Doe";

Combine two strings using the + operator.

Concatenate first and last names using the + operator. String fullName = firstName + " " + lastName;

about:blank 30/50
4/14/25, 9:26 AM about:blank

Description Example

System.out.println("Full Name: " + fullName); // Output: John Doe

Print the full name.

Here, we combined firstName and lastName using the + operator and added a space between them.

You can also use the concat() method:

Description Example

String anotherFullName = firstName.concat(" ").concat(lastName);

Combine strings using the concat()


method.

System.out.println("Another Full Name: " + anotherFullName); // Output: John Doe

Print the concatenated string.

String comparison
When you want to check if two strings are the same, use the equals() method. This checks if both strings have identical content.

Description Example

String str1 = "Hello";

Create three strings to compare.

Create another string to compare. String str2 = "Hello";

about:blank 31/50
4/14/25, 9:26 AM about:blank

Description Example

String str3 = "World";

Create a third string to compare.

boolean isEqual = str1.equals(str2);

Check if str1 is equal to str2.

System.out.println("str1 equals str2: " + isEqual); // Output: true

Print comparison result.

boolean isNotEqual = str1.equals(str3);

Check if str1 is equal to str3.

System.out.println("str1 equals str3: " + isNotEqual); // Output: false

Print comparison result.

In this example, isEqual returns true because both strings are "Hello". However, isNotEqual returns false since "Hello" and "World" are
different.

String immutability
One important thing to know about strings in Java is that they are immutable. This means that once a string is created, it cannot be changed. If
you try to change it, you will actually create a new string instead.

Description Example

Create an original string. String original = "Hello";

about:blank 32/50
4/14/25, 9:26 AM about:blank

Description Example

original = original + " World";

Add to the string (creates a new string).

System.out.println(original); // Output: Hello World

Print the new string.

In this case, we added "World" to original, but instead of changing the original string, we created a new string that combines both parts.

Finding substrings
You may want to get a smaller part of a string. You can do this using the substring() method, which allows you to specify where to start and
where to stop.

Description Example

String phrase = "Java Programming";

Create a string and extract a substring.

String sub = phrase.substring(5, 16);

Extract a substring from the string.

Print the extracted substring. System.out.println("Substring: " + sub); // Output: Programming

about:blank 33/50
4/14/25, 9:26 AM about:blank

Description Example

In this example, we started at index 5 and went up to (but did not include) index 16 to extract "Programming".

String methods
Java has many built-in methods for strings that help you manipulate and process them. Here are some useful ones:

toUpperCase(): This method converts all letters in a string to uppercase.

Description Example

String text = "hello";

Create a string.

System.out.println(text.toUpperCase()); // Output: HELLO

Convert the string to uppercase.

toLowerCase(): This converts all letters in a string to lowercase.

Description Example

String text = "WORLD";

Create a string.

System.out.println(text.toLowerCase()); // Output: world

Convert the string to lowercase.

trim(): This method removes any extra spaces at the beginning or end of a string.

about:blank 34/50
4/14/25, 9:26 AM about:blank

Description Example

String textWithSpaces = " Hello ";

Create a string with extra spaces and trim it.

System.out.println(textWithSpaces.trim()); // Output: Hello

Remove spaces from the string.

replace(): If you want to change all instances of one character or substring to another, use this method.

Description Example

String sentence = "I like cats.";

Create a sentence and replace a word.

String newSentence = sentence.replace("cats", "dogs");

Replace a word in the sentence.

System.out.println(newSentence); // Output: I like dogs.

Print the new sentence.

Splitting strings
You can break a string into smaller pieces using the split() method. This is useful when you have data separated by commas or spaces.

Description Example

Create a CSV string and split it. String csv = "apple,banana,cherry";

about:blank 35/50
4/14/25, 9:26 AM about:blank

Description Example

String[] fruits = csv.split(",");

Split the string at each comma.

for (String fruit : fruits) {


System.out.println(fruit);
}

Print each fruit in the array.

apple
banana
cherry

Output:

Joining strings
If you have an array of strings and want to combine them back into one single string, you can use the String.join() method.

Description Example

String[] colors = {"Red", "Green", "Blue"};

Create an array of strings.

Join the strings with a separator. String joinedColors = String.join(", ", colors);

about:blank 36/50
4/14/25, 9:26 AM about:blank

Description Example

System.out.println(joinedColors); // Output: Red, Green, Blue

Print the joined string.

Using Packages and Imports


Creating a package
To create a package, you simply declare it at the top of your Java source file using the package keyword followed by the package name. For
example:

Description Example

package com.example.myapp;

Declare a package at the top of the file.

In this example, com.example.myapp is the name of the package. It's common practice to use a reverse domain name as the package name to
ensure uniqueness.

Description Example

public class MyClass {


// Class code here
}

Define a class inside the package.

Creating and using a package

Description Example

Define a class inside the shapes package. package shapes;

about:blank 37/50
4/14/25, 9:26 AM about:blank

Description Example

public class Circle {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

public double area() {


return Math.PI * radius * radius;
}
Create the Circle class with a constructor and a method. }

To use this class in another Java file, you need to import it.

Importing classes
To import a specific class from a package, use the following syntax:

Description Example

import package_name.ClassName;

Import a specific class from a package.

Importing all classes from a package


You can also import all classes from a package using an asterisk (*).

Description Example

import shapes.*;

Import all classes from the shapes package.

This imports all classes in the shapes package, allowing you to use any class without needing to import them individually.

Implementing Functions and Methods


Function structure
about:blank 38/50
4/14/25, 9:26 AM about:blank

Description Example

returnType functionName(parameter1Type parameter1, parameter2Type parameter2) {


// code to be executed
return value; // optional
}

The structure of a function in Java.

Example of a Simple Function


Let's create a simple function that adds two numbers:

Description Example

public static int add(int a, int b) {


return a + b;
}

Create a function that adds two numbers.

int sum = add(5, 3);


Call the add function in the main method and print the result. System.out.println("The sum is: " + sum);

Example of a simple method


Let's create a method within a class:

Description Example

Define a multiply method inside the Calculator class. public class Calculator

The multiply method takes two integers and returns their product. public int multiply(int x, int y) {

about:blank 39/50
4/14/25, 9:26 AM about:blank

Description Example

Close the multiply method. }

Define the main method, which is the program's entry point. public static void main(String[] args) {

Create an instance of the Calculator class in the main method. Calculator calc = new Calculator();

Call the multiply method with 4 and 5 and store the result. int product = calc.multiply(4, 5)

Print the result to the screen. System.out.println("The product is: " + product);

Parameters and arguments


Parameters are the inputs to functions or methods, while arguments are the values passed when calling these functions or methods.

Description Example

Define a method with multiple parameters. public void greet(String name, int age) {
System.out.println("Hello " + name + ", you are " + age + " years old.");
}

about:blank 40/50
4/14/25, 9:26 AM about:blank

Description Example

Greeting greeting = new Greeting();


greeting.greet("Alice", 30);

Call the greet method with arguments in the


main method.

Return values
Functions and methods can return values or perform actions without returning anything.

Description Example

public double area(double length, double width) {


return length * width;
}

Define a method that returns a value.

Rectangle rect = new Rectangle();


double area = rect.area(4.5, 3.0);
System.out.println("The area of the rectangle is: " + area);

Call the area method and print the returned value.

Overloading methods
Java allows defining multiple methods with the same name but different parameters. This is known as method overloading.

Description Example

public class Display {

Define the Display class.

Define an overloaded method that takes an int. public void show(int number) {

about:blank 41/50
4/14/25, 9:26 AM about:blank

Description Example

System.out.println("Number: " + number);

Print the number.

Close the first method.

public void show(String text) {

Define an overloaded method that takes a String.

System.out.println("Text: " + text);

Print the text.

Close the second method.

Close the Display class.

about:blank 42/50
4/14/25, 9:26 AM about:blank

Description Example

public static void main(String[] args) {

Define the main method to call the overloaded methods.

Display display = new Display();

Create a Display object.

display.show(10);
display.show("Hello World");

Call show(int) and show(String).

Close the main method.

Scope of identifiers
The scope of an identifier refers to the part of the program where the identifier can be accessed.

Description Example

int x = 10; // x is local to this block

Local Scope: Identifiers are accessible only within the method or block.

Instance Scope: Variables are accessible by all methods in the class. private int x; // x is accessible by all methods

about:blank 43/50
4/14/25, 9:26 AM about:blank

Description Example

private static int count;

Static Scope: Static variables belong to the class and are accessible
throughout the class.

Void methods
A void method does not return a value.

Description Example

public void printMessage() {


System.out.println("Hello, World!");
}

Define a void method that prints a message.

Empty parameter lists


An empty parameter list means the method does not take any parameters.

Description Example

public void show() {


System.out.println("No parameters here.");
}

Define a method with an empty parameter list.

An Introduction to Exceptions
Basic exception handling

Description Example

Java provides a robust mechanism for public class ExceptionExample {


handling exceptions using the try, catch, public static void main(String[] args) {
int numerator = 10;
and finally blocks. int denominator = 0; // This will cause an ArithmeticException
try {
int result = numerator / denominator; // This line may throw an exception

about:blank 44/50
4/14/25, 9:26 AM about:blank

Description Example
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} finally {
System.out.println("This block executes regardless of an exception.");
}
}
}

Creating custom exceptions

Description Example

class MyCustomException extends Exception {


public MyCustomException(String message) {
super(message); // Pass the message to the parent Exception class
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
throw new MyCustomException("This is a custom exception message.");
} catch (MyCustomException e) {
Sometimes, you may want to create your own System.out.println(e.getMessage());
}
exception types. You can do this by extending the
}
Exception class. }

Using Finally Block


The structure of exception-handling

Description Example

try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}
One important feature of Java is its exception handling mechanism, which includes the
try, catch, and finally blocks.

about:blank 45/50
4/14/25, 9:26 AM about:blank

Understanding the finally block

Description Example

public class FinallyExample {


public static void main(String[] args) {
try {
System.out.println("In try block");
} catch (ArithmeticException e) {
int result = 10 / 0; // This line will throw an exception
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
} finally {
The code within the finally block always runs after System.out.println("Finally block executed");
the try and catch blocks, regardless of whether an }
}
exception was thrown or caught. It is commonly used }
for resource management.

Correct usage of the finally block

Description Example

public class CorrectFinallyUsage {


public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("example.txt");
// Code to read from the file
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
} finally {
Always executing try {
cleanup code: The if (file != null) {
primary purpose of file.close();
the finally block is System.out.println("File closed successfully.");
to ensure that the }
} catch (IOException e) {
cleanup code runs System.out.println("Error closing file: " + e.getMessage());
regardless of }
whether an }
exception was }
thrown or not.

Releasing database import java.sql.Connection;


connections: Using import java.sql.DriverManager;
import java.sql.SQLException;
the finally block to public class DatabaseConnectionCorrectUsage {
close database public static void main(String[] args) {
connections is Connection connection = null;
another correct try {
practice. connection = DriverManager.getConnection("jdbc//localhost:3306/mydb", "user", "password");
// Perform database operations
} catch (SQLException e) {
System.out.println("Database error: " + e.getMessage());
} finally {
try {
if (connection != null) {
connection.close();

about:blank 46/50
4/14/25, 9:26 AM about:blank

Description Example
System.out.println("Database connection closed.");
}
} catch (SQLException e) {
System.out.println("Error closing connection: " + e.getMessage());
}
}
}

Incorrect usage of the finally block

Description Example

public class IncorrectFinallyUsage {


public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an exception
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
} finally {
int x = 10 / 0; // This will throw another exception
System.out.println("Finally block executed");
Not handling exceptions in finally: If an }
exception occurs in the finally block, it may }
suppress exceptions thrown in the try or catch }
blocks.

public class ReturnInFinally {


public static void main(String[] args) {
System.out.println(testMethod());
}
public static int testMethod() {
try {
return 1; // Return from try block
} catch (Exception e) {
return 2; // Return from catch block
} finally {
Using return statements in finally: This can lead return 3; // This will override previous returns
}
to unexpected behavior, as it overrides any return }
statements from the try or catch blocks. }

Assuming finally will not execute: This is public class FinallyAlwaysExecutes {


incorrect; the finally block will always execute public static void main(String[] args) {
try {
unless the program crashes or is forcibly System.out.println("Trying risky operation...");
terminated. int result = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught an ArithmeticException.");

about:blank 47/50
4/14/25, 9:26 AM about:blank

Description Example
// Not exiting or terminating the program here
}
// Assuming finally won't execute (this is wrong)
}
// The finally block should be here to ensure it executes.
}

Using Multiple Try Catch


Basic try-catch structure

Description Example

try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}

Multiple try-catch blocks allow developers to handle different types of exceptions in a


structured way. In Java, the basic structure of a try-catch block looks like this.

Multiple try-catch

Description Example

public class MultipleCatchExample {


public static void main(String[] args) {
int[] numbers = {1, 2, 3};
int index = 5; // Invalid index
try {
// Trying to access an invalid index
System.out.println("Number: " + numbers[index]);
// Trying to divide by zero
int result = 10 / 0;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds.");
Multiple try-catch refers to the use of more than one catch } catch (ArithmeticException e) {
System.out.println("Error: Division by zero.");
block within a single try statement or multiple try-catch
}
statements in the code. }
}

about:blank 48/50
4/14/25, 9:26 AM about:blank

Throws keyword

Description Example

public class ThrowsExample {


public static void main(String[] args) {
try {
readFile("nonexistentfile.txt");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
// Method that declares an exception
static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader fileInput = new BufferedReader(file);
The throws keyword is used in method declarations to indicate // Reading the file
System.out.println(fileInput.readLine());
that a method can throw one or more exceptions. fileInput.close();
}
}

Checked and Runtime Exceptions Compared


Checked exceptions

Description Example

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
File myFile = new File("nonexistentfile.txt");
Scanner myReader = new Scanner(myFile);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
Checked exceptions are exceptions checked at myReader.close();
} catch (FileNotFoundException e) {
compile time. They usually represent recoverable System.out.println("An error occurred: " + e.getMessage());
conditions, such as file not found or network issues. }
}
}

Runtime exceptions

about:blank 49/50
4/14/25, 9:26 AM about:blank

Description Example

public class RuntimeExceptionExample {


public static void main(String[] args) {
int numerator = 10;
int denominator = 0;
try {
int result = numerator / denominator; // This will cause an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
Runtime exceptions do not need System.out.println("An error occurred: Cannot divide by zero.");
to be explicitly caught or }
declared. They usually indicate }
programming errors, such as }
logic errors or improper use of
APIs.

Summary
In addition to viewing this resource here, you can select the printer icon located at the top of the screen to print this information or save this
information to a PDF file, based on your computer's capabilities. Also, return to the course itself to access the PDF file within the course for
direct downloading.

Author(s)
Ramanujam Srinivasan
Lavanya Thiruvali Sunderarajan

about:blank 50/50

You might also like