UNIT-2
Constants, Variables and Data Types: Constants,
Variables, Data Types, Declaration of Variables, Giving
values to Variables, Symbolic Constants, Typecasting.
Operators & Expressions: Arithmetic operators,
Relational operators, Logical operators, Assignment
operators, Increment & Decrement operators, conditional
operators, Bitwise operators, Arithmetic Expressions,
Evaluation of Expressions, Type Conversions in
Expressions, Operator Precedence & Associativity.
Q1. Constant.
Definition:
A constant is a fixed value that cannot be changed once
assigned during program execution. It is declared using
the final keyword and is used to store values that remain
constant throughout the program.
Types of Constants
1. Literal Constants
These are fixed values directly written in the program.
Example: 10, 3.14, 'A', "Hello"
2. Symbolic Constants
These are named constants declared using the final
keyword.
Example:
final int MAX = 100;
final double PI = 3.14;
Q2. Variables.
Definition:
A variable in Java is a named storage location in memory
that holds a value. The value stored in a variable can
change during program execution, unlike constants which
remain fixed.
Types of Variables
1. Local Variables
Declared inside a method and used only within that
method.
2. Instance Variables
Declared inside a class but outside any methods, and
belong to an object.
3. Static Variables
Declared using the static keyword and shared among all
objects of the class.
Q3. Data Types.
Definition:
A data type in Java specifies the kind of values a variable
can hold and the operations that can be performed on
those values. It defines the size and nature of the data
stored in memory.
Types of Data Types
1. Primitive Data Types: These are the most basic data
types built into Java.
o byte → 8-bit integer
o short → 16-bit integer
o int → 32-bit integer
o long → 64-bit integer
o float → 32-bit floating-point
o double → 64-bit floating-point
o char → 16-bit Unicode character
o boolean → true/false
2. Non-Primitive Data Types: These data types store
references (addresses) of objects rather than actual
values. They are used to store more complex data and
allow the use of methods.
o String → sequence of characters
o Arrays → collection of similar elements
o Classes → user-defined types
o Interfaces → abstract types for contracts.
Q4. Declaration of Variables.
1. A variable must be declared before it is used in Java.
2. Each variable has a data type, such as int, float, char,
or String.
3. Declaration only allocates memory; assigning value is
called initialization.
4. Multiple variables of the same type can be declared in
one line: int a, b, c;
Syntax:
data_type variable_name;
Examples:
int age;
double salary;
char grade;
String name;
Q5. Giving values to Variables.
Definition:
Giving values to variables in Java is called initialization. It
means assigning a value to a variable after or at the time of
its declaration.
Syntax:
variable_name = value;
Examples:
1. Initialization after declaration:
int age;
age = 20;
2. Initialization at the time of declaration:
int age = 20;
String name = "Rahul";
Q6. Symbolic Constants
Definition:
Symbolic constants are fixed values that are represented
by names and cannot be changed during program
execution. They are declared using the final keyword.
Syntax:
final data_type CONSTANT_NAME = value;
Examples:
final int MAX = 100;
final double PI = 3.14;
final String NAME = "Java";
Key Points:
1. Symbolic constants use the keyword final.
2. Their values remain constant throughout the
program.
3. By convention, constant names are written in
uppercase letters.
4. They improve readability and make programs easier
to maintain.
5. Once assigned, the value of a constant cannot be
modified.
Q7. Typecasting.
Definition:
Typecasting is the process of converting a variable from
one data type to another. It is used when we need to
change the type of data for proper operations.
Types of Typecasting:
1. Implicit Typecasting
• Done automatically by Java.
• Converts smaller data type into larger data type.
Example:
int a = 10;
double b = a; // int to double
2. Explicit Typecasting (Narrowing)
• Done manually by the programmer.
• Converts larger data type into smaller data type.
Example:
double a = 10.5;
int b = (int) a; // double to int
Key Points:
1. Typecasting helps in data conversion between
different types.
2. Implicit casting is safe and automatic.
3. Explicit casting may cause data loss.
4. Syntax for explicit casting: (data_type) variable
Q8. Arithmetic Operators
Definition:
Arithmetic operators are used to perform basic
mathematical operations such as addition, subtraction,
multiplication, division, and modulus. They are commonly
used in programs to perform calculations on numeric
data.
Example:
int a = 10, b = 5;
[Link](a + b);
Q9. Relational Operators
Definition:
Relational operators are used to compare two values or
variables. They return a boolean result (true or false)
based on the comparison.
Types of Relational Operators:
== (equal to)
!= (not equal to)
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)
Example:
int a = 10, b = 5;
[Link](a > b);
Q10. Logical Operators
Definition:
Logical operators are used to combine or modify
multiple conditions in a program.
They return true or false depending on the logical
relationship between expressions.
Types of Logical Operators:
1. AND Operator (&&)
The AND operator returns true only when both
conditions are true.
If any one condition is false, the result becomes false.
Example:
int a = 10, b = 5;
[Link](a > b && b > 0); // true
2. OR Operator (||)
The OR operator returns true if at least one condition is
true.
It returns false only when both conditions are false.
Example:
int a = 10, b = 5;
[Link](a < b || b > 0); // true
3. NOT Operator (!)
The NOT operator is used to reverse the result of a
condition.
If the condition is true, it becomes false, and vice versa.
Example:
int a = 10;
[Link](!(a > 5)); // false
Q11. Assignment Operators
Definition:
Assignment operators are used to assign values to
variables. They can also perform a calculation and assign
the result to the same variable in a single step.
Types of Assignment Operators:
= , += , -= , *= , /= , %=
Example:
int a = 10;
a += 5; // a = a + 5 → 15
a -= 2; // a = a - 2 → 13
a *= 2; // a = a * 2 → 26
a /= 2; // a = a / 2 → 13
a %= 3; // remainder → 1
[Link](a);
Q12. Increment & Decrement Operators
Increment Operators
Definition:
Increment operator is used to increase the value of a
variable by 1. It is commonly used in loops (like for and
while) and counters.
Types of Increment:
• Pre-increment (++a) → Value is increased first, then
used
• Post-increment (a++) → Value is used first, then
increased
Example:
int a = 5;
[Link](++a); // 6 (pre-increment)
[Link](a++); // 6 (post-increment)
[Link](a); // 7
Decrement Operators
Definition:
Decrement operator is used to decrease the value of a
variable by 1. It is also widely used in loops and counters.
Types of Decrement:
• Pre-decrement (--a) → Value is decreased first, then
used
• Post-decrement (a--) → Value is used first, then
decreased
Example:
int a = 5;
[Link](--a); // 4 (pre-decrement)
[Link](a--); // 4 (post-decrement)
[Link](a); // 3
Q13. Conditional Operator (Ternary Operator)
Definition:
The conditional operator is a short form of if-else
statement used to make decisions.
It selects one of two values based on a condition.
Operator:
? : (Ternary Operator)
Syntax:
condition ? value1 : value2;
Example:
int a = 10, b = 5;
int max = (a > b) ? a : b;
[Link](max); // 10
Q14. Bitwise Operators
Definition:
Bitwise operators are used to perform operations on
individual bits of data.
They work at the bit level and are mainly used in low-level
programming and optimization.
Types of Bitwise Operators:
& (AND), | (OR), ^ (XOR), ~ (NOT), << (Left Shift), >> (Right
Shift)
Example:
int a = 5, b = 3;
[Link](a & b); // 001 = 1
[Link](a | b); // 111 = 7
[Link](a ^ b); // 110 = 6
Q15. Arithmetic Expressions.
Definition:
An arithmetic expression is a combination of variables,
constants and arithmetic operators used to perform
mathematical calculations.
These expressions are evaluated according to operator
precedence rules to produce a single numeric result.
They are widely used in programs for solving problems,
performing calculations, and implementing formulas.
Example
int a = 10, b = 5, c = 2;
int result = a + b * c;
[Link](result); // 20
Key Points:
1. Arithmetic expressions are used to perform
calculations in programs.
2. They follow operator precedence and associativity
rules.
3. Parentheses () can be used to change the order of
evaluation.
4. The result depends on the data types of operands.
Q16. Evaluation of Expressions
1. Evaluation of expressions in Java is the process of
computing the value of an expression using operators
and operands.
2. Java follows operator precedence, where higher
priority operators (like *, /) are evaluated before lower
ones (like +, -).
3. When operators have the same precedence,
associativity (generally left-to-right) determines the
order of evaluation.
4. Parentheses () are used to change the normal order
of evaluation and give priority to specific operations.
5. Java performs automatic type conversion (type
promotion) when different data types are used in an
expression.
6. In logical expressions, Java uses short-circuit
evaluation, meaning it skips unnecessary conditions
once the result is known.
7. The expression is evaluated step-by-step until the
final result is obtained.
Example:
int result = 10 + 5 * 2; // Output: 20
Q17. Type Conversion in Expressions
Type conversion in expressions refers to the process of
converting one data type into another while evaluating an
expression. It ensures that operations involving different
data types are performed correctly without loss of data.
• Java performs automatic type conversion (type
promotion) when different data types are used
together in an expression.
• In type promotion, smaller data types like byte, short,
and int are converted into larger types such as float or
double.
• The result of an expression is generally of the higher
data type among the operands.
• Java also allows explicit type conversion (casting),
where the programmer manually converts a data
type.
• Type conversion helps in maintaining accuracy and
consistency during calculations.
Example:
double result = 5 + 2.5; // int is converted to double → 7.5
Q18. Operator Precedence & Associativity.
Operator Precedence
Operator precedence in Java refers to the priority assigned
to different operators when an expression contains more
than one operator. It determines which operation will be
performed first during evaluation. Operators with higher
precedence, such as multiplication (*), division (/), and
modulus (%), are evaluated before lower precedence
operators like addition (+) and subtraction (-). This rule
helps Java follow standard mathematical conventions and
ensures correct results. Parentheses () can be used to
override the default precedence.
Associativity
Associativity in Java defines the direction in which an
expression is evaluated when operators of the same
precedence level appear in an expression. It helps decide
whether evaluation should proceed from left to right or
right to left. Most arithmetic operators follow left-to-right
associativity, while assignment operators like = follow
right-to-left associativity. Associativity ensures consistent
and correct evaluation of expressions.
UNIT-3
Decision Making, Branching & Looping: Decision Making
with Control Statements, Looping statements, Jump in
loops, Labelled loops.
Classes, Objects and Methods: Defining Class, Methods
Declaration, Constructors, Methods Overloading,
Overriding Methods, Inheritance
Q1. Decision Making
Definition:
Decision making refers to the process of executing
different statements based on certain conditions. It allows
a program to choose between multiple paths of execution
depending on whether a condition is true or false. This
makes programs dynamic and capable of handling real-
life situations logically.
Types of Decision Making Statements:
• if statement
• if-else statement
• if-else-if ladder
• switch statement
Q2. Branching
Definition:
Branching in Java refers to decision-making statements
that control the flow of execution in a program. It allows
the program to choose different paths based on
conditions, making the program more flexible and logical.
Types of Branching Statements:
1. if Statement
Executes a block of code only when the condition is
true.
2. if-else Statement
Executes one block if the condition is true and
another if it is false.
3. if-else-if Ladder
Used to check multiple conditions one by one.
4. Nested if Statement
An if statement inside another if statement for
complex conditions.
5. switch Statement
Used to select one case from multiple options based
on a value.
Q3. Looping
Definition:
Looping is a process of executing a block of code
repeatedly until a given condition is satisfied. It helps
reduce code repetition and makes programs more
efficient.
Types of Loops:
1. for Loop
Used when the number of iterations is known in
advance.
2. while Loop
Executes the block of code as long as the condition is
true.
3. do-while Loop
Executes the code at least once, then checks the
condition.
Q4. Decision Making with Control
Statements
Definition:
Decision making is the process of selecting a block of
code to execute based on a given condition. It helps in
controlling the flow of program execution. These
statements check conditions and decide which part of the
code should run.
Types with Examples:
1. if Statement
It is used to execute a block of code only when the
condition is true. If the condition is false, the block is
skipped.
Example:
int age = 18;
if (age >= 18) {
[Link]("Eligible to vote");
}
2. if-else Statement
It is used when there are two possible outcomes. One
block runs if the condition is true, otherwise the else
block runs.
Example:
int num = 5;
if (num % 2 == 0) {
[Link]("Even Number");
} else {
[Link]("Odd Number");
}
3. else-if Ladder
It is used to check multiple conditions one by one. The
first true condition block gets executed.
Example:
int marks = 75;
if (marks >= 90) {
[Link]("A Grade");
} else if (marks >= 60) {
[Link]("B Grade");
} else {
[Link]("C Grade");
}
4. nested if Statement
It is an if statement written inside another if statement.
It is used when multiple conditions depend on each
other.
Example:
int age = 20;
int weight = 55;
if (age >= 18) {
if (weight >= 50) {
[Link]("Eligible for donation");
}
}
5. switch Statement
It is used to select one option from many cases based
on the value of a variable. It makes the program easier
to read than multiple if-else.
Example:
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid Day");
}
Q5. Looping Statements
Definition:
Looping statements are used to execute a block of code
repeatedly as long as a given condition is true. They help in
reducing code repetition and make programs efficient.
Loops are mainly used when we want to perform the same
task multiple times.
Types of Looping Statements:
1. for loop
It is used when the number of iterations is known in
advance. It consists of initialization, condition, and
increment/decrement in a single line. It is the most
commonly used loop in Java for fixed repetitions.
Example:
for (int i = 1; i <= 5; i++) {
[Link](i);
}
2. while loop
It checks the condition before executing the loop body. It
is used when the number of iterations is not fixed. The
loop may not execute even once if the condition is false.
Example:
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
3. do-while loop
It executes the block at least once, even if the condition is
false. After execution, it checks the condition. It is useful
when at least one execution is required.
Example:
int i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
Q6. Jump in loops
Definition:
Jump statements are used to transfer the control of a
program from one statement to another. In loops, they are
mainly used to change the normal flow of execution.
These statements help in controlling loop execution based
on certain conditions.
Types of Jump Statements in Loops:
1. break statement
It is used to terminate the loop immediately when a
certain condition is met. After break, control moves
outside the loop. It is useful to stop the loop early.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
[Link](i);
}
2. continue statement
It is used to skip the current iteration and move to the next
iteration of the loop. It does not terminate the loop
completely. It is useful when we want to skip specific
values.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
[Link](i);
}
3. return statement (in loops)
It is used to exit from a method completely and also stops
loop execution if used inside a method. It returns control
back to the calling function.
Example:
public class Main {
static void show() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
return;
}
[Link](i);
}
}
}
Q7. Labelled Loops
Definition:
Labelled loops are used to give a name (label) to a loop.
These labels help in controlling nested loops easily using
break and continue statements. They are mainly used
when we want to exit or skip specific outer loops in nested
looping structures.
Example:
outer: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outer;
}
[Link](i + " " + j);
}
}
Q8. Classes.
Definition:
A class in Java is a user-defined blueprint or template that
is used to create objects. It defines properties (variables)
and behaviors (methods) that the objects will have. A
class does not occupy memory until objects are created
from it.
Structure of a Class:
A class is defined using the class keyword followed by the
class name. Inside the class, variables and methods are
declared to represent data and actions.
Q9. Methods
Definition:
A method in Java is a block of code that performs a
specific task. It is used to define the behavior of a class
and helps in code reusability. Methods are executed only
when they are called, and they can return a value or
perform an action without returning anything.
Types of Methods:
1. Predefined Methods (Library Methods)
These are already available in Java libraries and can
be used directly in the program.
Example: [Link](), [Link]()
2. User-defined Methods
These are created by the programmer to perform
specific tasks according to program requirements.
Q10. Objects
Definition:
An object is a real-world entity that is created from a class.
It is an instance of a class that contains its own data and
methods. Objects occupy memory space and are used to
access the properties and behaviors defined in the class.
How Objects are Created:
Objects are created using the new keyword followed by
the class constructor. Each object has its own copy of
data members.
Syntax:
ClassName objectName = new ClassName();
Q11. Method Declaration
Definition:
Method declaration refers to defining a method by
specifying its name, return type, and parameters without
executing it. It tells the compiler what the method will do
and how it can be used. A method is executed only when it
is called.
Components of Method Declaration:
1. Return Type
It specifies the type of value the method will return
(e.g., int, void, String). If no value is returned, void is
used.
2. Method Name
It is the name given to the method to identify and call
it in the program.
3. Parameters
These are values passed to the method to perform
operations. A method may or may not have
parameters.
Syntax:
returnType methodName(parameterList) {
// method body
}
Example:
class Demo {
// Method declaration
int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Demo obj = new Demo();
int result = [Link](10, 20);
[Link]("Sum = " + result);
}
}
Q12. Constructors
Definition:
A constructor is a special type of method used to initialize
objects. It has the same name as the class and does not
have any return type, not even void. It is automatically
called when an object is created.
Characteristics of Constructor:
• It has the same name as the class.
• It does not return any value.
• It is called automatically when an object is created.
• It is mainly used to initialize data members of a class.
Types of Constructors:
1. Default Constructor
It is a constructor without any parameters. If no
constructor is defined, Java provides it automatically.
It assigns default values to variables.
2. Parameterized Constructor
It is a constructor that takes parameters. It is used to
initialize objects with specific values provided by the
user.
Q13. Method Overloading
Definition:
Method overloading is a feature in which a class has
multiple methods with the same name but different
parameter lists. It is used to increase the readability of the
program and allows the same method to perform different
tasks based on input.
Q14. Method Overriding
Definition:
Method overriding is a feature in which a subclass
provides a specific implementation of a method that is
already defined in its parent class. The method in the
subclass must have the same name, same parameters,
and same return type as in the parent class. It is used to
achieve runtime polymorphism.
Rules for Method Overriding:
• Method name must be same in both parent and child
class.
• Parameters must be same.
• It requires inheritance.
• The method in child class replaces the parent class
method.
Q15. Inheritance
Definition:
Inheritance is a mechanism in which one class acquires
the properties and behaviors of another class. It is used to
achieve code reusability and establishes a relationship
between classes.
Types of Inheritance in Java:
1. Single Inheritance
In single inheritance, one child class inherits from one
parent class. It is the simplest form of inheritance.
2. Multilevel Inheritance
In multilevel inheritance, a class is derived from another
derived class, forming a chain.
3. Hierarchical Inheritance
In hierarchical inheritance, multiple child classes inherit
from a single parent class.