0% found this document useful (0 votes)
36 views113 pages

Java Object-Oriented Programming Guide

The document is a textbook titled 'Object Oriented Programming using JAVA' by Satish Naik, aimed at BCA students, providing a systematic understanding of Java programming concepts. It covers fundamental topics from basic syntax to advanced object-oriented principles, with practical examples and exercises. The book emphasizes Java's features such as platform independence, security, and robustness, making it suitable for various applications in modern computing.

Uploaded by

prasadaili44
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)
36 views113 pages

Java Object-Oriented Programming Guide

The document is a textbook titled 'Object Oriented Programming using JAVA' by Satish Naik, aimed at BCA students, providing a systematic understanding of Java programming concepts. It covers fundamental topics from basic syntax to advanced object-oriented principles, with practical examples and exercises. The book emphasizes Java's features such as platform independence, security, and robustness, making it suitable for various applications in modern computing.

Uploaded by

prasadaili44
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

Object Oriented Programming using JAVA

BCA-III Semester NEP-Revised

By:

Satish Naik

Published by

Kamadhenu BCA College Karwar


Affiliated to Karnatak University Dharwad, Redg by Govt of Karnataka

Kamadhenu BCA College Object Oriented Programming using JAVA 1


Preface
Java has emerged as one of the most powerful, versatile, and widely used programming languages
in the modern computing world. Its object-oriented features, platform independence, and
robustness make it the preferred choice for developing applications ranging from simple desktop
programs to large-scale enterprise systems.

This book, “Object-Oriented Programming Using Java”, is designed primarily for BCA students,
with the aim of providing a clear and systematic understanding of fundamental programming
concepts through Java. It follows a simple, concept-first and example-later approach inspired by
the teaching style of E. Balagurusamy, ensuring that even beginners can grasp complex topics with
ease.

Each chapter begins with concise theoretical explanations, supported by easy-to-understand


syntax, diagrams, and well-commented programs. Topics are arranged in a logical sequence—
starting from the basics of Java, data types, decision-making, looping, and arrays, to advanced
concepts such as classes, objects, inheritance, polymorphism, interfaces, and exception handling.

The book also includes:


 Numerous solved examples for hands-on practice
 Short questions and programming exercises at the end of each chapter
 Real-world examples to connect theory with application

I sincerely hope this book serves as a useful guide for students beginning their journey in object-
oriented programming and helps them build a strong foundation in Java.

Suggestions and constructive feedback from readers, teachers, and students are most welcome and
will be appreciated for the improvement of future editions.

Satish Naik
Author

Kamadhenu BCA College Object Oriented Programming using JAVA 2


Acknowledgment
I would like to express my heartfelt gratitude to all those who have supported, guided, and inspired
me throughout the journey of writing this book.

First and foremost, I bow with deep respect and devotion to my revered Guru, Shri Vishnu Sawant
Bosle of Santoshimata Temple, whose wisdom and blessings have been a constant source of
inspiration and strength. His divine guidance has enlightened my path and given me the courage to
complete this work.

I am sincerely thankful to Kekare Sir, for his continuous encouragement and motivation to pursue
my passion for teaching and writing. His belief in my abilities has played a major role in
transforming this idea into a meaningful book.

Lastly, I express my sincere appreciation to all my students, readers, and well-wishers. Your trust,
enthusiasm, and eagerness to learn have always inspired me to do better. I hope this book serves
as a useful companion in your journey of learning Object-Oriented Programming with Java.

— Satish Naik

Kamadhenu BCA College Object Oriented Programming using JAVA 3


Unit I: Introduction to JAVA
Java Evolution: Java History, Java Features, How Java differs from C and C++, Java and Internet, Java and
World Wide Web, Web browsers, Hardware and software requirements, Java Support Systems, Java
Environment.
Overview of JAVA Language: Introduction, Simple Java Program, More of Java, An Application with Two
Classes, Java Program Structure, Java Tokens, Java Statements, Implementing a Java Program, Java Virtual
Machine, Command Line Arguments, Programming Style.
Constants, Variables, and Data Types: Introduction, Constants, Variables, Data Types, Declaration of
Variables, Giving Values to Variables, Scope of Variables, Symbolic Constants, Type Casting, Getting Values of
Variables, Standard Default Values.
Operators and Expressions: Introduction, Arithmetic Operators, Relational Operators, Logical Operators,
Assignment Operators, Increment and Decrement Operators, Conditional Operators, Bitwise Operators,
Special Operators, Arithmetic Expressions, Evaluation of Expressions, Procedure of Arithmetic Operators,
Type Conversion and Associatively, Mathematical functions.
Decision Making and Branching: Introduction, Decision Making with if statement, simple if statement,
if...else statement, nesting of if.... else statements, the else if Ladder, the switch statement, ?: Operator.
Decision Making and Looping: The while statement, do statement, for statement, Jumps in Loops, Labeled
Loops.

Java Evolution: Java evolution refers to how the Java programming language has grown and improved
since its creation. It has continuously adapted to new technologies and developer needs, ensuring its
relevance in modern computing.

Java History Java History


The development of Java began in 1991 at Sun Microsystems by James Gosling and his team as part of the
Green Project. Initially, the language was named Oak, Inspired by big oak tree which was there outside
Gosling’s office at Sun Microsystems, so he decided to call the language “Oak.” The name symbolized
strength, stability, and growth—qualities that the team wanted the language to represent. The main goal
was to create a language for programming small electronic devices like televisions, set-top boxes, and
handheld [Link] 1995, Oak was renamed Java (because “Oak” was already trademarked).

Why the Name “Java”? (Coffee Story)


When the Green Team had to rename Oak in 1995, they brainstormed hundreds of names. Options like Silk,
DNA, Pearl, Ruby were considered. Finally, they settled on “Java.”
Here’s the story:
 During their late-night coding sessions, the team drank a lot of coffee.
 Much of this coffee came from Java Island in Indonesia, which is world-
famous for its coffee beans.
 The name “Java” was short, catchy, unique, and easy to spell and
remember.
 It also gave the language a lively and dynamic identity, compared to
technical names like “DNA” or “Silk.”
 To match the name, the Java logo was designed as a coffee cup with
steam, symbolizing energy, speed, and productivity.

That same year, Java 1.0 was officially released with the famous slogan “Write Once, Run Anywhere
(WORA)”, highlighting its ability to run on any platform using the Java Virtual Machine (JVM).

Kamadhenu BCA College Object Oriented Programming using JAVA 4


Java quickly gained popularity, especially on the Internet, because of its ability to create applet programs
that could run inside web browsers. Over the years, Java evolved with new versions adding powerful
features such as Collections, Generics, Multithreading, Lambdas, and Modules, making it one of the most
widely used programming languages in the world.

Today, Java is maintained by Oracle Corporation and continues to be used in diverse areas like web
applications, mobile apps (Android), enterprise software, cloud computing, and artificial intelligence.

Timeline of Java Evolution


 1991 – Green Project initiated by James Gosling at Sun Microsystems.
 1995 – Oak renamed as Java, first official version released (Java 1.0).
 1997 – Java 1.1 released (introduced inner classes, JDBC).
 1998 – Java 2 (J2SE 1.2): major update, introduced Swing & Collections.
 2004 – Java 5: added Generics, Annotations, Enhanced for-loop.
 2006 – Java 6: improved performance, JDBC 4.0, scripting support.
 2011 – Java 7: introduced try-with-resources, switch on strings.
 2014 – Java 8: Lambda expressions, Streams API, new Date & Time API.
 2017 – Java 9: Modular system (Project Jigsaw), JShell.
 2018 – Java 10/11: Local variable var, HTTP Client API, LTS release.
 2021 – Java 17 (LTS): Sealed classes, Pattern matching.
 2023 – Java 21 (LTS): Virtual Threads (Project Loom), Record patterns.

Key Contributors to Java (Green Project Team) : In 1991, Sun Microsystems formed the Green
Project team with about 13 members to work on a new language for
programming small devices. The most notable among them were:
 James Gosling – Father of Java, designed the language.
 Mike Sheridan – Project manager who coordinated the effort.
 Patrick Naughton – Helped bring Java into practical use.
 Bill Joy – Co-founder of Sun, strong supporter and promoter of
Java.
While many contributed, Gosling, Sheridan, and Naughton are
recognized as the main creators of Java. Other important members of
the Green Project team who contributed to the development of Java
were: Jon Payne, Cindy Long, David Lavallee, Al Frazier, Joe Palrang,
Don Jackson, Chuck Clanton, Bob Weisblatt, Sheueling Chang, Chris Warth, Ed Frank, and Craig Forrest.

Features of Java
Java became one of the most popular programming languages because of its powerful features. These
features make Java different from earlier languages like C and C++ and ensure its wide use in modern
applications such as web, mobile, and enterprise systems.

1. Simple
Java is considered simple because:
 Its syntax is based on C/C++, which makes it familiar, but it avoids confusing features such as
pointers, multiple inheritance (through classes), and operator overloading.
 It provides automatic memory management through Garbage Collection, which reduces
programmer effort and prevents memory leaks.
 Java programs are easier to read, write, and debug compared to older languages.

Kamadhenu BCA College Object Oriented Programming using JAVA 5


2. Object-Oriented
Java is a pure object-oriented language, where everything is built around the concept of objects and classes.
 Encapsulation: Data and related functions are bundled together.
 Inheritance: Existing classes can be extended to create new classes.
 Polymorphism: One method name can perform different tasks depending on the context.
 Abstraction: Complex details are hidden, and only the essential features are exposed.
This makes Java programs modular, reusable, and easy to maintain.

3. Platform-Independent
One of Java’s strongest features is platform independence.
 Programs are compiled into an intermediate form called bytecode, not machine code.
 Bytecode is executed by the Java Virtual Machine (JVM) on any platform.
 The same Java program can run on Windows, Linux, or Mac without any change.
This gives Java its famous slogan: “Write Once, Run Anywhere (WORA)”.

4. Secure
Java has strong built-in security:
 It does not support pointers, eliminating memory corruption and unauthorized access.
 The JVM verifies bytecode before execution to prevent malicious operations.
 Java supports security mechanisms like the Security Manager and Sandboxing, which restrict
untrusted code.
Because of these features, Java is widely used in banking, financial, and web applications where security is
crucial.

5. Robust
Java is designed to be strong and reliable.
 It emphasizes compile-time checking and runtime checking, reducing chances of errors.
 Exception handling mechanisms prevent programs from crashing unexpectedly.
 Automatic Garbage Collection ensures better memory management.
This makes Java applications more stable and dependable than many older languages.

6. Distributed
Java supports distributed computing, where programs can run and interact across multiple systems
connected by a network.
 It includes a rich set of classes in the [Link] package for networking.
 Supports technologies like RMI (Remote Method Invocation), CORBA, and web services.
These features allow Java to build powerful client-server and internet-based applications.

7. Multithreaded
Java provides built-in support for multithreading—executing multiple tasks simultaneously.
 Each task is executed as a thread, which is lightweight and managed by the JVM.
 Multithreading is useful in applications like games, animations, multimedia processing, and real-time
systems.
 Threads allow better CPU utilization by performing multiple operations in parallel.

8. High Performance
Although Java is an interpreted language, it achieves high performance with the help of:
 Just-In-Time (JIT) Compiler, which converts bytecode into native machine code at runtime for faster
execution.
 Efficient memory management and optimization techniques.
Java is not as fast as low-level languages like C, but its performance is good enough for large-scale
enterprise, web, and mobile applications.

Kamadhenu BCA College Object Oriented Programming using JAVA 6


9. Dynamic
Java is a dynamic language, meaning it can adapt to an evolving environment.
 Classes can be loaded at runtime, making programs more flexible.
 The Reflection API allows inspection and modification of program behavior while it is running.
 This is useful for building frameworks, plugins, and systems where new modules can be added
without restarting the program.
10. Portable
Java programs are portable because:
 The compiled bytecode can run on any system with a JVM.
 Data type sizes are fixed across all platforms (e.g., int is always 32 bits).
 There are no machine-dependent features.
This ensures consistent behavior of Java programs regardless of the operating system or hardware.

Summary of Features
Feature Description
Simple Easy to learn, no pointers, no operator overloading, automatic memory management.
Object-Oriented Follows OOP principles: Encapsulation, Inheritance, Polymorphism, Abstraction.
Platform-Independent Compiled into bytecode, runs on JVM anywhere (WORA).
Secure No pointers, bytecode verification, security manager, sandboxing.
Robust Strong error handling, garbage collection, memory safety.
Distributed Built-in networking support, RMI, CORBA, web services.
Multithreaded Supports concurrent execution of multiple threads.
High Performance JIT compiler and efficient memory management improve speed.
Dynamic Supports runtime linking and reflection for flexibility.
Portable Bytecode and fixed data types ensure consistent behavior everywhere.

Difference between Java, C, and C++


Java, C, and C++ are all programming languages, but they differ in design philosophy, features, and usage.
 C is a procedural language, mainly used for system programming.
 C++ is a hybrid language (supports both procedural and object-oriented programming).
 Java is a pure object-oriented language (except for primitive types) and is designed for platform
independence, security, and internet-based applications.

Key Differences
1. Paradigm
 C → Procedural (focuses on func ons and procedures).
 C++ → Supports both Procedural and Object-Oriented Programming.
 Java → Purely Object-Oriented (everything is an object except primitive types).
2. Platform Dependence
 C & C++ → Pla orm dependent. Compiled programs run only on the system they are compiled for.
 Java → Pla orm independent. Code is compiled into bytecode, which runs on the Java Virtual
Machine (JVM).
3. Memory Management
 C & C++ → Programmer manually allocates and frees memory (malloc, free, delete).
 Java → Automa c memory management with Garbage Collection.
4. Pointers
 C & C++ → Use pointers for direct memory access.
 Java → No explicit pointers (uses references instead), which improves security.
5. Multiple Inheritance
 C++ → Supports mul ple inheritance (a class can inherit from mul ple classes).
 Java → Does not support mul ple inheritance through classes (to avoid ambiguity problems).
Instead, it uses interfaces to achieve multiple inheritance of behavior.
 C → Not object-oriented, so no concept of inheritance.

Kamadhenu BCA College Object Oriented Programming using JAVA 7


6. Operator Overloading
 C++ → Allows operator overloading (redefining operators like +, -).
 Java → Does not allow operator overloading (except + for string concatenation).
 C → Does not support operator overloading.
7. Execution
 C & C++ → Compiled directly to machine code (fast execu on but pla orm dependent).
 Java → Compiled into bytecode, executed by JVM (slightly slower but portable).
8. Libraries and API
 C → Standard library is small, mostly system-level functions.
 C++ → Rich Standard Template Library (STL).
 Java → Very large API library covering networking, database, GUI, collec ons, etc.
9. Security
 C & C++ → Less secure due to pointers and direct memory manipula on.
 Java → More secure due to no explicit pointers, bytecode verifica on, and sandboxing.
10. Application Domain
 C → System programming, opera ng systems, embedded systems.
 C++ → System so ware, games, high-performance applications.
 Java → Web applica ons, mobile apps (Android), enterprise systems, cloud compu ng.

Comparison Table
Feature C C++ Java
Procedural + Pure Object-Oriented (except
Programming Paradigm Procedural
Object-Oriented primitives)
Platform Dependency Dependent Dependent Independent (via JVM)
Manual Manual
Memory Management Automatic (Garbage Collector)
(malloc/free) (new/delete)
Not supported (only
Pointers Fully supported Fully supported
references)
Not supported (via interfaces
Multiple Inheritance Not supported Supported
only)
Not supported (except + for
Operator Overloading Not supported Supported
strings)
Compiled to Compiled to Compiled to bytecode (runs on
Execution
machine code machine code JVM)
Libraries Limited STL Huge API library
Security Low Low High
System-level, OS Games, system
Application Domain Web, mobile, enterprise, cloud
dev software

Java and the Internet


Java became popular during the rise of the Internet because it provided exactly what the web needed: a
portable, secure, and interactive programming language. In the mid-1990s, Java applets allowed web
browsers to run small interactive programs, bringing life to otherwise static HTML pages. Even though
applets are no longer used today, Java’s role in Internet programming continued through technologies such
as Servlets, JSP, and modern enterprise frameworks. Java’s platform independence, with its famous slogan
“Write Once, Run Anywhere,” made it the perfect fit for web-based applications.

Another major strength of Java on the Internet is its networking capabilities. With the [Link] package,
developers can easily create client–server applications, work with sockets, and access information over URLs.
These features earned Java the title of a network-centric language. At the same time, Java placed a strong
emphasis on security, ensuring that Internet applications could run safely. Features like the absence of
pointers, bytecode verification, and sandboxing protected users from malicious code and made Java a
trusted choice for online banking, e-commerce, and enterprise systems.

Kamadhenu BCA College Object Oriented Programming using JAVA 8


Java also played a vital role in building distributed applications, allowing communication between objects on
different machines through technologies like RMI, CORBA, and later web services. With the growth of mobile
Internet, Java extended its dominance through Java ME in early phones and continues today as the
foundation of Android applications. Overall, Java’s portability, robustness, scalability, and rich libraries made
it a preferred choice for Internet programming, from simple websites to complex cloud-based enterprise
solutions.

Java and the Internet – Key Points


1. Java and Web Programming – Java enabled interactive web pages using applets, and later through
Servlets, JSP, and modern frameworks.
2. Networking Capabilities – The [Link] package supports sockets, URLs, and client–server
applications, making Java a network-centric language.
3. Security on the Internet – Java ensures safety with sandboxing, no pointers, bytecode verification,
and secure APIs for online apps.
4. Distributed Applications – Java supports distributed computing via RMI, CORBA, Web Services, and
Enterprise Java (J2EE/Jakarta EE).
5. Mobile Internet – Java ME powered early mobile phones; today, Java is the foundation of Android,
dominating smartphones.
6. Advantages – Platform independence, security, robustness, rich libraries, and scalability make Java
ideal for Internet apps.

Java and the World Wide Web


The World Wide Web (WWW) became the face of the Internet in the 1990s, and Java played a key role in
making it interactive. Traditional web pages created with HTML were static and could only display text and
images. Java changed this by introducing applets, small programs that could be embedded into web pages
and executed inside browsers. These applets allowed animations, interactive forms, and games, making the
web more engaging and user-friendly.
As web technologies advanced, applets became outdated, but Java continued to dominate the server side of
the WWW. Technologies like Java Servlets and JavaServer Pages (JSP) allowed developers to create dynamic
web applications where content could be generated on the fly, responding to user input and database
queries. Over time, enterprise frameworks such as Spring, Struts, and JSF provided powerful tools for
building scalable and secure web applications.
Today, even though Java no longer powers the browser directly, it remains one of the most important
languages for the backend of the World Wide Web. From e-commerce platforms to social media and cloud-
based services, Java ensures robustness, scalability, and security in web-based systems. Its strong ecosystem
continues to make it a preferred choice for enterprise-level web development.
Java and the Internet – Refers to how Java supports networking, security, distributed systems, mobile apps,
and web applications, making it a complete Internet programming language.
Java and the World Wide Web – Focuses on how Java adds interactivity and dynamic features to web pages
through Applets, Servlets, JSP, and modern web frameworks.

Web Browsers
A Web Browser is application software that allows users to access, retrieve, and view information on the
World Wide Web. It interprets HTML, CSS, JavaScript, and other web technologies to display web pages in a
user-friendly format.
Browsers act as the interface between the user and the Internet: when a URL is entered, the browser sends
a request to a web server using the HTTP/HTTPS protocol, retrieves the response (usually HTML documents,
images, or multimedia), and renders it for the user.

Kamadhenu BCA College Object Oriented Programming using JAVA 9


Popular web browsers include Google Chrome, Mozilla Firefox, Microsoft Edge, Safari, and Opera. Early
browsers like Netscape Navigator and Internet Explorer played a major role in popularizing the Internet in
the 1990s.
A web browser is also capable of running plug-ins and extensions, supporting interactive content such as
videos, online games, and applications. Earlier, Java Applets were executed inside browsers using the Java
plug-in, though today modern web applications rely more on JavaScript and backend frameworks.
Did you know?
Java’s history is closely linked with web browsers. After Java was created at Sun Microsystems, one of the
first demonstrations of its power was through a browser called HotJava. This was the first web browser
written in Java itself, and it could run Java applets directly inside web pages. Released in 1995, HotJava
showed how web pages could become dynamic and interactive, far beyond the static text-and-image model
of early HTML.
The story goes that the Green Project team at Sun originally developed HotJava (initially called WebRunner)
as a proof of concept to showcase Java’s “Write Once, Run Anywhere” capability. It impressed the tech
community because, unlike other browsers, HotJava could download and run small programs (applets)
securely inside the browser. Although HotJava was later replaced by faster browsers like Netscape and
Internet Explorer, it played a historic role in proving that Java could transform the World Wide Web into an
interactive platform.

Hardware and Software Requirements for Java Programming


Before developing and running Java programs, certain hardware and software requirements must be
fulfilled. These requirements ensure that the system can install the Java Development Kit (JDK), compile
source code, and execute programs smoothly.

1. Hardware Requirements
The exact requirements depend on the version of Java, but a basic system configuration for Java
programming is:
 Processor: Minimum Pentium IV (1 GHz or higher); modern systems use multi-core processors
(i3/i5/i7, AMD Ryzen).
 RAM: Minimum 512 MB (for older JDK versions); recommended 2 GB or more for smooth
development with IDEs (like Eclipse, NetBeans, IntelliJ).
 Hard Disk: Around 500 MB free space for JDK; additional space required for IDEs, libraries, and
projects.
 Monitor: Standard VGA/LED monitor with at least 1024 × 768 resolution.
 Keyboard & Mouse: For program input and interaction.
2. Software Requirements
To develop and execute Java programs, the following software is required:
 Operating System (OS):
o Java is platform-independent and works on Windows, Linux, and macOS.
o For academic use, Windows (7/8/10/11) or Linux distributions (Ubuntu, Fedora) are
common.
 Java Development Kit (JDK):
o The JDK includes the compiler (javac), interpreter (java), libraries, and tools required for
writing and running Java programs.
o Example: JDK 8, JDK 11, JDK 17 (LTS versions commonly used).
 Java Runtime Environment (JRE):
o Required to run Java programs.
o JDK already contains JRE, so separate installation is optional for developers.
 Integrated Development Environment (IDE): (optional but recommended)
o Tools like Eclipse, NetBeans, IntelliJ IDEA, BlueJ make coding easier with features like syntax
highlighting, debugging, and project management.
o Beginners can also use a simple text editor (Notepad/Notepad++/gedit) with the command-
line tools.

Kamadhenu BCA College Object Oriented Programming using JAVA 10


Components of Java Environment / Support System
Java programs require certain components to be developed, compiled, and executed. The main components
are:
1. Java Development Kit (JDK)
 Definition: The JDK is a complete software development kit used to develop Java applications.
 Purpose: It provides all the tools necessary to write, compile, debug, and run Java programs.
 Components of JDK:
1. Java Compiler (javac) – Converts Java source code (.java) into bytecode (.class).
2. Java Runtime Environment (JRE) – Embedded in JDK to run programs.
3. Tools – javadoc (documentation), jar (create packages), debugger (jdb), and others.
 Use: Without JDK, you cannot compile Java programs, so it’s essential for developers.
2. Java Runtime Environment (JRE)
 Definition: JRE is the runtime environment required to execute Java programs.
 Purpose: It provides the libraries and JVM needed to run compiled bytecode.
 Components of JRE:
1. JVM – Executes bytecode.
2. Core Java Libraries – Classes for basic programming, GUI, networking, collections, etc.
 Use: Users who only want to run Java programs (not develop them) need only the JRE.
3. Java Virtual Machine (JVM)
 Definition: JVM is the virtual machine that executes Java bytecode and converts it into machine
code for the underlying OS.
 Purpose: Ensures platform independence — the same Java program can run on any system with
JVM.
 Features:
1. Bytecode Execution – Converts compiled code into machine instructions.
2. Memory Management – Automatic garbage collection.
3. Security – Runs programs in a secure sandbox.
4. Error Handling – Checks runtime errors.
4. Java API (Application Programming Interface)
 Definition: Java API is a set of pre-written classes and interfaces that provide standard functionality
for Java programs.
 Purpose: Saves development time by allowing developers to reuse code.
 Key Packages in Java API:
1. [Link] – Core classes like String, Math, Object.
2. [Link] – Collections, Date, Random, etc.
3. [Link] – Input/Output operations.
4. [Link] – Networking classes.
5. [Link] / [Link] – GUI programming.
6. [Link] / JDBC – Database connectivity.
 Use: The API is essential for writing programs efficiently without reinventing the wheel.
5. Integrated Development Environment (IDE)
 Definition: IDE is a software application that provides a complete environment for Java
development.
 Purpose: Simplifies coding, debugging, and project management.
 Popular Java IDEs: Eclipse, NetBeans, IntelliJ IDEA, BlueJ.
 Features of IDE:
1. Code Editor – Syntax highlighting, auto-completion.
2. Compiler Integration – Compiles code within the IDE.
3. Debugger – Step-by-step execution and error detection.
4. Project Management – Organize files, libraries, and dependencies.
 Use: Though optional, IDEs increase productivity and reduce errors, especially for large projects.

Kamadhenu BCA College Object Oriented Programming using JAVA 11


Summary Table
Component Purpose Key Features
JDK Write, compile, debug, and run Compiler, tools, JRE
programs
JRE Run Java programs JVM + Core libraries
JVM Execute bytecode on any OS Platform independence, memory management, security
Java API Pre-written classes for common [Link], [Link], [Link], [Link], Swing, JDBC
tasks
IDE Simplify development Code editor, debugger, project management, compiler
integration

Java Virtual Machine (JVM) Architecture


The Java Virtual Machine (JVM) is the core component of Java that allows it to be platform-independent. It
executes Java bytecode and provides runtime services like memory management, security, and exception
handling. The JVM has a well-defined architecture consisting of multiple components that work together to
execute Java programs efficiently.

Components of JVM Architecture

1. Class Loader Subsystem


 Purpose: Loads Java classes into the JVM.
 Function:
o Reads .class files (bytecode) from local file systems, networks, or other sources.
o Checks for validity and format of the class file.
o Loads classes dynamically when required, supporting Java’s dynamic linking.
2. Method Area
 Purpose: Stores class-level information.
 Function:
o Contains metadata about classes, methods, constructors, and static variables.
o Stores runtime constant pool (constants like strings, numeric literals).
3. Heap Memory
 Purpose: Stores objects and instance variables created during program execution.
 Function:
o All new objects are allocated in the heap.
o Managed by Garbage Collector (GC) to free memory of objects no longer in use.
4. Stack Memory
 Purpose: Stores method execution details.
 Function:
o Each thread has its own stack.
o Stores local variables, partial results, and return addresses for method calls.
o Follows LIFO (Last In First Out) principle.
5. Program Counter (PC) Register
 Purpose: Keeps track of the address of the currently executing instruction.
 Function:
o Each thread has its own PC register.
o JVM uses it to know which instruction to execute next.
6. Native Method Stack
 Purpose: Supports execution of native methods written in other languages like C/C++.
 Function:
o Stores information needed for calling native methods.
o Interacts with OS-level resources when Java calls native libraries.

Kamadhenu BCA College Object Oriented Programming using JAVA 12


7. Execution Engine
 Purpose: Executes Java bytecode.
 Components:
1. Interpreter – Reads bytecode instruction by instruction and executes it.
2. Just-In-Time
Time (JIT) Compiler – Converts bytecode into native machine code for faster
execution.
3. Garbage Collector (GC) – Automatically frees memory of objects no longer in use.
8. Native Interface (JNI)
 Purpose: Connects JVM with native applications or libraries.
 Function:
o Allows Java programs to interact with programs written in other languages.
9. Native Method Libraries
 Purpose: Provide precompile
precompiled native code libraries.
 Function:
o Used by JNI and execution engine for performing platform
platform-specific
specific tasks.

Flow of JVM Execution


1. Class Loader loads .class file into JVM.
2. Bytecode is stored in Method AreaArea.
3. Heap stores objects created during execution.
4. Execution Engine interprets or compiles bytecode into machine code.
5. Stack, PC Register, and Native Method Stack manage execution details.
6. Garbage Collector cleans unused objects in Heap.

Kamadhenu BCA College Object Oriented Programming using JAVA 13


Overview of JAVA Language:

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is


platform-independent, secure, and robust, following the principle “Write Once, Run Anywhere (WORA).”
Java is widely used for web applications, mobile apps, enterprise software, and distributed systems.

Types of Java Programs: Java programs can be broadly classified into two types based on how they are
executed:

1. Standalone Applications
 Definition: Standalone applications are programs that run independently on a computer using the
JVM.
 Characteristics:
o They do not require a web browser to run.
o Typically executed from the command line or an IDE.
o Can be desktop software like calculators, text editors, or business applications.
 Example: Programs like HelloWorld, Student & Test, or Bank Management Systems.
2. Web Applets
 Definition: Applets are Java programs that run inside a web browser or an applet viewer.
 Characteristics:
o Require a web browser to execute.
o Used to provide interactive features on web pages, like animations or simple games.
o Run in a restricted security environment (sandbox) for safety.
 Example: Java applets embedded in web pages to display interactive forms, animations, or
educational tools.

Simple Java Program


A Java program is a set of instructions written in the Java programming language that can be executed by
the Java Virtual Machine (JVM). Writing and running a simple Java program helps beginners understand the
basic structure, syntax, and execution flow of Java.

Structure of a Simple Java Program: A basic Java program usually contains:


1. Class Declaration – Every Java program must have at least one class.
2. Main Method – The entry point of the program: public static void main(String[] args)

1. public static void main(String[] args)


The main method is the entry point of every Java program. It tells the JVM where to start execution. Each
keyword has a specific meaning:
Keyword Meaning
public The method is accessible from anywhere. JVM can call it from outside the class.
static The method belongs to the class, not an object. JVM can call it without creating an
object of the class.
void The method does not return any value after execution.
main Name of the method where execution starts.
String[] args Parameter that stores command-line arguments passed to the program. It is an array of
Strings.
1. Statements / Instructions – Code written inside the main method that the program executes.
2. [Link](): This statement is used to display output on the console. Each part has a specific
role:

Kamadhenu BCA College Object Oriented Programming using JAVA 14


Part Meaning
System A pre-defined class in Java that provides access to system resources.
out A static member of the System class representing the standard output stream (usually
the console).
println() A method that prints the given message or value on the console and moves the cursor
to the next line.

Example of a Simple Java Program


public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Explanation:
1. public class HelloWorld → Declares a class named HelloWorld.
2. public static void main(String[] args) → The main method where program execution starts.
3. [Link]("Hello, World!"); → Prints the message Hello, World! on the screen.

Steps to Run a Java Program


1. Write the program in a text editor or IDE and save it as [Link].
2. Compile the program using the Java compiler:
3. javac [Link]
This generates the bytecode file [Link].
4. Run the program using the JVM:
5. java HelloWorld
Output: Hello, World!

Program 2: Sum of Two Numbers


public class Sum {
public static void main(String[] args) {
int a = 10, b = 20;
int sum = a + b;
[Link]("Sum: " + sum);
}
}

Output:
Sum: 30

An Application with Two Classes


A Java application can have more than one class, where one class can interact with another. Writing and
running a two-class application helps beginners understand class interaction, object creation, and method
calling in Java.

Structure of a Two-Class Java Application


A basic two-class Java program usually contains:
1. Class Declarations – There are at least two classes: one may contain data or methods, and the other
contains the main method.
2. Main Method – The entry point of the program:
3. public static void main(String[] args)
4. Objects and Method Calls – One class creates objects of another class and calls its methods to perform
tasks.

Kamadhenu BCA College Object Oriented Programming using JAVA 15


Example of a Two-Class Java Program

// Class 1: Student
class Student {
private String name;
private int rollNo;

// Constructor
public Student(String name, int rollNo) {
[Link] = name;
[Link] = rollNo;
}

// Method to display details


public void display() {
[Link]("Name: " + name);
[Link]("Roll No: " + rollNo);
}
}

// Class 2: Test
public class Test {
public static void main(String[] args) {
// Creating an object of Student class
Student s1 = new Student("Ram", 101);
[Link]();
}
}

Explanation:
 class Student → Declares a class with data members and a constructor.
 display() → A method to print student details.
 public class Test → Contains the main method, the starting point of program execution.
 Student s1 = new Student("Ram", 101) → Creates an object of the Student class and passes data.
 [Link]() → Calls the method to display student information.

Steps to Run the Program


1. Write the program in a text editor or IDE and save it as [Link].
2. Compile the program using the Java compiler:
3. javac [Link]
4. This generates bytecode files for both classes: [Link] and [Link].
5. Run the program using the JVM:
6. java Test

Output:
Name: Ram
Roll No: 101

Java Program Structure


A Java program is a set of instructions written in the Java programming language that can be executed by
the Java Virtual Machine (JVM). Every Java program follows a well-defined structure to ensure it compiles
and runs correctly. Understanding this structure helps beginners write organized and error-free programs.

1. Documentation Section (Optional)


Documentation in a Java program is used to explain the purpose and functionality of the code. By adding
comments and descriptions, it makes the program easier to read, understand, and maintain. This is

Kamadhenu BCA College Object Oriented Programming using JAVA 16


especially useful when multiple programmers work on the same project or when revisiting the code after a
long time.

Example:
// This program prints a welcome message
[Link]("Welcome to Java!");

2. Package Statement (Optional)


Package statements define the package to which a class belongs. Packages help in organizing classes into
groups, making code management easier in large projects. The package statement must be the first line of
the program if used.
Example:
package mypackage; // Declares a package named mypackage

3. Import Statements (Optional)


Import statements are used to include pre-defined Java classes or libraries into the program. They help
avoid rewriting code and make programs more efficient.
Example:
import [Link]; // Imports Scanner class from [Link] package

4. Interface Statement (Optional)


Interfaces in Java define a set of methods that a class must implement. They act as a blueprint and help
achieve consistency, modular design, and flexibility in programs.
Example:
interface Drawable {
void draw();
}

5. Class Declaration (Mandatory)


Every Java program must have at least one class. A class defines the structure and behavior of the program.
Example:
public class Hello {
// Class body
}

6. Main Method (Mandatory)


The main method is the entry point of the program where execution starts. Without it, the JVM cannot run
the program.
Example:
public static void main(String[] args) {
[Link]("Hello Java!");
}

7. Statements / Instructions (Mandatory)


Statements inside the main method are executed sequentially, ensuring a logical flow of execution. Each
statement ends with a semicolon (;).
Example:
[Link]("Step 1");
[Link]("Step 2");
[Link]("Step 3");

Kamadhenu BCA College Object Oriented Programming using JAVA 17


Highlights :
 Documentation improves code readability and maintenance.
 Package and import statements are optional but help organize and reuse code.
 Interfaces define methods that classes must implement.
 Every program must have a class and a main method.
 Statements inside the main method execute sequentially, ensuring a proper flow.
/**
* This program demonstrates the complete structure of a Java program.
* It includes documentation, package, import, interface, class declaration,
* main method, and statements.
// Package statement (optional)
package mypackage;

// Import statements (optional)


import [Link];

// Interface declaration (optional)


interface Drawable {
void draw();
}

// Class declaration (mandatory)


public class ExampleProgram implements Drawable {

// Method from interface


public void draw() {
// Statement inside class method
[Link]("Drawing a shape...");
}

// Main method (mandatory)


public static void main(String[] args) {
// Statements inside main method
[Link]("Welcome to Java Programming!"); // Print message

// Create object of ExampleProgram


ExampleProgram obj = new ExampleProgram();
[Link](); // Call method from interface
}
}

Welcome to Java Programming!


Drawing a shape...

 Documentation: /** ... */ at the top explains the program.


 Package statement: package mypackage; organizes the class.
 Import statement: import [Link]; (example of library import).
 Interface statement: interface Drawable defines a method to implement.
 Class declaration: public class ExampleProgram is mandatory.
 Main method: public static void main(String[] args) is the entry point.
 Statements: [Link]() and method calls inside main.

Kamadhenu BCA College Object Oriented Programming using JAVA 18


Java Tokens
A token in Java is the smallest unit of a program that the compiler can recognize and process.
Just like a sentence is made of words, a Java program is made of tokens.
Example:
int num = 10;
Here:
int → Keyword
num → Iden fier
= → Operator
10 → Literal
; → Separator
Types of Java Tokens
1. Keywords
2. Identifiers
3. Literals (Constants)
4. Operators
5. Separators (Delimiters)

1. Keywords
 Keywords are reserved words in Java.
 They have a predefined meaning and cannot be used as identifiers.
 Java has around 50+ keywords like: class, int, if, else, while, switch, static, void, break, return,
public, private.
Example:
class Student {
int age; // 'class' and 'int' are keywords
}

2. Identifiers
 Identifiers are the names given to classes, variables, methods, and objects.
 They allow programmers to identify program elements.
Rules for Naming Identifiers
1. Must begin with a letter (A-Z or a-z), underscore (_), or dollar sign ($).
2. Can contain letters, digits, underscores, and dollar signs.
3. Cannot use keywords as identifiers.
4. Java is case-sensitive (Age and age are different).
Valid Identifiers
name, student1, _rollNo, $salary

Invalid Identifiers
❌123abc (cannot start with digit)
❌class (keyword)
❌stu dent (space not allowed)
❌@data (special character not allowed)

Literals (Constants) in Java


A literal (constant) in Java is a fixed value written
directly in the code. Unlike variables, literals do
not change during program execution.
Example:
int age = 20; // 20 is an integer literal
String name = "Ravi"; // "Ravi" is a string literal

Kamadhenu BCA College Object Oriented Programming using JAVA 19


Types of Literals in Java
Integer Literals
 Whole numbers without decimal points.
 Can be written in different number systems
systems:
 Decimal (base 10): 10, 0, -25
 Octal (base 8, starts with 0): 012 → (decimal 10)
 Hexadecimal (base 16, starts with 0x or 0X): 0x1A → (decimal 26)
 Binary (base 2, starts with 0b or 0B): 0b1010 → (decimal 10)

Operators: Operators are symbols that perform specific operations on variables and
a values.
Java has a rich set of operators grouped into categories.

A. Arithmetic Operators : Used for basic mathematical operations.


Operator Description Example
+ Addition 10 + 5 → 15
- Subtraction 10 - 5 → 5
* Multiplication 10 * 5 → 50
/ Division 10 / 5 → 2
% Modulus (remainder) 10 % 3 → 1
Example:
int a = 10, b = 3;
[Link](a + b); // 13

1. Arithmetic Operators
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 10, b = 3;

Kamadhenu BCA College Object Oriented Programming using JAVA 20


[Link]("Addition: " + (a + b));
[Link]("Subtraction: " + (a - b));
[Link]("Multiplication: " + (a * b));
[Link]("Division: " + (a / b));
[Link]("Modulus: " + (a % b));
}
}

B. Relational Operators: Used to compare values. Result is true/false.


Operator Meaning Example (a=10, b=5)
== Equal to a == b → false
!= Not equal to a != b → true
> Greater than a > b → true
< Less than a < b → false
>= Greater/Equal a >= b → true
<= Less/Equal a <= b → false

2. Relational Operators
public class RelationalOperators {
public static void main(String[] args) {
int x = 10, y = 20;
[Link]("x == y: " + (x == y));
[Link]("x != y: " + (x != y));
[Link]("x > y: " + (x > y));
[Link]("x < y: " + (x < y));
[Link]("x >= y: " + (x >= y));
[Link]("x <= y: " + (x <= y));
}
}

C. Logical Operators: Used with boolean values.


Operator Meaning Example
&& Logical AND (a>5 && b<10) → true
|| Logical OR (a>5 || b<10) → true
! Logical NOT !(a>5) → false

Logical Operators
public class LogicalOperators {
public static void main(String[] args) {
boolean a = true, b = false;
[Link]("a && b: " + (a && b));
[Link]("a || b: " + (a || b));
[Link]("!a: " + (!a));
}
}

D. Assignment Operators : Used to assign values to variables.


Operator Meaning Example
= Assign value x = 10
+= Add & assign x += 5 → x = x+5
-= Subtract & assign x -= 2 → x = x-2
*= Multiply & assign x *= 3 → x = x*3
/= Divide & assign x /= 2 → x = x/2
%= Modulus & assign x %= 3 → x = x%3

Kamadhenu BCA College Object Oriented Programming using JAVA 21


Assignment Operators
public class AssignmentOperators {
public static void main(String[] args) {
int a = 5;
[Link]("Initial a: " + a);

a += 3; // a = a + 3
[Link]("a += 3: " + a);

a *= 2; // a = a * 2
[Link]("a *= 2: " + a);

a -= 4; // a = a - 4
[Link]("a -= 4: " + a);

a /= 2; // a = a / 2
[Link]("a /= 2: " + a);
}
}

Increment & Decrement Operators


 ++ → Increases value by 1
 -- → Decreases value by 1

Example:
int x = 5;
[Link](x++); // 5 (post-increment)
[Link](++x); // 7 (pre-increment)

Program: Increment and Decrement Operators


public class IncDecExample {
public static void main(String[] args) {
int x = 5;

[Link]("Initial value of x: " + x);

// Pre-increment (++x): increment first, then use


[Link]("Pre-increment (++x): " + (++x)); // x becomes 6, then used

// Post-increment (x++): use first, then increment


[Link]("Post-increment (x++): " + (x++)); // prints 6, then x becomes 7

// Pre-decrement (--x): decrement first, then use


[Link]("Pre-decrement (--x): " + (--x)); // x becomes 6, then used

// Post-decrement (x--): use first, then decrement


[Link]("Post-decrement (x--): " + (x--)); // prints 6, then x becomes 5

[Link]("Final value of x: " + x);


}
}

