0% found this document useful (0 votes)
20 views31 pages

Certi 202506160617

This document introduces Object-Oriented Programming (OOP) and contrasts it with Procedure-Oriented Programming (POP), highlighting the limitations of POP in managing complex software. It outlines the fundamental features of OOP, such as encapsulation, inheritance, polymorphism, and abstraction, and discusses the benefits of OOP, including modularity, maintainability, and improved collaboration. The document also addresses the key characteristics and problems associated with the Procedure-Oriented Approach.

Uploaded by

malaveeresh19
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)
20 views31 pages

Certi 202506160617

This document introduces Object-Oriented Programming (OOP) and contrasts it with Procedure-Oriented Programming (POP), highlighting the limitations of POP in managing complex software. It outlines the fundamental features of OOP, such as encapsulation, inheritance, polymorphism, and abstraction, and discusses the benefits of OOP, including modularity, maintainability, and improved collaboration. The document also addresses the key characteristics and problems associated with the Procedure-Oriented Approach.

Uploaded by

malaveeresh19
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
You are on page 1/ 31

LESSON- 1

INTRODUCTION TO OOP
OBJECTIVES

By the end of this chapter, you should be able to:


 Understand the basic concepts of Object-Oriented Programming (OOP).
 Identify the key differences between Procedure-Oriented Programming (POP) and
OOP.
 Recognize the problems associated with Procedure-Oriented Programming.
 Explain the fundamental features of OOP, including encapsulation, inheritance,
polymorphism, and abstraction.
 Apply the principles of OOP to design and implement modular and maintainable
software solutions.

STRUCTURE

1.1 Introduction
1.2 Object-Oriented Programming (OOP)
1.2.1 Key Concepts of OOP
1.2.2 Benefits of OOP
1.3 Procedure Oriented Approach (POA)
1.3.1 Key Characteristics of Procedure-Oriented Approach
1.3.2 Problems with the Procedure-Oriented Approach
1.4 Features of OOP
1.5 Procedural Oriented Programming vs Object-Oriented Programming
1.6 Applications of OOP
1.7 Summary
1.8 Technical Terms
1.9 Self-Assessment Questions
1.10 Suggested Readings

1.1. INTRODUCTION

In the world of software development, different programming paradigms have been used to
solve problems. The two most prominent paradigms are Procedure-Oriented Programming
(POP) and Object-Oriented Programming (OOP). While POP was widely used in the early days
of programming, it presented challenges in managing complex software projects.

This chapter introduces OOP, a paradigm that overcomes the limitations of POP by
organizing software design around data, or objects, rather than functions and logic. You will
learn how OOP offers a more intuitive approach to problem-solving by closely mirroring real-
world entities and their interactions. Explain the fundamental features of OOP. Apply the
principles of OOP to design and implement modular and maintainable software solutions.

1.2 OBJECT-ORIENTED PROGRAMMING (OOP)

is a programming paradigm that organizes software design around data, or objects,


rather than functions and logic. An object in OOP is a self-contained unit that contains both
Centre for Distance Education 1.2 Acharya Nagarjuna University

data (attributes) and methods (functions) that manipulate the data. OOP focuses on creating
reusable code and models real-world entities and their interactions more naturally.

1.2.1 Key Concepts of OOP


The key concepts of Object-Oriented Programming (OOP) are essential principles that
guide the design and implementation of software in an object-oriented way The Key
Concepts of OOP described in Figure 1.1.

Fig 1.1. Key Concepts of OOP

 Object
An object is an instance of a class. It represents a specific implementation of the class
with actual values for its attributes. For example, a Car object might have make set to
"Toyota", model set to "Corolla", and year set to 2021. Each object can interact with
other objects or function independently.

Objects in OOP are fundamental to building complex systems, as they allow for
encapsulation of data and behavior, promoting modularity and reuse. The concept is
shown in Figure 1.2.

Fig 1.2. Object concept in OOP


OOP with Java 1.3 Introduction to OOP

 Class
A class is a blueprint for creating objects. It defines a data structure that holds attributes
(data) and methods (functions) that manipulate this data. Classes allow programmers to
create objects with specific properties and behaviors, providing a template that ensures
consistency across similar objects.

For example, consider a class Car. The Car class might have attributes like make, model,
and year, and methods like startEngine and stopEngine.

Every car object created from the Car class will have these attributes and methods, but
with different values. The concept is shown in Figure 1.3.

Fig 1.3. Class concept in OOP


 Encapsulation:

Encapsulation is the bundling of data and methods that operate on that data within a
single unit, usually a class. It restricts access to certain components, which is essential
for protecting the integrity of the data. By providing public methods to access private
data, encapsulation enables controlled interaction with the data.

 Inheritance:
Inheritance is a mechanism that allows a new class, known as a subclass, to inherit
attributes and methods from an existing class, known as a superclass. This promotes code
reuse and establishes a natural hierarchy among classes. For example, a Circle and Box
might inherit from the Shape class, sharing common attributes and methods while
introducing new ones Circle and Box. The concept is shown in Figure 1.4.

Fig 1.4. Inheritance concept in OOP


Centre for Distance Education 1.4 Acharya Nagarjuna University

 Polymorphism:
Polymorphism allows objects of different classes to be treated as objects of a common
superclass. It enables a single interface to represent different underlying data types. For
instance, both the Shape and Box classes might implement a Draw method, but each
class could have a different implementation of this method. The concept is shown in
Figure 1.5.

Fig 1.5. Polymorphism Concept in OOP

 Abstraction:
Abstraction involves hiding the complex implementation details of a class and exposing
only the necessary interfaces to the user. It simplifies interaction with complex systems
by focusing on the essential features and ignoring irrelevant details.

1.2.2 Benefits of OOP:

Object-Oriented Programming (OOP) offers several benefits that make it a preferred


approach in modern software development. Here are the key benefits of OOP followed and
described in figure 1.6:

Fig 1.6Key benefits of OOP


OOP with Java 1.5 Introduction to OOP

 Modularity and Reusability

 Modularity: OOP encourages the development of modular software, where the


program is divided into discrete, manageable units or classes. Each class encapsulates
data and behavior, making it easier to manage and understand.
 Reusability: Classes can be reused across different programs, reducing redundancy.
Inheritance further promotes code reuse by allowing new classes to be created based
on existing ones, minimizing the need to write code from scratch.
 Improved Maintainability
 Ease of Maintenance: The modular nature of OOP makes it easier to update or
modify parts of a program without affecting the entire system. Since changes are often
localized within specific classes, maintaining the software becomes more
straightforward and less error-prone.
 Encapsulation: By encapsulating data and exposing only necessary interfaces, OOP
helps maintain the integrity of the data and reduces the risk of unintended side effects
when making changes.

 Code Flexibility and Extensibility


 Polymorphism: OOP allows methods to be overridden or objects to be treated as
instances of their superclass, enabling flexible and dynamic code. This allows
developers to write more generic and adaptable code that can work with different
types of objects.
 Inheritance: New functionality can be added to existing classes through inheritance,
allowing developers to extend or modify behavior without changing the existing
codebase. This makes it easier to scale applications as new requirements emerge.

 Problem-Solving Capabilities
 Real-World Modeling: OOP aligns closely with real-world concepts, making it
easier to model complex systems and problems. By representing real-world entities as
objects with attributes and behaviors, OOP provides an intuitive way to design and
implement software.
 Abstraction: OOP allows developers to focus on high-level problem-solving by
abstracting away complex details. This simplifies the design process and allows
programmers to concentrate on the essential aspects of the problem.

 Data Security
 Encapsulation: Encapsulation helps protect data by restricting access to it. By
