[Go to site: main page, start]

0% found this document useful (0 votes)
2 views64 pages

1st Module Notes Java

The document is a course outline for Object Oriented Programming with Java, detailing its introduction, features, programming paradigms, and key concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It explains Java's platform independence and provides examples of basic Java programs, including the 'Hello World' program and demonstrates procedural versus object-oriented programming. Additionally, it covers abstraction and its implementation through abstract classes and interfaces, emphasizing the importance of OOP principles in software development.

Uploaded by

lavanyas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views64 pages

1st Module Notes Java

The document is a course outline for Object Oriented Programming with Java, detailing its introduction, features, programming paradigms, and key concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It explains Java's platform independence and provides examples of basic Java programs, including the 'Hello World' program and demonstrates procedural versus object-oriented programming. Additionally, it covers abstraction and its implementation through abstract classes and interfaces, emphasizing the importance of OOP principles in software development.

Uploaded by

lavanyas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

VISVESVARAYA TECHNOLOGICAL

UNIVERSITY
JNANA SANGAMA, BELGAVI-590018, KARNATAKA

Object Oriented
Programming with
JAVA
(AS PER CBCS SCHEME 2022)

SUB CODE: BCS306A

PREPARED BY:
LAVANYA S

ASSISTANT PROFESSOR

DEPT OF CSE-(DS), KNSIT

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING (DATA SCIENCE)


K.N.S INSTITUTE OF TECHNOLOGY
HEGDE-NAGAR, KOGILU ROAD,
THIRUMENAHALLI, YELAHANKA,
BANGALORE-560064
Oops with JAVA BCS306A

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.

How to run the above code?


• Write code in a file like [Link].
• The Java Compiler "javac" compiles it into bytecode "[Link]".
• The JVM (Java Virtual Machine) reads the .class file and interprets the bytecode.
• JVM converts bytecode to machine readable code i.e. "binary" (001001010) and then
execute the program.
Why is Java Platform Independent?
Java is called platform independent because its compiled code, known as bytecode,
can run on any operating system without needing changes. Unlike languages like C
or C++ that compile directly to machine-specific code, Java compiles to bytecode,
which is interpreted or compiled at runtime by the Java Virtual Machine (JVM).

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.

How is Java Platform Independent?


Java is platform independent because it does not compile code directly into
machine-specific instructions. Instead, when you write a Java program and compile
it, the Java compiler (javac) converts the code into bytecode, which is a universal
format stored in .class files. This bytecode is not tied to any specific operating
system.

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.

Two Paradigms in Java

Java supports two major programming paradigms:

1. Procedural (Structured) Programming


2. Object-Oriented Programming (OOP)

A programming paradigm is a style or approach to writing computer programs.


Java is primarily an object-oriented language, but it also supports procedural
programming features.

1. Procedural (Structured) Programming Paradigm

Procedural programming focuses on writing a sequence of instructions or


procedures (functions) that operate on data.

It emphasizes how to perform a task step by step.

Key Characteristics

• Divides program into functions or methods.


• Follows a top-down design approach.
• Data is separate from functions.
• Execution flows sequentially.
• Emphasizes reusable functions.

Example : Sum of Two Numbers

