KEMBAR78
Unit2 Java | PDF | Class (Computer Programming) | Control Flow
0% found this document useful (0 votes)
37 views27 pages

Unit2 Java

The document covers key concepts in Java programming, focusing on constants, variables, and data types. It explains how to declare constants using the 'final' keyword, the naming conventions for constants, and the different types of variables and their scopes. Additionally, it details Java's primitive and non-primitive data types, their characteristics, and the importance of choosing the right data type for efficient programming.

Uploaded by

fowmila j
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)
37 views27 pages

Unit2 Java

The document covers key concepts in Java programming, focusing on constants, variables, and data types. It explains how to declare constants using the 'final' keyword, the naming conventions for constants, and the different types of variables and their scopes. Additionally, it details Java's primitive and non-primitive data types, their characteristics, and the importance of choosing the right data type for efficient programming.

Uploaded by

fowmila j
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/ 27

Unit 2-Branching and Looping

Constants, variables, data types,-operators and expressions-decision Making and looping: while,
do while, for- jumps in loops-labeled loops-classes, objects and Methods.
Constants in Java:- A constant is a variable whose value cannot be changed once it has been
initialized. Java doesn't have built-in support for constants. To define a variable as a constant, we
just need to add the keyword "final" in front of the variable declaration. It is not mandatory that
we assign values to constants during declaration.
Syntax of Java Constant

final float pi = 3.14f;

The above statement declares the float variable "pi" as a constant with a value of 3.14f. We
cannot change the value of "pi" at any point in time in the program. Later, if we try to do that by
using a statement like "pi=5.25f", Java will throw errors at compile time itself.
Example: Defining Constants

In the below example, we define the primitive data type (byte, int, double, boolean, and char)
variables as constants by just adding the keyword "final" when we declare the variable.

public class ConstantsDemo {


public static void main(String args[]) {
final byte var1 = 2;
final byte var2;
var2 = -3;
final int var3 = 100;
final int var4;
var4 = -112;
final double var5 = 20000.3223;
final double var6;
var6 = -11223.222;
final boolean var7 = true;
final boolean var8;
var8 = false;
final char var9 = 'e';
final char var10;
var10 = 't';
// Displaying values of all variables
System.out.println("value of var1 : "+var1);
System.out.println("value of var2 : "+var2);
System.out.println("value of var3 : "+var3);
System.out.println("value of var4 : "+var4);
System.out.println("value of var5 : "+var5);
System.out.println("value of var6 : "+var6);
System.out.println("value of var7 : "+var7);
System.out.println("value of var8 : "+var8);
System.out.println("value of var9 : "+var9);
System.out.println("value of var10 : "+var10);
}
}
Output
value of var1 : 2
value of var2 : -3
value of var3 : 100
value of var4 : -112
value of var5 : 20000.3223
value of var6 : -11223.222
value of var7 : true
value of var8 : false
value of var9 : e
value of var10 : t

The final Keyword:-


The final keyword is a non-access modifier and is used with variables, methods, and classes so
that they cannot be changed. Methods that are defined as final cannot be overridden,
and classes that are defined as final cannot be inherited. And, the value of final variables, as
discussed above, cannot be changed as they become constant.
1. Naming Convention
 Constants are usually written in all uppercase letters with underscores separating words.
 This makes them easily identifiable in the code.
 Examples:
final int MAX_VALUE = 100;
final double PI = 3.14159;
2. Scope of Constants
A. Class-Level Constants (Static Constants)
 Declared with public static final.
 Belong to the class, not to any specific object.
 Accessible from anywhere (if public).
 Example:
public class MathConstants {
public static final double PI = 3.14159;
public static final int MAX_VALUE = 100;
}

// Access:
double area = MathConstants.PI * r * r;

B. Instance-Level Constants (Final Instance Variables)


 Declared with final (without static).
 Belong to individual objects.
 Must be initialized when the object is created (either at declaration or in the constructor).
 Example:
public class Circle {
public final double radius;

public Circle(double r) {
radius = r; // Must be initialized
}
}
C. Local Constants
 Declared with final inside a method or block.
 Scope is limited to that method or block.
 Example:
public void calculate() {
final int MAX = 50; // Local constant
System.out.println("Max value: " + MAX);
}

Summary – Constants in Java


 Definition: Constants are variables whose value cannot be changed after initialization.
 Keyword: Declared using the final keyword.
 Naming Convention: Written in UPPERCASE with underscores for readability (e.g.,
MAX_VALUE).
 Types by Scope:
1. Class-Level Constants → public static final → shared across all objects.
2. Instance-Level Constants → final → unique for each object, set at creation.
3. Local Constants → final → exist only inside a method or block.
 Advantages:
o Improves code readability.
o Prevents accidental modification of important values.
o Makes programs easier to maintain.

Java Variables
 In Java, a variable is a name given to a memory location used to store data.
 Each variable has a type that defines the kind of data it can hold, such as numbers, text,
