0% found this document useful (0 votes)
19 views

Notes

f

Uploaded by

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

Notes

f

Uploaded by

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

The main method is the starting point of the program and is declared with public static void

main() and takes an array of strings (String[] args) as a parameter, representing command-
line arguments.
Within the main method, the statement System.out.println("Hello, World!"); is used to
display the string "Hello, World!" as output on the console.
System – class
Out – accepts output data
Println – method to display string
Write about keywords:- reserved words

Import

New

Package
BINARY LITERALS

A binary literal is a number represented in binary (0s and 1s). In Java, you can use binary
literals for integral types such as byte, short, int, and long. To specify a binary literal, prefix
the number with 0b or 0B. This allows you to define numbers in binary format directly in
your code. When executed, Java will convert these binary literals to their decimal
equivalents.
Rules for Variable Names in Java

1. Do not use a Java keyword or reserved word:

public class KeywordExample {

public static void main(String[] args) {

// Incorrect: int int = 10; // 'int' is a reserved word

int myInt = 10; // Correct

2. Do not use a space in the variable name:

public class SpaceExample {

public static void main(String[] args) {

// Incorrect: int first name = 20;

int firstName = 20; // Correct

}
3. Use a combination of letters or a combination of letters and numbers:

public class LetterNumberExample {

public static void main(String[] args) {

int age = 25; // Letters and numbers

String name = "Alice"; // Letters only

The name age is a combination of letters and numbers.

The name name consists of only letters.

4. Cannot start with a number:

public class NumberStartExample {

public static void main(String[] args) {

// Incorrect: int 1stNumber = 10;

int firstNumber = 10; // Correct

5. The only symbols allowed are the underscore (_) and the dollar sign ($):

public class SymbolExample {

public static void main(String[] args) {

int _age = 30;

int $salary = 50000;

Conventions for Variable Names

1. Use full words instead of cryptic abbreviations:

public class FullWordsExample {

public static void main(String[] args) {


int studentAge = 20; // Clear and descriptive

// Avoid: int age = 20; // Less clear

2. Do not use single-letter variables:

public class SingleLetterExample {

public static void main(String[] args) {

int studentAge = 20; // Clear

// Avoid: int a = 20; // Less clear

3. Use lowercase for single-word variables:

public class LowercaseExample {

public static void main(String[] args) {

int age = 25; // Lowercase for single-word variable

4. Use camelCase for multi-word variables:

public class CamelCaseExample {

public static void main(String[] args) {

int studentAge = 20; // CamelCase for multi-word variable

Scope of Variable

public class ScopeExample {

public static void main(String[] args) {

int x = 10; // x is accessible within the main method


{

int y = 20; // y is accessible within the block

// y is not accessible here

x is declared within the main method, so it's accessible throughout the method.

y is declared within a block, so its scope is limited to that block. Once the block ends, y is no
longer accessible.

BOOLEAN OPERATORS
ARITHMETIC OPERATORs

PRECEDENCE

−Expressions in parenthesis are handled first

public class ArithmeticPrecedence {

public static void main(String[] args) {

int result = 5 + 2 * 3 - 4 / 2;

System.out.println(result); // Output: 10

Multiplication and Division: These operations are performed first, from left to right.

2*3=6

4/2=2

Addition and Subtraction: These operations are performed next, from left to right.

5 + 6 - 2 = 10

Increment and Decrement

public class IncrementDecrement {

public static void main(String[] args) {

int num = 10;

// Post-increment: Use the current value, then increment

int result1 = num++;


System.out.println(result1); // Output: 10

// Pre-increment: Increment first, then use the new value

int result2 = ++num;

System.out.println(result2); // Output: 12

// Post-decrement: Use the current value, then decrement

int result3 = num--;

System.out.println(result3); // Output: 12

// Pre-decrement: Decrement first, then use the new value

int result4 = --num;

System.out.println(result4); // Output: 11

Post-increment (num++): The current value of num is used first, then it's incremented by 1.

Pre-increment (++num): num is incremented by 1 first, and then the new value is used.

Post-decrement (num--): The current value of num is used first, then it's decremented by 1.

Pre-decrement (--num): num is decremented by 1 first, and then the new value is used.

ASSIGNMENT OPERATOR : =

TRUNCATION AND INTEGER DIVISION

public class TruncationAndIntegerDivision {

public static void main(String[] args) {

int a = 10;

int b = 3;

// Integer division: Divides two integers and returns the integer quotient

int quotient = a / b; // 10 / 3 = 3 (integer division)

// Truncation: Casting a floating-point number to an integer discards the decimal part

double decimalNumber = 10.5;

int truncatedNumber = (int) decimalNumber; // 10.5 becomes 10


System.out.println("Quotient: " + quotient);

System.out.println("Truncated number: " + truncatedNumber);

Integer Division:

When two integers are divided, the result is also an integer.

The decimal part of the result is truncated.

In the example, 10 / 3 results in 3.

Truncation:

Casting a floating-point number to an integer discards the decimal part.

In the example, 10.5 is cast to an integer, resulting in 10.

Implicit Type Conversions

public class ImplicitTypeConversion {

public static void main(String[] args) {

int a = 10;

double b = a; // Implicit conversion from int to double

System.out.println("Value of a: " + a);

System.out.println("Value of b: " + b);

In this example, we have an integer variable a and a double variable b. When we assign the
value of a to b, an implicit type conversion occurs. The integer value 10 is automatically
converted to a double value 10.0.

This is a common implicit type conversion in Java, where a smaller data type (like int) is
automatically converted to a larger data type (like double) to avoid data loss.

Output:
Value of a: 10

Value of b: 10.0

Type Casting

public class TypeCastingExample {

public static void main(String[] args) {

double d = 10.5;

int i = (int) d; // Explicit casting to int

System.out.println("Value of d: " + d);

System.out.println("Value of i: " + i);

}
In this example, we have a double variable d and an int variable i. We want to assign the
value of d to i. However, since double is a larger data type than int, we need to perform
explicit type casting.

The expression (int) d explicitly casts the double value 10.5 to an int. During this conversion,
the decimal part is truncated, resulting in the integer value 10.

Calculating Square Roots

public class SquareRootExample {

public static void main(String[] args) {

int number = 25;

double squareRoot = Math.sqrt(number); // Implicit conversion to double

System.out.println("Square root of " + number + " is: " + squareRoot);

Import: We import the Math class from the java.lang package to access mathematical
functions.
Declare a variable: We declare a double variable number and assign it the value 25.
Square Root Calculation:
We use Math.sqrt() method to calculate the square root.
Since Math.sqrt() expects a double argument, the integer number is implicitly converted to a
double value before the calculation.
Implicit Type Conversion:
This is an example of implicit type conversion, where a smaller data type (int) is
automatically converted to a larger data type (double) to avoid data loss.
Output:
The calculated square root, which is a double value, is printed to the console.
Output:
Square root of 25 is: 5.0
STRINGS
1. A String is an object that contains a sequence of characters
Sample 1:
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello"; // No 'new' keyword needed
String str2 = new String("World"); // Using 'new' keyword
}
}
String Declaration:
String str1 = "Hello";: This directly assigns the string literal "Hello" to the str1 variable.
String str2 = new String("World");: This explicitly creates a new String object using the new
keyword and initializes it with the string "World".
Sample 2:
public class StringExample {
public static void main(String[] args) {
String greeting = "Hello, World!";
System.out.println(greeting);

String firstName = "Alice";


String lastName = "Johnson";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
}
}
1. Declaring a String:
String greeting = "Hello, World!"; declares a string variable greeting and assigns the string
literal "Hello, World!" to it.
2. Concatenating Strings:
String fullName = firstName + " " + lastName; concatenates the firstName and lastName
strings with a space in between, creating the fullName string.
3. Printing Strings:
System.out.println(greeting); and System.out.println(fullName); print the contents of the
greeting and fullName strings to the console.
String Operations
public class StringOperations {
public static void main(String[] args) {
String str = "Hello, World!";

// Concatenation
String newStr = str.concat(" How are you?");

// Length
int length = str.length();

// Substring
String subStr = str.substring(7);

// Uppercase
String upperStr = str.toUpperCase();

System.out.println("Concatenated string: " + newStr);


System.out.println("Length of the string: " + length);
System.out.println("Substring: " + subStr);
System.out.println("Uppercase string: " + upperStr);
}
}
Output:
Concatenated string: Hello, World! How are you?
Length of the string: 13
Substring: World!
Uppercase string: HELLO, WORLD!
Instantiating a String
String str1 = "Hello";: This directly assigns the string literal "Hello" to the str1 variable.
String str2 = new String("World");: This explicitly creates a new String object using the new
keyword and initializes it with the string "World".
String References
public class StringReferenceExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = str1;

System.out.println("str1: " + str1); // Output: Hello


System.out.println("str2: " + str2); // Output: Hello

str2 = "World";

System.out.println("str1: " + str1); // Output: Hello


System.out.println("str2: " + str2); // Output: World
}
}
 String References: Both str1 and str2 are references to the same string object "Hello".
 Initial Output: Both variables print the same value "Hello".
 Reassignment: When str2 is assigned "World", it creates a new string object and
points to it.
 Immutability: The original "Hello" string remains unchanged.
 Final Output: str1 still points to the original "Hello", while str2 now points to the new
"World" string.
String Concatenation
public class StringConcatenation {
public static void main(String[] args) {
String firstName = "Alice";
String lastName = "Johnson";
// Concatenation using + operator
String fullName1 = firstName + " " + lastName;

// Concatenation using += operator


String fullName2 = firstName;
fullName2 += " " + lastName;

System.out.println(fullName1); // Output: Alice Johnson


System.out.println(fullName2); // Output: Alice Johnson
}
}
 Using the + operator:
The + operator is used to concatenate two or more strings.
In this case, firstName and lastName are concatenated with a space in between.
 Using the += operator:
The += operator is a shorthand for concatenation.
fullName2 is initially assigned the value of firstName.
Then, " " + lastName" is concatenated to fullName2.
Escape Sequences
public class EscapeSequences {
public static void main(String[] args) {
String text = "Hello,\nWorld!\n\"This is a string with quotes.\"";
System.out.println(text);
}
}
Output:
Hello,
World!
"This is a string with quotes."
Explanation
\n: Newline character. It inserts a new line in the output.
\": Double quote character. It allows you to include double quotes within a string.
compareTo() Method
public class CompareToExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
int result = str1.compareTo(str2);
System.out.println("Comparison result: " + result); // Output: Negative value
}
}
The compareTo() method is used to compare two strings lexicographically. It returns:
 A negative integer if the current string is lexicographically less than the argument
string.
 A positive integer if the current string is lexicographically greater than the argument
string.
 Zero if the strings are equal.
In the example above:
 str1 ("Hello") is lexicographically less than str2 ("World").
 Therefore, str1.compareTo(str2) returns a negative integer.
equals() Method
public class EqualsExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");

System.out.println(str1.equals(str2)); 1 // Output: true


System.out.println(str1.equals(str3)); // Output: true
}
}
The equals() method is used to compare the content of two strings. It returns:
 true if the strings have the same sequence of characters.
 false otherwise.
In the example above:
 str1 and str2 refer to the same string object in the string pool, so they are considered
equal.
 str3 is a different object, but it has the same character sequence as str1 and str2, so
the equals() method returns true for both comparisons.
Comparing Strings with ==
In Java, the == operator compares string references, not their content. If two strings point to
the same memory location, == returns true. Otherwise, it returns false, even if the strings
have the same content.
public class CompareStrings {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "Java";
String str3 = new String("Java");

System.out.println(str1 == str2); // true (same reference in string pool)


System.out.println(str1 == str3); // false (different reference)
System.out.println(str1.equals(str3)); // true (same content)
}
}
Output:
true
false
true
Explanation
String str1 = "Java";
Creates a string literal "Java" and stores it in the string pool. str1 points to this location.
String str2 = "Java";
Since "Java" is already in the string pool, str2 points to the same reference as str1.
String str3 = new String("Java");
A new String object is explicitly created in heap memory. str3 points to this new object, not
the string pool.
System.out.println(str1 == str2);
Compares str1 and str2 references.
Both point to the same string pool location, so it prints true.
System.out.println(str1 == str3);
Compares str1 (points to the pool) and str3 (points to the heap).
They reference different memory locations, so it prints false.
System.out.println(str1.equals(str3));
Uses the .equals() method, which compares the content of the strings.
Both str1 and str3 have the content "Java", so it prints true.
length(), substring(), indexOf, charAt
public class StringMethods {
public static void main(String[] args) {
String str = "Hello, World!";

// Length of the string


int length = str.length();

// Substring from index 7 to the end


String substring = str.substring(7);

// Index of the first occurrence of 'o'


int indexOfO = str.indexOf('o');

// Character at index 1
char firstChar = str.charAt(1);

System.out.println("Length: " + length);


System.out.println("Substring: " + substring);
System.out.println("Index of 'o': " + indexOfO);
System.out.println("First character: " + firstChar);
}
}
Explanation:
 length(): Returns the number of characters in the string.
 substring(int index): Returns a substring starting from the specified index.
 indexOf(char ch): Returns the index of the first occurrence of the specified character.
 charAt(int index): Returns the character at the specified index.
Output
Length: 13
Substring: World!
Index of 'o': 4
First character: e
Prompting the User for Input: Scanner
The Scanner class in Java is essential for creating interactive programs that can receive input
from the user.
Import Scanner: The java.util.Scanner class is imported to create a scanner object.
Common Methods of the Scanner Class:
 next(): Reads the next token (word) from the input.
 nextLine(): Reads an entire line of input.
 nextInt(): Reads the next integer value.
 nextDouble(): Reads the next double value.
 nextBoolean(): Reads the next boolean value.
Relational operators in java
public class RelationalOperators {
public static void main(String[] args) {
int a = 10;
int b = 5;

// Equal to (==)
System.out.println(a == b); // Output: false

// Not equal to (!=)


System.out.println(a != b); // Output: true

// Greater than (>)


System.out.println(a > b); // Output: true

// Less than (<)


System.out.println(a < b); // Output: false

// Greater than or equal to (>=)


System.out.println(a >= b); // Output: true

// Less than or equal to (<=)


System.out.println(a <= b); // Output: false
}
}
Relational operators are used to compare values and return a boolean result (true or
false). In the code above:
 ==: Checks for equality.
 !=: Checks for inequality.
 >: Checks if the left operand is greater than the right operand.
 <: Checks if the left operand is less than the right operand.
 >=: Checks if the left operand is greater than or equal to the right operand.
 <=: Checks if the left operand is less than or equal to the right operand.1
Logic operators in java
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true;
boolean b = false;

// Logical AND (&&)


System.out.println(a && b); // Output: false

// Logical OR (||)
System.out.println(a || b); // Output: true

// Logical NOT (!)


System.out.println(!a); // Output: false
}
}
Explanation:
 Logical AND (&&): Both operands must be true for the result to be true.
 Logical OR (||): At least one operand must be true for the result to be true.
 Logical NOT (!): Inverts the boolean value of the operand.
if else statement in java
public class IfElseExample {
public static void main(String[] args) {
int age = 25;

if (age >= 18) {


System.out.println("You are an adult.");
} else {
System.out.println("You 1 are a minor.");
}
}
}
Explanation:
 if statement: Checks a condition. If the condition is true, the code inside the if block
is executed.
 else statement: If the condition in the if statement is false, the code inside the else
block is executed.
 In this example, the age is 25, which is greater than or equal to 18. So, the condition
in the if statement is true, and the message "You are an adult." is printed.
Switch statement in java
public class SwitchExample {
public static void main(String[] args) {
int day = 4;

switch (day) {
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;
default:
System.out.println("Invalid day");
}
}
}
Explanation:
 The switch statement is used to execute different code blocks based on the value of
an expression.
 The case labels specify the values to be matched against the expression.
 The break statement is used to exit the switch block after executing the
corresponding case.
 The default case is optional and is executed if none of the case labels match the
expression.
 In this example, the value of day is 4, so the code inside the case 4 block is executed,
printing "Thursday" to the console.
Switch expression statement in java
public class SwitchExpressionExample {
public static void main(String[] args) {
int day = 4;

String dayName = switch (day) {


case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
default -> "Invalid day";
};

System.out.println("Today is " + dayName);


}
}
 It replaces traditional switch statements with a more concise and readable syntax.
 Arrow Operator (->): Used to associate a case label with an expression.
 Concise Syntax: Eliminates the need for break statements.
 The result of the expression is assigned to the dayName variable.
Ternary operators in java
The ternary operator, also known as the conditional operator, is a concise way to express
conditional logic. It has the following syntax:
condition ? expression1 : expression2
Condition: An expression that evaluates to a boolean value (true or false).
Expression1: The expression to be evaluated if the condition is true.
Expression2: The expression to be evaluated if the condition is false.

public class TernaryOperatorExample {


public static void main(String[] args) {
int number = 10;
String result;
result = (number > 0) ? "Positive" : "Negative or Zero";
System.out.println(result); // Output: Positive
}
}
In the example above:
 The condition number > 0 is evaluated to true.
 Therefore, the expression Positive is assigned to the result variable.
 Ternary operators can be used to make code more concise and readable, especially
for simple conditional assignments. However, they should be used judiciously to
avoid making the code too complex.
While Loop
A while loop is a control flow statement that repeatedly executes a block of code as long as a
given condition is true.
Syntax
while (condition) {
// code to be executed
}
Example
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5
In the example above:
 The loop starts with i = 1.
 The condition i <= 5 is checked. Since it's true, the loop body executes.
 The value of i is printed.
 i is incremented by 1.
 The loop repeats until i becomes 6, at which point the condition is false, and the loop
terminates.
do-while Loop
A do-while loop is similar to a while loop, but it executes the loop body at least once,
regardless of the initial condition.
Syntax:
do {
// code to be executed
} while (condition);
How it works:
 Code Execution: The code inside the loop body is executed first.
 Condition Check: The condition is then evaluated.
 Repeat: If the condition is true, the loop body is executed again, and the process
repeats.
Example
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;

do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
Output:
1
2
3
4
5
In the example above:
 The loop body prints the value of i (initially 1).
 i is incremented to 2.
 The condition i <= 5 is checked, which is true.
 The loop body executes again, printing 2.
 This process continues until i becomes 6, at which point the condition is false, and
the loop terminates.
For Loop
A for loop is a control flow statement that executes a block of code a specific number of
times.
Syntax
for (initialization; condition; increment/decrement) {
// code to be executed
}
How it works:
 Initialization: The initialization statement is executed once, before the loop starts.
 Condition Check: The condition is evaluated. If it's true, the loop body is executed.
 Code Execution: The code inside the loop body is executed.
 Increment/Decrement: The increment/decrement statement is executed.
 Repeat: Steps 2-4 are repeated until the condition becomes false.
Example
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
In the example above:
 The int i = 1 initializes the loop counter i to 1.
 The condition i <= 5 is checked. Since it's true, the loop body executes.
 The value of i is printed.
 i is incremented by 1.
 The loop repeats until i becomes 6, at which point the condition is false, and the loop
terminates.
Break and Continue Statements in Java
 These statements are used to control the flow of loops in Java.
Break Statement:
 Immediately terminates the innermost loop it's inside.
 Execution jumps to the statement immediately following the loop.
Continue Statement:
 Skips the remaining code within the current iteration of the loop.
 The loop moves to the next iteration.
Example:
public class BreakContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Breaks out of the loop when i is 3
}
System.out.println(i);
}

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


if (i == 3) {
continue; // Skips the rest of the iteration when i is 3
}
System.out.println(i);
}
}
}
Output:
1
2
1
2
4
5
Explanation:
 First loop: When i reaches 3, the break statement is executed, and the loop
terminates.
 Second loop: When i reaches 3, the continue statement skips the println statement
for that iteration, and the loop proceeds to the next iteration.
Arrays
Declaring an Array
• An array declaration can be done in one or two lines
Example
public class ArrayExample {
public static void main(String[] args) {
// One-line declaration and initialization
int[] numbers = {1, 2, 3, 4, 5};

// Two-line declaration and initialization


String[] fruits = new String[3];
fruits[0] = "Apple";
fruits[1] = "Banana";
fruits[2] = "Orange";

// Accessing elements
System.out.println(numbers[2]); // Output: 3
System.out.println(fruits[1]); // Output: Banana
}
}
Explanation:
One-line Declaration and Initialization:
 int[] numbers = {1, 2, 3, 4, 5}; directly declares and initializes an integer array with
five elements.
Two-line Declaration and Initialization:
 String[] fruits = new String[3]; declares an array of strings with a size of 3.
 Each element is then assigned a value using the index.
Arrays Object Types
In Java, arrays can hold objects of any data type, including primitive data types and other
objects.
Example
public class ArrayObjectTypes {
public static void main(String[] args) {
// Array of Strings
String[] names = {"Alice", "Bob", "Charlie"};

// Array of Integers
int[] numbers = {1, 2, 3, 4, 5};

// Array of Objects
Object[] objects = {10, "Hello", 3.14};

// Accessing elements
System.out.println("Name: " + names[1]);
System.out.println("Number: " + numbers[2]);
System.out.println("Object: " + objects[0]);
}
}
Array of Strings:
 String[] names = {"Alice", "Bob", "Charlie"}; declares an array of strings.
 Each element in the array is a string object.
Array of Integers:
 int[] numbers = {1, 2, 3, 4, 5}; declares an array of integers.
 Each element in the array is an integer value.
Array of Objects:
 Object[] objects = {10, "Hello", 3.14}; declares an array of objects.
 This array can hold objects of different data types, as long as they are all instances of
the Object class or its subclasses.
Accessing Elements:
 Array elements are accessed using their index, which starts from 0. For example,
names[1] accesses the second element of the names array, which is "Bob".
Accessing Array Length
public class ArrayLengthExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Get the length of the array
int length = numbers.length;

System.out.println("Length of the array: " + length);


}
}
Output:
Length of the array: 5
Explanation:
 The length property of an array provides the number of elements in the array. It's
important to note that array indices in Java start from 0, so the last index of an array
is always length - 1.
For Each Loop
A for-each loop, also known as an enhanced for loop, is a simplified way to iterate over
elements of an array or collection. It's particularly useful when you don't need to know the
index of each element.
Syntax
for (data_type variable : array_name) {
// code to be executed
}
How it works:
 Initialization: The loop variable number is declared and initialized with the first
element of the numbers array.
 Condition Check: The loop continues as long as there are more elements in the array.
 Code Execution: The code inside the loop body is executed with the current element
assigned to the loop variable number.
 Increment: The loop variable automatically moves to the next element in the array.
Example
public class ForEachLoopExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

// Iterate over the array using a for-each loop


for (int number : numbers) {
System.out.println(number);
}
}
}
Output:
10
20
30
40
50
 The for-each loop iterates over each element in the numbers array and prints its
value. This approach is often more concise and readable than a traditional for loop.
Two Dimensional Arrays
A two-dimensional array, also known as a matrix, is an array of arrays. It's used to represent
tabular data with rows and columns.
data_type[][] array_name;
Accessing Elements:
To access an element at a specific row and column, use the following syntax:
array_name[row_index][column_index]
Example
public class TwoDimensionalArrayExample {
public static void main(String[] args) {
String[][] names = {
{"Alice", "Bob"},
{"Charlie", "David"}
};

// Accessing elements
System.out.println("Name at row 1, column 0: " + names[1][0]);
}
}
Output:
Name at row 1, column 0: Charlie
Explanation:
In this example, we create a two-dimensional array of strings. Each element in the outer
array is an array of strings itself.
names[0][0] accesses "Alice"
names[0][1] accesses "Bob"
names[1][0] accesses "Charlie"
names[1][1] accesses "David"
Length of Outer and Inner Arrays in a Two-Dimensional Array
public class TwoDimensionalArrayLength {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Length of the outer array (number of rows)


int rows = matrix.length;

// Length of the inner array (number of columns)


int columns = matrix[0].length;

System.out.println("Number of rows: " + rows);


System.out.println("Number of columns: " + columns);
}
}
Output:
Number of rows: 3
Number of columns: 3
Explanation:
 matrix.length: This gives the number of rows in the two-dimensional array.
 matrix[0].length: This gives the number of columns in the first row. Since all rows in a
2D array have the same number of columns, we can use this to get the number of
columns for any row.
 In this example, the outer array matrix has 3 rows, and each inner array (row) has 3
columns.
Two-Dimensional Arrays of Objects in Java
A two-dimensional array of objects in Java is a data structure that stores objects in a tabular
format, similar to a spreadsheet. Each element in the array can reference an object of any
data type.
Syntax
Object[][] arrayName = new Object[rows][columns];
Example
public class TwoDimensionalArrayObjects {
public static void main(String[] args) {
Object[][] data = new Object[2][3];

data[0][0] = "Alice";
data[0][1] = 25;
data[0][2] = 3.14;

data[1][0] = "Bob";
data[1][1] = 30;
data[1][2] = true;

// Accessing elements
System.out.println("Name: " + data[0][0]);
System.out.println("Age: " + data[0][1]);
System.out.println("Pi: " + data[0][2]);
}
}
Explanation:
In this example, we create a two-dimensional array data of type Object[][]. This allows us to
store different data types (String, Integer, Double) in the same array.
data[0][0] stores the string "Alice".
data[0][1] stores the integer 25.
data[0][2] stores the double value 3.14.
Nested For Loop
Nested Loops are loops within loops. They are used to create patterns, iterate over multi-
dimensional arrays, and perform repetitive tasks that require multiple levels of iteration.
Syntax
for (initialization1; condition1; increment/decrement1) {
for (initialization2; condition2; increment/decrement2) {
// code to be executed
}
}
 Outer Loop: The outer loop iterates a specific number of times.
 Inner Loop: For each iteration of the outer loop, the inner loop executes a specific
number of times.
 Nested Execution: The code within the inner loop is executed for each combination
of outer and inner loop iterations.
Example
public class NestedLoopsExample {
public static void main(String[] args) {
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i * j + " ");
}
System.out.println();
}
}
}
Output:
123
246
 The outer loop iterates twice (i = 1, 2).
 For each outer loop iteration, the inner loop iterates three times (j = 1, 2, 3).
 The product of i and j is printed for each combination of i and j.
 After each inner loop completes, a newline character is printed to move to the next
row.
Errors
There are three types of errors:
−Syntax errors
−Logic errors
−Exceptions
Syntax Errors: Missing Semicolons and Incorrect Symbols
public class SyntaxErrorsExample {
public static void main(String[] args) {
int x = 10
System.out.println(x); // Missing semicolon

int y = 5;
int z = y; // Incorrect assignment operator

System.out.println("The value of z is: " + z);


}
}
Explanation:
Missing Semicolon:
 Every statement in Java must end with a semicolon (;).
 In the first line, the missing semicolon causes a compilation error.
Incorrect Assignment Operator:
 The = operator is used for assignment.
 The == operator is used for comparison.
 In the second line, y = z is incorrect and should be z = y to assign the value of y to z.
Corrected Code:
public class CorrectedExample {
public static void main(String[] args) {
int x = 10;
System.out.println(x);

int y = 5;
int z = y;

System.out.println("The value of z is: " + z);


}
}
Output:
10
The value of z is: 5
Syntax Errors: Misspelling Methods or Variables
Syntax errors occur when the program violates Java's grammar rules, such as misspelling
method names or variables. These errors are caught at compile-time and prevent the
program from running.
Sample Java Code:
public class SyntaxErrorExample {
public static void main(String[] args) {
int number = 10;
System.out.println(numbber); // Misspelled variable 'number'
System.ouut.println("Hello"); // Misspelled method 'out'
}
}
Explanation:
 The variable numbber is misspelled.
 The method ouut is misspelled.
 Both errors result in compile-time failures.
Logic Errors in Java
Logic errors occur when the code compiles and runs without errors, but the output is
incorrect due to a flaw in the program's logic. These errors can be difficult to identify and
debug as the compiler doesn't flag them.
Example
public class LogicErrorExample {
public static void main(String[] args) {
int a = 10;
int b = 5;

// Incorrect calculation: Should be a * b


int product = a + b;

System.out.println("Product of a and b: " + product); // Output: 15


}
}
Explanation:
In this example, the intended operation is to multiply a and b, but due to a typo, the *
operator is mistakenly replaced with +. This results in an incorrect output of 15 instead of
the correct answer 50.

You might also like