controlling how data is accessed and modified, OOP ensures that the internal state of
an object remains consistent and secure.
 Access Control: OOP provides mechanisms to define access levels (e.g., public,
private, protected) for class members, ensuring that sensitive data is not exposed or
altered inappropriately.
 Scalability and Manageability
 Scalability: OOP systems are inherently scalable due to their modular design. New
features can be added with minimal impact on existing code, making it easier to scale
applications as they grow in size and complexity.
 Manageability: The clear structure of OOP programs, with distinct classes and well-
defined interfaces, makes large codebases easier to manage, understand, and
document.
Centre for Distance Education 1.6 Acharya Nagarjuna University

 Improved Collaboration
 Team Development: OOP's modular approach allows different team members to
work on separate classes or modules simultaneously, improving collaboration and
speeding up development.
 Code Sharing: Reusable classes and components can be shared across teams or
projects, fostering collaboration and reducing duplication of effort.
 Increased Productivity
 Rapid Development: OOP's features like inheritance, polymorphism, and reusable
components can significantly speed up the development process. Developers can
build upon existing code rather than starting from scratch, leading to faster and more
efficient coding.
 Code Reuse: The ability to reuse classes across different projects or parts of a
program reduces development time and increases productivity.
 Better Software Design
 Design Patterns: OOP encourages the use of design patterns, which are proven
solutions to common design problems. These patterns help in creating robust,
scalable, and maintainable software architectures.
 Clear Structure: OOP provides a clear and logical structure for software design,
making it easier to plan, develop, and understand complex systems.
 Interoperability with Modern Frameworks and Tools
 Support for Frameworks: Many modern software development frameworks and
libraries are designed with OOP principles in mind. Using OOP makes it easier to
integrate with these tools and take advantage of their capabilities.
 Adaptation to New Technologies: OOP principles are widely adopted in various
programming languages, making it easier to adapt to new technologies, platforms, and
languages that also support OOP.

These benefits make OOP a powerful and effective approach for developing complex,
scalable, and maintainable software systems.

1.3 PROCEDURE ORIENTED APPROACH (POA)

The Procedure-Oriented Approach (also known as Procedural Programming) is a


programming paradigm that is centred around the concept of procedure calls, where
procedures, also known as routines, subroutines, or functions, are the fundamental building
blocks. This approach is one of the earliest and most widely used paradigms, especially in
languages like C, Pascal, and Fortran.

1.3.1 Key Characteristics of Procedure-Oriented Approach:

The Procedure-Oriented Approach is a programming paradigm that centers around the


concept of organizing code into procedures or functions. This approach is widely used in
languages like C, Pascal, and Fortran. Below are the key characteristics of the Procedure-
Oriented Approach and also concept is illustrated in figure 1.7:

 Focus on Functions
 The core idea of procedural programming is to structure the program as a series of
functions or procedures, each designed to perform a specific task. Functions are the
OOP with Java 1.7 Introduction to OOP

building blocks of the program, and the overall program is a sequence of these
function calls.
 Example: In a program that calculates the area of a rectangle, functions might include
get Length (), get Width (), and calculate Area ().

 Sequential Execution
 The execution flow in a procedural program typically follows a linear and sequential
order. The program starts from a specific entry point (often the main function) and
proceeds through a series of function calls in a defined sequence.
 Example: A procedural program might execute functions in the order they are called
within the main function, one after the other.

 Global Data Sharing


 Data in procedural programming is often stored in global variables that are accessible
by multiple functions. These global variables are shared across different parts of the
program, making it easier for functions to operate on the same data.
 Example: A global variable counter might be used and modified by various functions
to track the number of times an operation is performed.

Fig 1.7. Key Characteristics of POA

 Top-Down Design Approach


 Procedural programming often follows a top-down design methodology, where the
main problem is broken down into smaller, more manageable sub-problems. Each
sub-problem is then solved by a specific function.
 Example: In designing a program to manage a library system, the top-down approach
would first identify major functions like issue Book (), return Book (), and search
Catalog (), and then further break these down into smaller functions.
Centre for Distance Education 1.8 Acharya Nagarjuna University

 Emphasis on Procedures Over Data


 The primary focus in the procedural approach is on the procedures or functions
themselves rather than the data being processed. The functions dictate how the data is
manipulated and processed.
 Example: In a payroll system, the focus might be on functions like calculate Salary ()
and generate Pay slip () rather than on the employee data being processed.

 Limited Modularity
 While procedural programming allows for some degree of modularity by dividing the
program into functions, this modularity is limited compared to Object-Oriented
Programming (OOP). Functions are not encapsulated within objects and often depend
on global data, reducing their independence.
 Example: Functions in a procedural program can be reused, but because they rely on
global variables, their reusability is limited to contexts where those global variables
are applicable.

 Reusability
 Functions can be reused within the program, especially if they are general-purpose.
However, the reusability is not as robust as in OOP, where classes and objects can be
more easily reused across different programs.
 Example: A function that calculates the sum of an array can be reused in different
parts of the program, but it might need to be rewritten for a different context where
the array format or data type changes.

 No Data Hiding
 In procedural programming, there is no inherent mechanism for hiding data from
other parts of the program. Data is often accessible to any function that needs it,
leading to potential security issues and difficulties in maintaining the code.
 Example: A global variable userBalance might be accessible and modifiable by any
function, leading to potential inconsistencies or security risks.

 Linear Code Structure


 Procedural programs tend to have a linear structure, where the control flow is
straightforward and follows the sequence of function calls. This can make the
program easier to understand but limits its flexibility.
 Example: A program that reads data from a file, processes it, and then writes the
output to another file would follow a linear sequence of read(), process(), and write()
functions.
These characteristics define how procedural programs are structured and how they
operate. While effective for simpler tasks, this approach has limitations when dealing with
complex systems, leading many developers to adopt Object-Oriented Programming (OOP)
and other modern paradigms.

1.3.2 Problems with the Procedure-Oriented Approach:

The Procedure-Oriented Approach, while effective for smaller and simpler programs,
faces several limitations when applied to more complex software development. Here are the
key problems associated with the Procedure-Oriented Approach and are described in figure
OOP with Java 1.9 Introduction to OOP

1. Difficulty in Managing Large Programs


 Problem: As the size and complexity of a program increase, it becomes difficult to
manage and maintain the code. Functions in procedural programming are often tightly
coupled, meaning that changes in one part of the program can have widespread,
unintended effects on other parts.
 Impact: This tight coupling leads to "spaghetti code," where the program's logic is
tangled, making it hard to follow, debug, and maintain.

2. Poor Data Security and Integrity


 Problem: Procedural programming typically relies on global variables that can be
accessed and modified by any function. This lack of data encapsulation makes it easy
for one function to inadvertently alter the data in ways that break the program's logic.
 Impact: This can introduce subtle bugs that are hard to track down and fix, especially
in large programs where many functions might interact with the same data.

3. Limited Code Reusability


 Problem: Functions in procedural programming are often written to handle specific
tasks with specific data, making them difficult to reuse in other contexts without
significant modification.
 Impact: This lack of reusability leads to code duplication, where similar code is
written multiple times for slightly different tasks, increasing the program's size and
maintenance burden.

4. Lack of Modularity
 Problem: Procedural programs often lack clear modularity because the separation of
concerns is not enforced as strictly as in Object-Oriented Programming. Functions are
not inherently designed to be independent modules, leading to code that is more
monolithic and harder to maintain.
 Impact: This reduces the ability to isolate and manage different parts of the program
independently, making the program harder to understand and modify.