public class SumExample {

static int add(int a, int b) { // function to add two numbers

return a + b;

} public static void main(String[] args) {

int result = add(10, 20);

5
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

[Link]("Sum = " + result);

Output:

Sum = 30

Explanation:

• Function add() performs a specific task.


• The focus is on functions (not objects).

[Link]-Oriented Programming (OOP) Paradigm

Object-Oriented Programming (OOP) focuses on objects — real-world entities that


have data (attributes) and behavior (methods).

OOP organizes software around objects instead of actions, and data instead of
logic.

Key Characteristics

• Follows a bottom-up approach.


• Combines data and methods inside classes.
• Improves reusability, modularity, and security.
• Based on key concepts like:
o Class
o Object
o Encapsulation
o Inheritance
o Polymorphism
o Abstraction

Example : Object-Oriented Addition

class Calculator {

int add(int a, int b) { // behavior


6
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

return a + b;

public class Main {

public static void main(String[] args) {

Calculator calc = new Calculator(); // object creation

int result = [Link](10, 20);

[Link]("Sum = " + result);

Output:

Sum = 30

Explanation:

• The Calculator class defines both data and behavior.


• The program focuses on objects instead of just functions.

Example : Student Information

class Student {

String name;

int age;

void displayInfo() {

[Link]("Name: " + name);

[Link]("Age: " + age);

7
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

public class Main {

public static void main(String[] args) {

Student s1 = new Student(); // creating object

[Link] = "Asha";

[Link] = 20;

[Link]();

Output:

Name: Asha

Age: 20

Comparison Between Procedural and Object-Oriented Paradigms

Feature Procedural Programming Object-Oriented Programming


Focus Functions Objects
Approach Top-down Bottom-up
Data and functions are
Data Handling Data and methods are combined
separate
Reusability Low High (through inheritance)
Low (data can be modified High (data hidden using
Security
directly) encapsulation)
Example
C, Pascal Java, C++, Python
Language

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.

Example 1: Abstract Class Implementation


abstract class Shape {

9
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

abstract void draw(); // abstract method (no body)


void display() {
[Link]("Drawing Shape");
}
}
class Circle extends Shape {
void draw() {
[Link]("Drawing a Circle");
}
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle(); // reference of abstract class
[Link]();
[Link]();
}
}
Output:
Drawing Shape
Drawing a Circle
Explanation:
• Shape is an abstract class that defines a general idea.
• Circle provides the specific implementation of the draw() method.

Example 2: Abstract Class with Multiple Subclasses


abstract class Animal {
abstract void sound(); // abstract method
}
class Dog extends Animal {

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().

The Three Principles of Object-Oriented Programming (OOP)


Java is an Object-Oriented Programming Language based on three fundamental principles:
1 Encapsulation — Data Hiding
2 Inheritance — Reusability
3 Polymorphism — One Interface, Many Forms
These principles make Java programs more modular, reusable, flexible, and secure.

11
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

1 Encapsulation — Data Hiding


Encapsulation means wrapping data (variables) and methods (functions) that operate on
that data into a single unit (class).
It also restricts direct access to internal data and allows controlled access using getters and
[Link] is often called Data Hiding.
(Or)
It is a process of giving controlled access to very important aspect of an application
Key Features
• Keeps data safe from unauthorized access.
• Achieved using private variables and public methods.
• Improves modularity and maintainability.
Syntax
class ClassName {
private dataType variable; // private data
public void setVariable(dataType value) { // setter
variable = value;
}
public dataType getVariable() { // getter
return variable;
}
}

Example: Encapsulation in Java


class Student {
private String name; // private variable
// Setter method
public void setName(String n) {
name = n;
}
// Getter method

12
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

public String getName() {


return name;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]("Asha"); // setting value
[Link]("Student Name: " + [Link]());
}
}
Output:
Student Name: Asha
Explanation:
• The variable name is private — cannot be accessed directly.
• It can only be modified through public methods.
Real-Life Example
A capsule in medicine hides all its ingredients inside — you only take the capsule without
knowing its inner composition.
Similarly, a class hides its data inside methods.

[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...

Types of Inheritance in Java

14
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

Type Description Example

Single One subclass inherits one superclass Dog extends Animal

A class inherits from another which is also a Dog → Mammal →


Multilevel
subclass Animal

Hierarchical Multiple subclasses inherit one superclass Dog, Cat → Animal

Note: Java does not support multiple inheritance with classes (to avoid ambiguity), but it
can be achieved using interfaces.

[Link] — One Name, Many Forms


Polymorphism means the ability of a method or object to take many forms.
It allows one interface to be used for different types of actions.
(Or)
It is a process of a single entity taking multiple form
In Java, polymorphism is of two types:
1. Compile-time Polymorphism (Method Overloading)
2. Runtime Polymorphism (Method Overriding)

1. Compile-Time Polymorphism — Method Overloading


When multiple methods have the same name but different parameters, Java determines
which one to call at compile time.
Example:
class MathUtil {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {

15
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

MathUtil m = new MathUtil();


[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
}
}
Output:
30
60
Explanation:
• The add() method is overloaded — different versions exist for different parameter
counts.

2. Runtime Polymorphism — Method Overriding


When a subclass provides its own implementation of a method defined in the parent class,
Java decides which method to call at runtime.
Example:
class Animal {
void sound() {
[Link]("Animal sound");
}
}
class Cat extends Animal {
void sound() {
[Link]("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Cat(); // reference of parent, object of child

16
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

[Link](); // runtime decision


}
}
Output:
Meow
Explanation:
• Even though the reference is of type Animal, the method from Cat executes at
runtime.

Comparison Table

Principle Meaning Achieved By Benefit

Wrapping data & methods in one


Encapsulation private, getters/setters Data security
unit

Acquiring properties of another Code


Inheritance extends
class reusability

Overloading,
Polymorphism Same method behaves differently Flexibility
Overriding

Using Blocks of Code in Java


In Java, a block of code is a group of one or more statements enclosed within curly braces {
}.
Blocks define scope, lifetime, and execution order of code.
They help structure programs logically and control variable visibility.
Why Use Code Blocks?
• To group multiple statements logically.
• To define the scope of variables.
• To control execution order.
• To initialize values (using static or instance blocks).
• To ensure thread safety (using synchronized blocks).
Types of Code Blocks in Java
There are five main types of blocks:

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.

2. Conditional or Loop Block


Conditional and loop blocks are used with if-else, for, while, or switch statements.
They control which part of the program executes or repeats.

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

Type of Block When It Executes Purpose

Method Block When the method is called Defines the method logic

Conditional/Loop Block When condition/loop executes Controls program flow

Nested Block When inner block executes Controls variable scope

Static Block Once, when class loads Initialize static variables

Instance Block Before constructor, every object creation Initialize instance data

Lexical Issues in Java


In Java, lexical analysis is the first step the compiler performs. It breaks the program into
tokens, which are the smallest meaningful units of code.
Lexical issues deal with the basic building blocks of Java programs: whitespace, identifiers,
literals, comments, separators, and keywords.
[Link]
Whitespace refers to spaces, tabs, and newline characters in a Java program.
It is primarily used to separate tokens and improve code readability.
Rules:
• Extra whitespaces are ignored by the compiler except inside string literals.
• At least one whitespace is required to separate two tokens if they are not separated
by operators or punctuation.
Example:
public class WhitespaceExample {
public static void main(String[] args) {
int a = 10; // normal space
int b=20; // no space, still valid
int c = a+b; // extra spaces ignored
[Link]("Sum: " + c);
}
}
Output:
Sum: 30

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

6. Null Literal: e.g., String s = null;


Example:
public class LiteralExample {
public static void main(String[] args) {
int num = 100;
float pi = 3.14f;
char grade = 'A';
String name = "Java";
boolean status = true;
[Link](num + ", " + pi + ", " + grade + ", " + name + ", " + status);
}
}
Output:
100, 3.14, A, Java, true

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

public static void main(String[] args) {


int number = 10; // 'int' is a keyword
if(number > 0){ // 'if' is a keyword
[Link]("Positive Number");
}
}
}
Output:
Positive Number

Data Types in Java


Data type are mechanism to convert real world data into binary and store it in computer
memory
In Java, a data type specifies the type of data a variable can store. Every variable must be
declared with a data type, and Java provides strong type checking.
Classification of Data Types
Java data types are broadly classified into two categories:
1. Primitive Data Types – Basic types provided by Java (8 types).
2. Non-Primitive / Reference Data Types – Objects, Strings, Arrays, and Classes.
1. Primitive Data Types
Primitive types are predefined by Java and represent single values. They store actual data in
memory.
List of Primitive Data Types:

Default
Type Size Range / Description
Value

byte 1 byte 0 Stores small integers (-128 to 127)

short 2 bytes 0 Stores medium integers (-32,768 to 32,767)

int 4 bytes 0 Stores standard integers

long 8 bytes 0L Stores large integers

26
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

Default
Type Size Range / Description
Value

float 4 bytes 0.0f Stores decimal numbers (single precision)

double 8 bytes 0.0d Stores decimal numbers (double precision)

char 2 bytes '\u0000' Stores a single Unicode character

boolean 1 bit false Stores true/false values

[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

Stores true or false.


• Syntax: boolean variableName = true/false;
• Example:
boolean flag = true;
[Link]("Boolean value: " + flag);
Output:
Boolean value: true
Example for data types
public class PrimitiveExample {
public static void main(String[] args) {
byte b = 100;
short s = 1000;
int i = 10000;
long l = 100000L;
float f = 3.14f;
double d = 3.14159;
char c = 'A';
boolean flag = true;
[Link]("byte: " + b);
[Link]("short: " + s);
[Link]("int: " + i);
[Link]("long: " + l);
[Link]("float: " + f);
[Link]("double: " + d);
[Link]("char: " + c);
[Link]("boolean: " + flag);
}
}
Output:

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

2. Non-Primitive / Reference 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.
Reference types store the address of objects rather than actual data. They include Strings,
Arrays, and Classes.
[Link]
String 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.
String name = "Java Programming";
[Link]("Name: " + name);
Output:
Name: Java Programming
[Link]
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. (discussed below)
• 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.
31
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

• 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

2 Instance Variables (Non-static Fields)


Declared inside a class but outside any method, constructor, or block.
A variable defined inside a class but outside any method, block, or constructor is called an
instance variable.
Instance variables are created when an object of the class is instantiated and destroyed
when the object is garbage collected.
Each object of the class has its own copy of instance variables, so their values can vary
between objects.
If we do not explicitly initialize the instance variables, then default values are assigned to
them based on their data types (e.g., 0 for integers, null for objects).
Example: class Student {
String name; // Instance variable
33
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

int age; // Instance variable


void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
public class InstanceVariableExample {
public static void main(String[] args) {
Student s = new Student();
[Link] = "java";
[Link] = 21;
[Link]();
}
}
Output:
Name: java
Age: 21

3 Static Variables (Class Variables)


Declared with the static keyword inside a class but outside any method.
• A variable defined with the static keyword inside a class is called a static variable.
• Static variables are shared among all objects of the class; a single copy is created
and stored in the memory.
• These variables are created when the class is loaded and destroyed when the class
is unloaded.
• Static variables can be accessed without creating an object, using the class name.
Scope: Belongs to the class, shared among all objects.
• Default Value: Automatically initialized.
Example:
class Student {

34
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

static String schoolName = "ABC School"; // Static variable


int rollNo; // Instance variable
void display() {
[Link]("Roll No: " + rollNo);
[Link]("School: " + schoolName);
}
}
public class StaticVariableExample {
public static void main(String[] args) {
Student s1 = new Student();
[Link] = 101;
[Link]();
Student s2 = new Student();
[Link] = 102;
[Link]();
}
}
Output:
Roll No: 101
School: ABC School
Roll No: 102
School: ABC School

Type Conversion and Casting in Java


In Java, Type Conversion and Type Casting are used to convert one data type into another.
This is important because operations often involve different types, and Java is a strongly
typed language.
1. Type Conversion (Widening Conversion / Implicit Conversion)
Type Conversion is the process of automatically converting a smaller data type to a larger
data type by the compiler.
• Also called implicit type casting or type promotion.
35
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

• No data is lost during this conversion.


Rules:
• Smaller → Larger type:
byte → short → int → long → float → double
char → int → long → float → double
• No data loss occurs.
• Compiler automatically handles the conversion.
Syntax:
largerType variable = smallerTypeVariable;
Example:
public class WideningExample {
public static void main(String[] args) {
int i = 100;
double d = i; // int to double (implicit)
[Link]("int i = " + i);
[Link]("double d = " + d);
}
}
Output:
int i = 100
double d = 100.0

[Link] Casting (Narrowing Conversion / Explicit Conversion)


Type Casting is the process of manually converting a larger data type to a smaller data type
using parentheses.
• Also called explicit type casting.
• May cause data loss if the value exceeds the range of the target type.
Rules:
• Larger → Smaller type:
double → float → long → int → short → byte

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

[Link]("Result = " + result);


}
}
Output:
Result = 35.5

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).

Syntax of Array Declaration


Declaration
dataType[] arrayName; // Recommended
dataType arrayName[]; // Allowed but less recommended
Memory Allocation
arrayName = new dataType[size];
Combined Declaration and Allocation
dataType[] arrayName = new dataType[size];
Example:
int[] numbers = new int[5]; // Array of 5 integers

Array Initialization

38
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

1. Static Initialization (at the time of declaration):


int[] numbers = {10, 20, 30, 40, 50};
2. Dynamic Initialization (assigning values later):
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

Accessing Array Elements


• Use index number to access or modify elements.
int value = numbers[2]; // Access 3rd element
numbers[4] = 100; // Update 5th element
• Example Program:
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
[Link]("First element: " + numbers[0]);
[Link]("Third element: " + numbers[2]);
numbers[4] = 100;
[Link]("Updated fifth element: " + numbers[4]);
}
}
Output:
First element: 10
Third element: 30
Updated fifth element: 100

39
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

Types of Arrays in Java


1 One-Dimensional Array
2 Two-Dimensional Array
3 Multi-Dimensional Array
1 One-Dimensional Array
A single-dimensional array is a linear data structure that holds multiple values of the same
data type under one name. Each element is stored at a specific index, starting from 0. It's
most useful for managing simple lists, like storing marks, names, or IDs, where data is
arranged in a straight line.
Arrays are fixed in size, meaning you need to define the length when the array is created.
Java provides various ways to initialize and loop through single-dimensional arrays using for
or for-each loops.
Stores elements in a single row.
Syntax:
dataType[] arrayName = new dataType[size];
Example:
public class SingleDimensionalArray {
public static void main(String[] args) {
// Declare and initialize a single-dimensional array
int[] marks = new int[5];
// Assigning values
marks[0] = 85;
marks[1] = 90;
marks[2] = 78;
marks[3] = 92;
marks[4] = 88;
// Accessing and printing elements
for (int i = 0; i < [Link]; i++) {
[Link]("Student " + (i + 1) + ": " + marks[i]);
}
}

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

A 3D array stores data in layers or blocks. Think of it as a collection of multiple 2D


arrays stacked on top of each other. It's useful in simulations, games, and advanced
data modeling.

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

Key Points About Arrays

42
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

1. Array size cannot be changed after creation.


2. Array index starts from 0.
3. Accessing an invalid index throws ArrayIndexOutOfBoundsException.
4. Length of array can be obtained using [Link].
5. Arrays can be passed to methods or returned from methods.

Common Operations on Arrays in Java

Operation Description Sample Syntax / Example

Declaration Creating a reference to an int[] arr;


array

Initialization Allocating memory and int[] arr = new int[5];


assigning values

Assignment Setting a value at a specific arr[0] = 10;


index

Accessing Elements Reading a value from a [Link](arr[2]);


specific index

Finding Length Getting total number of [Link]


elements

Traversing (for loop) Iterating through elements for(int i=0; i<[Link]; i++)
using index

Enhanced for loop Simpler loop to iterate for(int num : arr)


elements

Copying Arrays Copy one array into another [Link](src, 0, dest,


0, length);

Sorting Sorting elements in ascending [Link](arr);


order

43
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

Searching Finding an element (binary [Link](arr, key);


search requires sorted array)

Filling Array Fill entire array with a value [Link](arr, 1);

Converting to String Convert array to printable [Link](arr);


string

Multidimensional Accessing elements in 2D/3D matrix[i][j];, cube[x][y][z];


Access arrays

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:

Operator Description Example (a=10, b=5) Result

+ Addition a+b 15

- Subtraction a-b 5

* Multiplication a*b 50

/ Division a/b 2

% Modulus (Remainder) a%b 0

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

commonly used in decision-making statements like if conditions and loops.


They return a boolean result (true or false).
Operators List:

Operator Meaning Example (a=10, b=5) Result

== Equal to a == b false

!= Not equal to a != b true

> Greater than a>b true

< Less than a<b false

>= Greater than or equal to a >= b true

<= Less than or 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:

Operator Meaning Example Result

&& Logical AND (a > b) && (a > 0) true

|| Logical OR (a>b)||(a>2) true

! Logical NOT !(a > b) false

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:

Operator Example Meaning Equivalent To

= a = 10 Assigns 10 to a —

+= a += 5 Add and assign a=a+5

-= a -= 5 Subtract and assign a=a-5

*= a *= 2 Multiply and assign a=a*2

47
Dept of CSE-DS,KNSIT
Oops with JAVA BCS306A

Operator Example Meaning Equivalent To

/= a /= 2 Divide and assign a=a/2

%= a %= 2 Modulus and assign a=a%2

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

[Link]("Maximum number: " + max);


}
}
Output:
Maximum number: 20

6. Operator Precedence
Operator precedence determines the order in which operations are performed in an
expression.
Example Table (Highest → Lowest Precedence):

Precedence Level Operators Description

1 (), [], . Parentheses, array index, member access

2 ++, -- Unary increment/decrement

3 *, /, % Multiplication, division, modulus

4 +, - Addition, subtraction

5 <, >, <=, >= Relational operators

6 ==, != Equality operators

7 && Logical AND

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

public static void main(String[] args) {


int result1 = 10 + 5 * 2; // Multiplication first
int result2 = (10 + 5) * 2; // Addition first
[Link]("Without parentheses: " + result1);
[Link]("With parentheses: " + result2);
}
}
Output:
Without parentheses: 20
With parentheses: 30

[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 −

Operator Description Example

Binary AND Operator copies a bit to the (A & B) will give


& (bitwise and)
result if it exists in both operands. 12 which

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 XOR Operator copies the bit if it is (A ^ B) will give 49 which


^ (bitwise XOR)
set in one operand but not both. is 0011 0001

(⁓A ) will give -61 which


⁓ (bitwise Binary Ones Complement Operator is unary
is 1100 0011 in 2's
compliment) and has the effect of 'flipping' bits.
binary number.

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

Binary Right Shift Operator. The left


operands value is moved right by the A >> 2 will give 15 which
>> (right shift)
number of bits specified by the right is 1111
operand.

Shift right zero fill operator. The left


operands value is moved right by the A >>>2 will give 15 which
>>> (zero fill
number of bits specified by the right
right shift) is 0000 1111
operand and shifted values are filled up
with zeros.

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

[Link]("A & B: " + (A & B)); // 12 (0000 1100)


[Link]("A | B: " + (A | B)); // 61 (0011 1101)
[Link]("A ^ B: " + (A ^ B)); // 49 (0011 0001)
[Link]("~A: " + (~A)); // -61 (1100 0011 in 2's complement)
[Link]("A << 2: " + (A << 2)); // 240 (1111 0000)
[Link]("A >> 2: " + (A >> 2)); // 15 (0000 1111)
[Link]("A >>> 2: " + (A >>> 2)); // 15 (0000 1111)
}
}
When the above code is compiled and executed, it produces the following result −
A & B: 12
A | B: 61
A ^ B: 49
~A: -61
A << 2: 240
A >> 2: 15
A >>> 2: 15

Operator Type Example Description

Arithmetic a+b Performs mathematical operations

Relational a>b Compares two values

Logical a > b && b > 0 Combines conditions

Assignment a += 10 Assigns and updates values

Conditional (?:) (a > b) ? a : b Short form of if-else

Precedence * before + Defines order of operation

Parentheses (a + b) * c Changes order of operation

Control Statements in Java

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

2. Iteration/Looping Statements Used to repeat a block of code

Used to transfer control to another part of


3. Jump Statements
the program

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

public static void main(String[] args) {


int age = 25;
boolean hasVoterID = true;
if (age >= 18) {
if (hasVoterID) {
[Link]("You can vote");
} else {
[Link]("Apply for voter ID first");
}
} else {
[Link]("You are underage");
}
}
}
Output:
You can vote

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

public static void main(String[] args) {


int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
}
}
Output:
1
2
3
4
5

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

d) Enhanced for Loop (for-each Loop)


Used to traverse arrays or collections easily.
Syntax:
for (dataType variable : arrayName) {
// use variable
}
Example:
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int num : numbers) {
[Link](num);
}
}
}
Output:
10
20
30

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

Type Statement Description

Executes code based on


Decision if, if-else, switch
condition

Looping for, while, do-while Repeats a block of code

Jump break, continue, return Transfers control flow

63
Dept of CSE-DS,KNSIT

You might also like