Unit 1 Notes
Unit 1 Notes
String: Used to represent a sequence of characters. In Java, strings are objects and
belong to the String class.
Arrays: Collections of elements of a single type. For example, int[] numbers = {1,
2, 3, 4}; represents an array of integers.
// Array example
int[] numbers = {1, 2, 3, 4, 5};
}
}
II - Java Operators
Operators in Java allow you to perform various computations and control the flow of your
program.
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations.
Example:
int a = 10, b = 5;
System.out.println("Addition: " + (a + b)); // 15
System.out.println("Subtraction: " + (a - b)); // 5
System.out.println("Multiplication: " + (a * b)); // 50
System.out.println("Division: " + (a / b)); // 2
System.out.println("Modulus: " + (a % b)); // 0
2. Relational Operators
Relational operators compare two values and return a boolean result ( true or false ).
Example:
int a = 10, b = 5;
System.out.println("Equal to: " + (a == b)); // false
System.out.println("Not equal to: " + (a != b)); // true
System.out.println("Greater than: " + (a > b)); // true
System.out.println("Less than: " + (a < b)); // false
System.out.println("Greater or equal: " + (a >= b)); // true
System.out.println("Less or equal: " + (a <= b)); // false
3. Logical Operators
Logical operators are used to perform logical AND , OR , and NOT operations on boolean
expressions.
Example:
Example:
int a = 10;
a += 5; // Equivalent to a = a + 5
System.out.println("a after += 5: " + a); // 15
a *= 2; // Equivalent to a = a * 2
System.out.println("a after *= 2: " + a); // 30
5. Bitwise Operators
Bitwise operators perform operations on binary representations of integers.
Example:
int a = 5, b = 3; // a = 0101, b = 0011 in binary
System.out.println("Bitwise AND: " + (a & b)); // 1 (0001)
System.out.println("Bitwise OR: " + (a | b)); // 7 (0111)
System.out.println("Bitwise XOR: " + (a ^ b)); // 6 (0110)
System.out.println("Bitwise NOT of a: " + (~a)); // -6
System.out.println("Left shift a by 1: " + (a << 1)); // 10 (1010)
System.out.println("Right shift a by 1: " + (a >> 1)); // 2 (0010)
Example:
int a = 5;
System.out.println("Pre-Increment: " + (++a)); // 6
System.out.println("Post-Increment: " + (a++)); // 6, then a becomes 7
System.out.println("a after Post-Increment: " + a); // 7
System.out.println("Pre-Decrement: " + (--a)); // 6
System.out.println("Post-Decrement: " + (a--)); // 6, then a becomes 5
7. Ternary Operator
The ternary operator ( ? : ) is a shorthand for if-else conditions. It evaluates a boolean
expression and returns one of two values based on the result.
Syntax:
result = (condition) ? valueIfTrue : valueIfFalse;
Example:
int a = 5, b = 10;
int max = (a > b) ? a : b;
System.out.println("Max value is: " + max); // 10
1. Simple if Statement
The if statement evaluates a condition inside its parentheses. If the condition is true, the
code block within the if statement is executed.
Syntax:
if (condition) {
// code to execute if condition is true
}
Example:
In this example, the program checks if age is greater than or equal to 18. If true, it prints the
eligibility message.
2. if-else Statement
The if-else statement provides an alternative action if the condition is false. The if block
executes if the condition is true, and the else block executes if it’s false.
Syntax:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
Example:
In this example, if age is less than 18, it displays a message indicating ineligibility.
3. else if Ladder
The else if ladder is used to test multiple conditions sequentially. Once a condition is true,
its corresponding block is executed, and the ladder stops.
Syntax:
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else if (condition3) {
// code if condition3 is true
} else {
// code if none of the conditions are true
}
Example:
Here, marks is checked against multiple conditions, and only the first true condition’s block
executes.
4. Nested if Statement
A nested if is an if statement within another if or else block, allowing multiple levels
of conditions.
Syntax:
if (condition1) {
if (condition2) {
// code if both condition1 and condition2 are true
}
}
Example:
In this example, eligibility is checked based on both age and weight . Only if both are true
does the program print that the person is eligible.
5. switch Statement
The switch statement is used when multiple conditions are based on a single variable or
expression, usually an integer, string, or enum. It allows checking several values in a clear,
concise manner.
Syntax:
switch (variable) {
case value1:
// code if variable == value1
break;
case value2:
// code if variable == value2
break;
// other cases
default:
// code if none of the cases are matched
}
Example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
Here, day is checked against the case values. Since it matches 3 , it prints "Wednesday".
Syntax:
while (condition) {
// code to execute while the condition is true
}
Example:
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
In this example, the loop prints numbers 1 to 5. The condition checks if i is less than or
equal to 5, incrementing i each time.
2. do-while Loop
The do-while loop is similar to while , but it guarantees at least one execution of the code
block, as the condition is evaluated at the end of the loop.
Syntax:
do {
// code to execute at least once
} while (condition);
Example:
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
Here, the loop prints numbers 1 to 5, with i incremented after each iteration. Since the
condition is evaluated after the block, the loop executes at least once, even if the condition is
initially false.
3. for Loop
The for loop is typically used when the number of iterations is known beforehand. It
initializes a variable, checks a condition, and updates the variable in one line.
Syntax:
Example:
This example prints numbers 1 to 5. The for loop initializes i , checks the condition, and
increments i after each iteration.
Syntax:
Example:
This example prints a 3x3 grid of asterisks. The outer loop manages rows, and the inner
loop manages columns.
5. for-each Loop
The for-each loop (enhanced for loop) is specifically designed to iterate over arrays or
collections. It’s simpler than a for loop, especially when you don’t need to track the index.
Syntax:
Example:
This loop iterates through each element in the numbers array and prints it.
6. break Statement
The break statement is used to exit a loop immediately, regardless of the loop’s condition.
It’s commonly used in situations where a certain condition requires stopping the loop early.
Example:
This example stops printing at 2 because the loop exits when i is equal to 3.
7. continue Statement
The continue statement skips the current iteration and moves to the next one. It’s often
used when certain conditions require skipping part of the loop’s code but not ending the loop
itself.
Example:
Here, the number 3 is skipped, but the loop continues to print 1, 2, 4, and 5.
Classes: The blueprint for creating objects, containing attributes (fields) and behaviors
(methods).
Objects: Instances of classes that represent entities with specific properties.
Methods: Blocks of code performing specific tasks. Defined inside classes, they
operate on data and often return results.
Variables: Containers for storing data values.
Interfaces: Contracts defining a set of methods a class can implement.
Packages: Collections of classes and interfaces that help organize and modularize
code (e.g., java.util , java.io ).
In Java, code is organized into packages, classes, and methods, creating a clear and
structured approach to building applications.
2. Java Tokens
Tokens are the smallest individual elements in Java and include:
Keywords: Reserved words with specific meanings, like class , public , static .
Identifiers: Names given to variables, methods, classes, etc. They must start with a
letter, $ , or _ and cannot be keywords.
Literals: Constants directly assigned to variables, like 42 , 3.14 , 'a' , "Hello" .
Operators: Symbols that perform operations on values (e.g., + , - , * , && ).
Separators: Characters that separate code elements, like parentheses () , braces {} ,
and semicolons ; .
Java uses these tokens to create syntactically correct statements and expressions.
3. Statements
Java statements are individual instructions for the Java Virtual Machine (JVM) to execute.
They include:
Example:
4. Command-Line Arguments
Java allows programs to receive input from the command line, stored in the String[] args
parameter of the main method.
Example:
public class CommandLineExample {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for (String arg : args) {
System.out.println(arg);
}
}
}
// To run: java CommandLineExample arg1 arg2 arg3
Command-line arguments are useful for running programs with custom inputs without
modifying the code.
Example:
import java.util.Scanner;
System.out.println("Hello, " + name + ". You are " + age + " years
old.");
scanner.close();
}
}
6. Escape Sequences
Escape sequences allow us to represent special characters within strings. Some common
sequences:
Escape sequences are essential for formatting output and displaying complex text.
7. Comments in Java
Java supports three types of comments:
Example:
/* This is a
multi-line comment */
/**
* This is a documentation comment
* Used for generating JavaDocs.
*/
Example:
9. Type Casting
Java supports both implicit (automatic) and explicit (manual) casting:
Example:
Example:
final int MAX_SCORE = 100;
%d for integers
%f for floating-point numbers
%s for strings
Example:
Example:
Example:
final int MAX = 100;
Associativity Operators
Direction
Left-to-Right * , / , % , + , - , << , >> , >>> , < , <= , > , >= , == , != , & , ^ ,
` , && ,
Right-to-Left = , += , -= , *= , /= , %= , &= , = , ^= , <<= , >>= , >>>= , ++ , -- ,
+ (Unary), - (Unary), ~ , ! , ?: