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

UNIT-I Object-Oriented Programming Updated

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also covers basic Java programming elements such as data types, variables, operators, and user input, along with examples of simple Java programs and best practices for coding style. Additionally, the document discusses the use of comments, escape sequences, and the Javadoc tool for documentation.

Uploaded by

Praveena
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

UNIT-I Object-Oriented Programming Updated

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also covers basic Java programming elements such as data types, variables, operators, and user input, along with examples of simple Java programs and best practices for coding style. Additionally, the document discusses the use of comments, escape sequences, and the Javadoc tool for documentation.

Uploaded by

Praveena
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT – I

Object-Oriented Programming (OOP)


Object-Oriented Programming (OOP) in Java: Basic Concepts, Principles, and
Program Structure

Introduction

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of


"objects," which are instances of classes. It aims to implement real-world entities like
inheritance, polymorphism, abstraction, and encapsulation in programming. Java is a widely-
used OOP language.

Basic Concepts and Principles of OOP

1. Class: A blueprint for objects. It defines properties (attributes) and behaviors (methods)
of objects.
2. Object: An instance of a class. Objects represent real-world entities.
3. Inheritance: The mechanism by which one class can inherit properties and behaviors
from another class.
4. Polymorphism: The ability of a variable, function, or object to take multiple forms. It
allows methods to do different things based on the object it is acting upon.
5. Abstraction: Hiding complex implementation details and showing only the essential
features of the object.
6. Encapsulation: The wrapping of data (variables) and code (methods) into a single unit,
typically a class. It restricts direct access to some of an object's components.

Writing Simple Java Programs

Let's write a simple Java program that prints "Hello, World!" to the console.

1. Create a Java file: Create a file named HelloWorld.java.


2. Write the code:

java
Copy code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
3. Compile and run the program:
o Compile: javac HelloWorld.java

o Run: java HelloWorld

Elements or Tokens in Java Programs

Java programs are composed of various elements or tokens. These include:

1. Keywords: Reserved words that have a predefined meaning in Java, such as class,
public, static, void, if, else, etc.
2. Identifiers: Names given to classes, variables, methods, etc. Identifiers must start with a
letter, underscore (_), or dollar sign ($), followed by letters, digits, underscores, or dollar
signs.
3. Literals: Fixed values assigned to variables. Java supports several types of literals
including integer, floating-point, character, string, and boolean.
4. Operators: Symbols that perform operations on variables and values, such as +, -, *, /,
=, ==, etc.

5. Separators: Characters that separate tokens in a Java program, such as ;, ,, ., (), {}, [].

6. Comments: Text in the code that is not executed. Used to explain the code. Java supports
single-line (//) and multi-line (/* ... */) comments.

Java Statements

Statements are instructions executed by the Java interpreter. They form the basic building blocks
of a Java program.

1. Declaration Statements: Declare variables and specify their types.

java
Copy code
int age;
double salary;
2. Expression Statements: Execute operations and assign values.

java
Copy code
age = 25;
salary = 50000.0;
3. Control Flow Statements: Control the flow of execution (e.g., if, for, while).

java
Copy code
if (age > 18) {
System.out.println("Adult");
}
4. Method Calls: Invoke methods.
java
Copy code
System.out.println("Hello, World!");

Command Line Arguments

Command line arguments are parameters passed to the main method when a Java program is
executed. They are stored in the args array.

Example:

java
Copy code
public class CommandLineExample {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
}

To run this program: java CommandLineExample arg1 arg2 arg3

User Input to Programs

Java provides several ways to accept user input. One common way is using the Scanner class.

Example:

java
Copy code
import java.util.Scanner;

public class UserInputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}

Escape Sequences and Comments

 Escape Sequences: Special characters in string literals, such as \n (new line), \t (tab),
\" (double quote), \\ (backslash).

java
Copy code
System.out.println("Hello, \nWorld!"); // prints Hello, (new line)
World!
 Comments:
o Single-line comment: // This is a comment

o Multi-line comment: /* This is a multi-line comment */

Programming Styles

 Indentation: Properly indent your code for readability.


 Naming Conventions:
o Classes: CamelCase, starting with an uppercase letter (HelloWorld).

o Variables and methods: camelCase, starting with a lowercase letter (userName,


printMessage).

o Constants: ALL_UPPERCASE with underscores (MAX_VALUE).

Example of good programming style:

java
Copy code
public class Example {
public static void main(String[] args) {
int number = 5;
if (number > 0) {
System.out.println("Positive number");
} else {
System.out.println("Non-positive number");
}
}
}

Java Statements

Statements in Java are the building blocks of any program. They are instructions that the Java
Virtual Machine (JVM) executes.

Types of Statements

1. Expression Statements: Perform operations such as assignments and method calls.


2. Declaration Statements: Declare variables.

3. Control Flow Statements: Direct the flow of execution (e.g., if, for, while).

Example:

java
Copy code
int a = 10; // Declaration statement
a = a + 5; // Expression statement
System.out.println(a); // Expression statement

Compound Statements

Compound statements (also known as blocks) group multiple statements and are enclosed in
braces {}.

Example:

java
Copy code
{
int b = 20;
System.out.println(b);
}

Command Line Arguments

Java programs can accept command line arguments, which are passed to the main method as a
String array.

Example:

java
Copy code
public class CommandLineExample {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
}

To run the program with command line arguments:

Copy code
java CommandLineExample arg1 arg2 arg3

User Input to Programs

The Scanner class is commonly used to get user input from the console.

Example:

java
Copy code
import java.util.Scanner;

public class UserInputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}

Escape Sequences

Escape sequences are special characters used in string literals to perform certain tasks.

Common escape sequences:

 \n: New line


 \t: Tab

 \\: Backslash

 \": Double quote

Example:

java
Copy code
public class EscapeSequenceExample {
public static void main(String[] args) {
System.out.println("Hello,\nWorld!");
System.out.println("Tab\tSpace");
System.out.println("Backslash: \\");
System.out.println("Double quote: \"");
}
}

Comments

Comments are used to describe and explain the code. They are ignored by the compiler.

Types of Comments

1. Single-line comments: Start with //


2. Multi-line comments: Enclosed between /* and */

3. Documentation comments: Enclosed between /** and */, used by Javadoc tool

Example:

java
Copy code
public class CommentExample {
public static void main(String[] args) {
// This is a single-line comment
System.out.println("Hello, World!"); /* This is a multi-line comment
*/
}
}

Programming Styles

Programming style refers to the conventions and best practices used to write clean, readable, and
maintainable code.

Common Programming Styles

1. Naming Conventions: Use camelCase for variables and methods, PascalCase for classes.
2. Indentation: Use consistent indentation to enhance readability.

3. Code Documentation: Write comments and use Javadoc to document your code.

4. Modularization: Break down your code into small, reusable methods and classes.

Example:

java
Copy code
public class ProgrammingStyleExample {
public static void main(String[] args) {
int userAge = 25; // CamelCase for variable names
System.out.println("User age: " + userAge);
}

// PascalCase for class names


public static void printMessage(String message) {
System.out.println(message);
}
}

Javadoc

Javadoc is a tool for generating API documentation in HTML format from doc comments in the
source code.

Example:

java
Copy code
/**
* This is a Javadoc comment.
* @author John
*/
public class JavadocExample {
/**
* This method prints a greeting message.
* @param name The name to greet.
*/
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
}

Data Types, Variables, and Operators in Java

Introduction

Understanding data types, variables, and operators is fundamental to writing effective Java
programs. This section covers the basics of data types, how to declare and use variables, and the
different operators available in Java.

Data Types in Java

Java is a statically-typed language, meaning all variables must be declared with a specific data
type. Data types specify the size and type of values that can be stored in variables.

Primitive Data Types

Java has eight primitive data types:

1. byte: 8-bit signed integer.


2. short: 16-bit signed integer.
3. int: 32-bit signed integer.
4. long: 64-bit signed integer.
5. float: 32-bit floating-point number.
6. double: 64-bit floating-point number.
7. char: 16-bit Unicode character.
8. boolean: true or false.

Example:

java
Copy code
byte b = 100;
short s = 10000;
int i = 100000;
long l = 100000L;
float f = 10.5f;
double d = 10.5;
char c = 'A';
boolean bool = true;

Non-Primitive Data Types

Non-primitive data types (reference types) include classes, interfaces, and arrays. Examples
include String, ArrayList, and custom classes.

Example:

java
Copy code
String str = "Hello, World!";
int[] numbers = {1, 2, 3, 4, 5};

Declaration of Variables

A variable is a container for storing data values. Variables must be declared with a type before
they can be used.

Syntax:

java
Copy code
type variableName;
type variableName = value;

Example:

java
Copy code
int age;
double salary = 50000.0;

Type Casting

Type casting is converting a variable from one data type to another. There are two types of
casting in Java:

1. Implicit (Widening) Casting: Automatically converting a smaller type to a larger type


size.

java
Copy code
int i = 100;
long l = i; // implicit casting
float f = l; // implicit casting
2. Explicit (Narrowing) Casting: Manually converting a larger type to a smaller type size.

java
Copy code
double d = 9.78;
int i = (int) d; // explicit casting

Scope of Variable Identifier

The scope of a variable is the part of the program where the variable is accessible. Java has
several types of variable scope:

1. Local Variables: Declared inside a method or block. Accessible only within that method
or block.
2. Instance Variables: Declared inside a class but outside any method. Accessible by all
methods in the class.
3. Class/Static Variables: Declared with the static keyword inside a class but outside any
method. Shared among all instances of the class.

Literal Constants and Symbolic Constants

 Literal Constants: Fixed values assigned to variables. Examples include 100, 3.14, 'A',
"Hello", true.
 Symbolic Constants: Variables declared as final to represent constant values.

Example:

java
Copy code
final int MAX_VALUE = 100;

Formatted Output with printf()

The printf() method in Java allows formatted output. It is similar to the printf() function in
C.

Example:

java
Copy code
System.out.printf("Name: %s, Age: %d, Salary: %.2f", "John", 25, 30000.00);

Static Variables and Methods

 Static Variables: Variables that are shared among all instances of a class. Declared using
the static keyword.
 Static Methods: Methods that belong to the class rather than any object instance. Can be
called without creating an instance of the class.
Example:

java
Copy code
public class Example {
static int count = 0;

static void increment() {


count++;
}
}

public class Main {


public static void main(String[] args) {
Example.increment();
System.out.println(Example.count);
}
}

The final Attribute

The final keyword is used to declare constants. A final variable's value cannot be changed
once it is initialized.

Example:

java
Copy code
final int MAX_VALUE = 100;
// MAX_VALUE = 200; // This will cause a compile-time error

Operators in Java

Operators are special symbols that perform operations on variables and values.

Arithmetic Operators

Perform basic arithmetic operations.

 Addition (+)
 Subtraction (-)

 Multiplication (*)

 Division (/)

 Modulus (%)

Example:
java
Copy code
int a = 10;
int b = 5;
System.out.println("a + b = " + (a + b)); // 15
System.out.println("a - b = " + (a - b)); // 5
System.out.println("a * b = " + (a * b)); // 50
System.out.println("a / b = " + (a / b)); // 2
System.out.println("a % b = " + (a % b)); // 0

Increment and Decrement Operators

Increase or decrease the value of a variable by one.

 Increment (++)
 Decrement (--)

Example:

java
Copy code
int x = 10;
x++; // x is now 11
x--; // x is now 10 again

Relational Operators

Compare two values and return a boolean result.

 Equal to (==)
 Not equal to (!=)

 Greater than (>)

 Less than (<)

 Greater than or equal to (>=)

 Less than or equal to (<=)

Example:

java
Copy code
int a = 10;
int b = 5;
System.out.println(a == b); // false
System.out.println(a != b); // true
System.out.println(a > b); // true
System.out.println(a < b); // false
System.out.println(a >= b); // true
System.out.println(a <= b); // false

Boolean Logical Operators

Perform logical operations on boolean values.

 Logical AND (&&)


 Logical OR (||)

 Logical NOT (!)

Example:

java
Copy code
boolean a = true;
boolean b = false;
System.out.println(a && b); // false
System.out.println(a || b); // true
System.out.println(!a); // false

Bitwise Logical Operators

Perform bit-level operations on integer types.

 Bitwise AND (&)


 Bitwise OR (|)

 Bitwise XOR (^)

 Bitwise Complement (~)

 Left Shift (<<)

 Right Shift (>>)

 Unsigned Right Shift (>>>)

Example:

java
Copy code
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
System.out.println(a & b); // 0001 (1 in decimal)
System.out.println(a | b); // 0111 (7 in decimal)
System.out.println(a ^ b); // 0110 (6 in decimal)
System.out.println(~a); // 1010 (two's complement representation of -6)
System.out.println(a << 1); // 1010 (10 in decimal)
System.out.println(a >> 1); // 0010 (2 in decimal)
System.out.println(a >>> 1); // 0010 (2 in decimal)
Type Casting

Type casting is the process of converting one data type into another.

Types of Type Casting

1. Implicit Casting (Widening Conversion)


o Automatic conversion of a smaller type to a larger type.

o Safe because there is no loss of information.

o Example: int to double.

java
Copy code
int num = 10;
double d = num; // Implicit casting
System.out.println(d); // 10.0
2. Explicit Casting (Narrowing Conversion)
o Manual conversion of a larger type to a smaller type.

o May result in loss of information.

o Example: double to int.

java
Copy code
double d = 10.5;
int num = (int) d; // Explicit casting
System.out.println(num); // 10

Scope of Variable Identifier

The scope of a variable determines where the variable can be accessed and modified.

1. Local Variables
o Declared inside a method or block.

o Accessible only within that method or block.

java
Copy code
public void someMethod() {
int localVar = 5; // Local variable
System.out.println(localVar);
}
2. Instance Variables
o Declared inside a class but outside any method.
o Accessible by all methods of the class.

java
Copy code
public class Example {
int instanceVar = 10; // Instance variable

public void display() {


System.out.println(instanceVar);
}
}
3. Class Variables (Static Variables)
o Declared with the static keyword inside a class.

o Shared among all instances of the class.

java
Copy code
public class Example {
static int staticVar = 100; // Static variable

public static void main(String[] args) {


System.out.println(Example.staticVar);
}
}

Literal Constants

Literals are fixed values assigned to variables. They can be of different types:

1. Integer Literals: 10, -20


2. Floating-point Literals: 3.14, -0.01

3. Character Literals: 'a', '1'

4. String Literals: "Hello", "123"

5. Boolean Literals: true, false

java
Copy code
int num = 10; // Integer literal
char letter = 'A'; // Character literal
String text = "Hello"; // String literal
boolean flag = true; // Boolean literal

Symbolic Constants

Symbolic constants are declared using the final keyword and cannot be changed once assigned.

java
Copy code
final int MAX_VALUE = 100;
MAX_VALUE = 200; // Error: Cannot assign a value to final variable 'MAX_VALUE'

Formatted Output with printf()

The printf() method provides a way to format output.

Format Specifiers

 %d: Integer
 %f: Floating-point number

 %s: String

 %c: Character

java
Copy code
int age = 25;
double salary = 50000.50;
String name = "John";

System.out.printf("Name: %s, Age: %d, Salary: %.2f", name, age, salary);


// Output: Name: John, Age: 25, Salary: 50000.50

Static Variables and Methods

Static Variables

Static variables are shared among all instances of a class.

java
Copy code
public class Example {
static int staticVar = 0;

public static void main(String[] args) {


Example.staticVar = 10;
System.out.println(Example.staticVar); // 10
}
}

Static Methods

Static methods can be called without creating an instance of the class.

java
Copy code
public class Example {
static void display() {
System.out.println("This is a static method.");
}

public static void main(String[] args) {


Example.display(); // Call static method without creating an instance
}
}

Attribute final

The final keyword is used to declare constants, prevent inheritance, and prevent method
overriding.

Final Variables

Values cannot be changed once assigned.

java
Copy code
final int MAX_VALUE = 100;

Final Methods

Cannot be overridden by subclasses.

java
Copy code
public class Example {
public final void display() {
System.out.println("This is a final method.");
}
}

Final Classes

Cannot be subclassed.

java
Copy code
public final class FinalClass {
// class code
}

Introduction to Operators in Java

Operators

Operators are special symbols or keywords used to perform operations on variables and values.
Java supports various types of operators:
1. Arithmetic Operators
2. Assignment Operators
3. Increment and Decrement Operators
4. Relational Operators
5. Logical Operators
6. Bitwise Operators
7. Ternary Operator

Precedence and Associativity of Operators

Operator precedence determines the order in which operations are performed in an expression.
Associativity determines the direction in which an expression is evaluated when operators of the
same precedence appear together.

 Precedence: Higher precedence operators are evaluated first.


 Associativity: The direction (left-to-right or right-to-left) in which operators of the same
precedence level are evaluated.

Assignment Operator (=)

The assignment operator is used to assign a value to a variable.

Example:

java
Copy code
int a = 10; // assigns the value 10 to the variable a

Basic Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

1. Addition (+): Adds two operands.

java
Copy code
int sum = 10 + 5; // sum is 15
2. Subtraction (-): Subtracts the second operand from the first.

java
Copy code
int difference = 10 - 5; // difference is 5
3. Multiplication (*): Multiplies two operands.
java
Copy code
int product = 10 * 5; // product is 50
4. Division (/): Divides the first operand by the second.

java
Copy code
int quotient = 10 / 5; // quotient is 2
5. Modulus (%): Returns the remainder when the first operand is divided by the second.

java
Copy code
int remainder = 10 % 3; // remainder is 1

Increment and Decrement Operators

Increment and decrement operators are used to increase or decrease the value of a variable by
one.

1. Increment Operator (++): Increases the value of a variable by one.


o Prefix Increment (++variable): Increments the value before the expression is
evaluated.

java
Copy code
int a = 10;
int b = ++a; // a is incremented to 11, then b is assigned the
value 11
o Postfix Increment (variable++): Increments the value after the expression is
evaluated.

java
Copy code
int a = 10;
int b = a++; // b is assigned the value 10, then a is incremented
to 11
2. Decrement Operator (--): Decreases the value of a variable by one.
o Prefix Decrement (--variable): Decrements the value before the expression is
evaluated.

java
Copy code
int a = 10;
int b = --a; // a is decremented to 9, then b is assigned the
value 9
o Postfix Decrement (variable--): Decrements the value after the expression is
evaluated.

java
Copy code
int a = 10;
int b = a--; // b is assigned the value 10, then a is decremented
to 9

Operator Precedence and Associativity

Here is a summary of the precedence and associativity of some common operators in Java:

Operator Type Operators Associativity


Postfix expr++, expr-- Left to Right
Unary ++expr, --expr, +expr, -expr, ~, ! Right to Left
Multiplicative *, /, % Left to Right
Additive +, - Left to Right
Shift <<, >>, >>> Left to Right
Relational <, >, <=, >=, instanceof Left to Right
Equality ==, != Left to Right
Bitwise AND & Left to Right
Bitwise XOR ^ Left to Right
Bitwise OR ` `
Logical AND && Left to Right
Logical OR `
Ternary ? : Right to Left
Assignment =, +=, -=, *=, /=, %=, &=, ^=, ` =, <<=, >>=, >>>=`

Ternary Operator

The ternary operator is a shorthand for the if-else statement. It takes three operands and is used
to evaluate a boolean expression, returning one of two values based on the result.

Syntax
java
Copy code
condition ? expression1 : expression2;
 condition: A boolean expression.
 expression1: The value returned if the condition is true.

 expression2: The value returned if the condition is false.

Example
java
Copy code
int a = 10;
int b = 20;
int max = (a > b) ? a : b; // max will be 20
System.out.println("The maximum value is " + max);

Relational Operators

Relational operators are used to compare two values. They return a boolean result ( true or
false).

List of Relational Operators

 ==: Equal to
 !=: Not equal to

 >: Greater than

 <: Less than

 >=: Greater than or equal to

 <=: Less than or equal to

Example
java
Copy code
int a = 10;
int b = 20;

System.out.println(a == b); // false


System.out.println(a != b); // true
System.out.println(a > b); // false
System.out.println(a < b); // true
System.out.println(a >= b); // false
System.out.println(a <= b); // true

Boolean Logical Operators

Boolean logical operators are used to perform logical operations on boolean values.

List of Boolean Logical Operators

 &&: Logical AND


 ||: Logical OR

 !: Logical NOT

Example
java
Copy code
boolean a = true;
boolean b = false;

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


System.out.println(a || b); // true
System.out.println(!a); // false

Short-Circuit Evaluation

Logical AND (&&) and OR (||) use short-circuit evaluation, meaning the second operand is
evaluated only if necessary.

Example
java
Copy code
int x = 5;
int y = 10;

if (x > 1 && y < 20) {


System.out.println("Both conditions are true");
}

if (x > 1 || y > 20) {


System.out.println("At least one condition is true");
}

Bitwise Logical Operators

Bitwise operators perform operations on the individual bits of integer values. They are mainly
used for low-level programming.

List of Bitwise Operators

 &: Bitwise AND


 |: Bitwise OR

 ^: Bitwise XOR (exclusive OR)

 ~: Bitwise NOT (complement)

 <<: Left shift

 >>: Right shift

 >>>: Unsigned right shift

Example
java
Copy code
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary

System.out.println(a & b); // 0001 (1 in decimal)


System.out.println(a | b); // 0111 (7 in decimal)
System.out.println(a ^ b); // 0110 (6 in decimal)
System.out.println(~a); // 1010 (inverted bits, -6 in decimal)

System.out.println(a << 1); // 1010 (10 in decimal)


System.out.println(a >> 1); // 0010 (2 in decimal)
System.out.println(a >>> 1); // 0010 (2 in decimal)

Practical Usage

Bitwise operators are often used in systems programming, cryptography, and situations where
performance is critical.

Example of Combining Operators

You can combine different types of operators to create complex expressions.

java
Copy code
int x = 5;
int y = 10;
boolean result = (x < y) && ((x + y) < 20) ? true : false; // true
System.out.println(result);

Control Statements in Java

Control statements allow you to manage the flow of execution in a Java program. They include
conditional statements, loops, and branching statements.

Introduction to Control Statements

Control statements enable decision-making, looping, and branching in programs, making them
more dynamic and responsive to different conditions and inputs.

Conditional Statements

If Expression

The if statement executes a block of code if a specified condition is true.

Syntax:

java
Copy code
if (condition) {
// code to be executed if condition is true
}

Example:

java
Copy code
int age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
}

Nested If Expression

if statements can be nested within other if statements to check multiple conditions.

Syntax:

java
Copy code
if (condition1) {
// code to be executed if condition1 is true
if (condition2) {
// code to be executed if condition2 is true
}
}

Example:

java
Copy code
int number = 10;
if (number > 0) {
System.out.println("Number is positive.");
if (number % 2 == 0) {
System.out.println("Number is even.");
}
}

If-Else Expression

The if-else statement executes one block of code if the condition is true, and another block if
the condition is false.

Syntax:

java
Copy code
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

Example:

java
Copy code
int age = 16;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are not an adult.");
}

Ternary Operator

The ternary operator (? :) is a shorthand for the if-else statement. It takes three operands and
returns a value based on a condition.

Syntax:

java
Copy code
variable = (condition) ? valueIfTrue : valueIfFalse;

Example:

java
Copy code
int age = 18;
String message = (age >= 18) ? "You are an adult." : "You are not an adult.";
System.out.println(message);

Switch Statement

The switch statement executes one block of code from multiple options based on the value of an
expression.

Syntax:

java
Copy code
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// you can have any number of case statements
default:
// code to be executed if expression doesn't match any case
}

Example:

java
Copy code
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");
}

Iteration Statements

While Loop

The while loop repeatedly executes a block of code as long as a specified condition is true.

Syntax:

java
Copy code
while (condition) {
// code to be executed
}

Example:

java
Copy code
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}

Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the block of code is
executed at least once.

Syntax:
java
Copy code
do {
// code to be executed
} while (condition);

Example:

java
Copy code
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);

For Loop

The for loop is used to execute a block of code a specific number of times.

Syntax:

java
Copy code
for (initialization; condition; update) {
// code to be executed
}

Example:

java
Copy code
for (int i = 0; i < 5; i++) {
System.out.println(i);
}

Enhanced For Loop (For-Each Loop)

The enhanced for loop is used to iterate over elements in an array or a collection.

Syntax:

java
Copy code
for (type element : array) {
// code to be executed
}

Example:

java
Copy code
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}

Break and Continue Statements

 Break: Exits the current loop or switch statement.


 Continue: Skips the current iteration of a loop and proceeds to the next iteration.

Example with break:

java
Copy code
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}

Example with continue:

java
Copy code
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
System.out.println(i);
}

While Loop

The while loop repeats a block of code as long as a specified condition is true.

Syntax
java
Copy code
while (condition) {
// Code to be executed
}

Example
java
Copy code
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}

Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the loop body will be
executed at least once because the condition is evaluated after the loop body.

Syntax
java
Copy code
do {
// Code to be executed
} while (condition);

Example
java
Copy code
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);

For Loop

The for loop is commonly used for iterating a specific number of times. It consists of three
parts: initialization, condition, and increment/decrement.

Syntax
java
Copy code
for (initialization; condition; increment/decrement) {
// Code to be executed
}

Example
java
Copy code
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Nested For Loop

A nested for loop is a for loop inside another for loop. It is used to iterate over multi-
dimensional arrays or to perform more complex iterations.

Example
java
Copy code
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i = " + i + ", j = " + j);
}
}

For-Each Loop

The for-each loop, also known as the enhanced for loop, is used to iterate over arrays or
collections.

Syntax
java
Copy code
for (type variable : array/collection) {
// Code to be executed
}

Example
java
Copy code
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}

Break Statement

The break statement is used to exit from a loop or switch statement prematurely.

Example
java
Copy code
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println(i);
}

Continue Statement

The continue statement is used to skip the current iteration of a loop and continue with the next
iteration.

Example
java
Copy code
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}

Combining Break and Continue

Both break and continue can be used to control the flow of loops effectively.

Example
java
Copy code
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}

Practical Usage

Loops and control statements are fundamental tools in programming. They allow for efficient
and concise code, especially when dealing with repetitive tasks and complex logic.

Example: Printing a Multiplication Table


java
Copy code
public class MultiplicationTable {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}
}
}

You might also like