or true/false values.
 Common data types include String for text, int for whole numbers, float for decimal
numbers, char for single characters, and boolean for true/false values.
 Variables can be given values when declared or assigned later in the program. If a new
value is assigned to the same variable, it replaces the old value.
 To make a variable constant (unchangeable), we use the final keyword, and constants are
usually written in uppercase letters.
Rules for Naming Variables in Java
1. Variable names can contain letters, digits, underscore (_), and dollar sign ($).
2. The first character must be a letter, _, or $ — it cannot start with a number.
3. Spaces are not allowed in variable names.
4. Variable names are case-sensitive (age and Age are different).
5. Java keywords (like int, class, public) cannot be used as variable names.
6. Use meaningful names that describe the data (e.g., marks, studentName).
7. Follow camelCase naming style — first word lowercase, each new word starting with
uppercase (totalMarks).
1. What is a Variable?
 A variable is a container for storing data values.
 In Java, variables must have a data type and a name.
 Example:
int age = 25;

2. Common Variable Types

Type Description Example


String Stores text (surrounded by double quotes) "Hello"
int Stores whole numbers (without decimals) 123, -45
float Stores decimal numbers (with 'f' suffix) 19.99f
char Stores a single character (in single quotes) 'A', 'b'
boolean Stores true or false values true, false

3.Declaring Variables
Syntax:
type variableName = value;
Examples:
String name = "John"; // Text
int age = 25; // Integer
float price = 99.50f; // Decimal
4.Declaring Without Assigning
You can declare a variable first and assign later.
Example:
int myNum;
myNum = 15;
System.out.println(myNum);
5.Changing Values
Variables can be updated (overwritten).
int myNum = 15;
myNum = 20; // Previous value replaced
System.out.println(myNum); // Output: 20

6.Final Variables (Constants)


 Use final keyword to make a variable unchangeable.
 Once assigned, its value cannot be modified.
Example:
final int MAX_VALUE = 100;
MAX_VALUE = 200; // ❌ Error: Cannot change final variable

7.Multiple Variables in One Line


int x = 5, y = 10, z = 15;
System.out.println(x + y + z); // Output: 30

8.Memory Representation (Diagram)


Example:
int age = 25;

+-------------+----------------+
| Variable | Value |
+-------------+----------------+
| age | 25 |
+-------------+----------------+
Java stores:
 Variable name → Reference in memory
 Value → Data stored in a memory location

9. Examples of All Types


String myText = "Hello";
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;

System.out.println(myText);
System.out.println(myNum);
System.out.println(myFloatNum);
System.out.println(myLetter);
System.out.println(myBool);

Key Points to Remember


 Variables must have a type before use.
 Variable names cannot start with a number or contain spaces.
 Use camelCase naming (e.g., myNumber).
 final variables act as constants.
 Assigning a new value replaces the old one.

Summary
 Variables store data values in a program.
 Declared with type + name + optional value.
 Can be updated unless declared final.
 Use meaningful names for better code readability.
✅ Quick Revision Table
Feature Normal Final Variable
Variable
Value changeable? Yes No
Keyword None final
Naming style camelCase UPPER_CASE

Other Examples
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
Summary – Java Variables

 Variables store data values of different types.


 Must be declared with a type before use.
 Can be assigned a value at declaration or later.
 Assigning a new value overwrites the old value.
 Use final to make a variable constant (unchangeable)..
 A variable is like a container that holds data in a Java program.
 Each variable:
o Has a name (identifier)
o Has a type (defines kind of data it stores)
o Has a value (the data itself)

Java Data Types


Java is a statically typed programming language, which means that the type of every
variable is known at compile time. The compiler checks that each variable is used
correctly according to its type. For example:
int x = "Hello"; // ❌ Error – Cannot store a string in an int variable
Here, Java gives a compilation error because x is declared as an integer, but a string is
assigned.
Data types in Java define the size, type of values, and range that a variable can store.
Choosing the right data type helps in writing efficient, clear, and error-free programs.
Java Data Types & Examples
Variables must have a data type. Common types:
Type Description Example
String Text values (double quotes) "Hello"
int Whole numbers (no decimals) 25, -5
float Decimal numbers (add 'f' 19.99f
suffix)
char Single character (single quotes) 'A', 'b'
boolean Logical values true, false

Why Data Types Matter in Java?


1. Memory Efficiency – Choosing smaller types like byte instead of int saves memory.
2. Performance – Correct types prevent type conversion overhead and reduce runtime
errors.
3. Code Clarity – Explicit typing makes programs easier to read and maintain.
Categories of Data Types in Java: Java data types are divided into two main categories:
1. Primitive Data Types
 Definition: The basic building blocks in Java that store simple values directly in memory.
 List of Primitive Types:
o boolean – Stores true or false
o char – Stores a single character (e.g., 'A')
o byte – Stores very small integers (-128 to 127)
o short – Stores small integers (-32,768 to 32,767)
o int – Stores whole numbers (-2,147,483,648 to 2,147,483,647)
o long – Stores large integers
o float – Stores decimal numbers (single precision)
o double – Stores decimal numbers (double precision, more accurate)
 Example:
int age = 25;
double price = 99.99;
char grade = 'A';
boolean isJavaFun = true;

2. Non-Primitive Data Types (Reference Types)


 Definition: These do not store the actual value but store the memory address (reference)
of the object.
 Examples:
o String – Stores sequences of characters
o Array – Stores multiple values of the same type
o Class – Blueprint for creating objects
o Interface – Collection of abstract methods
o Object – The base class of all classes in Java
 Example:
String name = "John";
int[] numbers = {1, 2, 3, 4};

Key Difference
 Primitive types → Store the actual value directly in memory.
 Non-primitive types → Store a reference (memory address) to the value.

 Java Primitive Data Types

Java has 8 primitive data types that store simple values directly in memory.
They differ in size, range, and usage.
1. boolean
 Purpose: Represents a logical value — only true or false.
 Size: Virtual Machine dependent (typically 1 byte = 8 bits).
 Default Value: false
 Special Note: Cannot be cast to other types directly.
 Syntax:
boolean flag;
 Example:
boolean b1 = true;
boolean b2 = false;
System.out.println("Is Java fun? " + b1);
System.out.println("Is fish tasty? " + b2);
Output:
Is Java fun? true
Is fish tasty? false

2. byte
 Purpose: 8-bit signed integer; saves memory in large arrays.
 Size: 1 byte (8 bits)
 Range: -128 to 127

Syntax:
byte age;
Example:
byte a = 25;
byte t = -10;
System.out.println("Age: " + a);
System.out.println("Temperature: " + t);

3. short
 Purpose: 16-bit signed integer; used when memory is limited.
 Size: 2 bytes (16 bits)
 Range: -32,768 to 32,767
Syntax:
short num;
Example:
short num = 1000;
short temp = -200;
System.out.println("Number of Students: " + num);
System.out.println("Temperature: " + temp);
4. int
 Purpose: Default integer type; 32-bit signed value.
 Size: 4 bytes (32 bits)
 Range: -2³¹ to 2³¹-1
(Unsigned range in Java 8+: 0 to 2³²-1 using Integer class)
Syntax:
int distance;
Example:
int p = 2000000;
int d = 150000000;
System.out.println("Population: " + p);
System.out.println("Distance: " + d);
5. long
 Purpose: 64-bit signed integer; stores very large numbers.
 Size: 8 bytes (64 bits)
 Range: -2⁶³ to 2⁶³-1
(Unsigned range in Java 8+: 0 to 2⁶⁴-1 using Long class)
Syntax:
long stars;
Example:
long w = 7800000000L;
long l = 9460730472580800L;
System.out.println("World Population: " + w);
System.out.println("Light Year Distance: " + l);
6. float
 Purpose: Single-precision decimal number.
 Size: 4 bytes (32 bits)
 Precision: ~6–7 decimal digits
Syntax:
float pi;
Example:
float pi = 3.14f;
float gravity = 9.81f;
System.out.println("Value of Pi: " + pi);
System.out.println("Gravity: " + gravity);
7. double
 Purpose: Double-precision decimal number (default for decimals).
 Size: 8 bytes (64 bits)
 Precision: ~15 decimal digits
 Note: Use BigDecimal if exact precision is required.
Syntax:
double pi;
Example:
double pi = 3.141592653589793;
double an = 6.02214076e23;
System.out.println("Value of Pi: " + pi);
System.out.println("Avogadro's Number: " + an);

8. char
 Purpose: Stores a single 16-bit Unicode character.
 Size: 2 bytes (16 bits)
 Range: 0 to 65,535 (Unicode characters)
 Reason for 2 bytes: Java uses Unicode (supports international characters)
unlike ASCII (1 byte).
Syntax:
char grade;
Example:
char g = 'A';
char s = '$';
System.out.println("Grade: " + g);
System.out.println("Symbol: " + s);

Quick Summary Table


Data Type Size Range/Values Default Value
boolean 1 byte* true/false false
byte 1 byte -128 to 127 0
short 2 bytes -32,768 to 32,767 0
int 4 bytes -2³¹ to 2³¹-1 0
long 8 bytes -2⁶³ to 2⁶³-1 0L
float 4 bytes ~6–7 digits 0.0f
double 8 bytes ~15 digits 0.0d
char 2 bytes 0 to 65,535 '\u0000'
*boolean size is JVM-dependent.

Non-Primitive - Data Types


The Non-Primitive (Reference) Data Types will contain a memory address of variable values
because the reference types won’t store the variable value directly in memory. They are strings,
objects, arrays, etc.

1. Strings
Strings are defined as an array of characters. The difference between a character array
and a string in Java is, that the string is designed to hold a sequence of characters in a
single variable whereas, a character array is a collection of separate char-type entities.
Unlike C/C++, Java strings are not terminated with a null character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Note: String cannot be modified after creation. Use StringBuilder for heavy string
manipulation

2. Class
A Class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
 Modifiers : A class can be public or has default access. Refer to access specifiers
for classes or interfaces in Java
 Class name: The name should begin with an initial letter (capitalized by
convention).
 Superclass(if any): The name of the class's parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
 Interfaces(if any): A comma-separated list of interfaces implemented by the class,
if any, preceded by the keyword implements. A class can implement more than
one interface.
 Body: The class body is surrounded by braces, { }.

3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life entities. A
typical Java program creates many objects, which as you know, interact by invoking
methods. An object consists of :
 State: It is represented by the attributes of an object. It also reflects the properties
of an object.
 Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact
with other objects.

4. Interface
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).
 Interfaces specify what a class must do and not how. It is the blueprint of the
class.
 An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies
a set of methods that the class has to implement.
 If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
 A Java library example is Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.

5. Array
An Array is a group of like-typed variables that are referred to by a common name. Arrays in
Java work differently than they do in C/C++. The following are some important points about
Java arrays.
 In Java, all arrays are dynamically allocated.
 Since arrays are objects in Java, we can find their length using member length.
This is different from C/C++ where we find length using size.
 A Java array variable can also be declared like other variables with [] after the
data type.
 The variables in the array are ordered and each has an index beginning with 0.
 Java array can also be used as a static field, a local variable, or a method
parameter.
 The size of an array must be specified by an int value and not long or short.
 The direct superclass of an array type is Object.
 Every array type implements the interfaces Cloneable and java.io.Serializable.

Operators in Java
Definition:
An operator in Java is a special symbol that performs a specific operation on one or more values
(called operands) and returns a result.
Operands:
Operands are the values or variables on which the operator acts.
Example:
java
CopyEdit
int sum = 10 + 5;
Here, + is the operator, and 10 and 5 are operands.

Types of Operators by Number of Operands


1. Unary Operators
o Work with only one operand.
o Example: ++a increases the value of a by 1.
o They are used for incrementing, decrementing, negating values, or logical NOT
operations.
2. Binary Operators
o Work with two operands.
o Example: a + b adds two numbers.
o Most operators in Java are binary (arithmetic, relational, logical, etc.).
3. Ternary Operator
o Works with three operands.
o Example: condition ? value1 : value2.
o It is a compact form of an if-else statement.

Types of operator
1. Arithmetic Operators (+, -, , /, %, ++, --)
Arithmetic operators are used to perform mathematical calculations such as addition, subtraction,
multiplication, division, and modulus. They work on numeric data types and return a numeric
result. Increment (++) and decrement (--) operators are used to increase or decrease a value by 1.
Operato Name of Operator Example Explanation
r
+ Addition 5+3→8 Adds two numbers
- Subtraction 10 - 4 → Subtracts second number from first
6
* Multiplication 4*2→8 Multiplies two numbers
/ Division 8/2→4 Divides first number by second
% Modulus 7%3→ Returns remainder after division
1
2. Relational Operators (==, !=, >, <, >=, <=)
Relational operators are used to compare two values. The result is always a boolean (true or
false). These operators are commonly used in decision-making statements like if and loops.
Operator Name of Operator Example Output (if example is true)
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 7>4 True
< Less than 3<8 True
>= Greater than or equal 10 >= 10 True
to
<= Less than or equal to 6 <= 7 True
3. Logical Operators (&&, ||, !)
Logical operators are used to combine multiple conditions. && (AND) returns true only if both
conditions are true, || (OR) returns true if at least one condition is true, and ! (NOT) reverses the
boolean value. They are mainly used in conditional statements and loops.

Operato Name Example Result


r
AND Logical AND (5 > 3) and (2 < 4) True
OR Logical OR (5 < 3) or (2 < 4) True
NOT Logical NOT not(5 > 3) False

*4. Assignment Operators (=, +=, -=, =, /=, %=)