Kamadhenu BCA College Object Oriented Programming using JAVA 22


Bitwise Operators : Work at bit level (0s and 1s).
Operator Meaning Example (a=5, b=3)
& Bitwise AND a&b→1
| Bitwise OR a|b→1
^ Bitwise XOR a^b→6
~ Bitwise NOT ~a → -6
<< Left shift a << 1 → 10
>> Right shift a >> 1 → 2
>>> Unsigned right shift a >>> 1

Bitwise Calculations in Java


Bitwise operators work directly on the binary representation of numbers. Instead of operating on the whole
number, they manipulate individual bits (0s and 1s).

1. Binary Number System Refresher


 Decimal 5 → Binary: 0101
 Decimal 3 → Binary: 0011
 Decimal 10 → Binary: 1010

Every bit position has a value (2⁰, 2¹, 2², …).

2. Types of Bitwise Operators

(a) AND (&)

 Rule: 1 & 1 = 1, else 0


 Example:
5 = 0101
3 = 0011
--------------
5 & 3 = 0001 (decimal 1)

(b) OR (|)
 Rule: 1 | 1 = 1, 1 | 0 = 1, 0 | 0 = 0
 Example:
5 = 0101
3 = 0011
--------------
5 | 3 = 0111 (decimal 7)

(c) XOR (^)


 Rule: 1 ^ 1 = 0, 1 ^ 0 = 1, 0 ^ 1 = 1, 0 ^ 0 = 0
 Example:
5 = 0101
3 = 0011
--------------
5 ^ 3 = 0110 (decimal 6)

(d) NOT (~)


 Rule: Inverts every bit → 0 → 1, 1 → 0
 Example:
5 = 0101
~5 = 1010 (in 4 bits)

Kamadhenu BCA College Object Oriented Programming using JAVA 23


In Java, numbers are stored in 32 bits (two’s complement).
So ~5 actually becomes -6.

(e) Left Shift (<<)


 Shifts bits to the left, filling 0s on the right.
 Equivalent to multiplying by 2^n.
 Example:
5 << 1 = 10 (5 × 2)
5 << 2 = 20 (5 × 4)

(f) Right Shift (>>)


 Shifts bits to the right, keeping the sign bit (arithmetic shift).
 Equivalent to dividing by 2^n.
 Example:
20 >> 1 = 10
20 >> 2 = 5

(g) Unsigned Right Shift (>>>)


 Shifts bits to the right, fills with 0 (ignores sign).
 Only useful for negative numbers.

Example:
-5 >>> 1 → large positive number (because sign bit is removed)

Bitwise Operators
public class BitwiseOperators {
public static void main(String[] args) {
int x = 5, y = 3; // Binary: 0101 and 0011
[Link]("x & y: " + (x & y)); // AND
[Link]("x | y: " + (x | y)); // OR
[Link]("x ^ y: " + (x ^ y)); // XOR
[Link]("~x: " + (~x)); // NOT
[Link]("x << 1: " + (x << 1)); // Left shift
[Link]("x >> 1: " + (x >> 1)); // Right shift
}
}

Output:
x & y: 1
x | y: 7
x ^ y: 6
~x: -6
x << 1: 10
x >> 1: 2

Conditional (Ternary) Operator


 Syntax: condition ? value1 : value2
 Works like an if-else in one line.
Example:
int age = 18;
String result = (age >= 18) ? "Adult" : "Minor";

Conditional (Ternary) Operator ?:


public class TernaryOperatorExample {
public static void main(String[] args) {
int a = 10, b = 20;

Kamadhenu BCA College Object Oriented Programming using JAVA 24


// Ternary operator: condition ? value_if_true : value_if_false
int max = (a > b) ? a : b;

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


}
}

H. Instanceof Operator
 Tests whether an object belongs to a particular class.
Example:
String s = "Hello";
[Link](s instanceof String); // true

2. instanceof Operator
class Animal {}
class Dog extends Animal {}

public class InstanceOfExample {


public static void main(String[] args) {
Animal a = new Dog();

[Link]("a instanceof Animal: " + (a instanceof Animal));


[Link]("a instanceof Dog: " + (a instanceof Dog));
[Link]("a instanceof Object: " + (a instanceof Object));
}
}

I. Type Cast Operator

 Used to convert one type to another.

Example:
double d = 10.5;
int x = (int) d; // converts double to int

5. Separators (Delimiters)
Separators help organize code.
 ; → Statement terminator
 { } → Defines a block of code
 ( ) → Encloses parameters/condi ons
 [ ] → Array indexing
 , → Separates mul ple variables
 . → Accesses class members
Example:
int arr[] = {1, 2, 3};
[Link](arr[0]);

Java Statements
A statement in Java is a complete unit of execution. Just like a sentence in English ends with a period, a Java
statement usually ends with a semicolon ( ; ). Statements tell the Java compiler what actions to perform.
Java provides several types of statements to control the execution flow of a program.

Kamadhenu BCA College Object Oriented Programming using JAVA 25


1. Expression Statements
These are simple statements that perform a single action.
Examples:
int x = 5; // Assignment statement
x++; // Increment statement
[Link](x); // Method call statement

2. Declaration Statements
Used to declare variables or constants.
Example:
int a;
final double PI = 3.14159;

3. Control Flow Statements


These control the order of execution of statements in a program. They are classified into three categories:
(a) Decision-making statements : if, if-else, if-else-if, switch
Example:
if (age >= 18) {
[Link]("Eligible to vote");
} else {
[Link]("Not eligible");
}

(b) Looping statements: for, while, do-while


Example:
for (int i = 1; i <= 5; i++) {
[Link](i);
}

(c) Jump statements: break, continue, return


Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) break; // exits the loop
[Link](i);
}

4. Block Statements
A block is a group of statements enclosed in curly braces { }, treated as one unit.
Example:
{
int x = 10;
int y = 20;
[Link](x + y);
}
Evaluation of Expressions in Java
Evaluation of expressions means the process of computing the final value of an expression by applying
operators on operands according to rules of precedence and associatively.

1. Order of Evaluation
1. Operator Precedence → Some operators are given higher priority (e.g., *, / before +, -).
2. Associativity → If operators have the same precedence, evalua on follows a fixed direc on (le -to-
right or right-to-left).
3. Parentheses () → Always evaluated first, overriding precedence.

Kamadhenu BCA College Object Oriented Programming using JAVA 26


2. Operator Precedence (Simplified Table)
Precedence Operators Associativity
Highest (), [], . (method call, array access, dot operator) Left to Right
2nd ++, --, + (unary), - (unary), !, ~ Right to Left
3rd *, /, % Left to Right
4th +, - Left to Right
5th <, >, <=, >= Left to Right
6th ==, != Left to Right
7th && Left to Right
8th || Left to Right
Lowest =, +=, -=, *= Right to Left

3. Steps in Evaluation
 Parentheses are solved first.
 Then unary operators (++, --, !).
 Multiplication/division/modulus are applied before addition/subtraction.
 Relational and logical operators are applied later.
 Finally, assignment happens.

Type Conversion: Type conversion is the process of converting a value from one data type to another.
There are two main types:

a) Implicit Type Conversion (Type Casting or Type Promotion)


 Also called type promotion.
 Done automatically by the compiler.
 Happens when you assign a smaller data type to a larger data type (no data loss).

Rules in Java:
byte → short → int → long → float → double
char → int → long → float → double

Example (Java):
int x = 10;
double y = x; // int is promoted to double
[Link](y); // Output: 10.0

Here, int x is implicitly converted to double because double can store integer values without loss.

b) Explicit Type Conversion (Type Casting)


 Done manually by the programmer.
 Use casting operator.
 Can lead to data loss if the target type is smaller.

Example (Java):
double a = 9.78;
int b = (int) a; // explicit casting
[Link](b); // Output: 9

Here, decimal part .78 is lost.

c) Type Conversion in Expressions


When you perform operations between different data types, type promotion rules apply:
int x = 5;

Kamadhenu BCA College Object Oriented Programming using JAVA 27


double y = 4.5;
double result = x + y; // int x promoted to double
[Link](result); // Output: 9.5

Associatively
Associatively defines the order in which operators of the same precedence are evaluated in an expression.
a) Types of Associatively
1. Left-to-Right Associatively
o Most binary operators follow left-to-right.
o Example: +, -, *, /, %
2. int x = 20 - 5 - 3;
3. // evaluated as (20 - 5) - 3 = 12
4. Right-to-Left Associativity
o Some operators like assignment (=) and unary operators.
5. int a, b, c;
6. a = b = c = 10;
7. // evaluated as a = (b = (c = 10))

b) Why Associatively Matters


Example:
int x = 2, y = 3, z = 4;
int result = x + y * z;
 * has higher precedence → y * z evaluated first.
 Then x + 12 → 14
If operators have same precedence, associatively determines evaluation order.

Quick Table
Operator Associativity
*/%+- Left to Right
= Right to Left
++ -- Right to Left
?: (ternary) Right to Left

Mathematical Function: A mathematical function is a predefined method in Java that performs


common mathematical operations like:
 Calculating powers, roots
 Rounding numbers
 Finding maximum or minimum
 Trigonometric calculations
 Logarithms and exponentials
These functions are available in the Math class.
Syntax: [Link](arguments);

Common Mathematical Functions in Java


Function Description Function Description
abs(x) Returns absolute value of x min(a,b) Returns minimum of a and b
pow(a,b) Returns a raised to the power b sin(x) Returns sine of x (in radians)
sqrt(x) Returns square root of x cos(x) Returns cosine of x (in radians)
ceil(x) Rounds x up to nearest integer tan(x) Returns tangent of x (in radians)
floor(x) Rounds x down to nearest integer exp(x) Returns e^x
round(x) Rounds x to nearest integer log(x) Returns natural logarithm of x
max(a,b) Returns maximum of a and b log10(x) Returns base 10 logarithm of x

Kamadhenu BCA College Object Oriented Programming using JAVA 28


/*Example Program Using Mathematical Functions*/
public class MathFunctionsExample {
public static void main(String[] args) {
double num1 = -8.5;
double num2 = 4;

// Absolute value
[Link]("Absolute of num1: " + [Link](num1));

// Power
[Link]("num2 raised to 3: " + [Link](num2, 3));

// Square root
[Link]("Square root of 16: " + [Link](16));

// Rounding functions
[Link]("Ceil of num1: " + [Link](num1));
[Link]("Floor of num1: " + [Link](num1));
[Link]("Round of num1: " + [Link](num1));

// Maximum and Minimum


[Link]("Max of num1 and num2: " + [Link](num1, num2));
[Link]("Min of num1 and num2: " + [Link](num1, num2));

// Trigonometric function
[Link]("Sine of 45 degrees: " + [Link]([Link](45)));

// Logarithmic and exponential


[Link]("e^2: " + [Link](2));
[Link]("Natural log of 2: " + [Link](2));
}
}

Output:
Absolute of num1: 8.5
num2 raised to 3: 64.0
Square root of 16: 4.0
Ceil of num1: -8.0
Floor of num1: -9.0
Round of num1: -8
Max of num1 and num2: 4.0
Min of num1 and num2: -8.5
Sine of 45 degrees: 0.7071067811865475
e^2: 7.38905609893065
Natural log of 2: 0.6931471805599453

Command Line Arguments


In Java, when we execute a program, we can pass additional information to it through the command line.
These pieces of information are called Command Line Arguments. They allow a user to give input to the
program at the time of execution, rather than during program execution using Scanner or BufferedReader.

Kamadhenu BCA College Object Oriented Programming using JAVA 29


Definition:
Command Line Arguments are the values passed to the main() method when a Java program starts
execution. The main() method in Java is defined as:
public static void main(String args[])

Here, args is an array of type String that stores command-line arguments passed by the user.
Key Points:
1. All command-line arguments are treated as strings.
2. They are separated by spaces on the command line.
3. The first argument is stored in args[0], the second in args[1], and so on.
4. The number of arguments can be obtained using [Link].

Syntax:
java ProgramName arg1 arg2 arg3 ...

Where:
 ProgramName → name of the compiled .class file (without extension)
 arg1, arg2, arg3 → arguments passed to the program

Example Program:
// File: [Link]
class CommandLineDemo {
public static void main(String args[]) {
[Link]("Number of arguments: " + [Link]);

[Link]("The arguments are:");


for (int i = 0; i < [Link]; i++) {
[Link]("args[" + i + "] = " + args[i]);
}
}
}
How to Run:
Compile the program:
javac [Link]
Run with command line arguments:
java CommandLineDemo Hello Java World

Output:
Number of arguments: 3
The arguments are:
args[0] = Hello
args[1] = Java
args[2] = World

Explanation:
 When we run the program, the JVM passes the arguments (Hello, Java, World) to the main() method as a
String array.
 The for loop is used to display each argument separately.
 Even if numeric values are passed, they are read as strings. You can convert them using
[Link]() or [Link]() when needed.

Kamadhenu BCA College Object Oriented Programming using JAVA 30


Example 2: Adding Two Numbers from Command Line
// File: [Link]
class AddNumbers {
public static void main(String args[]) {
int a = [Link](args[0]);
int b = [Link](args[1]);
int sum = a + b;
[Link]("Sum = " + sum);
}
}

Why to use command line arguments: Command line arguments make a Java program flexible, reusable,
and automatable without code changes.

Uses of Command Line Arguments


1. Input Without Interaction: Allows users to pass input values directly while starting the program.
Example: java AddNumbers 10 20 → passes 10 and 20 as inputs.
2. Automation and Testing: Useful for running the same program with different inputs automatically,
especially during testing. Example:java AddNumbers 5 10 java AddNumbers 15 25 java
AddNumbers 50 100
3. Passing File Names: Enables the program to receive file names or paths as arguments instead of
hardcoding. Example: java ReadFile [Link] → reads data from [Link].
4. Configuration Settings: Used to supply configuration details like port numbers or URLs while running
programs. Example: java ServerConfig localhost 8080 → sets host and port dynamically.
5. Server and Web Applications: Helpful in CGI and server-side programs to pass form or user data.
Example: java GenerateReport user123 sales → passes user ID and report type.

Constants, Variables, and Data Types


Every program in Java works with data — and to handle data efficiently, we must store, identify, and
manipulate it properly. For this, Java provides variables, constants, and data types.
 Variable → a name given to a memory loca on where data can change during execu on.
 Constant → a fixed value that does not change during program execution.
 Data Type → defines the kind of data a variable can hold.

Variable : A variable is a named memory location that holds a value which can change during program
execution. It acts as a container to store data temporarily while the program runs.

Syntax
data_type variable_name;
or
data_type variable_name = value;

Examples
int age;
float salary;
char grade;

Initialization of Variables
Assigning an initial value to a variable at the time of declaration is called initialization.

Example:
int total = 100;
double pi = 3.14159;

Kamadhenu BCA College Object Oriented Programming using JAVA 31


boolean status = true;
Variables can also be initialized later in the program:
int num;
num = 25; // initialized later

Multiple Declarations
You can declare multiple variables of the same type in one line:
int a, b, c;
float x = 2.5f, y = 4.0f;

Good and Bad Variable Names


Type Example Explanation
Good Names studentName, totalMarks, average, Meaningful, descriptive, and follow Java naming
interestRate rules.
Bad Names a, x1, temp2, 123name, total marks Non-descriptive, invalid (space or number at
start), or confusing.
Rules for Naming Variables – same as indentfier naming rules.
1. Variable names must begin with a letter, $, or _.
2. Subsequent characters may be letters, digits, $, or _.
3. No spaces or special symbols allowed.
4. Java is case-sensitive — Total and total are different.
5. Should not be a keyword (e.g., int, class, etc.).
6. Use camelCase convention for readability (e.g., studentName).

Note : $ can be used, but not recommended for normal variable names. $ is mainly used by Java compilers
or tools (like auto-generated class names, inner classes, or proxies). Example: Outer$[Link] → created
for inner classes. It’s also sometimes used in machine-generated code or frameworks (like JSP or bytecode
tools).
Constant: A constant is a fixed value that cannot be changed during program execution. It is used to make
programs more readable, maintainable, and error-free.

Example: PI = 3.14159 → the value of π should not change anywhere in the program.

Syntax
In Java, constants are declared using the keyword final: final → makes the value unchangeable. By
convention, constant names are written in UPPERCASE.
Examples
final int MAX_STUDENTS = 60;
final double PI = 3.14159;
final char GRADE = 'A';

Example Program
class ConstantDemo {
public static void main(String args[]) {
final double PI = 3.14159;
double radius = 5.0;
double area = PI * radius * radius;

[Link]("Area of circle = " + area);

// PI = 3.14; // ❌Error: cannot assign a value to final variable PI


}
}

Kamadhenu BCA College Object Oriented Programming using JAVA 32


Output:
Area of circle = 78.53975
 Trying to change the value of PI will cause a compile-time error.

Types of Constant:
1. Literal Constants
These are fixed values written directly in the program.
Type Example Explanation
int constant 10, 250, -5 Fixed integer numbers
float/double constant 3.14, 9.81 Fixed decimal numbers
char constant 'A', 'z', '0' Single characters
String constant "Hello", "Ravi" Sequence of characters
boolean constant true, false Logical values

2. Symbolic Constants: using final


final int MAX = 100;
final double PI = 3.14159;
final char GRADE = 'A';
Here MAX, PI, GRADE are symbolic constants, not literals, because they are named constants.

Data Types in Java


A data type defines the kind of data a variable can hold and the operations that can be performed on it.
Java is a strongly typed language, so every variable must have a type.

2. Classification of Data Types


A. Primitive Data Types
These are predefined by Java and store simple values.
Type Size Example Description
byte 1 byte 100 Small integers (-128 to 127)
short 2 bytes 1000 Medium integers (-32,768 to 32,767)
int 4 bytes 25000 Standard integers
long 8 bytes 300000L Large integers
float 4 bytes 12.5f Single-precision decimal numbers
double 8 bytes 23.4567 Double-precision decimal numbers
char 2 bytes 'A' Single character (Unicode)
boolean 1 byte true/false Logical values
Notes:
 Integer types: byte, short, int, long
 Floating-point types: float, double
 Character type: char (stores a single character in Unicode)
 Logical type: boolean (stores true/false)

B. Non-Primitive (Reference) Data Types


 Store objects or references.
 Examples: String, arrays, classes, interfaces.
 Default value of reference types is null.

Example:
String name = "Ravi";
int[] marks = {85, 90, 75};

Kamadhenu BCA College Object Oriented Programming using JAVA 33


3. Default Values of Data Types
Type Default Value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0
char '\u0000'
boolean false

Scope of Variables in Java


The scope of a variable defines where it can be accessed in a program.
In other words, it tells the part of the program where the variable is visible and usable.

Types of Variables by Scope:


A. Local Variables: Declared inside a method, constructor, or block. Accessible only within that
method/block. Do not have default values — must be initialized before use.

Example:
class Example {
void show() {
int num = 10; // local variable
[Link]("Num = " + num);
}
}
num is only accessible inside show(). Outside, it gives an error.

B. Instance Variables (Non-Static): Declared inside a class but outside any method. Belongs to the object
— each object has its own copy. Default values are assigned automatically.

Example:
class Student {
int rollNo; // instance variable
String name; // instance variable

void display() {
[Link](rollNo + " " + name);
}
}
Each Student object has its own rollNo and name.

C. Static Variables (Class Variables) : Declared with static keyword inside a class. Belongs to the class, not to
objects — shared among all objects. Default values are assigned automatically.
Example:
class Example {
static int count; // static variable

void increment() {
count++;
}
}
All objects of Example share the same count.

Kamadhenu BCA College Object Oriented Programming using JAVA 34


Summary Table
Variable Type Declared Where Scope / Accessible Default Value
Local Inside method/block Only within method/block No default, must initialize
Instance Class (outside methods) By all methods of object Yes
Static (Class) Class with static keyword Shared by all objects Yes

Getting Values of Variables in Java


Getting values of variables means reading input from the user during program execution.
In Java, this is commonly done using the Scanner class from [Link] package.

Using Scanner Class


1. Import the Scanner class: import [Link];
2. Create a Scanner object: Scanner sc = new Scanner([Link]);
3. Read values using Scanner methods:
 nextInt() → reads integer
 nextFloat() → reads float
 nextDouble() → reads double
 next() → reads single word String
 nextLine() → reads en re line of text
 nextBoolean() → reads boolean

Example Program
import [Link];

class InputDemo {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);

[Link]("Enter your age: ");


int age = [Link](); // reading integer

[Link]("Enter your name: ");


String name = [Link](); // reading string (single word)

[Link]("Enter your salary: ");


float salary = [Link](); // reading float

[Link]("\n--- Output ---");


[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Salary: " + salary);
}
}
Sample Input / Output:
Enter your age: 20
Enter your name: Ravi
Enter your salary: 4500.5

--- Output ---