5. Inflexibility
 Problem: Procedural programming is less adaptable to changes. Adding new features
or modifying existing ones often requires changes across multiple functions and
global data structures.
 Impact: This can make the program brittle and prone to errors when changes are
made, reducing its long-term viability and maintainability.

6. Challenges in Modeling Real-World Problems


 Problem: Procedural programming focuses on functions and procedures, which do
not naturally correspond to real-world entities and their interactions. This makes it
difficult to model complex systems where objects with attributes and behaviors
interact in dynamic ways.
 Impact: This disconnect between the problem domain and the program structure can
lead to less intuitive code, making it harder to understand and maintain, especially for
larger projects.
7. Poor Scalability
 Problem: As a procedural program grows, the difficulty of managing the codebase
increases exponentially. The lack of clear modularity, encapsulation, and reusability
makes it hard to scale the program effectively.
Centre for Distance Education 1.10 Acharya Nagarjuna University

 Impact: This can limit the program's ability to evolve and grow over time, making it
less suitable for long-term projects or systems that require continuous development.

8. Increased Risk of Errors


 Problem: Because functions in procedural programming often interact with global
data and other functions in complex ways, the risk of introducing errors during
development and maintenance is higher.
 Impact: This increases the overall cost of development and maintenance, as more
time must be spent on debugging and testing to ensure the program behaves as
expected.
These problems are some of the key reasons why many developers and organizations
have moved towards Object-Oriented Programming (OOP) and other modern paradigms that
provide better support for modularity, encapsulation, reusability, and scalability.

1.4 FEATURES OF OBJECT-ORIENTED PROGRAMMING

Here are the key features of Object-Oriented Programming (OOP) listed in a concise,
point-wise format and shown in Table 1.1:

Table 1.1 Features of OOP


S.No. Feature Description
1. Encapsulation Combine data with functions
2. Abstraction Hides implementation
3. Inheritance Inherits super class properties to
sub class
4. Polymorphism Object with different forms
5. Modularity Split program into parts
6. Reusability Reuse of existing code
7. Dynamic Binding Runtime Polymorphism
8. Message Passing Objects communication

1. Encapsulation: Bundles data (attributes) and methods (functions) into a single unit
(class) and restricts access to some components to protect data integrity.
2. Abstraction: Hides complex implementation details and exposes only the necessary
parts, allowing focus on what an object does rather than how it does it.
3. Inheritance: Allows a new class to inherit properties and behaviors from an existing
class, promoting code reusability and reducing redundancy.
4. Polymorphism: Enables objects of different classes to respond to the same function
call in different ways, enhancing flexibility and scalability.
5. Classes and Objects: Classes serve as blueprints for creating objects, which are
instances containing both data and methods that manipulate that data.
6. Modularity: Encourages the division of a program into smaller, self-contained
modules (classes), improving code organization, readability, and maintainability.
7. Reusability: Facilitates the reuse of existing code in new applications, saving time
and reducing errors.
8. Dynamic Binding: Determines the method to be invoked at runtime, providing
flexibility and supporting polymorphism.
9. Message Passing: Objects communicate by sending messages (function calls) to each
other, enabling complex behaviors through object interactions.
OOP with Java 1.11 Introduction to OOP

1.5 PROCEDURAL ORIENTED PROGRAMMING VS OBJECT-ORIENTED


PROGRAMMING

Table 1.2 Differences between POA and OOP


Procedural -Oriented Programming Object-Oriented Programming
 Program is split into functions  Program is split into objects
 Top-down approach  Bottom-up approach
 No access specifiers  Has access specifiers
 Less secure  More Secure
 Overload is not possible  Overload is possible
 No data hiding  Has data hiding
 No inheritance  Has inheritance
 Focus more on function  Focus more on data
 No code reusability  Has code reusability

1.6 APPLICATION OF OOP

Here are the key applications of Object-Oriented Programming (OOP) listed in a


concise, point-wise format:
 Software Development:
o OOP is widely used in developing large-scale software systems, including enterprise
applications, due to its modularity, reusability, and scalability.
 Game Development:
o OOP is ideal for creating complex game environments where characters, objects, and
interactions are modeled as objects with attributes and behaviors.
 Graphical User Interface (GUI) Design:
o OOP facilitates the development of GUI applications where elements like buttons, windows,
and dialogs are treated as objects that can be manipulated independently.
 Simulation and Modeling:
o OOP is used in simulations (e.g., flight simulators, scientific models) where real-world
entities and their interactions are represented as objects.
 Web Development:
o OOP principles are used in web development frameworks and languages (like JavaScript,
Python, and PHP) to create dynamic, object-oriented web applications.
 Database Management Systems (DBMS):
o OOP is used in developing DBMS software where data can be modeled as objects, allowing
for complex data relationships and operations.
 Real-time Systems:
o OOP is applied in developing real-time systems, such as operating systems and embedded
systems, where modularity and efficient code management are critical.
 Distributed Systems:
o OOP is used in building distributed systems where objects can communicate across networks,
facilitating the development of scalable, distributed applications.
 Artificial Intelligence (AI) and Machine Learning (ML):
o OOP is used to develop AI and ML models, where different components (e.g., data
processing, model training, prediction) are encapsulated as objects.
 Mobile Application Development:
o OOP is integral to developing mobile apps, where different components of the app are
encapsulated into objects, improving code manageability and reusability.

These applications demonstrate the versatility and effectiveness of OOP in various


domains, making it a foundational paradigm in modern software development.
Centre for Distance Education 1.12 Acharya Nagarjuna University

1.7 SUMMARY

Object-Oriented Programming (OOP) is a programming paradigm that organizes


software design around objects, which are instances of classes. It emphasizes key concepts
like encapsulation, abstraction, inheritance, and polymorphism. Encapsulation bundles data
and methods together, while abstraction hides complex implementation details. Inheritance
allows new classes to inherit properties from existing ones, promoting code reuse.
Polymorphism enables objects to be treated as instances of their parent class, allowing for
flexible code. OOP is widely used in modern software development due to its modularity,
reusability, and ability to model real-world scenarios effectively.

1.8 TECHNICAL TERMS

 Object
 Class
 Encapsulation
 Abstraction
 Inheritance
 Polymorphism
 Method
 Attribute
 Dynamic Binding and etc.

1.9 SELF ASSESSMENT QUESTIONS

Essay questions:
1. Explain the principles of Object-Oriented Programming with examples.
2. Discuss the advantages of using OOP over procedural programming.
3. Describe the concept of inheritance in OOP with an example.
4. How does polymorphism enhance the flexibility of a program? Provide an example.
5. Explain encapsulation and its importance in software development.

Short questions:
1. What is an object in OOP?
2. Define a class in the context of OOP.
3. What is encapsulation?
4. Explain the concept of inheritance.
5. What is polymorphism in OOP?

1.10 SUGGESTED READINGS

1. "Java: The Complete Reference" by Herbert Schildt, 12th Edition (2021), McGraw-
Hill Education
2. "Head First Java" by Kathy Sierra and Bert Bates, 2nd Edition (2005), O'Reilly
Media
3. "Effective Java" by Joshua Bloch,3rd Edition (2018), Addison-Wesley Professional
4. "Object-Oriented Analysis and Design with Applications" by Grady Booch, 3rd
Edition (2007), Addison-Wesley Professional
5. "Thinking in Java" by Bruce Eckel,4th Edition (2006), Prentice Hall

Dr. KAMPA LAVANYA


LESSON- 2
INTRODUCTION TO JAVA
OBJECTIVES

By the end of this chapter, you should be able to:


 Understand Core Java Concepts.
 Develop Problem-Solving Skills Using Java.
 Build Foundational Programming Skills.
 Encourage Practical Application of Java Knowledge.
 Prepare for Advanced Java and Programming Studies.

STRUCTURE

2.1 Introduction
2.2 Features of JAVA
2.3 Parts of JAVA
2.3.1 Java Development Kit (JDK)
2.3.2 Java Runtime Environment (JRE)
2.3.3 Java Virtual Machine (JVM)
2.3.4 Java Application Programming Interface (API)
2.4 Java Naming Conventions
2.5 Data Types
2.6 Operators
2.7 Input and Output Statements
2.8 Command Line Arguments
2.9 Summary
2.1 Technical Terms
2.11 Self-Assessment Questions
2.12 Suggested Readings

2.1. INTRODUCTION

Java is a versatile, high-level programming language that emphasizes platform


independence using the Java Virtual Machine (JVM), which allows Java programs to run on
any device with a compatible JVM. The language is structured into several key parts: the Java
Development Kit (JDK) for development, the Java Runtime Environment (JRE) for running
applications, and the JVM itself for executing compiled bytecode. Java adheres to specific
naming conventions to ensure code readability, such as using Pascal Case for class names and
camelCase for method and variable names. It supports various data types, including integers,
floats, characters, and Booleans, and provides operators for performing arithmetic, relational,
and logical operations. Input and output in Java are handled through statements like System.
out. Print ln () and Scanner, enabling interaction with users. Additionally, Java allows the use
of command-line arguments, enabling users to pass parameters to a program at runtime,
enhancing flexibility and control in program execution.

This chapter introduces Java, covers the fundamental features of java, parts of Java,
naming conventions, data types, operators, input and output statements, and command line
arguments.
Centre for Distance Education 2.2 Acharya Nagarjuna University

2.2 JAVA FEATURES

Java is a powerful and versatile programming language known for its rich set of
features that make it one of the most popular choices for developers worldwide. Below are
some of the key features that define Java and are shown in Figure 2.1 :

Figure 2.1 Feature of Java

 Platform Independence:
Java's most celebrated feature is its ability to run on any device with a Java Virtual Machine
(JVM). This "write once, run anywhere" (WORA) capability ensures that Java applications
are portable across different environments, from desktops to servers to mobile devices.
 Object-Oriented:
Java is an object-oriented programming language, which means it organizes software design
around objects, rather than functions and logic. This approach encourages modular and
reusable code, making Java programs easier to maintain and scale.
 Simple and Easy to Learn:
Java is designed to be easy to use, with a syntax that is clean and easy to understand,
especially for those familiar with other programming languages like C or C++. Java removes
complex features like pointers and operator overloading, simplifying the learning curve.
 Robust and Secure:
Java is designed with a strong focus on error handling and runtime checking, making it less
prone to crashes and runtime errors. It also includes features like garbage collection to
manage memory automatically. Java's security model, including the JVM’s ability to sandbox
applications, makes it a secure choice for developing applications, especially for web-based
environments.
 Multithreaded:
Java natively supports multithreading, allowing the concurrent execution of two or more
threads. This feature is crucial for developing applications that need to perform multiple tasks
simultaneously, such as games, server applications, and real-time systems.
 High Performance:
While Java is an interpreted language, the introduction of Just-In-Time (JIT) compilers and
performance enhancements in the JVM allows Java applications to run with high efficiency,
making it competitive with natively compiled languages.
 Distributed:
Java is designed for distributed computing, enabling developers to create applications that
can run across networks and interact with other services. It provides robust support for
OOP with Java 2.3 Introduction to JAVA

networking through the java.net package and APIs for Remote Method Invocation (RMI) and
Enterprise JavaBeans (EJB).
 Dynamic:
Java is a dynamic language, capable of adapting to an evolving environment. It supports
dynamic loading of classes and functions, allowing for the development of flexible and
extensible programs. Java programs can also adapt to new environments and systems without
requiring changes in the source code.
 Memory Management:
Java provides automated memory management through its garbage collection mechanism,
which automatically removes objects that are no longer in use. This reduces the burden on
developers to manage memory manually, minimizing memory leaks and other memory-
related issues.
 Rich API and Libraries:
Java comes with a vast set of APIs and libraries that provide ready-to-use functions for
various tasks, from data structures and algorithms to networking and database management.
This extensive library support accelerates development and reduces the need for third-party
libraries.
These features collectively make Java a preferred language for a wide range of
applications, from web and mobile applications to enterprise-level systems and scientific
computing.

Table 2.1 Features of Java

S.No Feature Description


1. Simple Java is easy to learn, and its syntax is quite simple,
clean and easy to understand
2. Object Oriented Java can be easily extended as it is based on Object
Model
3. Robust automatic Garbage Collector and Exception Handling.

4. Platform Independent bytecode is platform independent and can be run on


any machine, allow security
5. Multi-Threading utilizes same memory and other resources to execute
multiple threads at the same time
6. High Performance the use of just-in-time compiler
7. Distributed designed to run on computer networks

2.3 PARTS OF JAVA

Java is composed of several key parts that work together to enable the development,
execution, and management of Java applications. Here’s an overview of the main parts of
Java:

2.3.1 Java Development Kit (JDK):

The Java Development Kit (JDK) is a comprehensive suite of tools and libraries
necessary for developing Java applications. It is the primary component for Java developers,
offering everything required to write, compile, debug, and run Java applications. The JDK is
available for various operating systems, including Windows, macOS, and Linux, ensuring
that Java development can be done across multiple platforms.
Centre for Distance Education 2.4 Acharya Nagarjuna University

Key Components of the JDK:


 Compiler (javac):
o The Java compiler (javac) converts Java source code (.java files) into bytecode (.class
files). This bytecode is platform-independent and can be executed by the Java Virtual
Machine (JVM). The compiler checks the code for errors and ensures that it adheres
to Java syntax and rules before generating bytecode.
 Java Runtime Environment (JRE):
o The JRE is bundled with the JDK and provides the runtime environment necessary to
execute Java applications. It includes the JVM, core libraries, and other supporting
components that allow Java programs to run. While the JRE can run Java
applications, it does not include tools for developing them.
 Debugger (jdb):
o The Java debugger (jdb) is a tool used to find and fix bugs in Java programs. It allows
developers to step through code, set breakpoints, inspect variables, and evaluate
expressions, making it easier to identify and resolve issues in the code.
 JavaDoc:
o JavaDoc is a documentation generator that creates API documentation in HTML
format from comments in the source code. This tool is essential for generating clear
and professional documentation, which is crucial for maintaining and sharing code
with others.
 Java Archive Tool (jar):
o The Java Archive tool (jar) is used to package Java classes and associated resources
(such as images and text files) into a single archive file with a .jar extension. This
archive can be used to distribute and deploy Java applications or libraries. The JAR
format also supports compression, reducing the file size of the archive.
 Java Virtual Machine (JVM):
o While the JVM is technically part of the JRE, it is included in the JDK as well, since
the JDK encompasses all the components required to both develop and run Java
applications. The JVM is responsible for executing the bytecode produced by the Java
compiler.
 Additional Tools:
o The JDK includes several other tools that assist in Java development, such as:
 javap: A class file disassembler that helps developers understand the structure of
compiled classes.
 jconsole: A monitoring tool that provides information about the performance and
resource consumption of Java applications.
 jarsigner: A tool for signing JAR files, ensuring the authenticity and integrity of
the code within them.
The JDK is essential for Java developers, as it provides all the tools necessary for
writing, compiling, debugging, and running Java applications. Whether developing simple
applications or complex enterprise-level systems, the JDK offers the flexibility and
functionality required to manage the entire software development lifecycle in Java.

2.3.2 Java Runtime Environment (JRE):


The Java Runtime Environment (JRE) is a crucial component of the Java platform,
providing the necessary environment for running Java applications. It includes everything
required to execute Java programs but does not contain the development tools (like the
compiler) found in the Java Development Kit (JDK). The JRE is used by end-users who need
to run Java programs but do not need to develop them.
OOP with Java 2.5 Introduction to JAVA

Key Components of the JRE:


 Java Virtual Machine (JVM):
o The JVM is the core of the JRE and is responsible for executing Java bytecode. It
provides the abstraction that allows Java programs to run on any platform, making
Java platform independent. The JVM interprets or compiles bytecode into machine
code that the operating system can execute. It also manages memory allocation,
garbage collection, and runtime security checks.
 Core Libraries:
o The JRE includes a comprehensive set of libraries that provide the necessary
functionality to run Java applications. These libraries include essential classes and
APIs that Java programs use to perform tasks such as:
 Input/Output Operations: Libraries like java.io for reading from and writing to
files.
 Networking: Libraries like java.net for networking capabilities.
 Utilities: Libraries like java.util that provide data structures (e.g., collections), date
and time utilities, and other common utilities.
 Math Functions: Libraries like java.math for complex mathematical operations.
 Java Class Loader:
o The class loader is part of the JVM that dynamically loads Java classes into memory
as needed. It allows Java applications to load classes from various sources, such as the
local file system, network, or even a remote server. The class loader also ensures that
the correct version of a class is loaded, which is essential for maintaining application
stability.
 Java Security Manager:
o The security manager in the JRE controls access to system resources by Java
applications. It enforces security policies that prevent potentially harmful operations,
such as reading or writing to files, accessing network connections, or executing
certain native code. This is particularly important for running Java applets or
applications from untrusted sources.
 Java Plug-in:
o The Java plug-in enables web browsers to run Java applets. It allows Java applications
embedded in web pages to be executed within the browser environment. Although
less commonly used today with the decline of applets, it was an essential part of
Java’s role in web development.
 Java Web Start:
o Java Web Start allows users to run Java applications directly from the web. It
downloads the necessary Java application files from the internet and launches them,
simplifying the distribution and installation of Java applications.

The JRE is essential for running Java applications on any device. It is used by end-users
who need to execute Java programs but do not need to write or compile Java code. The JRE
ensures that Java applications can run consistently across different platforms by providing a
standardized runtime environment. Whether it's a desktop application, a server-side
application, or a small applet, the JRE provides the necessary components to run the Java
code reliably and securely. In summary, the JRE is a runtime environment that includes the
JVM, core libraries, and other components needed to execute Java applications, ensuring that
Java programs can run on any platform with a compatible JRE installed.
Centre for Distance Education 2.6 Acharya Nagarjuna University

2.3.3 Java Virtual Machine (JVM):

The Java Virtual Machine (JVM) is a critical component of the Java platform,
responsible for executing Java bytecode on any device or operating system the complete
architecture of JVM is shown in Figure 2.2. The JVM provides an abstraction layer that
allows Java applications to be "write once, run anywhere," meaning that the same Java
program can run on any platform without modification, if a compatible JVM is available.

Key Components and Functions of the JVM:


 Class Loader:
o The class loader is a part of the JVM that loads Java class files into memory. It reads
the .class files containing Java bytecode and brings them into the runtime
environment. The class loader also performs tasks such as verifying the bytecode and
linking the classes by resolving references to other classes, ensuring that all
dependencies are satisfied before execution begins.
 Runtime Memory Areas (JVM Memory):
o The JVM manages memory during the execution of Java programs using different
memory areas:
 Heap: The heap is where all the objects and their corresponding instance variables
are stored. It is shared among all threads.
 Stack: Each thread in a Java application has its own stack. The stack stores method
call frames, including local variables and partial results. The stack is also where
method return values are stored.
 Method Area: The method area is a shared memory space that stores class-level data
such as the runtime constant pool, field and method data, and code for methods.
 Program Counter (PC) Register: The PC register keeps track of the current
instruction being executed in the thread.
 Native Method Stack: This stack is used for native method calls, which are methods
written in languages other than Java, such as C or C++.
 Execution Engine:
o The execution engine is the core of the JVM, responsible for executing the bytecode
instructions. It consists of several components:
 Interpreter: The interpreter reads and executes the bytecode instructions one at a
time. While the interpreter is simple and fast, it can be slower because it processes
each instruction individually.
 Just-In-Time (JIT) Compiler: To improve performance, the JIT compiler compiles
frequently executed bytecode sequences into native machine code at runtime. This
compiled code is then executed directly by the CPU, leading to significant
performance gains.
 Garbage Collector: The garbage collector automatically manages memory by
identifying and disposing of objects that are no longer in use, freeing up memory
and preventing memory leaks.
 Java Native Interface (JNI):
o The JNI is an interface that allows Java code running in the JVM to call and be called
by native applications and libraries written in other languages like C, C++, or
assembly. This capability is important for integrating Java applications with legacy
systems or specialized hardware.
OOP with Java 2.7 Introduction to JAVA

 Native Method Libraries:


o These are libraries that contain native code, usually written in languages other than
Java, which the JVM can call. These libraries are platform-specific and provide low-
level operations that are not possible in standard Java.

Fig 2.2 The Architecture of JVM with Key Components

Key Characteristics of the JVM:


 Platform Independence:
o The JVM is what makes Java platform independent. By translating Java bytecode into
machine-specific code, the JVM allows the same Java program to run on different
types of hardware and operating systems without modification.
 Memory Management:
o The JVM manages memory through its garbage collection mechanism, which
automatically reclaims memory by removing objects that are no longer in use. This
helps prevent memory leaks and improves application stability.
 Security:
o The JVM includes built-in security features, such as the bytecode verifier, which
checks for illegal code that could violate access rights or cause security issues. The
security manager and class loaders further enhance the security by controlling access
to system resources and ensuring that only trusted code is executed.

The JVM is the cornerstone of the Java platform, providing the environment in which
Java programs execute. Its ability to abstract the underlying hardware and operating system
allows Java developers to focus on writing code without worrying about platform-specific
details. The JVM’s features, such as garbage collection, JIT compilation, and security
mechanisms, contribute to Java’s reputation for being robust, secure, and high-performance.

The JVM is a powerful and flexible component that enables the execution of Java
applications across various platforms, managing memory, ensuring security, and optimizing
performance through advanced execution techniques.
Centre for Distance Education 2.8 Acharya Nagarjuna University

2.3.4 Java Application Programming Interface (API):

The Java Application Programming Interface (API) is a vast collection of pre-written


packages, classes, and interfaces that provide developers with ready-to-use functionalities for
various tasks. The Java API simplifies the process of writing Java applications by offering
reusable code components, enabling developers to focus on the unique aspects of their
applications rather than reinventing the wheel for common tasks.

Key Components of the Java API:


 Core Libraries:
o The core libraries form the foundation of the Java API, providing essential classes and
interfaces needed for basic programming tasks. These libraries include:
 java.lang: Contains fundamental classes such as String, Math, Integer, and Thread,
which are automatically imported into every Java program.
 java.util: Provides utility classes for data structures (like ArrayList, HashMap), date
and time manipulation, random number generation, and more.
 java.io: Offers classes for input and output operations, including reading from and
writing to files, handling streams, and performing serialization.
 Networking Libraries:
o Java’s networking libraries, found primarily in the java.net package, enable
developers to build networked applications. These libraries support operations like
connecting to remote servers, sending and receiving data over the network, handling
URLs, and implementing sockets for communication.
 Database Connectivity (JDBC):
o The Java Database Connectivity (JDBC) API, located in the java.sql package, allows
Java applications to interact with relational databases. JDBC provides methods to
connect to a database, execute SQL queries, and retrieve and manipulate data from a
database.
 User Interface (UI) Libraries:
o Java offers several APIs for building graphical user interfaces (GUIs):
 AWT (Abstract Window Toolkit): Provides the basic components for building
simple graphical user interfaces.
 Swing: An extension of AWT, Swing provides a richer set of components for
building more sophisticated UIs, such as buttons, tables, text fields, and more.
 JavaFX: A more modern library for creating rich internet applications (RIAs) with
advanced UI features, including 2D/3D graphics, media playback, and web
rendering.
 Concurrency and Multithreading:
o The java.util. concurrent package contains classes and interfaces that simplify the
development of multithreaded applications. It includes utilities for managing threads,
synchronizing data between threads, and implementing high-level concurrency
patterns like executors, thread pools, and concurrent data structures.
 Security Libraries:
o Java’s security API, primarily found in the java. security package, offers tools for
implementing security features in Java applications. This includes classes for
encryption, decryption, key generation, digital signatures, and secure random number
generation. Java also provides APIs for managing authentication and authorization
through the Java Authentication and Authorization Service (JAAS).
OOP with Java 2.9 Introduction to JAVA

 XML Processing:
o Java provides APIs for working with XML, such as the javax.xml.parsers package for
parsing XML documents, the javax.xml.bind (JAXB) package for binding XML
documents to Java objects, and the javax.xml. transform package for transforming
XML documents.
 Web and Enterprise Development:
o Java has a robust set of APIs for developing web and enterprise applications:
 Servlets and JSP: Found in the javax.servlet and javax.servlet.jsp packages, these
APIs allow developers to create dynamic web content using Java.
 Java EE (Enterprise Edition): Provides a comprehensive set of APIs for building
large-scale, distributed, and transactional applications, including technologies like
EJB (Enterprise JavaBeans), JMS (Java Message Service), and JPA (Java
Persistence API).
 Remote Method Invocation (RMI):
o The RMI API, found in the java.rmi package, allows Java applications to invoke
methods on remote objects, enabling distributed computing. This API is used to create
applications that can communicate over a network, with objects residing on different
machines.

The Java API is a critical component of the Java platform, enabling developers to write
powerful applications without needing to implement every functionality from scratch. By
providing a rich set of pre-built classes and interfaces, the Java API accelerates development,
enhances code reliability, and promotes the reuse of well-tested code components. Whether
working on simple applications or complex enterprise systems, developers can rely on the
Java API to provide the tools and resources needed to build robust and efficient software. The
Java API is an extensive and versatile toolkit that provides everything from basic
programming constructs to advanced functionalities for networking, database access, user
interface design, and more, making it an essential resource for Java developers.

2.4 NAMING CONVENTIONS

Java naming conventions are guidelines for naming various elements in a Java
program, ensuring that code is consistent, readable, and maintainable. Adhering to these
conventions is crucial, especially when working in teams or contributing to large codebases.

1. Class Names:
 Convention: Use PascalCase (also known as UpperCamelCase).
 Description: Each word in the class name starts with an uppercase letter. Class names
should typically be nouns or noun phrases, as they represent objects or entities.
 Example: Customer, EmployeeDetails, InvoiceProcessor.
2. Method Names:
 Convention: Use camelCase.
 Description: Start with a lowercase letter, and capitalize the first letter of each
subsequent word. Method names should typically be verbs or verb phrases, as they
represent actions or behaviors.
 Example: calculate Total, getEmployeeName, processInvoice.
3. Variable Names:
 Convention: Use camelCase.
Centre for Distance Education 2.10 Acharya Nagarjuna University

 Description: Like method names, variable names start with a lowercase letter, and
subsequent words are capitalized. Variable names should be descriptive and represent
the data they hold.
 Example: totalAmount, employeeName, invoiceList.
4. Constant Names:
 Convention: Use ALL_UPPERCASE with words separated by underscores.
 Description: Constants are usually declared using the final keyword and should be
named in all uppercase letters to distinguish them from variables. Each word is
separated by an underscore.
 Example: MAX_HEIGHT, DEFAULT_TIMEOUT, PI.
5. Package Names:
 Convention: Use lowercase letters.
 Description: Package names are typically written in all lowercase letters and often
follow the reverse domain name convention to avoid name conflicts. Words in
package names are usually separated by periods.
 Example: com.example.projectname, org.companyname.module.
6. Interface Names:
 Convention: Use PascalCase.
 Description: Interface names should be written like class names, using PascalCase.
They often represent capabilities or behaviors, and in some cases, they may be
adjectives.
 Example: Runnable, Serializable, Comparable.
7. Enum Names:
 Convention: Use PascalCase for the enum name and ALL_UPPERCASE for the
enum constants.
 Description: The name of the enum itself follows the same convention as classes,
while the constants within the enum are typically named using uppercase letters with
underscores separating words.
 Example: enum DayOfWeek { SUNDAY, MONDAY, TUESDAY }, enum Color {
RED, GREEN, BLUE }.
8. Type Parameter Names:
 Convention: Use single uppercase letters.
 Description: In generic types or methods, type parameters are usually named with
single, uppercase letters. Commonly used letters include T for type, E for element, K
for key, and V for value.
 Example: class Box<T>, interface List<E>, Map<K, V>.

Importance of Following Naming Conventions:


 Consistency: Uniform naming across a codebase helps in understanding and
maintaining the code.
 Readability: Clear and descriptive names make it easier for developers to understand
what a piece of code does.
 Maintainability: Well-named classes, methods, and variables reduce the cognitive
load on developers, making it easier to navigate and modify the code over time.
 Collaboration: When working in teams, consistent naming conventions ensure that
everyone can read and understand each other's code, reducing the chances of errors
and misunderstandings.
OOP with Java 2.11 Introduction to JAVA

2.5 DATA TYPES

In Java, data types specify the size and type of values that can be stored in variables.
Java is a statically typed language, meaning that each variable must be declared with a data
type before it can be used. Java's data types are categorized into two main groups: primitive
data types and non-primitive data types and are shown in Figure 2.3.

Figure 2.3 Classification of Java Data Types

 Primitive Data Types:


 Primitive data types are the most basic data types available in Java. They are
predefined by the language and named by a keyword. Java has eight primitive data
types which are shown in Table 2.2:
 byte:
o Size: 8 bits
o Range: -128 to 127
o Description: Useful for saving memory in large arrays, where the memory savings
are most needed. It can also be used in place of int where the range of values is known to be
small.
o Example: byte b = 100;
 short:
o Size: 16 bits
o Range: -32,768 to 32,767
o Description: A data type that is larger than byte but smaller than int. It's also used to
save memory in large arrays.
o Example: short s = 10000;
 int:
o Size: 32 bits
o Range: -2^31 to 2^31-1 (-2,147,483,648 to 2,147,483,647)
o Description: The default choice for integral values unless there is a reason to use byte
or short. Most commonly used for integer arithmetic.
o Example: int i = 100000;
 long:
o Size: 64 bits
o Range: -2^63 to 2^63-1 (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
o Description: Used when a wider range than int is needed.
Centre for Distance Education 2.12 Acharya Nagarjuna University

o Example: long l = 100000L;


 float:
o Size: 32 bits
o Range: Varies, approximately ±3.40282347E+38F (6-7 significant decimal digits)
o Description: Used for single-precision floating-point numbers. It’s recommended to
use float if you need to save memory in large arrays of floating-point numbers.
o Example: float f = 234.5f;
 double:
o Size: 64 bits
o Range: Varies, approximately ±1.79769313486231570E+308 (15 significant decimal
digits)
o Description: Used for double-precision floating-point numbers and is the default
choice for decimal values.
o Example: double d = 123.456;
 char:
o Size: 16 bits (2 bytes)
o Range: 0 to 65,535 (unsigned)
o Description: Used to store a single character. Java uses Unicode, so it can store any
character from any language.
o Example: char c = 'A';
 boolean:
o Size: Not precisely defined (depends on JVM implementation, but typically 1 bit)
o Range: true or false
o Description: Used for flags that track true/false conditions.
o Example: boolean isJavaFun = true;

Table 2.2 Primitive Data Types in Java


Data Type Default Value Default size Range
byte 0 1 byte or 8 bits -128 to 127
short 0 2 bytes or 16 bits -32,768 to 32,767
int 0 4 bytes or 32 bits 2,147,483,648 to 2,147,483,647
9,223,372,036,854,775,808 to
long 0 8 bytes or 64 bits
9,223,372,036,854,775,807
float 0.0f 4 bytes or 32 bits 1.4e-045 to 3.4e+038
double 0.0d 8 bytes or 64 bits 4.9e-324 to 1.8e+308
char ‘\u0000’ 2 bytes or 16 bits 0 to 65536
boolean FALSE 1 byte or 2 bytes 0 or 1

 Non-Primitive Data Types


 Non-Primitive data types are not predefined like primitive data types. Instead, they are
created by the programmer and can refer to any object in Java. Reference variables
store the memory address of the object they refer to, rather than the data itself.
 Strings:
o Description: Strings are objects in Java, represented by the String class. They are
used to store sequences of characters.
o Example: String message = "Hello, World!";
 Arrays:
o Description: Arrays are objects that store multiple variables of the same type. The
size of an array is fixed upon creation.
OOP with Java 2.13 Introduction to JAVA

o Example: int[] numbers = {1, 2, 3, 4, 5};


 Classes and Objects:
o Description: Classes define new data types by grouping data and methods that
operate on the data. When you create an instance of a class, it is called an object.
o Example:
java
Copy code
class Car {
String model;
int year;
}
Car myCar = new Car();
myCar.model = "Tesla";
myCar.year = 2021;
 Interfaces:
o Description: Interfaces define a contract or a set of methods that a class must
implement. They are used to achieve abstraction and multiple inheritance in Java.
o Example:
java
Copy code
interface Vehicle {
void start();
}
class Bike implements Vehicle {
public void start() {
System.out.println("Bike started");
}
}

Understanding and properly using data types is fundamental in Java programming.


The correct data type ensures that you use memory efficiently and avoid errors. Primitive
types are straightforward and efficient for basic data handling, while non-primitive types
allow for more complex data structures and operations.

2.6 OPERATORS

Operators in Java are special symbols or keywords used to perform operations on


variables and values. Java provides a rich set of operators to manipulate data and variables,
ranging from simple arithmetic to complex logical operations. These operators are grouped
into several categories based on their functionality.

1. Arithmetic Operators:
 Description: These operators perform basic arithmetic operations such as addition,
subtraction, multiplication, and division.
 Operators and Examples:
o + (Addition): Adds two operands.
Example: int sum = 5 + 3; // sum = 8
o - (Subtraction): Subtracts the right operand from the left operand.
Example: int difference = 5 - 3; // difference = 2
Centre for Distance Education 2.14 Acharya Nagarjuna University

o * (Multiplication): Multiplies two operands.


Example: int product = 5 * 3; // product = 15
o / (Division): Divides the left operand by the right operand.
Example: int quotient = 6 / 3; // quotient = 2
o % (Modulus): Returns the remainder of a division.
Example: int remainder = 7 % 3; // remainder = 1

2. Assignment Operators:
 Description: These operators are used to assign values to variables.
 Operators and Examples:
o = (Assignment): Assigns the value on the right to the variable on the left.
Example: int a = 5;
o += (Add and Assign): Adds the right operand to the left operand and assigns
the result to the left operand.
Example: a += 3; // a = a + 3, so a becomes 8
o -= (Subtract and Assign): Subtracts the right operand from the left operand
and assigns the result to the left operand.
Example: a -= 2; // a = a - 2, so a becomes 6
o *= (Multiply and Assign): Multiplies the left operand by the right operand
and assigns the result to the left operand.
Example: a *= 2; // a = a * 2, so a becomes 12
o /= (Divide and Assign): Divides the left operand by the right operand and
assigns the result to the left operand.
Example: a /= 3; // a = a / 3, so a becomes 4
o %= (Modulus and Assign): Takes the modulus of the left operand by the
right operand and assigns the result to the left operand.
Example: a %= 3; // a = a % 3, so a becomes 1

3. Relational Operators:
 Description: These operators compare two values and return a boolean result (true or
false).
 Operators and Examples:
o == (Equal to): Checks if two values are equal.
Example: boolean isEqual = (5 == 3); // isEqual = false
o != (Not Equal to): Checks if two values are not equal.
Example: boolean isNotEqual = (5 != 3); // isNotEqual = true
o > (Greater than): Checks if the left operand is greater than the right operand.
Example: boolean isGreater = (5 > 3); // isGreater = true
o < (Less than): Checks if the left operand is less than the right operand.
Example: boolean isLess = (5 < 3); // isLess = false
o >= (Greater than or Equal to): Checks if the left operand is greater than or
equal to the right operand.
Example: boolean isGreaterOrEqual = (5 >= 3); // isGreaterOrEqual = true
o <= (Less than or Equal to): Checks if the left operand is less than or equal to
the right operand.
Example: boolean isLessOrEqual = (5 <= 3); // isLessOrEqual = false

4. Logical Operators:
 Description: These operators are used to perform logical operations on boolean
values.
OOP with Java 2.15 Introduction to JAVA

 Operators and Examples:


o && (Logical AND): Returns true if both operands are true.
Example: boolean result = (5 > 3 && 8 > 6); // result = true
o || (Logical OR): Returns true if at least one of the operands is true.
Example: boolean result = (5 > 3 || 8 < 6); // result = true
o ! (Logical NOT): Reverses the logical state of its operand.
Example: boolean result = !(5 > 3); // result = false

5. Unary Operators:
 Description: These operators operate on a single operand.
 Operators and Examples:
o + (Unary Plus): Indicates a positive value (typically optional as numbers are
positive by default).
Example: int positive = +5;
o - (Unary Minus): Negates the value of the operand.
Example: int negative = -5;
o ++ (Increment): Increases the value of the operand by 1.
Example: int a = 5; a++; // a becomes 6
o -- (Decrement): Decreases the value of the operand by 1.
Example: int a = 5; a--; // a becomes 4
o ! (Logical NOT): Inverts the value of a boolean operand.
Example: boolean isTrue = true; isTrue = !isTrue; // isTrue becomes false

6. Bitwise Operators:
 Description: These operators perform bit-level operations on integer types.
 Operators and Examples:
o & (Bitwise AND): Performs a bitwise AND operation on two operands.
Example: int result = 5 & 3; // result = 1 (0101 & 0011 = 0001)
o | (Bitwise OR): Performs a bitwise OR operation on two operands.
Example: int result = 5 | 3; // result = 7 (0101 | 0011 = 0111)
o ^ (Bitwise XOR): Performs a bitwise XOR operation on two operands.
Example: int result = 5 ^ 3; // result = 6 (0101 ^ 0011 = 0110)
o ~ (Bitwise Complement): Inverts all the bits of the operand.
Example: int result = ~5; // result = -6 (bitwise complement of 0101)
o << (Left Shift): Shifts the bits of the left operand to the left by the number of
positions specified by the right operand.
Example: int result = 5 << 2; // result = 20 (0101 << 2 = 10100)
o >> (Right Shift): Shifts the bits of the left operand to the right by the number
of positions specified by the right operand.
Example: int result = 5 >> 2; // result = 1 (0101 >> 2 = 0001)
o >>> (Unsigned Right Shift): Shifts the bits of the left operand to the right by
the number of positions specified by the right operand, filling the leftmost bits with zeros.
Example: int result = 5 >>> 2; // result = 1

7. Ternary Operator:
 Description: The ternary operator is a shorthand for an if-else statement. It has three
operands and is used to evaluate a boolean expression.
 Operator and Example:
Centre for Distance Education 2.16 Acharya Nagarjuna University

o ? : (Ternary): Evaluates a condition and returns one of two values depending


on whether the condition is true or false.
Example: int result = (5 > 3) ? 10 : 20; // result = 10

8. Instanceof Operator:
 Description: The instanceof operator checks whether an object is an instance of a
specific class or subclass.
 Operator and Example:
o instanceof: Returns true if the object is an instance of the specified class or
subclass, otherwise false.
Example: boolean isString = "Hello" instanceof String; // isString = true
Operators are fundamental to performing operations on variables and data in Java. They
allow developers to build complex expressions and perform calculations, comparisons, and
logical operations. Understanding and using operators correctly is essential for writing
effective and efficient Java code.

2.7 INPUT AND OUTPUT STATEMENTS

Java provides various ways to handle input and output (I/O) operations, enabling
interaction between the user and the program. Two of the most commonly used tools for this
purpose are the Scanner class for input and the System.out.println method for output.
 Scanner
The Scanner class in Java is used to read input from various sources, most commonly from
the keyboard (standard input). It is a part of the java.util package, so you need to import it
before using it.
 Importing the Scanner Class:
import java.util.Scanner;
 Creating a Scanner Object: To read input from the keyboard, you need to create a
Scanner object that uses System.in as the input stream.
Scanner scanner = new Scanner(System.in);
 Reading Different Types of Input:
o Reading a String:
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Reads a line of text
System.out.println("Hello, " + name + "!");
o Reading an Integer:
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Reads an integer
System.out.println("You are " + age + " years old.");
o Reading a Double:
System.out.print("Enter your salary: ");
double salary = scanner.nextDouble(); // Reads a double value
System.out.println("Your salary is " + salary);
o Reading a Single Word:
System.out.print("Enter your first name: ");
String firstName = scanner.next(); // Reads a single word (until a space is encountered)
System.out.println("First Name: " + firstName);
 Key Points:
o The nextLine() method reads an entire line of input, including spaces.
OOP with Java 2.17 Introduction to JAVA

o The nextInt(), nextDouble(), etc., methods read specific types of input and
automatically convert them to the appropriate data type.
o The next() method reads input until a space or newline is encountered, making
it useful for single-word inputs.

Output: System.out.println
The System.out.println method is used to print information to the console. It's one of the most
frequently used methods in Java for outputting text, variables, and results of operations.
 Syntax:
System.out.println(expression);
Where expression can be a string, a variable, or a combination of strings and variables.
 Examples:
System.out.println("Hello, World!"); // Prints: Hello, World!
System.out.println(100); // Prints: 100
System.out.println("Total: " + 50); // Prints: Total: 50
 Key Points:
o The println method prints the specified message and then moves the cursor to
the next line.
o There is also a System.out.print method that prints the message without
moving to the next line, allowing multiple outputs to be printed on the same line.

2.8 COMMAND LINE ARGUMENTS

Command line arguments in Java are the inputs that are passed to a Java program
during its execution from the command line or terminal. These arguments are typically
passed as strings, and they are accessible within the main method of the Java program.
Here’s a basic overview of how command line arguments work in Java:
 Accessing Command Line Arguments
Command line arguments in Java are stored in the String array that is passed to the main
method of the class. The main method signature looks like this:
public static void main(String[] args) {
// Code goes here
}
Where args is an array of String objects that contains the arguments passed from the
command line.
 Example: Simple Java Program with Command Line Arguments
public class CommandLineExample {
public static void main(String[] args) {
// Check if arguments are passed
if (args.length > 0) {
System.out.println("Command line arguments are:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
} else {
System.out.println("No command line arguments found.");
}
}
}
Centre for Distance Education 2.18 Acharya Nagarjuna University

 Running the Program


To run this program and pass command line arguments, you would use the following
command in the terminal or command prompt:
java CommandLineExample arg1 arg2 arg3
Where arg1, arg2, and arg3 are the command line arguments being passed to the program.
The program will output:

Command line arguments are:


Argument 0: arg1
Argument 1: arg2
Argument 2: arg3

Important Points
 Indexing: The command line arguments are indexed starting from 0. So args[0] is the
first argument, args[1] is the second, and so on.
 Argument Count: You can determine the number of arguments by checking
args.length.
 Data Types: Command line arguments are always passed as strings. If you need them
in another data type (e.g., int), you need to parse the string to that type using methods like
Integer.parseInt(args[0]).

2.9 SUMMARY

Java is a widely used, object-oriented programming language designed for portability,


security, and high performance. It operates on the Java Virtual Machine (JVM), which allows
Java programs to run on any platform without modification, making it platform independent.

Java features a rich set of data types, including primitive types like int, float, char, and
boolean, as well as reference types like arrays and objects. The language offers a variety of
operators, such as arithmetic, relational, and logical operators, to perform operations on
variables and data. Command line arguments in Java allow users to pass input to programs
via the terminal, accessible through the String[] args parameter in the main method.

Additionally, the Scanner class provides a way to take user input during runtime,
while the System.out.println method is commonly used for outputting data to the console,
making it easy to display results or messages. Java's combination of simplicity, portability,
and powerful features has made it a popular choice for developing everything from mobile
applications to enterprise-level systems.

2.10 TECHNICAL TERMS

 JVM
 Data Type
 Scanner
 Println
 Boolean
 Platform Independence
 Portable
 Command Line Argument
OOP with Java 2.19 Introduction to JAVA

2.11 SELF ASSESSMENT QUESTIONS

Essay questions:
1. Explain the structure and significance of data types in Java programming.
2. Describe the architecture and functionality of the Java Virtual Machine (JVM).
3. Analyze the key features of Java that make it a robust and versatile programming
language
4. Discuss the different types of operators in Java and their role in program development.
5. Compare and contrast command line arguments and the Scanner class for input
handling in Java.

Short questions:

1. List and briefly describe three key features of Java.


2. What is the purpose of arithmetic operators in Java?
3. How does the Java Virtual Machine (JVM) contribute to Java's platform independence?
4. What is the role of data types in Java?

2.12 SUGGESTED READINGS

1. "Java: The Complete Reference" by Herbert Schildt, 12th Edition (2021), McGraw-
Hill Education
2. "Head First Java" by Kathy Sierra and Bert Bates, 2nd Edition (2005),O'Reilly Media
3. "Effective Java" by Joshua Bloch,3rd Edition (2018),Addison-Wesley Professional
4. "Object-Oriented Analysis and Design with Applications" by Grady Booch, 3rd
Edition (2007), Addison-Wesley Professional
5. "Thinking in Java" by Bruce Eckel,4th Edition (2006), Prentice Hall

Dr. KAMPA LAVANYA

You might also like