Assignment operators are used to assign values to variables. They can also combine assignment
with arithmetic, for example, x += 5 means x = x + 5. This helps in writing shorter and cleaner
code.
Operator Name Example Equivalent to
= Assign x=5 x=5
+= Add and assign x += 3 x=x+3
-= Subtract and assign x -= 3 x=x-3
*= Multiply and assign x *= 3 x=x*3
/= Divide and assign x /= 3 x=x/3
%= Modulus and assign x %= 3 x=x%3
**= Power and assign x **= 3 x = x ** 3
//= Floor div and assign x //= 3 x = x // 3
&= Bitwise AND assign x &= 3 x=x&3
5. Unary Operators (+, -, ++, --, !)
Unary operators work with a single operand. They can be used to indicate positive/negative
values, increase/decrease a variable, or reverse a boolean value. For example, ++x increases x by
1 before using it.
6. Bitwise Operators (&, |, ^, ~, <<, >>, >>>)
Bitwise operators perform operations on the binary representation of numbers. They are useful
for low-level programming and performance optimization. For example, & performs AND on
bits, << shifts bits to the left.
Operato Name Exampl Result
r e
& AND 5&3 1
` ` OR `5
^ XOR 5^3 6
~ NOT ~5 -6
<< Left shift 5 << 1 10
>> Right shift 5 >> 1 2

7. Ternary Operator (?:)


The ternary operator is a shorthand for the if-else statement. It has the form condition ? value1 :
value2. If the condition is true, it returns value1; otherwise, it returns value2.
In Java, an expression is a combination of variables, operators, constants (literals), and method
calls that work together to produce a single value. Expressions are one of the core components of
Java programming and are used in assignments, conditions, loops, and many other situations.
Main Features of Java Expressions:
 Produces a Single Result: Every expression is evaluated to give one final value. The
type of this value depends on the operands and operators used.
 Made from Different Elements: Expressions are created by combining variables,
values, and operators according to Java’s syntax rules.
 Part of Larger Statements: Often, an expression is just one piece of a bigger statement.
For example, in int sum = a + b;, the part a + b is the expression whose value is assigned
to sum.
Types of Expressions in Java:
1. Arithmetic Expressions:
Use arithmetic operators (+, -, *, /, %) and return a numeric value.
int result = 5 * 10; // Gives 50
2. Relational (Boolean) Expressions:
Compare two values using relational operators (==, !=, <, >, <=, >=) and produce a
boolean result (true or false).
boolean isGreater = (x > y); // true or false
3. Logical Expressions:
Combine boolean results with logical operators (&&, ||, !) to get a true or false outcome.
boolean condition = (age > 18 && hasLicense); // true or false
4. Conditional (Ternary) Expressions:
Use the ?: operator to choose between two values depending on a condition.
String status = (score >= 60) ? "Pass" : "Fail";
5. Method Invocation Expressions:
Call a method and use its return value as the result of the expression.
double squareRoot = Math.sqrt(25.0); // Gives 5.0
6. Assignment Expressions:
Assign a value to a variable; the expression’s result is the value being assigned.
int x = 10; // Expression "x = 10" evaluates to 10
1. What is Branching in Java?
Branching in Java refers to control flow statements that allow the program to make decisions
and execute different code blocks depending on certain conditions.
They are also called conditional statements.
We use conditional statements in Java to make decisions in a program.
They allow the program to execute different blocks of code depending on whether a certain
condition is true or false.
We use conditional statements in Java when we want a program to make decisions and
execute different code blocks based on certain conditions.
When We Use Conditional Statements
1. Decision Making – When different actions are required for different situations.
Example:
o If the student’s score is above 50 → print “Pass”
o Else → print “Fail”
2. Checking User Inputs – To decide what to do based on input values.
Example: If the user enters a correct password → login; else → show error.
3. Validating Data – Ensuring that the provided data meets certain rules.
Example: If the entered age is greater than 18 → allow registration; else → deny.
4. Executing Code Conditionally – Running a block of code only if a condition is true.
Example: Only display a discount if the purchase is above ₹500.
5. Controlling Program Flow – Directing the program to different paths.
Example: In a menu-based program, if the user selects 1 → open file, if 2 → save file,
else → exit.
1. if Statement
Definition
An if statement is a decision-making statement in programming that allows the program to
execute a block of code only if a specified condition is true.
If the condition evaluates to false, the code inside the if block is skipped.
Syntax
if (condition) {
// code to execute if condition is true
}
 condition – An expression that evaluates to true or false.
 Curly braces {} – Enclose the block of statements to execute when the condition is true.
(If there is only one statement, curly braces are optional, but using them is recommended
for clarity.)
Flowchart
┌──────────────┐
│ Condition │
└──────┬───────┘

True ──┘──▶ Execute statements

└── False ─▶ Skip statements
Working
1. The program evaluates the condition inside parentheses ().
2. If true, the block of code inside {} runs.
3. If false, the block is skipped, and the program continues with the next statement after the
if.
Key Points
 if checks only one condition.
 Used when you need to take action only if the condition is true.
 If the condition is false, nothing happens unless you add an else block.
Real-Life Example
 Condition: If it’s raining, take an umbrella.
 If the weather is sunny, you simply don’t take the umbrella.
Common Mistakes
 Using = instead of == for comparison.
 Forgetting curly braces when multiple statements are inside if.
2. If else statements
The if-else statement is a conditional branching statement in programming that allows the
program to execute one block of code if a condition is true and another block if the condition
is false.
Syntax
if (condition) {
// Code to execute if condition is TRUE
} else {
// Code to execute if condition is FALSE
}
Flowchart
┌─────────────┐
│ Condition │
└──────┬──────┘

┌──────┴──────┐
True │ │ False
▼ ▼
[If block] [Else block]
▼ ▼
└──────┬──────┘

Next statement

Explanation
 Condition: A boolean expression that evaluates to either true or false.
 If the condition is true, the if block runs, and the else block is skipped.
 If the condition is false, the else block runs, and the if block is skipped.
Example in Java
public class Main {
public static void main(String[] args) {
int age = 18;

if (age >= 18) {


System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote.");
}
}
}
Output (if age = 18):
You are eligible to vote.
Output (if age = 16):
You are not eligible to vote.
Key Points
 if-else ensures only one block of code executes.
 The else part is optional — if omitted, nothing happens when the condition is false.
 Used when two mutually exclusive outcomes are needed.
Real-Life Analogy
If you have an umbrella:
 If it is raining → Take the umbrella.
 Else → No umbrella needed.
n Java, if-else-if ladder is used when we want to check multiple conditions one after another.
It is called a ladder because conditions are evaluated step-by-step like climbing a ladder — as
soon as one condition is true, the rest are skipped.
Syntax
if (condition1) {
// code block if condition1 is true
} else if (condition2) {
// code block if condition2 is true
} else if (condition3) {
// code block if condition3 is true
} else {
// code block if all above conditions are false
}
How It Works
1. Step 1 → Java checks condition1. If it is true, the corresponding block executes and the
ladder stops.
2. Step 2 → If condition1 is false, it checks condition2.
3. Step 3 → This continues until a true condition is found or until the final else block.
4. Step 4 → If no condition is true, the else block executes.

public class IfElseIfExample {


public static void main(String[] args) {
int marks = 75;

if (marks >= 90) {


System.out.println("Grade: A+");
} else if (marks >= 80) {
System.out.println("Grade: A");
} else if (marks >= 70) {
System.out.println("Grade: B+");
} else if (marks >= 60) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: Fail");
}
}
}
Output:
Grade: B+
 Conditions are checked in order.
 Only one block will execute, even if multiple conditions are true.
 Good for mutually exclusive options.
 For many fixed options, switch-case can sometimes be better.
Nested if Statement
Definition
A nested if statement is an if statement inside another if statement.
It allows you to check multiple conditions in a hierarchy — the second condition is checked
only if the first condition is true.

Syntax
java
CopyEdit
if (condition1) {
// Executes if condition1 is true
if (condition2) {
// Executes if both condition1 and condition2 are true
}
}

Flow of Execution
1. Step 1: Check the outer if condition.
2. Step 2: If true, then check the inner if condition.
3. Step 3: If the inner if is also true, execute the inner block.
4. If any condition is false, its corresponding block is skipped.
 Used when one decision depends on another.
 Improves decision hierarchy clarity.
 Can become hard to read if nesting is too deep → Consider using logical operators
(&&) instead.
Java Switch Statements
 Instead of writing many if..else statements, you can use the switch statement.
 The switch statement selects one of many code blocks to be executed:
Syntax : switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
 This is how it works:
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional
The break Keyword
 When Java reaches a break keyword, it breaks out of the switch block.
 This will stop the execution of more code and case testing inside the block.
 When a match is found, and the job is done, it's time for a break. There is no need for
more testing.
 A break can save a lot of execution time because it "ignores" the execution of all the rest
of the code in the switch block.
The default Keyword
 The default keyword specifies some code to run if there is no case match:
 if the default statement is used as the last statement in a switch block, it does not need a
break.
Loops in Programming
Loops in programming allow a set of instructions to run multiple times until a certain condition
is met (or becomes false).
In Java, loops help in avoiding repetitive code, making programs shorter, easier to maintain,
and more efficient.
Why Loops are Important in Java:
 Reduce code duplication by executing the same logic repeatedly.
 Make programs more dynamic by running code based on conditions.
 Enable working with collections, arrays, and data sets effectively.
 Improve readability and organization of code.
 Allow automation of repetitive tasks without manual coding for each step.
 Save time and effort during development and maintenance.
 Can be nested (loop inside another loop) for more complex operations.
Types of Loops in Java:
1. for loop – Used when the number of iterations is known beforehand.
2. while loop – Used when the number of iterations is not known in advance and depends
on a condition.
3. do-while loop – Similar to while, but runs at least once regardless of the condition.
4. Enhanced for loop (for-each loop) – Simplified loop for iterating over arrays or
collections.
1. while Loop
A while loop in Java is used when we want to check the condition before executing the loop
body.
It is an entry-controlled loop, meaning the condition is evaluated first — if it’s true, the loop
runs; if false, it is skipped entirely.
Syntax: while (condition)
{ // code to be executed }
 The while loop begins by evaluating a Boolean condition.
 If the condition is true, the loop body statements are executed.
 If the condition is false, the loop is skipped, and the program continues with the
next statement after the loop.
 Because the condition is checked before executing the loop body, it is called an
Entry control loop.
 After executing the loop body, the variable involved is usually updated to
prepare for the next iteration.
 The loop repeats as long as the condition remains true.
 When the condition becomes false, the loop terminates, marking the end of its
execution cycle.

2. do-while Loop
 The do-while loop executes the code block at least once before checking the
condition.
 After executing the block, it evaluates the Boolean condition.
 If the condition is true, the loop repeats; if false, the loop terminates.
 This makes it a post-test loop because the condition is checked after the
execution.
 Useful when you want the loop body to run at least once, regardless of the
condition.
Here’s the syntax of the do-while loop in Java:
do {
// code to be executed
} while (condition);

 The code block inside do runs at least once.


 After executing the block, the condition inside while is checked.
 If the condition is true, the loop repeats.
 If the condition is false, the loop stops.

Common Loop Mistakes and How to Avoid Them


 Infinite Loops: Occur when the loop’s exit condition is never met.
Avoidance: Ensure the loop variable is updated correctly inside the loop.
 Off-by-One Errors: Loop runs one time too many or too few, often caused by incorrect
loop bounds.
Avoidance: Carefully set loop start and end conditions.
 Incorrect Condition Logic: Using wrong logical operators or conditions can lead to
unexpected results.
Avoidance: Double-check logical expressions and test thoroughly.
 Modifying Loop Variable Inside the Loop Improperly: Can cause unexpected jumps or
skipped iterations.
Avoidance: Update the loop control variable in a predictable and consistent way.
 Resource Leaks Inside Loops: Opening resources like files or connections without
closing them in each iteration.
Avoidance: Manage resources carefully and close them properly.
 Unnecessary Computations Inside Loop: Heavy operations inside the loop can degrade
performance.
Avoidance: Move invariant code outside the loop.
3. for loop
 The for loop is used when we know the number of iterations (we know how many times
we want to repeat a task).
 The for statement includes the initialization, condition, and increment/decrement in one
line.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
 Initialization: Sets the starting value of the loop variable (runs once at the beginning).
 Condition: Checked before each iteration; if true, the loop body executes; if false, the
loop stops.
 Increment/Decrement: Updates the loop variable after each iteration.
How it works:
1. The loop variable is initialized.
2. The condition is checked.
3. If the condition is true, the loop body executes.
4. After the body executes, the loop variable is incremented or decremented.
5. The condition is checked again, and the process repeats.
6. When the condition becomes false, the loop ends.
Unconditional Statements in Java
Unconditional statements, also called jump statements, allow you to change the normal
sequential flow of program execution without any conditions. They help control how and when
the program moves from one section of code to another. Unlike conditional statements (like if or
switch), these statements transfer control immediately, ignoring any other logic.
Types of Unconditional Statements:

1. break Statement
 Purpose:
Used to immediately terminate the nearest enclosing loop (for, while, do-while) or switch
statement.
 Effect:
When encountered, control jumps to the statement immediately following the loop or
switch block.
 Use cases:
o To stop a loop prematurely when a certain condition is met.
o To exit from a switch case block and prevent fall-through to the next case.
 Important notes:
o break affects only the innermost loop or switch containing it.
o Helps improve efficiency by avoiding unnecessary iterations.
Example:
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println(i);
}
// Output: 1 2 3 4

2. continue Statement
 Purpose:
Used to skip the remaining statements inside the current iteration of a loop and proceed
directly to the next iteration.
 Effect:
Control jumps to the loop’s next iteration (for for loops, this means going to the
increment/decrement step, and for while/do-while loops, this means re-evaluating the
condition).
 Use cases:
o To skip processing certain data without terminating the whole loop.
o Useful when you want to ignore some iterations based on specific criteria.
 Important notes:
o Only skips the current iteration, the loop continues normally afterward.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip printing number 3
}
System.out.println(i);
}
// Output: 1 2 4 5

3. return Statement
 Purpose:
Used to exit from the current method immediately.
 Effect:
When return is executed, the method stops running, and control is transferred back to the
calling method. If the method is not void, it also returns a value.
 Use cases:
o To send back results from methods to the caller.
o To exit early from a method when a certain condition is met.
 Important notes:
o After a return statement, no other code in the method is executed.
o If the method’s return type is not void, return must be followed by a value
matching the method's declared return type.
Example:
public int square(int number) {
return number * number; // Exit method and return squared value
}

public void greet(boolean morning) {


if (!morning) {
return; // Exit method if not morning
}
System.out.println("Good morning!");
}

Additional Notes:
 These statements alter the control flow by transferring execution to a different place
without any checks.
 Improper use of break and continue can lead to infinite loops or hard-to-debug logic
errors, so use them carefully.
 Use return to improve code clarity by exiting a method early instead of nesting multiple
conditions.
Summary Table
Statement Description Usage Context Effect
break Exit loop or switch Inside loops or Terminates nearest
immediately switch enclosing loop/switch
continue Skip remaining code in Inside loops Skips current iteration,
current loop iteration continues with next
return Exit method immediately, Inside Stops method execution,
optionally returns a value methods/functions returns control/value

Java - What is OOP?


OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform operations on the
data, while object-oriented programming is about creating objects that contain both data and
methods.
Object-oriented programming has several advantages over procedural programming:
 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter
development time
Java - What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented programming.
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.

Structure and Members in a Java Program


Java programs have a defined structure that organizes code into classes containing
variables and methods. The program starts execution from the main() method inside a
class.

Basic Blocks of a Java Program


package list;

public class ClassName {


// Data members (variables)
// Constructor functions
// User-defined methods

public static void main(String[] arguments) {


// Program execution starts here
}
}
Explanation:
 Package:
A package groups related classes, interfaces, and sub-packages. It helps in organizing
classes and avoiding naming conflicts.
Example: package list;
Java automatically imports java.lang.* by default.
 Class:
A blueprint or template defining new data types. A Java program must have at least one
class.
If declared public, it can be accessed from other packages.
 Class Name:
The identifier for the class, used to create objects.
 Data Members:
Variables declared inside a class to store object data.
 Constructor:
A special method with the same name as the class that initializes objects when created.
It has no return type and runs automatically during object creation.
 User-Defined Methods:
Functions inside a class that define behaviors. These can be instance or static methods.
 Main Method:
The starting point of a Java program:
public static void main(String[] args) {
// code executed on start
}
Types of Data Members
1. Instance (Non-Static) Data Members
 Belong to individual objects.
 Memory is allocated separately for each object.
 Each object has its own copy.
 Accessed via object reference.
2. Static (Class) Data Members
 Belong to the class itself.
 Memory allocated once when the class loads.
 Shared by all objects of the class.
 Accessed using the class name.
Instance Data Members vs Static Data Members
Aspect Instance Data Members Static Data Members
Memory Per object Once per class
allocation
Copy per object Yes Single shared copy
Declaration Without static keyword With static keyword
Access Using object reference Using class name
Level Object-level Class-level
Value variation Different for each object Same for all objects

Types of Methods
1. Instance (Non-Static) Methods
 Operate on individual objects.
 Can access both instance and static variables.
 Called using object reference.
 Do not have the static keyword.
2. Static (Class) Methods
 Belong to the class.
 Operate on class-level data or perform utility functions.
 Can only directly access static variables and methods.
 Must be declared with static keyword.
 Called using the class name.
Instance Methods vs Static Methods
Aspect Instance Methods Static Methods
Purpose Work with individual object data Work with class-level data
Declaration No static keyword With static keyword
Access Through object reference Through class name
Access to Can access instance and static Can access only static members
variables members directly
Use case Example: processing an object's Example: utility or helper methods
data

Example: Java Class with Members and Methods


package example;

public class Employee {

// Instance data members


String name;
int age;

// Static data member


static String company = "Tech Solutions";

// Constructor
public Employee(String name, int age) {
this.name = name;
this.age = age;
}

// Instance method
public void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Company: " + company);
}

// Static method
public static void showCompany() {
System.out.println("Company: " + company);
}

public static void main(String[] args) {


// Create an object of Employee class
Employee emp1 = new Employee("Alice", 28);

// Call instance method using object


emp1.display();

// Call static method using class name


Employee.showCompany();
}
}
Output:
Name: Alice
Age: 28
Company: Tech Solutions
Company: Tech Solutions
Summary
Java Program Description
Component
Package Grouping of related classes
Class Template for objects
Data Members Variables holding data (instance or static)
Constructor Special method to initialize objects
Methods Functions defining object/class behavior
Instance Method Accessed via objects, can access all data members
Static Method Accessed via class name, access only static members

Java Scanner Class


The Scanner class in Java is part of the java.util package and is used to read input from
various sources, including the keyboard (standard input), files, and strings. It is one of the
simplest ways to get user input in a Java program.

Key Points about Scanner:

 It reads input of various types like int, double, String, etc.


 It parses the input according to the specified data type.
 It breaks input into tokens using delimiters (default is whitespace).
 You need to import java.util.Scanner before using it.

How to Use Scanner to Take Input from the User

Step 1: Import Scanner class


import java.util.Scanner;

Step 2: Create a Scanner object


Scanner scanner = new Scanner(System.in);
 System.in means the input will be taken from the keyboard.
Step 3: Use methods to read data

Some common methods:

 nextInt() — reads an integer

 nextDouble() — reads a double (decimal)

 nextLine() — reads a line of text (string)

 next() — reads a word (token)

You might also like