Unit2 Java
Unit2 Java
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
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.
// Access:
double area = MathConstants.PI * r * r;
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);
}
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;
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
+-------------+----------------+
| Variable | Value |
+-------------+----------------+
| age | 25 |
+-------------+----------------+
Java stores:
Variable name → Reference in memory
Value → Data stored in a memory location
System.out.println(myText);
System.out.println(myNum);
System.out.println(myFloatNum);
System.out.println(myLetter);
System.out.println(myBool);
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
Key Difference
Primitive types → Store the actual value directly in memory.
Non-primitive types → Store a reference (memory address) to the value.
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);
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 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.
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
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;
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);
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
}
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
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
// 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);
}