Certi 202506160617
Certi 202506160617
INTRODUCTION TO OOP
OBJECTIVES
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
Here are the key features of Object-Oriented Programming (OOP) listed in a concise,
point-wise format and shown in Table 1.1:
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.7 SUMMARY
Object
Class
Encapsulation
Abstraction
Inheritance
Polymorphism
Method
Attribute
Dynamic Binding and etc.
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. "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
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
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
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 :
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.
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:
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
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
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.
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
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.
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>.
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.
2.6 OPERATORS
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
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
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
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.
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.
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
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 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.
JVM
Data Type
Scanner
Println
Boolean
Platform Independence
Portable
Command Line Argument
OOP with Java 2.19 Introduction to JAVA
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. "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