Name: Ravi
Age: 20
Salary: 4500.5

Kamadhenu BCA College Object Oriented Programming using JAVA 35


Decision Making and Branching Statement
Decision making statements are used in a program to execute a block of code based on a condition.
They allow the program to choose between two or more paths depending on the result of a condition (true
or false).
 Branching refers to the process of jumping to a different part of the program based on a decision.
 In Java, decision making statements guide the flow of control using conditions.
Helps the program take decisions at runtime. Executes certain code only if a condition is true. Supports
multiple alternatives using branching. Conditions usually involve relational (>, <, ==) or logical (&&, ||, !)
operators.
Types of Decision Making / Branching Statements in Java
1. if statement – execute block if condition is true.
2. if-else statement – choose between two alternatives.
3. nested if statement – if statements inside another if.
4. switch statement – select among multiple alternatives based on a value.

The if Statement in Java: The if statement is used to execute a block of code only when a specified
condition is true. If the condition is false, the block of code is skipped. It is the simplest form of
decision-making in Java.
Syntax
if (condition) {
// statements to execute if condition is true
}

 condition → a Boolean expression (true or


false)
 The block inside { } executes only if condition is
true
 If there is only one statement, then braces { }
are optional.

Flow of Control
1. Condition is evaluated.
2. If true → execute the statements inside if block.
3. If false → skip the if block and continue with the rest of the program.

Example Program
class IfExample {
public static void main(String args[]) {
int marks = 75;

if (marks >= 50) {


[Link]("You have passed the exam.");
}

[Link]("Exam result checked.");


}
}
Output:
You have passed the exam.
Exam result checked.

Kamadhenu BCA College Object Oriented Programming using JAVA 36


The if-else Statement in Java : The if-else statement is used to choose between two alternatives
based on a condition. If the condition is true, the if block
executes. If the condition is false, the else block executes.
Use if-else when you want the program to take action in
both cases.

Syntax
if (condition) {
// statements executed if condition
is true
} else {
// statements executed if condition
is false
}

 condition → a boolean expression (true or false)


 Curly braces {} are optional for single statements.

Flow of Control
1. Condition is evaluated.
2. If true → execute if block.
3. If false → execute else block.
4. Program continues after if-else.

Example Program Output:


class IfElseExample { You have failed the exam.
public static void main(String args[]) {
Exam result checked.
int marks = 35;
 Here, marks >= 50 is false.
if (marks >= 50) {
[Link]("You have passed the exam.");  So, the else block executes and
} else { prints "You have failed the exam."
[Link]("You have failed the exam.");
}

[Link]("Exam result checked.");


}
}
Nested if Statement in Java : When an if statement appears inside another if or else block, it is
called a nested if statement. It allows testing multiple conditions in sequence. Useful when one decision
depends on another.

Syntax
if (condition1) {
if (condition2) {
// statements if both condition1 and condition2 are true
}
}

The inner if executes only if the outer if condition is true.

Kamadhenu BCA College Object Oriented Programming using JAVA 37


Flow of Control
1. Test condition1.
2. If true, test condition2.
3. If both are true,, inner block executes.
4. If any condition is false,, control skips to
the next part of the program.

Example Program
class NestedIfExample {
public static void main(String
(String
args[]) {
int marks = 85;

if (marks >= 50) {


if (marks >= 75)) {
[Link](
[Link]("Distinction");
} else {
[Link](
[Link]("Pass Class");
}
} else {
[Link](
[Link]("Fail");
}
}
}

Output:
Distinction

The else-if Ladder in Java: The else


else-if ladder is used when multiple conditions need to be tested one
after another. As soon as one condition becomes true, the corresponding block executes, and the rest are
skipped. It provides a multi-way
way decision in a clear, structured manner.

Syntax
if (condition1) {
// statements for condition1
}
else if (condition2) {
// statements for condition2
}
else if (condition3) {
// statements for condition3
}
else {
// statements if all conditions
are false
}

Flow of Control
1. The first if condition is checked.
2. If true,, its block executes and the rest
are skipped.
3. If false, the next else if is checked.
4. If all conditions are false, the else block (if present) executes.

Kamadhenu BCA College Object Oriented Programming using JAVA 38


Example Program
class ElseIfLadderExample {
public static void main(String args[]) {
int marks = 68;

if (marks >= 75) {


[Link]("Distinction");
}
else if (marks >= 60) {
[Link]("First Class");
}
else if (marks >= 50) {
[Link]("Second Class");
}
else if (marks >= 35) {
[Link]("Pass Class");
}
else {
[Link]("Fail");
}
}
}
Output:
First Class

The switch-case Statement in Java: The switch statement is used to select one action from
multiple alternatives based on the value of a variable or expression. It is an alternative to multiple if-else
statements when you have many discrete values to
check. Best for situations where a variable can have
many possible constant values.

Syntax
switch (expression) {
case value1:
// statements for value1
break;
case value2:
// statements for value2
break;
...
default:
// statements if none of the
above matches
}

Notes:
 expression → must return a byte, short, int,
char, String (Java 7+), or enum.
 break → prevents fall-through to the next
case.
 default → optional, executes if no case
matches.

Kamadhenu BCA College Object Oriented Programming using JAVA 39


Flow of Control
1. The expression is evaluated.
2. Control jumps to the matching case.
3. Executes statements until break or end of switch.
4. If no case matches, the default block executes.

Example Program
class SwitchExample {
public static void main(String args[]) {
int day = 3;

switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
default:
[Link]("Invalid day");
}
}
}

The ?: (Ternary) Operator in Java: The ternary operator is a shortcut for if-else statements. It
evaluates a condition and returns one value if true, another if false. Called ternary because it uses three
operands: condition, value if true, value if false.

Syntax
variable = (condition) ? value_if_true : value_if_false;
 condition → boolean expression (true or false)
 value_if_true → returned if condition is true
 value_if_false → returned if condition is false

Example Program
class TernaryExample {
public static void main(String args[]) {
int marks = 75;

String result = (marks >= 50) ? "Pass" : "Fail";

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


}
}

Kamadhenu BCA College Object Oriented Programming using JAVA 40


Output:
Result: Pass

 Here, marks >= 50 is true → "Pass" is assigned to result.


 If marks were less than 50 → "Fail" would be assigned.

Example of nested ternary:

int marks = 85;


String grade = (marks >= 75) ? "Distinction" :
(marks >= 50) ? "Pass" : "Fail";
[Link]("Grade: " + grade);

Output:
Grade: Distinction

Kamadhenu BCA College Object Oriented Programming using JAVA 41


Looping (Iteration) : Looping means repeating a set of instructions multiple times until a certain
condition becomes false. Instead of writing the same code repeatedly, we use loops to execute a block of
statements many times.

Example in real life:


“Write ‘Good Morning’ 5 times” — Instead of writing the statement five ti
times,
mes, you can use a loop to do it
automatically.

In programming terms:

for (int i = 1; i <= 5; i++) {


[Link]("Good Morning");

Key Looping Statements in Java:


 while loop
 do...while loop
 for loop
 Enhanced for loop (for arrays and collections)

While Loop
The while loop is a control structure that allows a set of statements to be executed repeatedly as long as a
given condition is true. It is also called an entry-controlled loop,, because the condition is checked
checke before
executing the loop body.

In simple words: “While the condition remains true, keep repeating


the statements.”

Usage:
 When the number of iterations is not known in advance.
 Commonly used for situations like:
o Reading data until the end of file.
o Waiting for user input until a valid response is
entered.
o Repeating an operation until a particular condition
changes.

Syntax:
while (condition) {
// Body of the loop
// Statements to be executed repeatedly

}
 condition → a logical or rela onal ex expression that controls the loop.
 If the condition is true,, the loop body executes.
 After execution, the condition is tested again.
 If the condition becomes false,, the loop terminates and control goes to the next statement
after the loop.

Example Program in Java:


// Program to print numbers from 1 to 5 using while loop
class WhileExample {
public static void main(String
(String args[]) {
int i = 1; // initialization
while (i <= 5) { // condition

Kamadhenu BCA College Object Oriented Programming using JAVA 42


[Link]("Number: " + i);
i++; // increment
}
}
}

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Do While
The do...while loop is a control structure used to execute a block of statements at least once, and
then repeatedly execute it as long as the given condition is true. Unlike the while loop, which
checks the condition before executing the loop body, the do...while loop checks the condition after
the loop body is executed.

Hence, it is known as a post-test loop or exit-


controlled loop.

In simple words: “Do something first, and then


check whether to repeat it.”

Usage:
 Used when the loop must execute at least
once, even if the condition is false initially.
 Commonly used for:
o Menu-driven programs.
o Input validation (e.g., asking user to
continue or stop).
o Repetitive tasks where the first
action must always happen.

Syntax:
do {
// Body of the loop
// Statements to be executed
} while (condition);

Note: The semicolon (;) at the end of the while statement is mandatory.

Example Program in Java:


// Program to print numbers from 1 to 5 using do...while loop
class DoWhileExample {
public static void main(String args[]) {
int i = 1; // initialization
do {
[Link]("Number: " + i);
i++; // increment
} while (i <= 5); // condition
}
}

Kamadhenu BCA College Object Oriented Programming using JAVA 43


Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Example 2: Demonstrating At Least One Execution


class DoWhileDemo {
public static void main(String args[]) {
int num = 10;
do {
[Link]("Inside loop once even if condition is
false.");
} while (num < 5);
}
}

Output:
Inside loop once even if condition is false.

Here, the condition num < 5 is false, but still the body runs once because the condition is tested after
execution.

For Loop : The for loop is a control structure that allows a block of statements to be executed repeatedly
for a fixed number of times. It is called an entry-controlled loop, because the condition is checked before
each iteration.

In simple words: “When you know exactly how many times you want to repeat a task, use a for loop.”

Usage:
 Used when the number of repetitions (iterations) is known in advance.
 Commonly used for:
o Printing a series of numbers.
o Calculating sums or factorials.
o Iterating through arrays or lists.
o Repeating a task a specific number of times.

Syntax:
for (initialization; condition; increment/decrement) {
// Body of the loop
// Statements to be executed repeatedly
}

Explanation of parts:
Part Description
Initialization Initializes loop control variable (executes once before loop starts).
Condition Tested before each iteration; if true → loop body executes.
Increment/Decrement Updates the control variable after each iteration.

Kamadhenu BCA College Object Oriented Programming using JAVA 44


Example Program in Java:

// Program to print numbers from 1 to 5 using


for loop
class ForExample {
public static void main
main(String args[]) {
for (int i = 1;
; i <= 5; i++) {
[Link](
[Link]("Number: " + i);
}
}
}

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Explanation:
1. Initialization: int i = 1; sets the starting value.
2. Condition: i <= 5 is checked — if true, the loop body executes.
3. Execution: [Link]("Number: " + i); prints the current value.
4. Increment: i++ increases the value of i by 1.
5. The process repeats until the condition becomes false.

Example 2: Printing Even Numbers


class EvenNumbers {
public static void main
main(String args[]) {
for (int i = 2;
; i <= 10; i = i + 2) {
[Link](i);
}
}
}

Output:
2
4
6
8
10

Example 3: Reverse Counting


class ReverseCount {
public static void main
main(String args[]) {
for (int i = 5;
; i >= 1; i--) {
[Link](
[Link]("Countdown: " + i);
}
}
}

Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1

Kamadhenu BCA College Object Oriented Programming using JAVA 45


Difference Between while, do...while, and for Loops

Feature while Loop do...while Loop for Loop


1. Type of Loop Entry-controlled loop Exit-controlled loop Entry-controlled loop
Condition is checked Condition is checked Condition is checked
2. Condition Checking before the loop body after the loop body before executing the
executes. executes. loop body.
May not execute even Executes at least once May not execute even
3. Minimum Execution once if condition is even if condition is false once if condition is false
false initially. initially. initially.
Number of iterations You want the loop to run Number of iterations is
4. Use When is not known in at least once regardless known in advance.
advance. of condition.
while do { ... } while for (init;
5. Syntax (condition) { (condition); condition; update)
... } { ... }
Done before the loop Done before the loop Done within the for
6. Initialization
separately. separately. loop header.
7. Increment / Done inside the loop Done inside the loop Done within the loop
Decrement body. body. header.
Suitable for simple Suitable for menu-driven Compact and clear for
8. Readability
indefinite loops. or input-validation tasks. definite loops.
9. Control Flow Type Pre-test loop Post-test loop Pre-test loop
while (i <= 5) do { ... } while (i for (i = 1; i <=
10. Example <= 5); 5; i++)

Enhanced for Loop (for Arrays and Collections) : The enhanced for loop (or for-each loop) is
used to access all elements of an array or collection one by one without using an index.
Type:
Simplified entry-controlled loop introduced in Java 1.5.

Syntax:
for (dataType variable : array_or_collection) {
// statements
}
Example:
int numbers[] = {10, 20, 30, 40, 50};
for (int n : numbers) {
[Link](n);
}

Output:
10
20
30
40
50

 Usage:
o To read or display elements of arrays and collections.
o Removes need for loop counters or index management.

Kamadhenu BCA College Object Oriented Programming using JAVA 46


 Limitations:
o Cannot modify elements directly.
o Cannot access element indexes.
 Best Use:
When you just need to traverse all elements sequentially.

Jump Statements in Java


Jump statements are used to alter the normal flow of execution in a program. They allow the
program to jump to another part of the code, skipping some statements or exiting loops/methods.

In simple terms: “Jump statements make the program skip, exit, or repeat sections of code based
on conditions.”

Types of Jump Statements in Java:


Statement Purpose
break Exits the current loop or switch immediately.
continue Skips the current iteration of a loop and moves to the next iteration.
return Exits from a method and optionally returns a value.
throw Exits from the normal flow by throwing an exception.

1. break Statement: To terminate the nearest enclosing loop or switch case immediately.
for (int i = 1; i <= 5; i++) {
if (i == 3)
break; // loop exits when i is 3
[Link](i);
}

Output:

1
2

2. continue Statement : To skip the current iteration and continue with the next iteration of the
loop.
for (int i = 1; i <= 5; i++) {
if (i == 3)
continue; // skips printing 3
[Link](i);
}

Output:
1
2
4
5

3. return Statement : Use: To exit a method and optionally return a value.


int square(int n) {
return n * n; // returns the square of n
}

4. throw Statement : To throw an exception when an error occurs.


if (age < 18) {
throw new ArithmeticException("Age must be 18 or above");
}

Kamadhenu BCA College Object Oriented Programming using JAVA 47


Key Points:
 Jump statements alter normal flow of execution.
 break/continue → used inside loops and switch.
 return → used inside methods to exit and op onally return a value.
 throw → used to handle excep onal situa ons.

Labeled Loops in Java: Labeled loops are used to control the flow of nested loops more
precisely. A label is an identifier placed before a loop to name it. Using this label, we can break out of or
continue a specific loop — not just the innermost one.

In simple words: “A label allows you to jump out of or continue a particular loop in nested loop
situations.”

Syntax:
labelname:
for (initialization; condition; increment) {
// Outer loop statements
for (initialization; condition; increment) {
// Inner loop statements
if (condition)
break labelname; // or continue labelname;
}
}

Example 1: Using break with Labeled Loop


class LabeledBreak {
public static void main(String args[]) {
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2)
break outer; // breaks the outer loop
[Link](i + " " + j);
}
}
[Link]("Loop ended.");
}
}

Output:
1 1
1 2
1 3
2 1
Loop ended.

Explanation:
When i == 2 and j == 2, the statement break outer; causes the outer loop to terminate immediately.

Example 2: Using continue with Labeled Loop


class LabeledContinue {
public static void main(String args[]) {
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2)
continue outer; // skips to next iteration of outer loop
[Link](i + " " + j);

Kamadhenu BCA College Object Oriented Programming using JAVA 48


}
}
}
Output:
11
21
31

Explanation: Whenever j == 2, control skips the rest of the inner loop and continues the next
iteration of the outer loop.

Key Points:
 A label must be followed by a colon (:) and placed just before the loop.
 Labels are used with break or continue only.
 Useful in nested loops when you need to exit or skip a specific loop.
 Avoid overusing labels as they can make code harder to read.

2 Marks Questions (Answer in brief)


(Conceptual / Definition / Syntax type)

1. What is the significance of bytecode in Java?


2. List any four features of Java.
3. What is the difference between JDK, JRE, and JVM?
4. Define variable and constant in Java.
5. What are Java tokens?
6. What is type casting in Java?
7. Write the syntax of a simple if statement in Java.
8. What is the use of the break statement?
9. Define a conditional (ternary) operator with an example.
10. What is a labeled loop in Java?

5 Marks Questions (Short Answer / Application-based)


(Explain with syntax or short program)

1. Explain how Java differs from C and C++.


2. Describe the structure of a simple Java program with an example.
3. Explain the various data types supported by Java.
4. What are symbolic constants? Explain with example.
5. Describe relational and logical operators with suitable examples.
6. Write a program to find the largest of three numbers using nested if-else statements.
7. Explain the working of the switch statement with a suitable example.
8. What is type conversion? Differentiate between implicit and explicit type casting.
9. Explain the while, do-while, and for loops with suitable examples.
10. Discuss the role of the Java Virtual Machine (JVM) in program execution.

Kamadhenu BCA College Object Oriented Programming using JAVA 49


10 Marks Questions (Descriptive / Program-based / Long Answer)
(Concept, Explanation, Example Program, and Output)

1. Explain in detail the features of Java and how they contribute to platform independence
and security.
2. Describe the complete process of writing, compiling, and executing a Java program,
including the role of the JVM.
3. Explain operators in Java. Discuss arithmetic, relational, logical, and bitwise operators with
examples.
4. Discuss decision-making and looping statements in Java with suitable examples for each.
5. Explain the Java environment setup (hardware/software requirements, JDK tools, and Java
support systems) with a neat diagram.

Kamadhenu BCA College Object Oriented Programming using JAVA 50


Unit II: OOPS with Class & Objects

Classes, Arrays, Strings and Vectors: Classes, Objects and Methods: Introduction, Defining a class, Adding
Variables, Adding Methods, Creating Objects, Accessing class members, Constructors, Methods Overloading,
Static Members, and Nesting of Methods.
Inheritance: Extending a class, Overriding Methods, Final Variables and Methods, Finalizer Methods,
Abstract Methods and Classes, Visibility Control. Arrays, Strings and Vectors: Arrays, One dimensional Array,
Creating an array, Two-dimensional Arrays, Strings, Vectors and Wrapper Classes.

Brief History of Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) emerged to make programming more intuitive and closer to real-
world modeling. In the 1960s, Simula, developed by Ole-Johan Dahl and Kristen Nygaard in Norway,
introduced the concept of classes and objects for simulation purposes, which is considered the first OOP
language.

In the 1970s, Smalltalk, developed at Xerox PARC, refined OOP concepts like encapsulation, inheritance,
and polymorphism, making them practical for general-purpose programming.

In the 1980s and 1990s, OOP gained widespread adoption with languages like C++ and Java, which provided
robust support for creating modular, reusable, and maintainable software. Today, OOP is a standard
paradigm in software development, especially in Java, C++, Python, and C#.

Key Milestones:
 1960s: Simula → First object-oriented language.
 1970s: Smalltalk → Refined OOP principles.
 1980s: C++ → OOP in general-purpose programming.
 1990s: Java → Pla orm-independent OOP language with widespread use.

Definition:
Object-Oriented Programming (OOP) is a programming paradigm that organizes software around
objects rather than functions or logic. In OOP, real-world entities are modeled as objects, which
contain data (attributes) and behavior (methods).

Definition in Simple Words:


“OOP is a way of programming where real-world entities are modeled as objects, containing data
(attributes) and behavior (methods), to make programs easier to understand, modify, and reuse.”

Key Features of OOP in Java


1. Class: A class is a blueprint or template for creating objects. It defines the attributes (fields)
and behaviors (methods) that the objects of that class will have. Classes help in organizing
code logically and provide a structure for objects.
2. Object: An object is a specific instance of a class representing a real-world entity. It has its
own state (values of attributes) and behavior (methods it can perform). Objects allow
programs to model real-world problems effectively.
3. Encapsulation :Encapsulation is the process of wrapping data and methods together in a
single unit, i.e., a class. It protects the internal state of an object from unauthorized access
using access modifiers and provides getter/setter methods for controlled access.

Kamadhenu BCA College Object Oriented Programming using JAVA 51


4. Abstraction: Abstraction hides the implementation details and shows only the essential
features of an object. It allows programmers to focus on what an object does rather than
how it does it, typically using abstract classes or interfaces.
5. Inheritance: Inheritance allows a class (child/subclass) to acquire the properties and
methods of another class (parent/superclass). It promotes code reusability and forms a
hierarchical relationship between classes.
6. Polymorphism: Polymorphism means “many forms.” In Java, it allows an object to behave
differently in different contexts. It occurs in two ways: compile-time (method overloading)
and runtime (method overriding), enabling flexibility and dynamic behavior.

Class in Java : A class in Java is a blueprint or template used to create objects. It defines the state
(attributes) and behavior (methods) that the objects of that class will have. Essentially, a class
encapsulates data and functions into a single unit.
In simple words: “A class is like a blueprint of a house — it defines how the house should be, but
the actual house is the object created from it.”

Syntax of a Class in Java:


class ClassName {
// Attributes (Fields)
dataType variable1;
dataType variable2;

// Methods (Behavior)
returnType methodName(parameters) {
// method body
}
}

 class → Keyword used to declare a class.


 ClassName → Name of the class (follows naming conven ons: starts with uppercase).
 Attributes → Variables represen ng the state of the object.
 Methods → Func ons represen ng the behavior of the object.

Example of a Class:
// Class to represent a Car
class Car {
// Attributes
String color;
String model;
int year;

// Method
void displayDetails() {
[Link]("Model: " + model);
[Link]("Color: " + color);
[Link]("Year: " + year);
}
}
Explanation:
 Car is the class name.
 color, model, year are attributes representing the car’s state.
 displayDetails() is a method that prints the car details — representing its behavior.
 This class does not occupy memory until an object is created.

Kamadhenu BCA College Object Oriented Programming using JAVA 52


Kamadhenu BCA College Object Oriented Programming using JAVA 53
Here’s a list of simple class examples in Java:

1. Car Class 2. Student Class


class Car { class Student {
String color; String name;
String model; int rollNo;
void display() { void showDetails() {
[Link](name + " - " + rollNo);
[Link](model + " - " + color);
}
} }
}
3. BankAccount Class 4. Book Class
class BankAccount { class Book {
String accountHolder; String title;
double balance; String author;
void displayBalance() { void displayInfo() {
[Link](accountHolder + ": " + balance); [Link](title + " by " + author);
} }
} }
5. Employee Class 6. Rectangle Class
class Employee { class Rectangle {
String name; int length, width;
int empId; int area() {
double salary; return length * width;
void display() { }
[Link](name + " - " + empId + " - " + salary); }
}}
7. Phone Class 8. Laptop Class
class Phone { class Laptop {
String brand; String model;
double price; int ram;
void showDetails() { void displaySpecs() {
[Link](brand + " - " + price); [Link](model + " with " + ram + "GB
} RAM");
} }
}
9. Teacher Class 10. Movie Class
class Teacher { class Movie {
String name; String title;
String subject; int duration;
void showInfo() { void showMovie() {
[Link](name + " teaches " + subject); [Link](title + " - " + duration + " mins");
} }
} }

Kamadhenu BCA College Object Oriented Programming using JAVA 54


Creating Objects of a Class in Java :
An object is a real-world entity that has state (data) and behavior (methods). For example, a Student object
may have attributes like name, roll number, and marks, and methods such as displayDetails() or
calculateResult(). Similarly, a Car object can have properties like color, model, and speed, and methods like
start(), accelerate(), and brake(). Another example is a BankAccount object, which may include attributes
such as accountNumber and balance, and methods like deposit() and withdraw(). Thus, objects represent
real-life entities and make programming more organized and modular.

It is an instance of a class, created using the new keyword in Java. Objects help in encapsulating data and
functions together in one unit. Each object has its own identity, attributes, and actions. Objects interact
with one another through method calls. They form the basic building blocks of Object-Oriented
Programming (OOP).

An object is a specific instance of a class. It occupies memory and has its own copy of attributes. Objects are
used to access class members (attributes and methods).

In simple terms: “If a class is a blueprint, an object is the actual house built from it.”

Syntax for Creating an Object:


ClassName objectName = new ClassName();

 ClassName → Name of the class.


 objectName → Reference variable to access the object.
 new → Keyword used to allocate memory for the object.
 ClassName() → Constructor of the class (default constructor is used if none defined).

Program for Creating an Object:

class Car {
String model;
String color;

void display() {
[Link](model + " - " + color);
}
}

class Main {
public static void main(String args[]) {
// Creating an object of Car
Car myCar = new Car();

// Setting attributes
[Link] = "Honda";
[Link] = "Red";

// Calling method
[Link]();
}
}

Output:
Honda - Red

Kamadhenu BCA College Object Oriented Programming using JAVA 55


Accessing Class Members: Class members include attributes (variables) and methods (functions)
defined in a class. Once an object of the class is created, you can access these members using the object.
Access control is determined by access modifiers like public, private, or protected.
In simple terms: “To use the data or functions of a class, you first create an object and then access its
members through that object.”

Syntax:
[Link];

 objectName → Reference variable of the object.


 memberName → Name of the variable or method of the class.

Example 1: Accessing Attributes


class Car {
String model;
String color;
}

class Main {
public static void main(String args[]) {
// Create object
Car myCar = new Car();

// Access and set attributes


[Link] = "Honda";
[Link] = "Red";

// Access and print attributes


[Link]("Model: " + [Link]);
[Link]("Color: " + [Link]);
}
}

Output:

Model: Honda
Color: Red

Arrays of Objects in Java: In Java, an array of objects is used to store multiple objects of the same class
in a single array. Each element of the array is a reference to an object, and memory for objects must be
allocated individually using the new keyword.

In simple words: “An array of objects is just like an array of variables, but each element holds a
reference to an object instead of a simple value.”

Syntax:
ClassName arrayName[] = new ClassName[size];

Then, for each element:

arrayName[i] = new ClassName();

Kamadhenu BCA College Object Oriented Programming using JAVA 56


Example: Array of Student Objects
import [Link];
class Student
{
String name;
int rollNo;

// Method to take input from user


void input() {
Scanner sc = new Scanner([Link]);
[Link]("Enter name: ");
name = [Link]();
[Link]("Enter roll number: ");
rollNo = [Link]();
}

// Method to display student details


void display() {
[Link]("Name: " + name + ", Roll No: " + rollNo);
}
}

class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter number of students: ");
int n = [Link]();

// Create array of Student objects


Student students[] = new Student[n];

// Input details for each student


for (int i = 0; i < n; i++)
{
[Link]("\nEnter details of student " + (i + 1) + ":");
students[i] = new Student();
students[i].input();
}

// Display details of each student


[Link]("\n--- Student Details ---");
for (int i = 0; i < n; i++)
{
students[i].display();
}
[Link]();
}
}

Sample Output:
Enter number of students: 2

Enter details of student 1:


Enter name: Ravi
Enter roll number: 101

Kamadhenu BCA College Object Oriented Programming using JAVA 57


Enter details of student 2:
Enter name: Meena
Enter roll number: 102

--- Student Details ---


Name: Ravi, Roll No: 101
Name: Meena, Roll No: 102

Constructors in Java : A constructor is a special method in a class that is automatically invoked


when an object of that class is created. It is mainly used to initialize the object’s data members when
the object is created.

Key Points:
1. The name of the constructor is the same as the class name.
2. It does not have any return type, not even void.
3. Constructors are automatically called when an object is created.
4. There can be more than one constructor in a class (constructor overloading).
5. If no constructor is defined, Java provides a default constructor automatically.

Syntax:
class ClassName {
ClassName() {
// constructor body
}
}

Example:
class Student {
int rollNo;
String name;

// Constructor
Student() {
rollNo = 1;
name = "Default Student";
}

void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
}

class Main {
public static void main(String args[]) {
Student s1 = new Student(); // constructor called automatically
[Link]();
}
}

Output:
Roll No: 1, Name: Default Student

Kamadhenu BCA College Object Oriented Programming using JAVA 58


Types of Constructors in Java

In Java, constructors are mainly of three types:


1. Default Constructor:
2. Parameterized Constructor
3. Copy Constructor

Default Constructor: A default constructor is the one that does not take any parameters.
It is used to assign default values to object members. If no constructor is defined, Java automatically
provides a default one.

Example:

class Student {
int rollNo;
String name;

// Default constructor
Student() {
rollNo = 1;
name = "Unknown";
}

void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
}

class Main {
public static void main(String args[]) {
Student s1 = new Student(); // default constructor called
[Link]();
}
}

Parameterized Constructor : A parameterized constructor accepts arguments and is used to


initialize objects with user-defined values at the time of creation.

Example:

class Student {
int rollNo;
String name;

// Parameterized constructor
Student(int r, String n) {
rollNo = r;
name = n;
}

void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}

Kamadhenu BCA College Object Oriented Programming using JAVA 59


}
class Main {
public static void main(String args[]) {
Student s1 = new Student(101, "Amit");
Student s2 = new Student(102, "Priya");

[Link]();
[Link]();
}
}

Copy Constructor: Java does not have an inbuilt copy constructor like C++, but we can create one
manually to copy data from one object to another.

Example:

class Student {
int rollNo;
String name;

// Parameterized constructor
Student(int r, String n) {
rollNo = r;
name = n;
}

// Copy constructor
Student(Student s) {
rollNo = [Link];
name = [Link];
}

void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
}

class Main {
public static void main(String args[]) {
Student s1 = new Student(101, "Rahul");
Student s2 = new Student(s1); // copy constructor called

[Link]();
[Link]();
}
}

Summary Table
Type of Constructor Parameters Purpose Example of Use
Default Constructor No Assigns default values Student s = new
Student();
Parameterized Constructor Yes Initialize with given Student s = new
values Student(101, "Amit");
Copy Constructor Yes (object) Copy data from another Student s2 = new
object Student(s1);

Kamadhenu BCA College Object Oriented Programming using JAVA 60


Method Overloading: Method Overloading in Java means defining multiple methods with the same
name in a class but with different parameters (number, type, or order of parameters).
It is a form of compile-time polymorphism (also called static binding).
Key Points:
1. Methods must have the same name but different parameter lists.
2. The return type may be same or different — it does not affect overloading.
3. Overloading helps in code reusability and readability.
4. The compiler decides which method to call based on the arguments passed.
Syntax:
class ClassName {
void display(int a) { ... }
void display(int a, int b) { ... }
}

Example:
class Addition {
// Method with one parameter
void add(int a) {
[Link]("Sum = " + (a + 10));
}

// Overloaded method with two parameters


void add(int a, int b) {
[Link]("Sum = " + (a + b));
}

// Overloaded method with double parameters


void add(double a, double b) {
[Link]("Sum = " + (a + b));
}
}

class Main {
public static void main(String args[]) {
Addition obj = new Addition();
[Link](5); // calls add(int)
[Link](10, 20); // calls add(int, int)
[Link](4.5, 3.2); // calls add(double, double)
}
}

Output:
Sum = 15
Sum = 30
Sum = 7.7

Advantages of Method Overloading:


 Increases program readability.
 Allows same method name for different purposes.
 Supports compile-time polymorphism.

Kamadhenu BCA College Object Oriented Programming using JAVA 61


Overloading area() Method
class Area {
// Calculate area of square
void area(int side) {
[Link]("Area of square: " + (side * side));
}

// Calculate area of rectangle


void area(int length, int breadth) {
[Link]("Area of rectangle: " + (length * breadth));
}

// Calculate area of circle


void area(double radius) {
[Link]("Area of circle: " + (3.14 * radius * radius));
}

public static void main(String args[]) {


Area obj = new Area();
[Link](5); // square
[Link](5, 10); // rectangle
[Link](2.5); // circle
}
}

Output:

Area of square: 25
Area of rectangle: 50
Area of circle: 19.625

Static Members in Java : In Java, the keyword static is used to define class-level members — that is,
variables and methods that belong to the class, not to any specific object. Static members are shared by all
objects of that class and can be accessed without creating an object.

1. Static Variables (Class Variables) : A static variable is common to all objects of a class. It is created
only once in memory, regardless of how many objects exist.

Example:
class Student {
int rollNo;
String name;
static String college = "ABC College"; // static variable

Student(int r, String n) {
rollNo = r;
name = n;
}

void display() {
[Link](rollNo + " " + name + " " + college);
}

public static void main(String args[]) {


Student s1 = new Student(101, "Amit");
Student s2 = new Student(102, "Priya");
[Link]();
[Link]();
}

Kamadhenu BCA College Object Oriented Programming using JAVA 62


}
Output:
101 Amit ABC College
102 Priya ABC College

Note : Here, both students share the same college name, since it is static.

2. Static Methods : A static method belongs to the class rather than to objects. It can be called without
creating an object, using the class name.

Rules:
 Static methods can access only static variables and other static methods directly.
 They cannot use this or super keywords.

Example:

class MathUtility {
static int square(int x) {
return x * x;
}

public static void main(String args[]) {


[Link]("Square = " + [Link](5)); // called using
class name
}
}
Output:
Square = 25

3. Static Blocks : A static block is used to initialize static variables. It executes only once, when the class
is loaded into memory.

Example:

class Example {
static int count;

static {
count = 100;
[Link]("Static block executed");
}

public static void main(String args[]) {


[Link]("Count = " + count);
}
}

Output:

Static block executed


Count = 100

Summary Table
Static Member Description Accessed By Usage
Static Variable Shared by all objects [Link] Common data for all objects
Static Method Belongs to class [Link]() Utility or helper methods
Static Block Runs once when class loads Automatically Initialize static data

Kamadhenu BCA College Object Oriented Programming using JAVA 63


Nesting of Methods: Nesting of methods means calling one method from another method within the
same class. It helps in code reusability, modularity, and makes programs easier to manage by breaking large
tasks into smaller ones.

Key Points:
1. One method can call another method directly if it is in the same class.
2. If the called method is in a different class, it must be accessed using an object.
3. The method call is usually made using its name only, without the object reference (when
inside the same class).

Syntax:
class ClassName {
void method1() {
// statements
method2(); // calling another method
}

void method2() {
// statements
}
}

Example:
class Calculation {
void input() {
int a = 5, b = 10;
display(sum(a, b)); // calling sum() and display() methods
}

int sum(int x, int y) {


return x + y; // returns sum
}

void display(int result) {


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

public static void main(String args[]) {


Calculation obj = new Calculation();
[Link](); // starts the chain of method calls
}
}

Output:
Sum = 15

Kamadhenu BCA College Object Oriented Programming using JAVA 64


Inheritance in Java: Inheritance is an OOP concept where a class (called child/subclass)
acquires the properties and behaviors of another class (called parent/superclass).
parent/superclass It promotes code
reusability and establishes a hierarchical relationship between classes.

In simple words: “Inheritance allows a new class to use the fields and methods of an existing class
without rewriting the code.”

Advantages of Inheritance:
1. Code reusability – avoids rewriting common code.
2. Method overriding – allows runtime polymorphism.
3. Extensibility – easy to add new features without affecting existing code.
4. Hierarchical organization – models real-world
world relationships effectively.

Key Points:
1. Parent class / Superclass → The class whose features are inherited.
2. Child class / Subclass → The class that inherits the features of the parent class.
3. Java supports single, multilevel, and hierarchical inheritance
inheritance.
4. Java does not support multiple inheritance using classes (can be achieved
chieved with interfaces).

Syntax:
class Parent {
// fields and methods
}

class Child extends Parent {


// additional fields and methods
}

 extends → Keyword used to inherit from a parent class.

Kamadhenu BCA College Object Oriented Programming using JAVA 65


Example: Single Inheritance
class Animal {
void eat() {
[Link]("Animal eats food");
}
}

class Dog extends Animal {


void bark() {
[Link]("Dog barks");
}
}

class Main {
public static void main(String args[]) {
Dog d = new Dog();
[Link](); // inherited method
[Link](); // own method
}
}

Output:

Animal eats food


Dog barks

Types of Inheritance in Java: Inheritance allows a class to acquire properties and methods of another
class. Java supports four main types of inheritance:
Type Description Example
Single A child inherits from one class Dog extends Animal
parent class
Multilevel A class inherits from a subclass, class Puppy extends Dog
forming a chain
Hierarchical Multiple subclasses inherit class Cat extends Animal,
from one parent class Dog extends Animal
Multiple (via Interfaces) One class implements multiple class A implements X, Y
interfaces

Single Inheritance: Single Inheritance means that a child (subclass) inherits properties and
behaviors (methods and variables) from only one parent (superclass). This allows the subclass to
reuse and extend the functionality of the parent without rewriting the same code. It creates a
simple and clear hierarchy, making the program easier to understand and maintain. For example, a
Car class can inherit from a Vehicle class to gain all its common features like speed and fuel type,
while adding its own specific features like number of doors or model name.

Example:
class Student {
String name;
int rollNo;

void displayStudent() {
[Link]("Name: " + name + ", Roll No: " + rollNo);
}}

Kamadhenu BCA College Object Oriented Programming using JAVA 66


class Exam extends Student {
int marks;

void displayExam() {
[Link]("Marks: " + marks);
}
}

class Main {
public static void main(String args[]) {
Exam e = new Exam();
[Link] = "Ravi";
[Link] = 101;
[Link] = 85;

[Link](); // inherited Another Example


[Link](); // own method
}
}

Output:
Name: Ravi, Roll No: 101
Marks: 85

Multilevel Inheritance: occurs when a class is derived from another subclass, forming a chain of
inheritance. In this type, features of the base class are passed to the derived class, and then further
to another subclass. This allows gradual enhancement and reuse of code across multiple levels. For
example, if Animal is the base class, Mammal can inherit from Animal, and Dog can inherit from
Mammal. Thus, Dog gets the properties of both Mammal and Animal.

Example:

class Student {
String name;
int rollNo;

void displayStudent() {
[Link]("Name: " + name + ", Roll No: " + rollNo);
}
}

class Exam extends Student {


int marks;

void displayExam() {
[Link]("Marks: " + marks);
}
}

class Result extends Exam {


String grade;

void displayResult() {
[Link]("Grade: " + grade);
}
}

Kamadhenu BCA College Object Oriented Programming using JAVA 67


class Main {
public static void main(String args[]) {
Result r = new Result();
[Link] = "Meena";
[Link] = 102;
[Link] = 90;
[Link] = "A";

[Link](); // from Student


[Link](); // from Exam
[Link](); // own method
}
}
Output:
Name: Meena, Roll No: 102
Marks: 90
Grade: A

Hierarchical Inheritance: It occurs when two or more child classes inherit from the same
parent class. This allows multiple subclasses to share the common properties and methods of a
single base class, while also defining their own specific features. It promotes code reuse and
organized structure. For example, if Animal is the parent class, then Dog, Cat, and Horse can each
inherit from Animal, sharing common traits like eat() or sleep(), but having their own unique
behaviors.
class Student {
String name;
int rollNo;

void displayStudent() {
[Link]("Name: " + name + ", Roll No: " + rollNo);
}
}

class Exam extends Student {


int marks;

void displayExam() {
[Link]("Marks: " + marks);
}
}

class Sports extends Student {


String game;

void displaySports() {
[Link]("Game: " + game);
}
}

class Main {
public static void main(String args[]) {
Exam e = new Exam();
[Link] = "Kiran";
[Link] = 103;
[Link] = 75;

Sports s = new Sports();


[Link] = "Amit";
[Link] = 104;
[Link] = "Football";

Kamadhenu BCA College Object Oriented Programming using JAVA 68


[Link]();
[Link]();

[Link]();
[Link]();
}
}

4. Multiple Inheritance (via Interfaces) : Java does not support multiple inheritance with classes (to
avoid ambiguity). Achieved using interfaces where a class can implement multiple interfaces.

interface Academic {
void displayMarks();
}

interface Activity {
void displayGame();
}

class StudentDemo implements Academic, Activity {


String name;
int rollNo;
int marks;
String game;

public void displayMarks() {


[Link]("Name: " + name + ", Roll No: " + rollNo + ",
Marks: " + marks);
}

public void displayGame() {


[Link]("Name: " + name + ", Game: " + game);
}
}
class Main {
public static void main(String args[]) {
StudentDemo sd = new StudentDemo();
[Link] = "Priya";
[Link] = 105;
[Link] = 92;
[Link] = "Basketball";

[Link]();
[Link]();
}
}

Output:
Name: Priya, Roll No: 105, Marks: 92
Name: Priya, Game: Basketball

More on this is explained in interface unit.

Kamadhenu BCA College Object Oriented Programming using JAVA 69


Method Overriding in Java: Method Overriding happens when a subclass defines a method with the
same name, return type, and parameters as a method in its superclass, but provides its own
implementation. This allows the subclass to modify or extend the behavior of the parent class method. It is
an essential part of runtime polymorphism in Java, enabling dynamic method calls based on the actual
object being referred to. For example, if the superclass Animal has a method makeSound(), and the subclass
Dog overrides it, calling makeSound() on a Dog object will execute the Dog version of the method.

In simple words: “The child class redefines a method of the parent class with the same name,
parameters, and return type.”

Key Points:
1. The method name, return type, and parameters must be exactly the same.
2. The access level in the child class cannot be more restrictive than the parent class.
3. Private, static, and final methods cannot be overridden.
4. Use @Override annotation (optional but recommended) for compile-time checking.

Syntax:
class Parent {
void method() {
// parent method
}
}

class Child extends Parent {


@Override
void method() {
// child method
}
}

Example 1: Using Student Class


class Student {
void display() {
[Link]("This is a student.");
}
}

class Exam extends Student {


@Override
void display() {
[Link]("This student has appeared for an exam.");
}
}

class Main {
public static void main(String args[]) {
Student s = new Student();
[Link](); // calls parent method

Exam e = new Exam();


[Link](); // calls overridden method in child class
}
}

Output:
This is a student.
This student has appeared for an exam.

Kamadhenu BCA College Object Oriented Programming using JAVA 70


Final Variables and Methods:

Final Variables in Java are constants whose values cannot be changed once they are initialized. When a
variable is declared with the final keyword, it must be assigned a value only once, either at the time of
declaration or inside the constructor. Final variables are often used to define fixed values or constants that
should remain the same throughout the program, such as final double PI = 3.14159;. This helps make code
more reliable and easier to maintain..

Types of final variables:


1. Local final variable – defined inside a method.
2. Instance final variable – defined in a class but outside methods.
3. Static final variable – shared by all objects, like a constant.

Syntax:
final int MAX = 100; // constant variable

Example:
class Student {
final int maxMarks = 100; // final instance variable

void display() {
[Link]("Maximum Marks = " + maxMarks);
// maxMarks = 120; // Error: cannot assign a value to final variable
}

public static void main(String args[]) {


Student s = new Student();
[Link]();
}
}
Output:
Maximum Marks = 100

Final Methods: In Java, a method declared with the final keyword cannot be overridden by any subclass.
This ensures that the original implementation of the method remains unchanged and cannot be modified in
derived classes. It is mainly used to preserve important or core functionality that should not be altered. For
example, declaring final void show() in a parent class prevents subclasses from providing their own version of
the show() method..

Syntax:
class Parent {
final void display() {
[Link]("Final method in Parent");
}
}

Example:
class Student {
final void info() {
[Link]("This is a final method.");
}
}

class Exam extends Student {


// void info() { [Link]("Cannot override final method"); } //
Error
}

Kamadhenu BCA College Object Oriented Programming using JAVA 71


class Main {
public static void main(String args[]) {
Exam e = new Exam();
[Link]();
}
}
Output:
This is a final method.

Key Points:
Final Member Purpose / Rule
Final Variable Value cannot be changed once assigned
Final Method Cannot be overridden in subclass
Final Class Cannot be inherited (no subclass can extend it)

Kamadhenu BCA College Object Oriented Programming using JAVA 72


Finalizer Methods: A finalizer method (finalize()) is called automatically by the garbage collector before
an object is destroyed. It is used to clean up resources like closing files or network connections.

Key Points:
1. Declared as: protected void finalize() throws Throwable
2. Called by Garbage Collector before object removal.
3. Not guaranteed to run immediately.
4. Deprecated in Java 9; use try-with-resources or Cleaner instead.
Example:
class Student {
String name;

Student(String n) {
name = n;
[Link]("Student created: " + name);
}

protected void finalize() throws Throwable {


[Link]("Student destroyed: " + name);
}
}

class Main {
public static void main(String args[]) {
Student s1 = new Student("Ravi");
s1 = null;
[Link](); // request garbage collection
[Link]("End of main");
}
}

Sample Output:

Student created: Ravi


End of main
Student destroyed: Ravi

Abstract Methods and Classes in Java: An abstract class is a class that cannot be
instantiated directly and may contain abstract methods. An abstract method is a method without a
body; it only has a method signature. Abstract classes are used to provide a base class with common
behavior while leaving specific implementations to subclasses.
Key Points:
1. Declared using the keyword abstract.
2. Cannot create objects of an abstract class.
3. Abstract classes may have concrete methods (methods with body) as well as abstract methods.
4. Subclasses must override abstract methods unless the subclass is also abstract.

Syntax:
abstract class ClassName {
abstract void methodName(); // abstract method
void normalMethod() { // concrete method
// method body
}
}

Kamadhenu BCA College Object Oriented Programming using JAVA 73


Example: Student Class
abstract class Student {
String name;

Student(String n) {
name = n;
}

// Abstract method
abstract void examDetails();

// Concrete method
void displayName() {
[Link]("Student Name: " + name);
}
}

class Exam extends Student {


int marks;

Exam(String n, int m) {
super(n);
marks = m;
}

// Implement abstract method


void examDetails() {
[Link]("Marks: " + marks);
}
}

class Main {
public static void main(String args[]) {
// Student s = new Student("Ravi"); // Error: cannot instantiate
Exam e = new Exam("Ravi", 85);
[Link]();
[Link]();
}
}

Output:

Student Name: Ravi


Marks: 85

Visibility Control in Java: Visibility control in Java determines which classes or objects can access
members (variables or methods) of a class. It is achieved using access modifiers, which control access levels
for data and methods to ensure encapsulation.

Access Modifiers in Java


Modifier Where Accessible Description
private Within the same class only Members cannot be accessed outside the
class.
default (no modifier) Within the same package only Members are accessible by all classes in the
same package.
protected Same package + subclasses Allows inheritance access and package
(even in different packages) access.
public Anywhere Members are accessible from any class or
package.

Kamadhenu BCA College Object Oriented Programming using JAVA 74


Example: Using Student Class
class Student {
private int rollNo; // private: only in class
String name; // default: same package
protected int marks; // protected: package + subclasses
public String course; // public: anywhere

// Constructor
Student(int r, String n, int m, String c) {
rollNo = r;
name = n;
marks = m;
course = c;
}

// Getter for private variable


int getRollNo() {
return rollNo;
}

void display() {
[Link]("RollNo: " + rollNo + ", Name: " + name +
", Marks: " + marks + ", Course: " + course);
}
}

class Main {
public static void main(String args[]) {
Student s = new Student(101, "Ravi", 85, "Java");
// [Link]([Link]); // Error: private
[Link]([Link]()); // Allowed via getter
[Link]([Link]); // default
[Link]([Link]); // protected (same package)
[Link]([Link]); // public
}
}

Output:
101
Ravi
85
Java

Key Points:
1. Encapsulation: Hides data from unauthorized access.
2. Use private for sensitive variables and provide getter/setter methods.
3. protected is mainly used to allow inheritance access.
4. public members are fully accessible everywhere.

Arrays in Java: An array is a collection of elements of the same data type stored in contiguous
memory locations. It allows storing multiple values under a single variable name and accessing them
using an index.

Types of Arrays:
1. One-Dimensional Array – Stores elements in a single row (e.g., marks of students).
2. Two-Dimensional Array – Represents data in rows and columns (e.g., a matrix).

Kamadhenu BCA College Object Oriented Programming using JAVA 75


3. Multidimensional Array – An array of arrays, used for complex data structures like 3D matrices.

Declaring and Initializing Arrays

1D Array : A one-dimensional (1D) array in Java is a collection of elements of the same data type stored in
contiguous memory locations and accessed using a single index
Declaration:
int[] marks; // or int marks[];

Initialization:
marks = new int[5]; // size 5, default values 0
int[] marks = {85, 90, 75}; // directly initialize with values

2D Array : A two-dimensional (2D) array in Java is an array of arrays, used to store data in rows and columns
(like a table or matrix).

Declaration:
int[][] matrix; // or int matrix[][];

Initialization:
matrix = new int[3][3]; // 3x3 matrix, default 0
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}}; // directly initialize

1D Array Example
class Main {
public static void main(String args[]) {
// Declaration & Initialization
int[] marks = {85, 90, 75, 60};

// Display array elements


[Link]("Marks of students:");
for(int i = 0; i < [Link]; i++) {
[Link]("Student " + (i+1) + ": " + marks[i]);
}
}
}

Output:
Marks of students:
Student 1: 85
Student 2: 90
Student 3: 75
Student 4: 60

