Notes
Notes
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
}
3. Use a combination of letters or a combination of letters and numbers:
5. The only symbols allowed are the underscore (_) and the dollar sign ($):
Scope of Variable
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
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
System.out.println(result2); // Output: 12
System.out.println(result3); // Output: 12
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 : =
int a = 10;
int b = 3;
// Integer division: Divides two integers and returns the integer quotient
Integer Division:
Truncation:
int a = 10;
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
double d = 10.5;
}
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.
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);
// Concatenation
String newStr = str.concat(" How are you?");
// Length
int length = str.length();
// Substring
String subStr = str.substring(7);
// Uppercase
String upperStr = str.toUpperCase();
str2 = "World";
// Character at index 1
char firstChar = str.charAt(1);
// Equal to (==)
System.out.println(a == b); // Output: false
// Logical OR (||)
System.out.println(a || b); // Output: true
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;
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);
}
// 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;
// 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}
};
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
int y = 5;
int z = y;