1st Module Notes Java
1st Module Notes Java
UNIVERSITY
JNANA SANGAMA, BELGAVI-590018, KARNATAKA
Object Oriented
Programming with
JAVA
(AS PER CBCS SCHEME 2022)
PREPARED BY:
LAVANYA S
ASSISTANT PROFESSOR
Module 1
Introduction to Java
Java is a high-level, object-oriented programming language developed by Sun Microsystems
in 1995. It is mostly used for building desktop applications, web applications, Android apps,
and enterprise systems.
History:
• Java was developed by Sun Microsystems in 1995.
• James Gosling is know as the father of java.
• Before java, its name was Ook ,since Ook was already a registered company so James
gosling and his team changed the Ook name to JAVA
Features of java
• Object-Oriented Programming (OOP): Java supports OOP concepts to create
modular and reusable code.
• Platform Independence: Java programs can run on any operating system with a JVM.
• Robust and Secure: Java ensures reliability and security through strong memory
management and exception handling.
• Multithreading and Concurrency: Java allows concurrent execution of multiple tasks
for efficiency.
• Rich API and Standard Libraries: Java provides extensive built-in libraries for various
programming needs.
• Frameworks for Enterprise and Web Development: Java supports frameworks that
simplify enterprise and web application development.
• Open-Source Libraries: Java has a wide range of libraries to extend functionality and
speed up development.
• Maintainability and Scalability: Java’s structured design allows easy maintenance
and growth of applications.
Programming:
Programming is instructing the computer to perform a task.
Compiler:
It is software converting high level language[human lang] into low level language
Object Oriented Programming:
It is a programming paradigm[style] which intended to slove a real world prombles.
1
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Object means a real-world entity such as a mobile, book, table, computer, watch, etc.
Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects. It simplifies software development and maintenance by providing some
concepts.
Class
In object-oriented programming, a class is a blueprint from which individual objects are
created (or, we can say a class is a data type of an object type). In Java, everything is related
to classes and objects. Each class has its methods and attributes that can be accessed and
manipulated through the objects.
Examples of Class
If you want to create a class for students. In that case, "Student" will be a class, and student
records (like student1, student2, etc) will be objects.
We can also consider that class is a factory (user-defined blueprint) to produce objects.
// create a Student class
public class Student {
// Declaring attributes
String name;
int rollNo;
String section;
// print details
public void printDetails() {
[Link]("Student Details:");
[Link]([Link]+ ", "+", " + [Link] + ", " + section);
}
}
Object
In object-oriented programming, an object is an entity that has two characteristics (states
and behavior). Some of the real-world objects are book, mobile, table, computer, etc. An
object is a variable of the type class, it is a basic component of an object-oriented
programming system. A class has the methods and data members (attributes), these
methods and data members are accessed through an object. Thus, an object is an instance
of a class.
Example of Objects
2
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Continuing with the example of students, let's create some students as objects and print
their details.
// create a Student class
public class Student {
// Declaring attributes
String name;
int rollNo;
String section;
// print details
public void printDetails() {
[Link]("Student Details: ");
[Link]([Link]+ ", " + [Link] + ", " + section);
}
public static void main(String[] args) {
// create student objects
Student student1 = new Student("Robert", 1, "IX Blue");
// print student details
[Link]();
}
}
Output
Let us compile and run the above program, this will produce the following result −
Student Details: Robert, 1, IX Blue
Understanding the Hello World Program in Java
When we learn any programming language, the first step is writing a simple program to
display "Hello World". So, here is a simple Java program that displays "Hello World" on the
screen.
// A Java program to print Hello World!
public class HelloWorld {
public static void main(String[] args) {
3
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
[Link]("Hello World!");
}
}
Output
Hello World!
• // Starts a single-line comment. The comment is not executed by Java.
• public class HelloWorld defines a class named HelloWorld. In Java, every program
must be inside a class.
• public static void main(String[] args) is the entry point of any Java application. It tells
the JVM where to start executing the program.
• [Link]("Hello, World!"); prints the message to the console.
The JVM acts as a layer between the bytecode and the underlying system, allowing
the same program to run on Windows, Linux, macOS, or any other platform that has
a compatible JVM.
4
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
To run the program, the Java Virtual Machine (JVM) steps in. Each operating system
(Windows, macOS, Linux, etc.) has its own version of the JVM. The JVM reads the
bytecode and translates it into machine code suitable for that specific system at
runtime.
This setup—compile once, run anywhere with the help of JVMs—is what makes
Java platform independent.
Key Characteristics
return a + b;
5
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Output:
Sum = 30
Explanation:
OOP organizes software around objects instead of actions, and data instead of
logic.
Key Characteristics
class Calculator {
return a + b;
Output:
Sum = 30
Explanation:
class Student {
String name;
int age;
void displayInfo() {
7
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
[Link] = "Asha";
[Link] = 20;
[Link]();
Output:
Name: Asha
Age: 20
Abstraction in Java
Abstraction is one of the four main principles of Object-Oriented Programming (OOP) in
Java (along with Encapsulation, Inheritance, and Polymorphism).
8
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
It focuses on hiding unnecessary details from the user and showing only the essential
features of an object.
Definition
Abstraction means showing only what is necessary and hiding the implementation details.
It helps reduce complexity and allows the programmer to focus on what an object does,
rather than how it does it.
Real-Life Example
Think of a TV remote:
• You press buttons to control the TV (volume, channel, etc.).
• You don’t know or need to know the internal circuits.
This is abstraction — you use something without knowing its complex inner working.
Why Abstraction is Needed
• To reduce complexity in large programs.
• To increase reusability of code.
• To enhance security by hiding sensitive implementation.
• To improve maintainability — changes in implementation don’t affect users.
How Abstraction is Achieved in Java
In Java, abstraction can be achieved in two ways:
1 Using Abstract Classes
2 Using Interfaces
Using Abstract Classes
Definition
An abstract class is a class declared using the keyword abstract.
It may contain:
• Abstract methods (without body)
• Non-abstract methods (with body)
An abstract method is declared without implementation — subclasses must provide their
own version.
9
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
10
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
void sound() {
[Link]("Bark");
}
}
class Cat extends Animal {
void sound() {
[Link]("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();
[Link](); // calls Dog's implementation
[Link](); // calls Cat's implementation
}
}
Output:
Bark
Meow
Explanation:
Each subclass provides its own implementation for the abstract method sound().
11
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
12
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
[Link] — Reusability
Inheritance allows one class (child/subclass) to acquire the properties and behaviors of
another class (parent/superclass).
This promotes code reusability and reduces redundancy.
In Java, inheritance is implemented using the extends keyword.
Key Features
• Enables code reuse from an existing class.
• Supports hierarchical relationships.
• Allows method overriding.
Syntax
13
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
class ParentClass {
// parent class code
}
class ChildClass extends ParentClass {
// child class code
}
Example: Inheritance in Java
class Animal {
void eat() {
[Link]("Eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited method
[Link](); // subclass method
}
}
Output:
Eating...
Barking...
14
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Note: Java does not support multiple inheritance with classes (to avoid ambiguity), but it
can be achieved using interfaces.
15
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
16
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Comparison Table
Overloading,
Polymorphism Same method behaves differently Flexibility
Overriding
17
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
1 Method Block
2 Conditional or Loop Block
3 Nested Block
4 Static Block
5 Instance Block
1. Method Block
A method block defines the body of a method — the set of statements that execute when
the method is called.
Syntax:
returnType methodName(parameters) {
// method block
// statements to execute
}
Example:
public class MethodBlockExample {
void greet() {
[Link]("Hello Students!");
[Link]("Welcome to Java Programming.");
}
public static void main(String[] args) {
MethodBlockExample obj = new MethodBlockExample();
[Link](); // calling the method
}
}
Output:
Hello Students!
Welcome to Java Programming.
18
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Example:
public class ConditionalBlockExample {
public static void main(String[] args) {
int num = 3;
if (num > 0) { // conditional block
[Link]("Number is Positive");
} else {
[Link]("Number is Negative");
}
// Loop block
for (int i = 1; i <= 3; i++) {
[Link]("Count: " + i);
}
}
}
Output:
Number is Positive
Count: 1
Count: 2
Count: 3
3. Nested Block
A nested block means one block is placed inside another.
It helps manage variable scope and organize complex logic.
Example:
public class NestedBlockExample {
public static void main(String[] args) {
int a = 10;
19
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
{
int b = 20;
[Link]("Inside inner block: a + b = " + (a + b));
{
int c = 30;
[Link]("Inside nested block: a + b + c = " + (a + b + c));
}
}
[Link]("Outside all blocks: a = " + a);
}
}
Output:
Inside inner block: a + b = 30
Inside nested block: a + b + c = 60
Outside all blocks: a = 10
Key Point:
Variables declared inside a nested block cannot be accessed outside it.
4. Static Block
A static block is used to initialize static variables.
It executes once only, when the class is loaded, even before the main() method.
Example:
class StaticBlockExample {
static int count;
static {
count = 5;
[Link]("Static Block Executed: Count = " + count);
}
public static void main(String[] args) {
[Link]("Main Method Executed");
20
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
}
}
Output:
Static Block Executed: Count = 5
Main Method Executed
Key Point:
Used for class-level initialization (e.g., reading configuration, setting static variables).
5. Instance Block
An instance block runs every time a new object is created.
It executes before the constructor and is used to initialize instance variables.
Example:
class InstanceBlockExample {
{
[Link]("Instance Block Executed");
}
InstanceBlockExample() {
[Link]("Constructor Executed");
}
public static void main(String[] args) {
InstanceBlockExample obj1 = new InstanceBlockExample();
InstanceBlockExample obj2 = new InstanceBlockExample();
}
}
Output:
Instance Block Executed
Constructor Executed
Instance Block Executed
Constructor Executed
21
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Method Block When the method is called Defines the method logic
Instance Block Before constructor, every object creation Initialize instance data
22
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
2 .Identifiers
Identifiers are names given to variables, methods, classes, and labels in Java.
They are used to uniquely identify program elements.
Rules for Identifiers:
1. Must start with a letter (A-Z or a-z), $, or _ (underscore).
2. Can contain letters, digits (0-9), $, and _.
3. Case-sensitive: Name and name are different.
4. Cannot be a Java keyword.
Example:
public class IdentifierExample {
public static void main(String[] args) {
int age = 20;
int _salary = 5000;
int $bonus = 1000;
[Link]("Age: " + age + ", Salary: " + _salary + ", Bonus: " + $bonus);
}
}
Output:
Age: 20, Salary: 5000, Bonus: 1000
[Link]
Literals are fixed values directly used in a Java program. They represent data in its simplest
form.
Types of Literals:
1. Integer Literals: e.g., int a = 10;
2. Floating-point Literals: e.g., float f = 3.14f;
3. Character Literals: e.g., char c = 'A';
4. String Literals: e.g., String name = "Java";
5. Boolean Literals: e.g., boolean flag = true;
23
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
4. Comments
Comments are non-executable statements in Java used to explain code.
They are ignored by the compiler.
Types of Comments:
1. Single-line comment: // This is a comment
2. Multi-line comment: /* This is a comment */
3. Documentation comment: /** This is a Javadoc comment */
Example:
public class CommentExample {
public static void main(String[] args) {
// Single-line comment
[Link]("Hello Java"); /* Inline multi-line comment */
/*
Multi-line comment example
*/
24
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
}
}
5. Separators
Separators are special symbols used to divide or separate code elements like statements,
classes, methods, or blocks.
Common Separators:
• ; → Statement terminator
• { } → Defines a block of code (class, method, loop)
• ( ) → Method parameters or expressions
• [ ] → Arrays
• , → Separate multiple items (variables, arguments)
• . → Access members of a class or object
Example:
public class SeparatorExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for(int i = 0; i < [Link]; i++){
[Link](numbers[i]);
}
}
}
[Link] Keywords
Keywords are reserved words in Java with predefined meaning.
They cannot be used as identifiers.
Common Keywords:
int, float, if, else, for, while, class, static, void, return, public, private, new, this, try, catch
Example:
public class KeywordExample {
25
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Default
Type Size Range / Description
Value
26
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Default
Type Size Range / Description
Value
[Link]
The byte data type is an 8-bit signed two's complement integer. The byte data type is useful
for saving memory in large arrays.
Stores small integer values in the range -128 to 127.
• Syntax: byte variableName = value;
• Example:
byte b = 100;
[Link]("Byte value: " + b);
Output:
Byte value: 100
[Link]
The short data type is a 16-bit signed two's complement integer. Similar to byte, a short
is used when memory savings matter, especially in large arrays where space is
constrained.
Stores medium-sized integer values in the range -32,768 to 32,767.
• Syntax: short variableName = value;
• Example:
short s = 10000;
[Link]("Short value: " + s);
Output:
Short value: 10000
27
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
3. int
• Definition: Most commonly used integer type. Range: -2,147,483,648 to
2,147,483,647.
• Syntax: int variableName = value;
• Example:
int i = 50000;
[Link]("Integer value: " + i);
Output:
Integer value: 50000
4 .long
The long data type is a 64-bit signed two's complement integer. It is used when an int is not
large enough to hold a value, offering a much broader range.
Stores very large integers. Range: -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
• Syntax: long variableName = valueL;
• Example:
long l = 10000000000L;
[Link]("Long value: " + l);
Output:
Long value: 10000000000
[Link]
The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of
double) if you need to save memory in large arrays of floating-point numbers. The size of the
float data type is 4 bytes (32 bits).
Stores decimal numbers with single precision (7 digits).
• Syntax: float variableName = valuef;
• Example:
float f = 3.14f;
[Link]("Float value: " + f);
28
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Output:
Float value: 3.14
[Link]
The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values,
this data type is generally the default choice. The size of the double data type is 8 bytes or
64 bits.
Stores decimal numbers with double precision (15-16 digits).
• Syntax: double variableName = value;
• Example:
double d = 3.141592653589;
[Link]("Double value: " + d);
Output:
Double value: 3.141592653589
[Link]
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
• Stores a single character in Unicode format.
• Syntax: char variableName = 'character';
• Example:
char c = 'A';
[Link]("Character value: " + c);
Output:
Character value: A
[Link]
The boolean data type represents a logical value that can be either true or false.
Conceptually, it represents a single bit of information, but the actual size used by the virtual
machine is implementation-dependent and typically at least one byte (eight bits) in practice.
Values of the boolean type are not implicitly or explicitly converted to any other type using
casts. However, programmers can write conversion code if needed
29
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
30
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
byte: 100
short: 1000
int: 10000
long: 100000
float: 3.14
double: 3.14159
char: A
boolean: true
• 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.
Int[] numbers = {10, 20, 30};
[Link](numbers[1]); // Output: 20
Variables in Java
A variable is a named memory location used to store data in a program.
• The value of a variable can change during program execution.
• Every variable has a data type that determines what type of data it can store.
Rules to Name Java Variables
• Start with a Letter, $, or _ – Variable names must begin with a letter (a–z, A–Z),
dollar sign $, or underscore _.
• No Keywords: Reserved Java keywords (e.g., int, class, if) cannot be used as
variable names.
• Case Sensitive: age and Age are treated as different variables.
• Use Letters, Digits, $, or _ : After the first character, you can use letters, digits (0–9),
$, or _.
• Meaningful Names: Choose descriptive names that reflect the purpose of the
variable (e.g., studentName instead of s).
• No Spaces: Variable names cannot contain spaces.
• Follow Naming Conventions: Typically, use camelCase for variable names in Java
(e.g., totalMarks).
Syntax to declare a variable:
dataType variableName; // Declaration
variableName = value; // Initialization
Or combine both:
dataType variableName = value;
Types of Variables
Java supports 3 main types of variables:
1 Local Variables
32
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
2 Instance Variables
3 Static Variables
1 Local Variables
• Declared inside a method, constructor, or block. A variable defined within a block,
method, or constructor is called a local variable.
• Local variables are created when the block or method is executed and destroyed
when the block or method exits.
• The scope of a local variable is limited to the block in which it is declared; it cannot
be accessed outside that block.
• We have to initialize the local variables before using it
Example:
public class LocalVariableExample {
public static void main(String[] args) {
int age = 20; // Local variable
[Link]("Age: " + age);
}
}
Output:
Age: 20
34
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
36
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
• Possible data loss may occur (fraction part removed or value truncated).
• Must use explicit cast operator (type).
Syntax:
smallerType variable = (smallerType) largerTypeVariable;
Example:
public class NarrowingExample {
public static void main(String[] args) {
double d = 9.78;
int i = (int)d; // explicit casting
[Link]("double d = " + d);
[Link]("int i = " + i);
}}
Output:
double d = 9.78
int i = 9
Automatic Type Promotion in Expressions
Type Promotion is the automatic conversion of smaller data types to a larger data type
when different types are used in an arithmetic expression.
• Ensures the calculation is done using the largest data type in the expression.
Rules:
1. byte, short, char → promoted to int.
2. If int and float → promoted to float.
3. If int and double → promoted to double.
Example:
public class TypePromotionExample {
public static void main(String[] args) {
byte b = 10;
int i = 20;
double d = 5.5;
double result = b + i + d; // b and i promoted to double
37
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Arrays in Java
An array is a container that holds a fixed number of values of the same data type.
An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
• Each value in an array is called an element.
• Array elements are stored in contiguous memory locations.
• Arrays allow efficient storage and manipulation of multiple data items.
Key Points:
1. All elements must be of the same type.
2. Array size is fixed once declared.
3. Array index starts from 0 (zero-based indexing).
Array Initialization
38
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
39
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
40
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
}
Run Code
Output:
Student 1: 85
Student 2: 90
Student 3: 78
Student 4: 92
Student 5: 88
2 Two-Dimensional Array
A 2D array in Java represents data in a grid or table format. It requires two indices to
access each element: one for the row and one for the column.
Syntax:
dataType[][] arrayName = new dataType[rows][columns];
Example:
public class TwoDimensionalArray {
public static void main(String[] args) {
int[][] matrix = new int[2][3];
// Assign values
matrix[0][0] = 10;
matrix[0][1] = 20;
matrix[0][2] = 30;
matrix[1][0] = 40;
matrix[1][1] = 50;
matrix[1][2] = 60;
// Print 2D array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}
Run Code
Output:
10 20 30
40 50 60
• Stores elements in rows and columns (matrix form).
41
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
3 Multi-Dimensional Array
Syntax:
dataType[][][] arrayName = new dataType[depth][rows][columns];
Example:
public class ThreeDimensionalArray {
public static void main(String[] args) {
int[][][] cube = new int[2][2][3];
// Assign values
int value = 1;
for (int i = 0; i < 2; i++) { // depth
for (int j = 0; j < 2; j++) { // rows
for (int k = 0; k < 3; k++) { // columns
cube[i][j][k] = value++;
}
}
}
// Print 3D array
for (int i = 0; i < 2; i++) {
[Link]("Layer " + (i + 1));
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
[Link](cube[i][j][k] + " ");
}
[Link]();
}
[Link]();
}
}
}
Run Code
Output:
Layer 1
1 2 3
4 5 6
Layer 2
7 8 9
10 11 12
42
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Traversing (for loop) Iterating through elements for(int i=0; i<[Link]; i++)
using index
43
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Operators in Java
An operator is a symbol that performs an operation on variables and values.
Operators are used to manipulate data and control the flow of a Java program.
Example:
int a = 10, b = 5;
int sum = a + b; // '+' is an arithmetic operator
[Link](sum);
Output:
15
Types of Operators
Java operators are divided into several categories.
1. Arithmetic Operators
2. Relational Operators
3. Logical (Boolean) Operators
4. Assignment Operators
5. Conditional (Ternary) Operator ?:
6. Operator Precedence
7. Using Parentheses
8. Bitwise Operators
[Link] Operators
44
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra
Operators List:
+ Addition a+b 15
- Subtraction a-b 5
* Multiplication a*b 50
/ Division a/b 2
Example Program:
public class ArithmeticExample {
public static void main(String[] args) {
int a = 10, b = 5;
[Link]("Addition: " + (a + b));
[Link]("Subtraction: " + (a - b));
[Link]("Multiplication: " + (a * b));
[Link]("Division: " + (a / b));
[Link]("Modulus: " + (a % b));
}
}
Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Modulus: 0
2. Relational Operators
Relational operators are used to compare two values. These operators return a boolean
result: true if the condition is met and false otherwise. Relational operators are
45
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
== Equal to a == b false
Example Program:
public class RelationalExample {
public static void main(String[] args) {
int a = 10, b = 5;
[Link](a > b); // true
[Link](a < b); // false
[Link](a == b); // false
[Link](a != b); // true
}
}
Output:
true
false
false
true
3. Logical (Boolean) Operators
Logical operators are used to perform logical operations on boolean values. These
operators are commonly used in decision-making statements such as if conditions
and loops to control program flow.
46
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Operators List:
Example Program:
public class LogicalExample {
public static void main(String[] args) {
int a = 10, b = 5;
[Link]((a > b) && (a > 0)); // true
[Link]((a < b) || (a > 0)); // true
[Link](!(a > b)); // false
}
}
Output:
true
true
false
[Link] Operators
Assignment operators are used to assign values to variables. These operators modify the
value of a variable based on the operation performed. The most commonly used
assignment operator is =, but Java provides multiple compound assignment operators for
shorthand operations.
Operators List:
= a = 10 Assigns 10 to a —
47
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Example Program:
public class AssignmentExample {
public static void main(String[] args) {
int a = 10;
a += 5;
[Link]("a after += : " + a);
a *= 2;
[Link]("a after *= : " + a);
}
}
Output:
a after += : 15
a after *= : 30
[Link] (Ternary) Operator ?:
The ternary operator is a short form of if-else statement.
It has three operands.
Conditional operator is also known as the ternary operator. This operator consists of
three operands and is used to evaluate Boolean expressions. The goal of the operator is
to decide, which value should be assigned to the variable.
Syntax:
variable = (condition) ? expression1 : expression2;
If condition is true, expression1 executes; otherwise expression2.
Example Program:
public class TernaryExample {
public static void main(String[] args) {
int a = 10, b = 20;
int max = (a > b) ? a : b;
48
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
6. Operator Precedence
Operator precedence determines the order in which operations are performed in an
expression.
Example Table (Highest → Lowest Precedence):
4 +, - Addition, subtraction
8 `
9 ?: Conditional
10 =, +=, -= Assignment
[Link] Parentheses
Parentheses () are used to override the default precedence and control the order of
evaluation.
Example Program:
public class ParenthesesExample {
49
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
[Link] Operators
Bitwise operators are used to perform operations at the binary (bit) level. These
operators work on individual bits of numbers. They are commonly used in low-level
programming, encryption, and performance optimization.
Java defines several bitwise operators, which can be applied to the integer types, long,
int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b
= 13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then −
50
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
is 0000 1100
(A | B) will give
Binary OR Operator copies a bit if it exists in
| (bitwise or) 61 which is 0011
either operand.
1101
Binary Left Shift Operator. The left operands A << 2 will give 240 which
<< (left shift) value is moved left by the number of bits
specified by the right operand. is 1111 0000
Example
The following example demonstrates the usage of bitwise operators in Java:
public class BitwiseExample {
public static void main(String[] args) {
int A = 60; // 0011 1100
int B = 13; // 0000 1101
51
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
52
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
A control statement in Java is used to control the flow of execution of a program based on
conditions or loops.
They help the program to make decisions, repeat actions, or jump to specific parts of code.
Types of Control Statements
Java control statements are classified into three main categories:
Type Purpose
1. Decision-Making Statements/Selection
Used to make choices or decisions
Statements
1. Decision-Making Statements
These statements decide which block of code to execute based on a condition (true/false).
a) if Statement
Executes a block of code only if the given condition is true.
Syntax:
if (condition) {
// statements to execute if condition is true
}
Example:
public class IfExample {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
[Link]("You are eligible to vote");
}
}
53
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
}
Output:
You are eligible to vote
b) if–else Statement
Executes one block if the condition is true, otherwise executes the else block.
Syntax:
if (condition) {
// statements if true
} else {
// statements if false
}
Example:
public class IfElseExample {
public static void main(String[] args) {
int num = 10;
if (num % 2 == 0) {
[Link]("Even Number");
} else {
[Link]("Odd Number");
}
}
}
Output:
Even Number
c) if–else–if Ladder
Used to test multiple conditions sequentially.
Syntax:
54
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// default block
}
Example:
public class IfElseIfExample {
public static void main(String[] args) {
int marks = 85;
if (marks >= 90) {
[Link]("Grade A+");
} else if (marks >= 75) {
[Link]("Grade A");
} else if (marks >= 60) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}
}
}
Output:
Grade A
d) Nested if Statement
An if statement inside another if block.
Example:
public class NestedIfExample {
55
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
e) switch Statement
Used to select one option from multiple choices.
It is a replacement for long if–else–if ladders.
Syntax:
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// default statements
56
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
}
Example:
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid day");
}
}
}
Output:
Wednesday
2. Looping Statements
Used to execute a block of code repeatedly until a condition is false.
a) while Loop
A while loop in Java is a control statement that repeatedly executes a block of code as long
as a given condition is true.
It’s useful when you don’t know beforehand how many times you’ll need to repeat
something.
Syntax:
while (condition) {
// loop body
}
Example:
public class WhileExample {
57
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
b) do–while Loop
A do-while loop in Java is a control statement that allows a block of code to be executed at
least once, and then repeatedly executes the block as long as the given condition remains
true.
In this loop, the condition is tested after the execution of the loop body — hence, the loop
body always executes at least one time, even if the condition is false initially.
Syntax:
do {
// loop body
} while (condition);
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
58
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
[Link](i);
i++;
} while (i <= 5);
}
}
Output:
1
2
3
4
5
c) for Loop
A for loop in Java is a control flow statement that allows a block of code to be executed a
specific number of times.
It is generally used when you know in advance how many times you want to repeat a
statement or a block of code.
Syntax:
for (initialization; condition; increment/decrement) {
// loop body
}
Example:
public class ForExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
[Link]("Value: " + i);
}
}
}
Output:
59
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
3. Jump Statements
Jump statements in Java are used to control the flow of execution by transferring control
to another part of the program.
a) break Statement
60
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
The break statement in Java is a jump statement used to terminate the execution of a loop
(for, while, do-while) or a switch statement immediately.
When Java encounters break, it exits the loop or switch and transfers control to the next
statement following the loop or switch.
Key Points:
• Can be used in loops (for, while, do-while) and switch statements.
• Stops the current iteration and all remaining iterations of the loop.
• Useful when a condition is met and you want to exit early.
Exits a loop or switch statement immediately.
Example:
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3)
break;
[Link](i);
}
}
}
Output:
1
2
b) continue Statement
The continue statement in Java is a jump statement used to skip the current iteration of a
loop and immediately proceed to the next iteration.
Unlike break, it does not terminate the loop; the loop continues executing after skipping the
current iteration.
61
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Key Points:
• Can be used in for, while, and do-while loops.
• Skips the rest of the statements in the current iteration.
• Useful when you want to ignore certain conditions but continue looping.
Skips the current iteration and moves to the next one.
Example:
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3)
continue;
[Link](i);
}
}
}
Output:
1
2
4
5
c) return Statement
The return statement in Java is a jump statement used to exit from a method and optionally
return a value to the method’s caller.
When a return statement is executed:
• The current method terminates immediately.
• If the method is non-void, it sends a value back to the caller.
• If the method is void, it simply exits the method.
62
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A
Key Points:
• Used inside methods only.
• Can return a value (for non-void methods) or nothing (for void methods).
• Execution of statements after return in the method is skipped.
Used to exit from a method and optionally return a value.
Example:
public class ReturnExample {
public static void main(String[] args) {
int result = add(5, 10);
[Link]("Sum: " + result);
}
static int add(int a, int b) {
return a + b; // control returns here
}
}
Output:
Sum: 15
63
Dept of CSE-DS,KNSIT