2D Array Example
class Main {
public static void main(String args[]) {
// Declaration & Initialization
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};

// Display 2D array elements


[Link]("Matrix:");
for(int i = 0; i < [Link]; i++) {
for(int j = 0; j < matrix[i].length; j++) {

Kamadhenu BCA College Object Oriented Programming using JAVA 76


[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}

Output:

Matrix:
1 2 3
4 5 6
7 8 9

Key Points:
 Arrays are homogeneous (same data type).
 1D array is like a list, 2D array is like a table.
 Index starts from 0.
 Arrays are fixed in size once created.

Strings in Java: A String is an object that represents a sequence of characters. Strings are immutable,
which means that once a String object is created, its value cannot be changed. Any modification, like
concatenation or replacement, creates a new String object rather than altering the existing one.

For example, if String s = "Hello"; and you do s = s + " World";, a new String object "Hello World" is created, and s
now refers to this new object. This immutability makes strings thread-safe and efficient for many operations.

Common String Methods


Method Description Example
length() Returns number of characters "Ravi".length() → 4
charAt(index) Returns character at given index "Ravi".charAt(1) → 'a'
concat(str) Concatenates two strings "Ravi".concat(" Kumar")
→ "Ravi Kumar"
substring(start,end) Extracts substring "Ravi".substring(1,3) → "av"
equals(str) Compares two strings "Ravi".equals("Ravi") → true
toUpperCase() / Converts case "Ravi".toUpperCase() → "RAVI"
toLowerCase()
trim() Removes leading/trailing spaces " Ravi ".trim() → "Ravi"
replace(oldChar,newChar) Replaces characters "Ravi".replace('a','o') → "Rovi"
indexOf(char) Returns index of first occurrence "Ravi".indexOf('i') → 3

Example:

class Main {
public static void main(String args[]) {
String name = "Ravi Kumar";
[Link]("Length: " + [Link]());
[Link]("Character at 2: " + [Link](2));
[Link]("Uppercase: " + [Link]());
[Link]("Substring: " + [Link](0,4));
[Link]("Replace: " + [Link]('a','o'));
}
}

Output:

Kamadhenu BCA College Object Oriented Programming using JAVA 77


Length: 10
Character at 2: v
Uppercase: RAVI KUMAR
Substring: Ravi
Replace: Rovi Kumor

StringBuffer Class in Java: StringBuffer is a mutable sequence of characters, meaning you can
modify the contents of the string without creating a new object. It is thread-safe and part of [Link]
package.

Creating StringBuffer:

StringBuffer sb1 = new StringBuffer("Ravi");


StringBuffer sb2 = new StringBuffer(); // empty buffer

Common StringBuffer Methods


Method Description Example
append(str) Adds string at the end [Link](" Kumar")
insert(index,str) Inserts string at specified index [Link](4," XYZ")
replace(start,end,str) Replaces substring [Link](0,4,"John")
delete(start,end) Deletes substring [Link](0,4)
reverse() Reverses the buffer [Link]()
length() Returns length of buffer [Link]()
charAt(index) Returns character at index [Link](2)
setCharAt(index,ch) Replaces character at index [Link](0,'J')

Example:

class Main {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Ravi");
[Link](" Kumar");
[Link](4," XYZ");
[Link](0,4,"John");
[Link](8,12);
[Link]();
[Link](sb);
}
}
Output:
ramuHZY nhoJ

Key Points:
1. String → immutable, new object created on modifica on.
2. StringBuffer → mutable, modifies original object.

Vectors in Java: A Vector is a dynamic array that can automatically grow or shrink as elements are
added or removed. It is part of the [Link] package and is synchronized, which means it is thread-safe and
can be safely used in multi-threaded programs. Unlike a regular array, you don’t need to specify its size in
advance, and it provides methods like add(), remove(), get(), and size() to manipulate elements efficiently
Key Features:
1. Can store objects of any type.
2. Dynamic size unlike arrays.
3. Provides methods for adding, removing, and accessing elements.
4. Synchronized, so safe for multithreaded operations.

Kamadhenu BCA College Object Oriented Programming using JAVA 78


Creating a Vector
import [Link];

Vector<Integer> v1 = new Vector<>(); // empty vector


Vector<String> v2 = new Vector<>(10); // initial capacity 10

Common Methods
Method Description Example
add(element) Adds element at the end [Link](100);
add(index,element) Adds element at specific index [Link](1,200);
remove(index) Removes element at index [Link](0);
get(index) Returns element at index [Link](2);
size() Returns number of elements [Link]();
contains(element) Checks if element exists [Link](100);
clear() Removes all elements [Link]();
set(index, element) Replaces element at index [Link](1,300);

Example: Vector of Students


import [Link];

class Student {
String name;
int rollNo;

Student(String n, int r) {
name = n;
rollNo = r;
}

void display() {
[Link]("Name: " + name + ", Roll No: " + rollNo);
}
}

class Main {
public static void main(String args[]) {
Vector<Student> students = new Vector<>();

// Adding Student objects


[Link](new Student("Ravi", 101));
[Link](new Student("Meena", 102));
[Link](new Student("Kiran", 103));

// Display students
for(Student s : students) {
[Link]();
}

// Remove a student
[Link](1); // removes Meena
[Link]("After removal:");
for(Student s : students) {
[Link]();
}
}
}

Output:

Name: Ravi, Roll No: 101


Name: Meena, Roll No: 102

Kamadhenu BCA College Object Oriented Programming using JAVA 79


Name: Kiran, Roll No: 103
After removal:
Name: Ravi, Roll No: 101
Name: Kiran, Roll No: 103

Key Points:
1. Vector is like a dynamic array with automatic resizing.
2. Supports object storage, thread-safe, and legacy collection.
3. Can be replaced by ArrayList in modern applications for better performance if
synchronization is not needed.

Wrapper Classes in Java: A wrapper class in Java provides a way to use primitive data types as objects.
Every primitive type has a corresponding wrapper class in [Link] package.

 Primitive Types: int, char, double, boolean, etc.


 Wrapper Classes: Integer, Character, Double, Boolean, etc.

Wrapper classes are useful when objects are required, for example in Collections (Vector,
ArrayList), which cannot store primitives directly.

Primitive ↔ Wrapper Mapping


Primitive Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Autoboxing and Unboxing

Autoboxing: Automatic conversion from primitive → wrapper object


Integer i = 10; // int 10 is automatically converted to Integer object

Unboxing: Automatic conversion from wrapper object → primi ve


int j = i; // Integer object converted to int

Example: Wrapper Class for Integer and Double


class Main {
public static void main(String args[]) {
// Autoboxing: primitive → wrapper object
Integer a = 25;
Double b = 12.5;

// Unboxing: wrapper object → primitive


int x = a;
double y = b;

// Using wrapper class methods


String str = "100";

Kamadhenu BCA College Object Oriented Programming using JAVA 80


int num = [Link](str); // convert String to int
double d = [Link]("45.6"); // convert String to double

[Link]("Integer object: " + a);


[Link]("Double object: " + b);
[Link]("Primitive int: " + x);
[Link]("Primitive double: " + y);
[Link]("String to int: " + num);
[Link]("String to double: " + d);
}
}

Output:
Integer object: 25
Double object: 12.5
Primitive int: 25
Primitive double: 12.5
String to int: 100
String to double: 45.6

2 Marks Questions (Answer in brief)


(Conceptual / Definition / Syntax type)
1. Define a class and object in Java.
2. What is the purpose of a constructor in Java?
3. Differentiate between method overloading and method overriding.
4. What are static members in Java?
5. What is an abstract class?
6. Define a one-dimensional array with an example.
7. What is a vector in Java?
8. Write the syntax to declare and initialize a string.
9. What is the difference between a class and an interface?
10. What are wrapper classes in Java? Give examples.

5 Marks Questions (Short Answer / Application-based)


(Explain with syntax or short program)
1. Explain the steps involved in defining a class and creating its objects with an example.
2. Describe method overloading with an example Java program.
3. What are final variables and final methods? Explain with examples.
4. Discuss visibility control in Java.
5. Explain the concept of inheritance in Java with a suitable example.
6. What are arrays in Java? Explain one-dimensional and two-dimensional arrays.
7. What are constructors? Explain types of constructors in Java.
8. Explain how strings are created and manipulated in Java.
9. What are vectors? Explain their main methods and uses.
10. Explain the difference between arrays and vectors with examples.

Kamadhenu BCA College Object Oriented Programming using JAVA 81


10 Marks Questions (Descriptive / Program-based / Long Answer)
(Concept, Explanation, Example Program, and Output)

1. Explain in detail the concepts of classes, objects, and methods with a complete Java
program demonstrating all.
2. Discuss inheritance in Java. Explain how to extend a class, override methods, and use the
super keyword with examples.
3. Explain the concept of abstract classes and final methods in Java. How are they used in
object-oriented programming?
4. What are arrays, strings, and vectors in Java? Compare their features and illustrate each
with a suitable example.
5. Explain method overloading and nesting of methods with a program that demonstrates
both.

Kamadhenu BCA College Object Oriented Programming using JAVA 82


Unit III: Interfaces, Packages & Multithreading
Interfaces, Packages, and Multithreaded Programming: Interfaces: Multiple Inheritances: Introduction,
Defining Interfaces, Extending Interfaces, Implementing Interfaces, Accessing Interface Variables Putting
Classes together. Packages:: Introduction, Java API Packages, Using System Packages, Naming
Conventions, Creating Packages, Accessing a Package, Using a Package, Adding a Class to a Package,
Hiding Classes.

Multithreaded Programming: Introduction, Creating Threads, Extending the Thread Class, Stopping and
Blocking a thread, Life Cycle of a thread, Using Thread Methods, Thread Exceptions, Thread Priority,
Synchronization, Implementing the Runnable Interface.

Multiple Inheritances: Java does not support multiple inheritances with classes to avoid
ambiguity (diamond problem). Interfaces provide a way to achieve multiple inheritance because a
class can implement multiple interfaces. Interfaces can contain abstract methods, constants, and
in modern Java, default, static, and private methods.

Defining Interfaces
 Declared using the keyword interface.
 Members are public and abstract by default.
 Variables are public, static, and final by default.

Syntax:
interface InterfaceName {
int MAX = 100; // constant
void method1(); // abstract method
void method2(); // abstract method
}

Extending Interfaces
 One interface can extend another interface using the extends keyword.
 Supports multiple inheritance between interfaces.

Syntax:

interface Exam {
void displayMarks();
}

interface Result extends Exam {


void displayResult();
}

Implementing Interfaces
 A class implements an interface using the implements keyword.
 If a class implements multiple interfaces, separate them by comma.
 The class must override all abstract methods of the interfaces.

Kamadhenu BCA College Object Oriented Programming using JAVA 83


Example:

interface Exam {
void displayMarks();
}

interface Result {
void displayResult();
}

class Student implements Exam, Result {


String name;
int marks;

Student(String n, int m) {
name = n;
marks = m;
}

public void displayMarks() {


[Link]("Marks of " + name + " = " + marks);
}

public void displayResult() {


if(marks >= 50)
[Link](name + " has Passed");
else
[Link](name + " has Failed");
}
}

class Main {
public static void main(String args[]) {
Student s = new Student("Ravi", 85);
[Link]();
[Link]();
}
}

Output:

Marks of Ravi = 85
Ravi has Passed

Example: Student and Exam Interface


interface Exam {
void displayMarks();
void displayResult();
}
class Student implements Exam {
String name;
int marks;

Student(String n, int m) {
name = n;
marks = m;
}

Kamadhenu BCA College Object Oriented Programming using JAVA 84


// Implementing interface methods
public void displayMarks() {
[Link]("Marks of " + name + " = " + marks);
}

public void displayResult() {


if(marks >= 50)
[Link](name + " has Passed");
else
[Link](name + " has Failed");
}
}

class Main {
public static void main(String args[]) {
Student s1 = new Student("Ravi", 85);
[Link]();
[Link]();
}
}

Output:

Marks of Ravi = 85
Ravi has Passed

Example 1: Exam Interface (Student Marks)


interface Exam {
void displayMarks();
void displayResult();
}

class Student implements Exam {


String name;
int marks;

Student(String n, int m) {
name = n;
marks = m;
}

public void displayMarks() {


[Link]("Marks of " + name + " = " + marks);
}

public void displayResult() {


if(marks >= 50)
[Link](name + " has Passed");
else
[Link](name + " has Failed");
}
}

class Main {
public static void main(String args[]) {
Student s = new Student("Ravi", 85);

Kamadhenu BCA College Object Oriented Programming using JAVA 85


[Link]();
[Link]();
}
}

Output:

Marks of Ravi = 85
Ravi has Passed

Example 2: Vehicle Interface (Polymorphism)

interface Vehicle {
void start();
void stop();
}

class Car implements Vehicle {


public void start() {
[Link]("Car starts with key");
}

public void stop() {


[Link]("Car stops using brake");
}
}

class Bike implements Vehicle {


public void start() {
[Link]("Bike starts with kick or button");
}

public void stop() {


[Link]("Bike stops using brake");
}
}

class Main {
public static void main(String args[]) {
Vehicle v1 = new Car();
Vehicle v2 = new Bike();

[Link]();
[Link]();

[Link]();
[Link]();
}
}

Output:

Car starts with key


Car stops using brake
Bike starts with kick or button
Bike stops using brake

Kamadhenu BCA College Object Oriented Programming using JAVA 86


Accessing Interface Variables
 Variables in interfaces are public, static, and final by default.
 Can be accessed using either interface name or through a class implementing the interface.
interface

Example:

interface Exam {
int MAX_MARKS = 100
100; // public static final by default
}

class Student implements Exam {


void showMaxMarks()
() {
[Link](
[Link]("Maximum Marks: " + MAX_MARKS);
}
}

class Main {
public static void main(String args[]) {
Student s = new Student();
[Link]();
[Link](
[Link]("Access using interface: " + Exam.MAX_MARKS);
}
}

Output:
Maximum Marks: 100
Access using interface:
: 100

Packages in Java: A package in Java is a collection of related classes, interfaces, and sub-
sub
packages. It helps in organizing code
code, avoiding naming conflicts,, and reusing classes. Example:
[Link], [Link], [Link] are standard Java packages.

Java API Packages : Java provides a large set of predefined packages called API packages. Some
commonly used API packages
packages:

Kamadhenu BCA College Object Oriented Programming using JAVA 87


Package Description
[Link] Fundamental classes like String, Math, Object
[Link] Utility classes like Vector, ArrayList, Date
[Link] Input/Output classes like File, BufferedReader
[Link] Classes for database access
[Link] Networking classes

Using System Packages


 Java automatically imports [Link] package.
 Other packages can be imported using import keyword.

Example:

import [Link];

class Main {
public static void main(String args[]) {
Vector<String> v = new Vector<>();
[Link]("Ravi");
[Link](v);
}
}

Naming Conventions
 Package names are lowercase to avoid conflicts.
 Follow company domain style for unique names.
o Example: [Link]
 Class names inside packages follow CamelCase.

Creating Packages
 Use package keyword at the top of the Java file.
 Example:

package studentinfo; // package declaration

public class Student {


String name;
int rollNo;
}

 Save in a folder named studentinfo.

Accessing a Package
 Use import to use classes from a package.

Example:
import [Link];

class Main {
public static void main(String args[]) {
Student s = new Student();
[Link] = "Ravi";
[Link]("Name: " + [Link]);
}
}

Kamadhenu BCA College Object Oriented Programming using JAVA 88


 You can also use import studentinfo.*; to import all classes in the package.

Using a Package
 Once imported, classes can be instantiated and used normally.
 Helps in modular programming.

Adding a Class to a Package


1. Create folder with package name.
2. Add package package_name; at the top of your class file.
3. Compile with path of the package.
4. javac -d . [Link]
5. Access using import package_name.ClassName; in another file.

Key Points:
1. Packages organize code and avoid class name conflicts.
2. Java provides system packages for common tasks.
3. Custom packages are created using package keyword and accessed with import.
4. Proper naming conventions ensure clarity and uniqueness.

Hiding Classes in Java : Hiding classes means restricting access so they cannot be used
outside their package or outer class, enhancing encapsulation.

Ways to Hide Classes


1. Default Class (Package-Private):
o No access modifier.
o Accessible only within the same package.

package studentinfo;
class Student { // default class
String name;
}

2. Private Inner Class:


o Declared inside another class with private.
o Accessible only within the outer class.

class Outer {
private class Inner {
void display() {
[Link]("Private inner class");
}
}
void show() {
Inner i = new Inner();
[Link]();
}
}

Kamadhenu BCA College Object Oriented Programming using JAVA 89


Multithreaded Programming in Java: Multithreading allows a program to perform multiple tasks
simultaneously by dividing a program into smaller units called threads. A thread is a lightweight unit of
execution within a process, capable of running independently. Using multithreading, programs can achieve
better performance, responsiveness, and resource utilization.
For example, in a banking application, one thread can handle user input while another processes
transactions in the background. Threads can be created by extending the Thread class or implementing the
Runnable interface.

Benefits of multithreading:
1. Better CPU utilization
2. Faster execution for concurrent tasks
3. Simpler program structure for asynchronous operations

Creating Threads
Java provides two ways to create threads:
1. Extending the Thread class
2. Implementing the Runnable interface

Extending the Thread Class


1. Create a class that extends Thread.
2. Override the run() method with the task to execute.
3. Create an object of the class and call start() to begin execution.

Example:
class MyThread extends Thread {
public void run() {
for(int i=1; i<=5; i++) {
[Link]("Thread: " + i);
}
}
}

class Main {
public static void main(String args[]) {
MyThread t1 = new MyThread();
[Link](); // starts a new thread
}
}

Output (may vary due to thread scheduling):


Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5

Implementing the Runnable Interface: Another way to create threads in Java is by implementing
the Runnable interface.

Advantages over extending Thread:


1. Allows extending another class (Java supports single inheritance).
2. Multiple threads can share the same object.

Kamadhenu BCA College Object Oriented Programming using JAVA 90


Steps to Create a Thread Using Runnable
1. Implement the Runnable interface in a class.
2. Override the run() method with the code to execute.
3. Create a Thread object, passing the Runnable object to its constructor.
4. Call start() on the Thread object.

Example
class MyRunnable implements Runnable {
public void run() {
for(int i = 1; i <= 5; i++) {
[Link]("Runnable Thread: " + i);
}
}
}

class Main {
public static void main(String args[]) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r); // pass Runnable to Thread
[Link](); // start new thread
}
}

Output (may vary due to thread scheduling):


Runnable Thread: 1
Runnable Thread: 2
Runnable Thread: 3
Runnable Thread: 4
Runnable Thread: 5

Stopping and Blocking a Thread

1. Stopping a Thread:
o stop() method is deprecated.
o Use a boolean flag to stop the thread safely.

class MyThread extends Thread {


boolean running = true;
public void run() {
while(running) {
[Link]("Thread is running...");
}
}
void stopThread() {
running = false;
}
}

2. Blocking a Thread:
o sleep(milliseconds) → pauses thread temporarily.
o join() → waits for another thread to complete.

class MyThread extends Thread {


public void run() {
try {

Kamadhenu BCA College Object Oriented Programming using JAVA 91


for(int i=1;i<=5;i++){
[Link]("Thread: "+i);
[Link](1000); // pause 1 sec
}
} catch(InterruptedException e) {
[Link](e);
}
}
}

class Main {
public static void main(String args[]) {
MyThread t1 = new MyThread();
[Link]();
}
}

Output:
Thread prints numbers with 1-second interval.

Life Cycle of a Thread: A thread in Java goes through different states from creation to termination.
These states define the life cycle of a thread.
Thread State Description Methods / Events Causing This State
New (Created) Thread object is created but not yet started. Thread t = new Thread() (constructor)
Runnable Thread is ready to run and waiting for CPU [Link]() moves thread from New →
time. Runnable
Running Thread is currently executing its run() JVM scheduler picks a Runnable thread to
method. execute
Blocked / Thread is waiting for a resource, I/O, or wait(), waiting to acquire a lock, join(),
Waiting another thread to release a lock. sleep() (temporarily)
Timed Waiting Thread is waiting for a specified period of sleep(ms), join(ms), wait(ms)
time.
Terminated Thread has finished execution or stopped, run() completes, or stop() (deprecated)
(Dead) cannot be restarted.

Kamadhenu BCA College Object Oriented Programming using JAVA 92


Example Demonstrating Thread States
class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
try {
[Link](2000); // thread goes to Timed Waiting
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Thread finished execution");
}
}

class Main {
public static void main(String args[]) {
MyThread t = new MyThread(); // New state
[Link]("Thread created: " + [Link]());

[Link](); // Runnable -> Running


[Link]("Thread started: " + [Link]());

try {
[Link](500); // Main thread sleeps
[Link]("Thread state: " + [Link]()); // Likely
TIMED_WAITING
[Link](); // Wait for thread to finish
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Thread final state: " + [Link]()); // TERMINATED
}
}

Possible Output:

Thread created: NEW


Thread started: RUNNABLE
Thread is running...
Thread state: TIMED_WAITING
Thread finished execution
Thread final state: TERMINATED

Using Thread Methods: Java provides several methods to control thread behavior:

Method Description
start() Starts the thread and calls run() method.
run() Contains the code executed by the thread.
sleep(ms) Pauses thread for specified milliseconds.
join() Waits for another thread to complete.
getName() Returns thread’s name.
setName(String) Sets thread’s name.
getPriority() Returns thread’s priority (1–10).
setPriority(int) Sets thread’s priority.
isAlive() Checks if thread is alive.
yield() Temporarily pauses thread to allow other threads to execute.
Example:

Kamadhenu BCA College Object Oriented Programming using JAVA 93


class MyThread extends Thread {
public void run() {
[Link](getName() + " is running");
}
}

class Main {
public static void main(String args[]) {
MyThread t1 = new MyThread();
[Link]("Thread-A");
[Link]();
}
}

Output:
Thread-A is running

Thread Exceptions in Java: Threads in Java can throw exceptions during execution, mainly due
to interruption or illegal operations.

Common thread-related exceptions:


1. InterruptedException – occurs when a thread is sleeping or waiting and another thread
interrupts it.
2. IllegalThreadStateException – occurs if a thread is started more than once.

Example: InterruptedException
class MyThread extends Thread {
public void run() {
try {
[Link]("Thread starts sleeping...");
[Link](3000); // thread sleeps for 3 seconds
[Link]("Thread woke up");
} catch (InterruptedException e) {
[Link]("Thread was interrupted: " + e);
}
}
}

class Main {
public static void main(String args[]) {
MyThread t1 = new MyThread();
[Link]();

try {
[Link](1000); // main thread sleeps 1 second
[Link](); // interrupt t1 while it is sleeping
} catch (InterruptedException e) {
[Link](e);
}
}
}

Output:
Thread starts sleeping...
Thread was interrupted: [Link]

Explanation:
 Thread t1 is sleeping for 3 seconds.
 Main thread interrupts it after 1 second, causing InterruptedException.

Kamadhenu BCA College Object Oriented Programming using JAVA 94


Thread Priority in Java
Java: Every thread in Java has a priority that indicates the relative importance
of the thread. Thread priority helps the thread scheduler decide which thread to run first. Range: 1
(MIN_PRIORITY) to 10 (MAX_PRIORITY), default is 5 (NORM_PRIORITY).

Methods
Method Description
setPriority(int p) Sets thread priority (1–10).
getPriority() Returns the current thread’s priority.

Example
class MyThread extends Thread {
public void run() {
[Link](getName() + " priority: " + getPriority());
}
}

class Main {
public static void main
main(String args[]) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

[Link]("Thread
"Thread-A");
[Link]("Thread
"Thread-B");

[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.MAX_PRIORITY); // 10

[Link]();
[Link]();
}

Possible Output:

Thread-A priority: 1
Thread-B priority: 10

2 Marks Questions (Conceptual / Definition / Syntax Type)


1. What is an interface in Java?
2. Define multiple
ultiple inheritance. How is it achieved in Java?
3. Write the syntax to define an interface.
4. How is an interface different from a class?
5. What keyword is used to implement an interface?

Kamadhenu BCA College Object Oriented Programming using JAVA 95


6. What is a package in Java?
7. What are Java API packages? Give examples.
8. Write the syntax for creating a user-defined package.
9. What is a thread?
10. What is the difference between process and thread?
11. What is thread priority?
12. What is synchronization?
13. Name two ways to create a thread in Java.
14. What is the life cycle of a thread?
15. What is the Runnable interface used for?
16. What is the use of the import statement in Java?
17. What is meant by hiding classes in packages?
18. Define extending interfaces.
19. What is the use of the final keyword with methods?
20. Mention any two thread methods.

5 Marks Questions (Short Answer / Program Based / Conceptual Application)


1. Explain how multiple inheritance is achieved using interfaces in Java with a simple example.
2. Write a Java program to define and implement an interface.
3. What are the main advantages of using interfaces?
4. Explain the process of creating and using user-defined packages in Java.
5. What are Java API packages? Explain any three with examples.
6. Write a short note on naming conventions used in packages.
7. Explain the life cycle of a thread with a neat diagram.
8. Write a program to create a thread by extending the Thread class.
9. What are the different thread methods in Java? Explain any five.
10. Explain synchronization with an example.
11. Write a Java program to create multiple threads using the Runnable interface.
12. Explain the difference between abstract class and interface.
13. Write a short note on accessing interface variables.
14. What are system packages? How can they be used in a program?
15. Explain thread exceptions and thread priorities briefly.
16. Describe the steps involved in adding a class to a package.
17. What is meant by putting classes together in interface-based programming?
18. Write a short note on creating packages and hiding classes.
19. Explain blocking of threads with an example.
20. Explain naming conventions and import mechanisms used in packages.

10 Marks Questions (Descriptive / Analytical / Program-Based)


1. Explain in detail how multiple inheritance is achieved through interfaces in Java with suitable examples.
2. Describe the complete concept of packages — their creation, usage, and access mechanisms.
3. Write a detailed program that demonstrates multiple inheritance using interfaces.
4. Explain the concept of Java API packages. Discuss their role in modular programming.
5. Describe the life cycle of a thread with a neat labeled diagram and explain each state.
6. Discuss synchronization and thread communication in Java with suitable examples.
7. Explain in detail the two ways of creating threads in Java: extending Thread class and implementing Runnable
interface.
8. Explain the advantages and uses of packages and interfaces in large Java applications.
9. Write a detailed note on “Multithreading in Java” with example programs and thread control methods.
10. Explain the complete process of creating user-defined packages, adding classes, and accessing them from
another program.

Kamadhenu BCA College Object Oriented Programming using JAVA 96


Unit- IV : Managing Exceptions, Applet Programming
Managing Errors and Exception: Introduction, Types of Errors, Exceptions, Syntax of Exception Handling
Code, Multiple Catch Statements, Using Finally Statement, Throwing Our Own Exceptions, Using Exceptions
for Debugging. Applet Programming: Introduction, How Applets Differ from Applications, Preparing to Write
Applets, Building Applet Code, Applet Life Cycle, Creating an Executable applet, Designing a Web Page,
Applet Tag, Adding Applet to HTML File, Running the Applet, More about Applet Tag, Passing Parameters
to Applets, Aligning the Display, More About HTML Tags, Displaying Numerical Values, Getting Input from
the [Link] Programming, Input/Output: Graphics Programming: Introduction, The Graphics class,
Lines and rectangles, circles and ellipses, Drawing Arcs, Drawing Polygons, Line Graphs, Using Control Loops
in Applets, Drawing Bar Charts.

Managing Exceptions in Java: Exceptions are unusual or error conditions that occur during
program execution. Managing exceptions ensures the program does not terminate abruptly. Java
provides a robust exception handling mechanism using try, catch, throw, throws, and finally.

Exception Types
1. Checked Exceptions:
o Checked at compile-time.
o Example: IOException, SQLException.
2. Unchecked Exceptions:
o Checked at runtime.
o Example: ArithmeticException, NullPointerException.
3. Error:
o Serious problems not meant to be handled by the program.
o Example: OutOfMemoryError.

Basic Syntax
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// Handle exception of type ExceptionType2
} finally {
// Code that will always execute (optional)
}

Kamadhenu BCA College Object Oriented Programming using JAVA 97


Exception Handling Keywords
Keyword Purpose
try Contains code that may throw exception.
catch Handles the exception thrown by try block.
finally Executes code always,, whether exception occurs or not.
throw Used to explicitly throw an exception.
throws Declares exceptions a method may throw.

Example: Managing Exception


class Main {
public static void main(String
(String args[]) {
int a = 10, b = 0;
try {
int c = a / b; // may cause ArithmeticException
[Link](
[Link]("Result: " + c);
} catch (ArithmeticException e) {
[Link](
[Link]("Cannot divide by zero: " + e);
} finally {
[Link](
[Link]("Execution completed");
}
}
}

Output:
Cannot divide by zero: [Link]: / by zero
Execution completed

Common Exception Classes


Class Description
ArithmeticException Division by zero or invalid arithmetic.
NullPointerException Accessing object references that are null.
ArrayIndexOutOfBoundsException Accessing invalid array index.
ClassNotFoundException Trying to load a class that does not exist.
IOException Input/Output failures like file not found.
FileNotFoundException File is missing or path is wrong.
NumberFormatException
Exception Converting string to number fails.

Throwing Our Own Exceptions (User


(User-Defined Exceptions): Java allows programmers to
create and throw their own exceptions when specific conditions occur. These are called user-defined
user
exceptions. Useful when built-in
in exceptions do not accurately describe an error.
Steps to Create a User-Defined
Defined Exception
1. Create a new class that extends Exception
(for checked exceptions) or RuntimeException
(for unchecked exceptions).
2. Define a constructor to accept an error
message.
3. Throw the exception using throw keyword.

Syntax
class MyException extends Exception {
MyException(String message) {
super(message); // pass message
to Exception class
}
}

Kamadhenu BCA College Object Oriented Programming using JAVA 98


class Main {
public static void main(String args[]) {
try {
// code that may throw exception
throw new MyException("This is a custom exception");
} catch (MyException e) {
[Link]("Caught: " + [Link]());
}
}
}

Output:
Caught: This is a custom exception

Applet Programming in Java: An applet is a small Java program designed to run inside a web browser
or an applet viewer. Unlike regular Java applications, applets cannot run independently—they depend on a
host environment. Applets are mainly used to create interactive web applications, such as games,
animations, or visual components, providing dynamic content for web pages.

How Applets Differ from Applications


Aspect Application Applet
Execution Runs independently via JVM Runs inside browser/applet viewer
Class Extension Extends Object class Extends [Link] class
User Interface May use Swing/AWT or console Uses GUI only (no console)
Security Full access to system Restricted (sandboxed)
Lifecycle Methods Main method (main()) init(), start(), stop(), destroy()

Preparing to Write Applets


1. Import applet and GUI packages:
import [Link];
import [Link];
2. Extend the Applet class.
3. Override lifecycle methods like
init(), start(), stop(), destroy(), paint(Graphics g).

Building Applet Code


import [Link];
import [Link];

public class HelloApplet extends Applet {


public void init() {
[Link]("Applet Initialized");
}

public void start() {


[Link]("Applet Started");
}

public void stop() {


[Link]("Applet Stopped");
}

public void destroy() {


[Link]("Applet Destroyed");

Kamadhenu BCA College Object Oriented Programming using JAVA 99


}

public void paint(Graphics g) {


[Link]("Hello, Applet!", 50, 50);
}
}

Creating an Executable Applet


 Compile applet code using: javac [Link]
 Generates [Link] file.

Applet Life Cycle


1. init() – called once when the applet is first loaded.
2. start() – called every time the applet becomes active.
3. paint(Graphics g) – called to draw content on screen.
4. stop() – called when applet is no longer active.
5. destroy() – called before the applet is unloaded.

Designing a Web Page


Applets are embedded in HTML using <applet> tag or <object>/<embed> tag (modern browsers may
not support <applet>).

HTML Example:
<html>
<body>
<h2>My First Applet</h2>
<applet code="[Link]" width="300" height="100">
</applet>
</body>
</html>

Running the Applet


1. Use Applet Viewer:
appletviewer [Link]
2. Or use a web browser (modern browsers may require additional setup).

The <applet> Tag


 Used in HTML to embed an applet into a web page.
 Basic syntax:
<applet code="[Link]" width="widthValue" height="heightValue">
</applet>

Attribute Description
code Name of the compiled applet class
width Width of applet display area
height Height of applet display area
align Alignment of the applet in page
codebase Directory containing class file
alt Alternate text if applet not supported

Passing Parameters to Applets: When an applet runs inside an HTML page, we can send data
(parameters) from the HTML file to the Java applet.

Kamadhenu BCA College Object Oriented Programming using JAVA 100


For example:
 You might want to tell the applet what background color to use,
 What user name to display,
 Or what image file to load.

Those values are written in the HTML file and read by the applet at runtime.
 Use <param> tag inside <applet> to pass values.

HTML Example:
<applet code="[Link]" width="300" height="100">
<param name="username" value="Satish">
</applet>

Java Code to Access Parameters:


import [Link];
import [Link];

public class HelloApplet extends Applet {


String name;
public void init() {
name = getParameter("username"); // fetch parameter
}
public void paint(Graphics g) {
[Link]("Hello, " + name, 50, 50);
}
}

Aligning the Display


Use align attribute in <applet> tag:
<applet code="[Link]" width="300" height="100" align="center">
</applet>
Values can be left, center, right.

Displaying Numerical Values


 Use drawString with [Link] () or [Link]() to display numbers.
int x = 100;
[Link]("Value: " + x, 50, 50);

Getting Input from the User


 TextField and Button from AWT can be used in applets for input.

import [Link];
import [Link].*;
import [Link].*;

public class InputApplet extends Applet implements ActionListener {


TextField tf;
Label l;

public void init() {


tf = new TextField(10);
l = new Label("Enter name:");
add(l); add(tf);
[Link](this);
}

public void actionPerformed(ActionEvent e) {


String name = [Link]();
showStatus("Hello, " + name);
}}

Kamadhenu BCA College Object Oriented Programming using JAVA 101


Graphics Programming and Input/Output in Java Applets: Java applets can perform
graphics programming to display shapes, charts, and graphs. The Graphics class in [Link] provides
methods to draw lines, rectangles, circles, polygons, arcs, and text
text. Graphics programming is commonly
used in data visualization and interactive web applications
applications.

The Graphics Class


 Used to draw shapes and text on applets.
 Important Methods:

Method Description
drawLine(x1, y1, x2, y2) Draws a line between two points
drawRect(x, y, w, h) Draws a rectangle
fillRect(x, y, w, h) Draws filled rectangle
drawOval(x, y, w, h) Draws oval inside the rectangle bounds
fillOval(x, y, w, h) Draws filled oval
drawArc(x, y, w, h, startAngle, arcAngle) Draws an arc of ellipse
drawPolygon(int[] x, int[] y, n) Draws polygon with n points
drawString(String s, x, y) Displays string at (x,y)
setColor(Color c) Sets color for drawing
setFont(Font f) Sets font for text

Methods & Description


drawLine(x1, y1, x2, y2)
Description: Draws a straight line from point (x1, y1) to (x2, y2).
Example:
public void paint(Graphics g) {
[Link](50, 50, 150, 50); // horizontal line
}

drawRect(x, y, width, height)


Description: Draws a rectangle outline with top
top-left corner (x, y).
Example:
public void paint(Graphics g) {
[Link](50, 70, 100, 50); // rectangle
}

Kamadhenu BCA College Object Oriented Programming using JAVA 102


fillRect(x, y, width, height)
Description: Draws a filled rectangle with the specified dimensions.
Example:
public void paint(Graphics g) {
[Link]([Link]);
[Link](50, 130, 100, 50); // filled rectangle
}

drawOval(x, y, width, height)


Description: Draws an oval inside the bounding rectangle (x, y, width, height).
height)
Example:
public void paint(Graphics g) {
[Link](200, 50, 100, 100); // circle
}

Kamadhenu BCA College Object Oriented Programming using JAVA 103


fillOval(x, y, width, height)
Description: Draws a filled oval inside the bounding rectangle.
Example:
public void paint(Graphics g) {
[Link]([Link]);
[Link](200, 160, 150, 100); // filled ellipse
}

drawArc(x, y, width, height, startAngle, arcAngle)


Description: Draws a portion
on of an oval defined by angles in degrees.
Example:
public void paint(Graphics g) {
[Link]([Link]);
[Link](400, 50, 100, 100, 0, 180); // semicircle
}

drawPolygon(int[] x, int[] y, n)
Description: Draws a polygon connecting n points defined by arrays x[] and y[].
Example:
public void paint(Graphics g) {
int x[] = {500, 550, 600};
int y[] = {50, 150, 50};
[Link]([Link]);
[Link](x, y, 3); // triangle
}

Kamadhenu BCA College Object Oriented Programming using JAVA 104


drawString(String s, x, y)
Description: Displays a string at position (x, y) on the applet.
Example:
public void paint(Graphics g) {
[Link]("Hello, Applet!", 50, 50);
}

setColor(Color c)
Description: Sets the color for subsequent drawing operations.
Example:
public void paint(Graphics g) {
[Link]([Link]);
[Link](50, 70, 100, 50);
}

setFont(Font f)
Description: Sets the font style and size for text drawn using drawString().
Example:
public void paint(Graphics g) {
[Link](new Font("Arial", F [Link], 16));
[Link]("Java Graphics", 50, 100);
}

Kamadhenu BCA College Object Oriented Programming using JAVA 105


Using Control Loops in Applets & Drawing Bar Charts
 Loops like for, while, and do-while can be used to draw multiple shapes or repetitive patterns
in applets.
 This makes graphics dynamic and reduces code repetition.

Example: Drawing Multiple Rectangles Using a Loop

import [Link];
import [Link];
import [Link];

public class LoopApplet extends Applet {


public void paint(Graphics g) {
[Link]([Link]);
for(int i = 0; i < 5; i++) {
[Link](50 + i*60, 50, 50, 50); // draws 5 rectangles side by side
}
}
}

Explanation:

 The loop shifts each rectangle by 60 pixels horizontally.


 Easy to modify number of shapes or spacing.

Drawing Bar Charts


 Bar charts visualize numerical data.
 Use arrays to store values and loops to draw bars.

Example: Simple Bar Chart


import [Link];
import [Link];
import [Link];

public class BarChartApplet extends Applet {


public void paint(Graphics g) {
int data[] = {50, 100, 70, 120}; // heights of bars
[Link]([Link]);

for(int i = 0; i < [Link]; i++) {


[Link](50 + i*60, 200 - data[i], 50, data[i]); // draw bar
[Link]([Link]);
[Link]([Link](data[i]), 50 + i*60, 200 - data[i] - 5);
// display value
[Link]([Link]);
}
}
}

Explanation:
 data[i] determines the height of each bar.
 200 - data[i] sets the top-left corner of the
bar for correct vertical positioning.
 Looping makes it easy to draw multiple bars dynamically.

Applet: Bar Graph with User Input


import [Link];

Kamadhenu BCA College Object Oriented Programming using JAVA 106


import [Link].*;
import [Link].*;

public class BarGraphInputApplet extends Applet implements ActionListener {


TextField tf;
Button btn;
Label lbl;
int data[] = new int[10]; // maximum 10 bars
int n = 0; // number of bars
public void init() {
lbl = new Label("Enter numbers separated by commas:");
tf = new TextField(30);
btn = new Button("Draw Bar Graph");

add(lbl);
add(tf);
add(btn);

[Link](this);
}

public void actionPerformed(ActionEvent e) {


String input = [Link]();
String[] values = [Link](",");
n = [Link];

for(int i = 0; i < n; i++) {


try {
data[i] = [Link](values[i].trim());
} catch(NumberFormatException ex) {
data[i] = 0; // default 0 if input invalid
}
}
repaint(); // redraw bar graph
}

public void paint(Graphics g) {


[Link]([Link]);
int x = 50; // starting x coordinate
for(int i = 0; i < n; i++) {
[Link](x, 300 - data[i], 40, data[i]); // draw bar
[Link]([Link]);
[Link]([Link](data[i]), x, 300 - data[i] - 5);
// value above bar
x += 50; // spacing between bars
[Link]([Link]);
}

// Draw x-axis
[Link]([Link]);
[Link](40, 300, x, 300);
}
}

Explanation
o User Input:User enters numbers in the TextField, separated by commas (e.g., 50, 100, 80, 120).
o ActionListener: Button click triggers parsing of input into an integer array.
o Repaint: repaint() calls paint() to draw bars dynamically.
o Bar Graph:
 Bars are drawn using fillRect().
 Numbers displayed above each bar with drawString().

Kamadhenu BCA College Object Oriented Programming using JAVA 107


 X-axis
axis drawn for reference.

HTML to Run Applet


<html>
<body>
<h2>Bar
>Bar Graph Applet with User Input
Input</h2>
<applet code="[Link]"
"[Link]" width="600" height="400"
"400">
</applet>
</body>
</html>

Applet: Bouncing Ball


import [Link];
import [Link].*;
import [Link].*;

public class BouncingBallApplet extends Applet implements Runnable {


int x = 50, y = 50;
; // initial position
int radius = 30;
; // ball radius
int dx = 5, dy = 5;
; // movement speed
Thread t;

public void init() {


setBackground([Link]);
}

public void start() {


t = new Thread(this);
[Link](); // start animation thread
}

public void stop() {


t = null; // stop thread when applet stops
}

public void run() {


Thread currentThread = [Link]();
while (t == currentThread) {
// Update ball position
x += dx;

Kamadhenu BCA College Object Oriented Programming using JAVA 108


y += dy;

// Check for boundaries


if (x < 0 || x > getWidth() - radius) dx = -dx;
if (y < 0 || y > getHeight() - radius) dy = -dy;
dy;

repaint(); // redraw ball

try {
[Link](
[Link](50); // delay for smooth animation
} catch (InterruptedException e) {}
}
}

public void paint(Graphics


(Graphics g) {
[Link]([Link]);
[Link](x, y, radius, radius); // draw ball
}
}

Explanation
1. Thread for Animation:
o Implements Runnable and uses a thread to continuously update ball position.
2. Movement Variables:
o dx and dy control speed and direction.
3. Boundary Check:
o Ball reverses direction when it hits edges of applet (dx = -dx, dy = -dy).
4. Repaint Loop:
o repaint() redraws the ball at the new position every 50 ms for smooth animation.

HTML to Run Applet


<html>
<body>
<h2>Bouncing Ball Applet</h2>
<applet code="[Link]"
"[Link]"
width="400" height="300">
</applet>
</body>
</html>

Kamadhenu BCA College Object Oriented Programming using JAVA 109


2 Marks Questions (Conceptual / Definition / Syntax Type)
1. What is an exception?
2. Name two types of errors in Java.
3. What is the purpose of the try-catch block?
4. Define the finally statement.
5. What is the difference between throw and throws?
6. What is a user-defined exception?
7. What is an applet?
8. Write any two differences between applet and application.
9. Name the life cycle methods of an applet.
10. What is the purpose of the <APPLET> tag?
11. What is the use of the paint() method?
12. How can you pass parameters to an applet?
13. What is the Graphics class used for?
14. Write the method to draw a line in Java.
15. Which method is used to draw a rectangle?
16. What is a polygon?
17. Name two shapes that can be drawn using the Graphics class.
18. What is synchronization in multithreading?
19. What is meant by debugging?
20. Which package contains the Applet class?

5 Marks Questions (Short Answer / Program Based)


1. Explain the types of errors in Java with examples.
2. Write the syntax of exception handling and explain each part.
3. Explain the use of try, catch, and finally with a suitable example.
4. Write a program to demonstrate user-defined exceptions.
5. Explain the life cycle of an applet with a neat diagram.
6. Write a Java applet program to display a welcome message.
7. Explain how parameters are passed to an applet using HTML.
8. Write a short note on the Graphics class and its methods.
9. Write a program to draw lines and rectangles using applet graphics.
10. Explain the steps involved in building and executing an applet.

10 Marks Questions (Descriptive / Analytical / Program Based)


1. Explain in detail Java’s exception handling mechanism with syntax and example.
2. Write a Java program to demonstrate multiple catch and finally blocks.
3. Explain the complete applet life cycle with a neat diagram and example.
4. Describe how applets differ from applications. Write a simple applet program and explain it.
5. Write a Java program to create an applet that takes input from the user and displays output.
6. Explain the steps to build, compile, and run an applet using an HTML page.
7. Explain graphics programming in Java with methods for drawing different shapes.
8. Write a Java program to draw circles, rectangles, and polygons in an applet.
9. Explain exception handling keywords (try, catch, throw, throws, finally) in detail.
10. Write a Java applet program to draw and color a bar chart using loops.

Kamadhenu BCA College Object Oriented Programming using JAVA 110


All following papers are Tentative Question Paper (QP)

KARNATAKA UNIVERSITY, DHARWAD


BCA – III Semester Examination
Subject: Object-Oriented Programming Using Java
Duration: 3 Hours Max Marks: 80

SECTION – A (2 Marks each)

Answer any 10 questions.


(Each question carries 2 marks)
(12 Questions given – Attempt any 10) [10 × 2 = 20 Marks]

1. What is bytecode?
2. Mention any two features of Java.
3. What are command line arguments?
4. Define variable and give an example.
5. What is the difference between if and switch statements?
6. Define class and object.
7. What is inheritance?
8. What is an interface?
9. Define thread and mention any one method of creating it.
10. What is the use of the finally block?
11. What is an applet?
12. Name any two methods of the Graphics class.

SECTION – B (5 Marks each)

Answer any 6 questions.


(Each question carries 5 marks)
(8 Questions given – Attempt any 6) [5 × 6 = 30 Marks]

1. Explain the types of data types available in Java.


2. Explain the different decision-making statements in Java with examples.
3. Write a Java program to demonstrate method overloading.
4. Explain how multiple inheritance is achieved using interfaces in Java.
5. Explain the life cycle of a thread with a neat diagram.
6. Write a Java applet program to display a welcome message using HTML <APPLET> tag.
7. Explain the concept of exception handling with syntax.
8. Write a program to draw circles and rectangles using the Graphics class.

SECTION – C (10 Marks each)

Answer any 3 questions.


(Each question carries 10 marks)
(5 Questions given – Attempt any 3) [3 × 10 = 30 Marks]

1. Explain in detail the features of Java and discuss how Java differs from C and C++.
2. Discuss classes, objects, and constructors in detail with suitable examples.
3. Explain packages in Java — creation, usage, and accessing user-defined packages with examples.
4. Explain the complete applet life cycle with a neat diagram and suitable program.
5. Write a detailed Java program to demonstrate exception handling using try, catch, throw,
throws, and finally.

Kamadhenu BCA College Object Oriented Programming using JAVA 111


KARNATAKA UNIVERSITY, DHARWAD
BCA – III Semester Examination
Subject: Object-Oriented Programming Using Java
Duration: 3 Hours Max Marks: 80

SECTION – A (2 Marks each)

Answer any 10 questions.


(Each question carries 2 marks)
(12 Questions given – Attempt any 10) [10 × 2 = 20 Marks]

1. What is the difference between JDK and JVM?


2. What is a token in Java? Give two examples.
3. Define encapsulation.
4. What is a constructor?
5. Mention two differences between while and do-while loops.
6. What is the purpose of the super keyword?
7. Define polymorphism.
8. What is the significance of the static keyword?
9. What is an abstract class?
10. What is garbage collection?
11. What is a vector in Java?
12. Mention any two wrapper classes in Java.

SECTION – B (5 Marks each)

Answer any 6 questions.


(Each question carries 5 marks)
(8 Questions given – Attempt any 6) [5 × 6 = 30 Marks]

1. Explain the structure of a Java program with a suitable example.


2. Write a Java program to find the largest of three numbers using an if-else statement.
3. Explain different types of constructors with examples.
4. Write a Java program to demonstrate the use of this keyword.
5. Explain different access specifiers in Java.
6. Write a Java program to implement single inheritance.
7. Explain the purpose of the StringBuffer class with suitable methods.
8. Write a Java program to create a vector and perform add, remove, and display operations.

SECTION – C (10 Marks each)

Answer any 3 questions.


(Each question carries 10 marks)
(5 Questions given – Attempt any 3) [3 × 10 = 30 Marks]

1. Explain in detail the OOP principles and their advantages in Java programming.
2. Discuss method overriding and dynamic method dispatch with examples.
3. Explain exception handling hierarchy in Java and write a program demonstrating multiple catch
blocks.
4. Explain multithreading in Java. Write a program to create two threads executing simultaneously.
5. Write short notes on:
(a) Final variables and methods (b) Abstract methods and interfaces (c) Visibility control in
inheritance.

Kamadhenu BCA College Object Oriented Programming using JAVA 112


KARNATAKA UNIVERSITY, DHARWAD
BCA – III Semester Examination
Subject: Object-Oriented Programming Using Java
Duration:3 Hours Max Marks: 80

SECTION – A (2 Marks each)

Answer any 10 questions.


(12 questions given – attempt any 10) [10 × 2 = 20 Marks]

1. What is Java?
2. Define a class.
3. What is an object?
4. Name any two features of Java.
5. What is the use of the import statement?
6. What is the default value of an integer variable?
7. Write the syntax of a for loop in Java.
8. What is a constructor?
9. Define inheritance.
10. What is an interface?
11. What is the purpose of the final keyword?
12. What is meant by thread in Java?

SECTION – B (5 Marks each)

Answer any 6 questions.


(8 questions given – attempt any 6) [5 × 6 = 30 Marks]

1. Explain any five basic concepts of Object-Oriented Programming.


2. Write a Java program to find whether a number is even or odd.
3. Explain the difference between local and instance variables.
4. Write a Java program to calculate the sum of first 10 natural numbers using a for loop.
5. Explain constructor overloading with an example.
6. Write a short note on String and StringBuffer classes.
7. Write a Java program to demonstrate single inheritance.
8. Write a Java program to handle divide-by-zero exception using try-catch.

SECTION – C (10 Marks each)

Answer any 3 questions.


(5 questions given – attempt any 3) [3 × 10 = 30 Marks]

1. Explain in detail the features and advantages of Java.


2. Describe the life cycle of an applet with a neat diagram.
3. Explain multithreading in Java with a simple example program.
4. What is an array? Write a Java program to read and print 5 integer values using an array.
5. Explain how exceptions are handled in Java with an example using try, catch, and finally.

Kamadhenu BCA College Object Oriented Programming using JAVA 113

Common questions

Powered by AI

Method overriding in Java occurs when a subclass provides its own implementation of a method that is already defined by its superclass. It requires the method in the subclass to have the same name, return type, and parameters as the method in the superclass. This feature of Java enables polymorphism by allowing the runtime decision of method execution based on the actual object's class. This is essential for dynamic method calls, allowing subclasses to modify or enhance behavior defined in the parent class, thereby extending its functionality while maintaining a common interface.

In Java, the 'final' keyword is used to define constants, ensure methods cannot be overridden, and prevent subclassing. When used with variables, 'final' means the variable can be assigned only once, establishing a constant; with methods, it prevents overriding in subclasses, preserving original functionality; and with classes, it prohibits subclassing, meaning the class cannot have child classes. This mechanism helps secure code integrity and design intents against unintended extensions or manipulations.

Abstract classes in Java provide a means of facilitating code extension and maintenance by allowing classes to share a common interface and implement shared code. They serve as a base class that cannot be instantiated directly but can define both abstract (method signatures without implementation) and concrete methods that subclasses can utilize and extend. This helps enforce a common interface across different subclasses while allowing individual implementations, making code easier to manage and extend. Subclasses must provide concrete implementations of abstract methods, fostering consistent and predictable behavior.

Multiple inheritance in Java is achieved through interfaces because Java does not support multiple inheritance with classes directly, to avoid ambiguity. A class can implement multiple interfaces, which allows it to inherit abstract methods from more than one interface. For instance, a class can implement both the 'Academic' and 'Activity' interfaces: `class StudentDemo implements Academic, Activity`. This enables the class 'StudentDemo' to define behaviors of both interfaces without having direct class hierarchy issues. Each method in the interfaces is explicitly defined in the implementing class, ensuring clarity and preventing method conflicts.

Java's visibility control ensures encapsulation by allowing developers to restrict access to class members (fields and methods) through access modifiers. The modifiers 'private,' 'default' (no modifier), 'protected,' and 'public' define the level of accessibility. 'Private' restricts access to within the same class, 'default' allows it within the same package, 'protected' expands access to subclasses even outside the package, and 'public' provides access from any other class. By controlling access, encapsulation is maintained, which hides the internal state and functionality of an object and exposes a clean interface.

Constructors in Java are special methods used to initialize objects. They have the same name as the class and do not have a return type, unlike regular methods. Constructors are automatically called when an object is created, enabling the setup of initial state and allocation of resources. They can be overloaded to provide multiple ways to instantiate objects depending on input parameters. Unlike regular methods, constructors cannot be called explicitly via method calls and are central to object creation and initialization.

Multilevel inheritance in Java allows one class to inherit from another subclass, forming a chain of inheritance. This means that a base class passes its features to a derived class, which can then pass its own features onto a further subclass. The advantage of multilevel inheritance is that it allows for gradual enhancement and reuse of code across multiple levels. For example, if "Animal" is a base class, "Mammal" can inherit from "Animal," and "Dog" can then inherit from "Mammal." As a result, the "Dog" class has access to properties and methods from both "Mammal" and "Animal." This promotes code reusability and a clear hierarchical structure.

The thread life cycle in Java consists of several stages: 'New,' where the thread is created but not yet started; 'Runnable,' where it is ready to run and awaiting CPU allocation; 'Blocked,' where it cannot proceed until a particular resource is available; 'Waiting,' where it awaits another thread to perform a specific action or notification; 'Timed Waiting,' similar to 'Waiting,' but occurs for a specified period; and 'Terminated,' where the thread completes its execution. Understanding the thread life cycle is key for managing and controlling thread execution within applications.

Java manages error handling through its robust exception handling mechanism, which allows the definition and handling of exceptions separately from the main code logic. Key components include the 'try' block to enclose code that might throw an exception; 'catch' blocks to handle specific exceptions; 'finally' block to execute code after 'try' or 'catch' regardless of outcome; and 'throw' keyword to explicitly throw exceptions. The 'throws' keyword can denote methods that might throw exceptions, promoting clear but flexible error-handling paths. This structure encapsulates error management distinctly, promoting cleaner code and effective debugging.

Abstract classes in Java can have both abstract methods (without body) and concrete methods (with body), and they are used to provide a base class with some common functionality that can be extended by subclasses. Interfaces, on the other hand, can only contain abstract methods until Java 8, after which they can include default and static methods. Interfaces are intended to define a contract for the implementing classes without providing any method implementation. Abstract classes allow for shared code and can have instance variables, while interfaces ensure that classes adhere to a method signature contract, promoting flexibility and multiple inheritance. Abstract classes are instantiated by subclassing, whereas interfaces are implemented by classes.

You might also like