Java - Unit 1 Overview
1. Introduction to Java
Java is a high-level, class-based, object-oriented programming
language developed by James Gosling in 1991 at Sun Microsystems
(later acquired by Oracle Corporation). It was officially released in 1995.
Key Characteristics of Java:
High-level: Easy to understand, debug, and widely used today.
Class-based: All programs are structured around classes.
Object-Oriented Programming (OOP): A technology that
facilitates representing software methods in an easy way.
Platform Independent: Java's core philosophy is "Write Once, Run
Anywhere." Unlike C/C++, which are system-dependent, Java code
can run on any platform or operating system after being written
once.
Secure and Robust: It is considered a safe and strong language.
Easy to Use: Widely adopted due to its simplicity and ease of
debugging.
Applications of Java: Java is extensively used in:
Desktop Applications
Web Applications
Mobile Applications
Enterprise Applications
Smart Cards
Embedded Systems
Games
Robotics
Java Specifications:
Core Java (Java 2 Standard Edition - J2SE)
Advanced Java (Java 2 Enterprise Edition - J2EE)
Java 2 Mobile Edition (J2ME)
2. Features of Java
Simple: Easy to learn and understand with a straightforward
syntax.
Object-Oriented: Supports OOP principles.
Platform Independent: Achieved through the Java Virtual Machine
(JVM).
Secured: Programs are safe and virus-free.
Robust: Strong and reliable.
Architecture Neutral: Unlike C, Java takes a consistent memory
size (4 bytes for int) regardless of the system's architecture (e.g.,
32-bit or 64-bit).
Portable: Code written once can be run anywhere.
High Performance: Though slightly slower than C++ due to being
interpreted.
Distributed: Used in internet programming.
Multi-threaded: Supports multiple threads sharing a common
memory area, optimizing memory usage.
Dynamic: Allows changes at runtime and supports dynamic
compilation.
Automatic Memory Management (Garbage Collection):
Handles memory allocation and deallocation automatically.
3. Java Environment (JDK, JRE, JVM)
The Java environment comprises three main components:
JVM (Java Virtual Machine):
An abstract machine that does not exist physically.
A software written in C language, acting as an interpreter for Java
programs.
Function: "executes our Java program."
Process:
1. Java source code (.java) is compiled by javac into
bytecode (.class).
2. This bytecode is then platform-independent and can
be verified and executed by the JVM on any operating
system.
Operations: Loads, verifies, and executes code, and provides a
runtime environment.
JRE (Java Runtime Environment):
Provides the environment necessary to execute Java programs.
"JVM exists inside JRE." JRE is an implementation of JVM.
It is a software layer that runs on top of a computer's operating
system.
Components: JVM + a set of class libraries + other files.
"If I just want to run any Java program on my laptop, I will only
install JRE."
JDK (Java Development Kit):
The complete kit for Java development.
Components: "JDK consists of JRE + JVM." It includes JRE along with
a collection of development tools.
Purpose: "It includes a collection of tools that are used for
developing and running Java programs."
Use Case: "If I am a student, a programmer, a coder, I will have to
install JDK on my laptop because JDK is used to develop programs."
Tools: AppletViewer, Java interpreter, javac (Java Compiler), javap
(Java Disassembler), javah, javadoc, jdb (Java Debugger).
4. Structure of a Java Program
A basic Java program typically follows this structure:
Package Statement (Optional): "First, we have to write a
package statement." It groups related classes, sub-packages, and
interfaces together.
Example: package Example;
Import Statement (Optional): Used to "show input/output"
functionality or to import classes, packages, or interfaces.
Example: import java.util.Scanner;
Class Definition:A "blueprint or template" for creating objects.
All Java programs run within a class.
Example: public class Simple { ... }
Steps to write and run a simple Java program:
1. Download and Install JDK from Oracle Corporation.
2. Set the PATH environment variable by copying the JDK's bin
directory path.
3. Create the Java program (e.g., in Notepad, VS Code, or Eclipse).
4. Compile and Run the program.
Example of a Simple "Hello World" Program:
// Package and import statements are optional for basic programs
public class Simple {
public static void main(String[] args) { // Most important line
System.out.println("Hello World");
Explanation of public static void main(String[] args):
public: An access modifier indicating the method is visible and
accessible from anywhere.
static: A keyword meaning that "there is no need to create an
object to call the main method." It saves memory as the main
method is automatically executed by the JVM without needing an
object.
void: A return type indicating that "the method will not return
anything."
main: The method name and the starting point of any Java
program, recognized by the JVM.
String[] args: Command-line arguments, which are an array of
String objects used to hold command-line arguments.
System.out.println(): Used to "show output" in a Java program. println
adds a new line after printing.
Compilation and Execution Flow:
1. Java Source Program (.java)
2. Java Compiler (javac) compiles the source code into Java
Bytecode (.class file format).
3. The Bytecode (which is non-executable) is transferred to the target
system (e.g., via network/file system).
4. Bytecode Verifier checks the bytecode for security and format.
5. JVM executes the bytecode on the specific Operating System,
producing the desired output.
5. Classes and Objects
Class:
"Class is a template or blueprint for creating objects."
"Class is a collection of objects."
"Class does not take any memory or space." It's a logical entity.
Analogy: The blueprint of a house is the class; the actual house is
the object.
Declared using the class keyword.
Can contain data members, methods, constructors, nested classes,
and interfaces.
Object:
"Object is an instance of a class."
"An object is a real-world entity." It exists physically and logically.
Analogy: A specific car (e.g., "Honda City") is an object of the
"Vehicle" class. A student named "Ravi" is an object of the "B.Tech
Second Year" class.
Characteristics:State: The data an object possesses (e.g., a pen's
name and color).
Behavior: The actions an object can perform (e.g., a pen's ability to
write).
Identity: A unique identification (internal JVM functionality) for each
object.
"Once an object is initialized, its memory is automatically created."
6. Constructors
A special member function used to initialize objects within a
class.
Rules for Creation:Name: "Constructor name should be the same
as the class name."
Return Type: "It should not have any return type (it is void)."
Automatically called when an object instance is created.
Types of Constructors:
Default Constructor: Has "no parameters." Java provides
one if not explicitly defined. Default constructor can be
created by the programmer as well as the java itself can
create a default constructor.
Parameterized Constructor: "If it has parameters."
7. Methods
"A method is a block of code which only runs when it is called."
(Similar to functions in C/C++).
Purpose: To perform a "certain action."
Why use Methods? For code reusability and to organize large
programs.
Creation: Methods are always created inside a class.
Types: Pre-defined (e.g., System.out.println()) and User-defined.
Syntax: public static void myMethod() - where myMethod is the
method name.
8. Access Modifiers
Access modifiers "specify the accessibility or scope of fields, methods,
constructors, or classes." They control how elements can be accessed
from different parts of a program.
Types of Access Modifiers:
Private: Accessible "only within the class." (Most restrictive)
Default (no keyword): Accessible "only within the package."
Protected: Accessible "within the class, within the package, and
outside the package by subclass only."
Public: Accessible "everywhere" (within class, within package,
outside package by subclass, and outside package). (Least
restrictive)
Non-Access Modifiers: (Briefly mentioned) static, abstract, final,
transient, synchronized, volatile.
9. Static and Final Members
Static Members:
"Belong to the class" rather than an instance.
"You can access this member without creating an object of the class
".
Applied to methods, fields, and blocks.
Final Members:
A non-access modifier applicable to variables, methods, and classes.
Used to "restrict the user."
Final variable: Creates a constant variable.
Final method: Prevents method overriding.
Final class: Prevents inheritance.
10. Comments
"A part of the code that the compiler and interpreter do not
execute."
"Unparseable code." Used by programmers to "add details of the
code."
Purpose:Improve code readability and maintainability.
Provide information/explanation about variables, methods, classes.
Temporarily prevent code execution during testing.
Types:Single-line comments: // comment
Multi-line comments: /* comment */
Documentation comments: /** comment */ (Used for generating
API documentation).
11. Data Types
"Specify the different sizes and values that can be stored in a
variable."
Types:
Primitive Data Types (Machine-defined):Boolean: true or false
(1 bit).
Numeric:Character: char (2 bytes, stores single characters).
Integral:Integer: byte (1 byte), short (2 bytes), int (4 bytes), long
(8 bytes). Stores whole numbers.
Floating-point: float (4 bytes), double (8 bytes). Stores fractional
numbers.
Non-Primitive Data Types (User-defined): String, Array, Class,
Interface.
12. Variables
"Data containers that save data values during Java program
execution."
Analogy: A shoe box is a variable; it holds shoes (data values).
Assigned a data type that dictates the type and quantity of value it
can hold.
Rules:Values can change during program execution (hence
"variable").
"A variable is a memory location name for the data."
Must be declared before use.
Declaration: dataType variableName = value; (e.g., int age = 20;)
Types:Local Variable: Declared inside a method.
Instance Variable: Declared inside a class but outside any
method.
Class (Static) Variable: Declared inside a class with the static
keyword.
13. Operators
"Symbols used for performing specific operations in Java" (e.g.,
arithmetic, logical, relational).
1. Types of Operators:
2. Arithmetic Operators: +, -, *, /, % (modulus - remainder).
3. Unary Operators: Operate on a single operand (e.g., ++
increment, -- decrement, + unary plus, - unary minus, !
logical NOT).
4. Assignment Operators: = (assigns value), +=, -=, *= etc.
(shorthand).
5. Relational Operators: Compare two values, return boolean
(true/false) (e.g., == equals, != not equals, >, <, >=, <=).
6. Logical Operators: Combine conditional statements (&&
logical AND, || logical OR, ! logical NOT).
7. Ternary Operator: A "short-hand version" of the if-else
statement (condition ? if_true : if_false).
8. Bitwise Operators: Perform operations on individual bits
(e.g., & bitwise AND, | bitwise OR, ^ bitwise XOR).
9. Shift Operators: Shift bits to the left (<<) or right (>>,
>>>).
10. Instanceof Operator: Used for type checking, testing
if an object is an instance of a class, subclass, or interface.
14. Control Flow Statements
Control flow statements allow developers to "control the flow of Java
code," deviating from the default top-to-bottom execution.
Types of Control Flow Statements:
1. Decision Making Statements: Decide "which statement to
execute and when."
If Statement: "Evaluates a condition" (returns boolean
true/false). Executes code if condition is true
Syntax:
if (condition) {
// Code to execute if the condition is true
}
.
If-Else: Executes one block if true, another if false.
Syntax:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
If-Else If Ladder: Allows you to check multiple conditions
sequentially and execute the block of code associated with
the first true condition encountered.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (condition3) {
// Code to execute if condition3 is true
}
// ... more else if conditions
else {
// Code to execute if none of the above conditions are true}
Nested If: An if or if-else statement inside another if or else
statement.
Syntax:
if (outerCondition) {
// Code to execute if outerCondition is true
if (nestedCondition) {
// Code to execute if both outerCondition and
nestedCondition are true
} else {
// Code to execute if outerCondition is true, but
nestedCondition is false
}
} else {
// Code to execute if outerCondition is false
}
Switch Statement: "Similar to if-else if statement" but uses
case blocks.
The switch statement evaluates an expression and compares
its value to various case labels. When a match is found, the
code block associated with that case is executed.
Requires break to exit the switch block; otherwise, it will fall
through to the next case.
Includes an optional default case if no match is found.
Syntax:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
// ... more cases
default:
// code
}
1. Loop Statements: "Execute a block of code repeatedly" until a
condition is met. Used for code optimization (e.g., printing "Hello
World" 1000 times).
For Loop: Used when the "number of iterations is known
in advance." (for (initialization; condition;
increment/decrement))
o Example:
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
While Loop: An "entry-controlled loop" where the
condition is checked at the beginning. Used when the
number of iterations is not known beforehand. (while
(condition))
o Example:
int count = 0;
while (count < 5) {
System.out.println("Count is: " + count);
count++;
}
Do-While Loop: An "exit-controlled loop" where the
condition is checked at the end. Guarantees that the loop
body "executes at least once." (do { ... } while
(condition);)
o Example:
public class DoWhileExample {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 5);
System.out.println("Loop finished.");
}
}
1. Jump Statements: Allow for "jumping" the flow of control within
a loop or block. This allows you to alter the normal sequential
execution of your program.
Break Statement: "Breaks" the current flow, exiting the loop or
switch statement.
o Usage:
1. Exiting Loops: It's commonly used within loops when a specific
condition is met, and you want to stop the loop's execution
prematurely.
2. In switch statements: break is essential in switch statements
to prevent "fall-through," to the next case ;where code from
subsequent case labels is executed even if a match is found.
o Example
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
if (i == 3) {
break; // Exit the loop when i is 3
}
}
// Output:
// Iteration: 1
// Iteration: 2
// Iteration: 3
Continue Statement: "Skips" a specific part of the loop's current
iteration and moves to the next iteration.
o Example :
public class SkipEvenNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
// Check if the number is even
if (i % 2 == 0) {
// If it's even, skip the rest of this iteration
continue;
}
// If it's not even, print the number
System.out.println(i);
}
}
}
15. Arrays
An object in Java that represents a "sequence of character values."
A "collection of similar data type elements" stored in contiguous
memory locations.
"It is a data structure where we store similar elements." (e.g., an
array of integers or an array of characters).
Fixed set of elements.
Index-based: The first element is at index 0.
Length can be found using .length property (e.g.,
arrayName.length).
Types:
Single-Dimensional Arrays: A single row of elements.
Multi-Dimensional Arrays: Arrays of arrays (e.g., a 2D matrix).
Declaration:dataType[] arrayName;
dataType arrayName[];
dataType [] arrayName;
Initialization: dataType[] arrayName = new dataType[size]; (e.g.,
int[] numbers = new int[5];)
o Example :
public class ArrayExample {
public static void main(String[] args) {
// Declare and initialize an array of integers
int[] numbers = {10, 20, 30, 40, 50};
// Access and print an element at a specific index
System.out.println("Element at index 2: " + numbers[2]); //
Outputs: Element at index 2: 30
// Modify an element at a specific index
numbers[2] = 35; // Changes the 3rd element to 35
System.out.println("Modified element at index 2: " +
numbers[2]); // Outputs: Modified element at index 2: 35
// Get the length of the array
int arrayLength = numbers.length;
System.out.println("Length of the array: " + arrayLength); //
Outputs: Length of the array: 5
// Iterate through the array and print all elements
System.out.println("All elements in the array:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
// Outputs: All elements in the array: 10 20 35 40 50
// Another way to iterate using an enhanced for loop (for-each
loop)
System.out.println("\nAll elements using for-each loop:");
for (int number : numbers) {
System.out.print(number + " ");
}
// Outputs: All elements using for-each loop: 10 20 35 40 50
}
}
16. Strings
In Java, a String is an object that represents a "sequence of
character values."
Similar to a char array but with more built-in functionalities.
String is an object, part of the java.lang package.
Provides various methods for string manipulation (e.g., compare,
concat, length, replace, compareTo, intern, substring).
Strings in Java are immutable.( "Immutable" means that once
a String object is created, its value cannot be changed.)
Any operation that seems to modify a string, like concatenation or
replacement, actually creates a new String object with the altered
value, leaving the original string unchanged.
Creation Methods:String Literal: String s = "Welcome"; (Java
manages string pool for efficiency).
Example: String myString = "Hello, Java!";
You can create String objects using the new operator and
the String class constructor.
new Keyword: String s = new String("Welcome"); (Creates a new
object in heap memory).
17. OOPs Concepts (Pillars)
The core principles of Object-Oriented Programming:
1. Inheritance:
"An important pillar of OOPs."
A "mechanism in Java by which one class is allowed to inherit the
features (fields and methods) of another class."
Analogy: A child inheriting traits from parents.
Why use Inheritance?
Code Reusability: Reusing methods and fields from an existing
class.
Organization: It helps organize classes into a logical hierarchy
Terminology:
Super Class (Parent Class/Base Class): The class whose
features are inherited.
Sub Class (Child Class/Derived Class/Extended Class): The
class that inherits features from the superclass.
Usage: Achieved using the extends keyword (e.g., class Engineer
extends Employee).
Types (based on classes):
Single Inheritance: One subclass inherits from one superclass.
Multilevel Inheritance: A chain of inheritance (A -> B -> C).
Hierarchical Inheritance: One superclass is inherited by multiple
subclasses.
(Multiple and Hybrid inheritance are not directly supported by Java
classes but can be achieved using Interfaces).
o Example:
// Base class (Superclass for Single and Hierarchical Inheritance)
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
}
// Single Inheritance
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
}
// Multilevel Inheritance
class SportsCar extends Car {
void boost() {
System.out.println("Sports car boosting performance");
}
}
// Hierarchical Inheritance
class Bus extends Vehicle {
void carryPassengers() {
System.out.println("Bus is carrying passengers");
}
}
// Interfaces for Multiple Inheritance
interface Electric {
void charge();
}
interface Rechargeable {
void recharge();
}
// Hybrid Inheritance (Combining Multilevel and Multiple
Inheritance)
class ElectricCar extends SportsCar implements Electric,
Rechargeable {
@Override
public void charge() {
System.out.println("Electric car charging");
}
@Override
public void recharge() {
System.out.println("Electric car recharging battery");
}
// You can override methods from parent classes if needed
@Override
void drive() {
System.out.println("Electric car is silently driving");
}
}
public class HybridInheritanceExample {
public static void main(String[] args) {
// Demonstrate different inheritance types
// Single Inheritance
Car myCar = new Car();
myCar.start(); // Inherited from Vehicle
myCar.drive(); // Defined in Car
System.out.println(); // For better output formatting
// Multilevel Inheritance
SportsCar mySportsCar = new SportsCar();
mySportsCar.start(); // Inherited from Vehicle
mySportsCar.drive(); // Inherited from Car
mySportsCar.boost(); // Defined in SportsCar
System.out.println();
// Hierarchical Inheritance
Bus myBus = new Bus();
myBus.start(); // Inherited from Vehicle
myBus.carryPassengers(); // Defined in Bus
System.out.println();
// Hybrid Inheritance
ElectricCar myElectricCar = new ElectricCar();
myElectricCar.start(); // Inherited from Vehicle
myElectricCar.drive(); // Overridden in ElectricCar
myElectricCar.boost(); // Inherited from SportsCar
myElectricCar.charge(); // Implemented from Electric
interface
myElectricCar.recharge(); // Implemented from Rechargeable
interface
}
}
1. Polymorphism:
Derived from "Poly" (many) and "Morphism" (forms). Meaning:
"having many forms."
"The ability of a message to be displayed in more than one form."
Analogy: A single person (you) playing multiple roles (son, brother,
friend, student).
Purpose: Allows a "single action to be performed in different ways."
Types:
Compile-Time Polymorphism (Method Overloading / Operator
Overloading): Decided at compile time.
Overloading: "Two or more methods in the same class have the
same name but different parameters." (e.g., add(int a, int b) and
add(double a, double b)). Also known as Static Polymorphism or
Early Binding.
Run-Time Polymorphism (Method Overriding): Decided at
runtime.
Overriding: "Declaring a method in a subclass that is already
present in the parent class." (The subclass provides its own
implementation for an inherited method).
DIFFERENCE BETWEEN COMPILE TIME AND RUN TIME
POLYMORPHISM
Feature Compile-Time Polymorphism Run-Time Polymorphism
Mechanism Method Overloading Method Overriding
Resolution Time Compile Time Runtime
Binding Static Binding Dynamic Binding
Flexibility Less Flexible More Flexible
Performance Faster Slightly Slower
Inheritance Not Required Required
Method Same name, different Same name, same
Signature parameters parameters
Purpose Method variations based on Specific behavior in
input subclasses
o Example :
// Example for Compile-Time Polymorphism (Method Overloading)
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers (same name, different number of
parameters)
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double values (same name, different types
of parameters)
double add(double a, double b) {
return a + b;
}
}
// Example for Run-Time Polymorphism (Method Overriding)
// Superclass
class Animal {
void makeSound() {
System.out.println("Animal making a generic sound..."); //
Default behavior
}
}
// Subclass 1
class Dog extends Animal {
@Override // Annotation indicating method overriding
void makeSound() {
System.out.println("Dog barking: Woof!"); // Specific
behavior for Dog
}
}
// Subclass 2
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meowing: Meow!"); // Specific
behavior for Cat
}
}
public class PolymorphismExample {
public static void main(String[] args) {
// Demonstrating Compile-Time Polymorphism (Method
Overloading)
Calculator calc = new Calculator();
System.out.println("Sum of 2 integers: " + calc.add(5, 10));
// Calls add(int, int)
System.out.println("Sum of 3 integers: " + calc.add(5, 10,
15)); // Calls add(int, int, int)
System.out.println("Sum of 2 doubles: " + calc.add(5.5,
10.5)); // Calls add(double, double)
System.out.println("\n---"); // Separator for output
// Demonstrating Run-Time Polymorphism (Method Overriding)
Animal genericAnimal = new Animal();
Animal myDog = new Dog(); // Animal reference, Dog object
(Upcasting)
Animal myCat = new Cat(); // Animal reference, Cat object
(Upcasting)
genericAnimal.makeSound(); // Calls makeSound() in Animal
myDog.makeSound(); // Calls overridden makeSound()
in Dog (Runtime decision)
myCat.makeSound(); // Calls overridden makeSound()
in Cat (Runtime decision)
}
}
1. Encapsulation:
A "fundamental concept in OOPs that refers to the bundling of
data and methods that operate on that data within a single unit
(class)."
Controlled Access (Getters and Setters): Since the private
variables cannot be accessed directly, you provide public methods
called getters and setters to allow controlled access to them.
Analogy: A capsule containing different medicines.
Purpose: Data Integrity and Security: By restricting direct access,
you ensure that the data is not accidentally or maliciously modified
from outside the class.
Achievement: Achieved by declaring all variables as private and
providing public setter and getter methods to access/modify
them.
Advantages: Data hiding, code reusability, total control over code,
flexibility, improved testing.
Disadvantages: Can increase code complexity, potential
performance overhead, reduces flexibility in implementation if
overused.
1. Abstraction:
A process of "showing only essential functionalities to the user and
hiding the non-essential details."
Analogy: Using an ATM – you know how to withdraw money, but not
the internal processes. Driving a car – you know how to drive, but
not the engine's internal workings.
Achievement: In Java, achieved using Interfaces and Abstract
Classes.
"100% abstraction can be achieved with the help of Interfaces."
Abstract Class: A class declared with the abstract keyword. It can
contain one or more abstract methods (methods "without
implementation" or body) and/or concrete methods.
Abstract Method: A method declared without an implementation.
Interface:A "mechanism to achieve abstraction."
Contains only abstract methods (pre-Java 8) and/or default/static
methods (Java 8+).
Used to achieve multiple inheritance in Java (which classes do not
directly support).
Achieves loose coupling.
Declared using the interface keyword.
A class implements an interface, while it extends a class.
18. Packages
"A mechanism to encapsulate a group of classes, sub-
packages, and interfaces."
Analogy: A cupboard with different compartments for clothes and
jewelry.
Purpose:
Preventing Naming Conflicts: Allows using the same class names
in different packages.
Making Searching/Locating Easier: Organizes classes for easier
access.
Providing Controlled Access: Access modifiers can be applied
within packages.
Data Encapsulation: Hides internal structures.
Types:
User-Defined Packages: Created by the user.
In-built Packages: Provided by Java (e.g., java.lang, java.util,
java.io).
Naming Conventions:"Name should always be lowercase."
Should be period-delimited (e.g., com.example.project).
Often based on company/organization names (reversed URL format).
19. Classpath Settings for a Package
Classpath: "Describes the location where all the required files are
available which are used in the application."
Used by the Java compiler (javac) and JVM to locate .class files and
libraries.
Problem: If the classpath is not set correctly, programs might
encounter "Could not find or load main class" errors, even if the
code is correct.
Setting Classpath:On Windows (Command Prompt): set
PATH=.;C:\Program Files\Java\jdk-X\bin; (The . denotes the current
directory; ; is a separator).
For persistent setting: Set in Environment Variables (System
Properties).
20. JAR Files in Java
JAR (Java Archive): "A package file format typically used to
aggregate many Java class files and associated metadata and
resources into one file to distribute software libraries on the Java
platform."
Essentially a compressed version of .class files, audio, image, and
text files.
Similar to a .zip file; can be created and extracted.
Purpose: Facilitates distribution and efficient storage.
Creation Command: jar cf jarFileName.jar inputFiles (where cf
stands for "create file").
Other operations: Viewing, extracting, updating, running JAR files.
21. Static Import in Java
Introduced in Java 1.5 version.
"With the help of static import, we can access the static member of
a class directly without class name or any object."
Example: Importing Math.sqrt() as sqrt() directly.
Advantage: "Less coding is required."
Disadvantage: Can make programs "unreadable and
unmaintainable" if overused, leading to confusion among
programmers regarding which class a static member belongs to. Sun
Microsystems suggests it improves readability, but programming
experts often advise caution.
Frequently Asked Questions about
Object-Oriented Programming with
Java (Unit 1)
What is Java and why is it so widely used?
Java is a high-level, class-based, object-oriented programming language
developed by James Gosling in 1991. It's widely used because it's a secure
and robust language that is easy to use and debug. A key advantage of
Java is its "Write Once, Run Anywhere" (WORA) capability, meaning code
written in Java can be executed on any platform or operating system
without modification, unlike system-dependent languages like C or C++.
Java applications are found in various domains, including desktop
applications, web applications, mobile apps, enterprise applications, smart
cards, embedded systems, games, and robotics.
What are the core components of the Java Environment
(JDK, JRE, JVM)?
The Java environment consists of three key components:
JVM (Java Virtual Machine): An abstract, virtual machine
(software) written in C language. Its primary role is to execute Java
programs by converting compiled Java bytecode (.class files) into
machine-specific instructions. It acts as an interpreter, loading,
verifying, and executing code, and providing a runtime environment.
The bytecode generated by the Java compiler is platform-
independent, and the JVM is responsible for executing this bytecode
on any underlying operating system.
JRE (Java Runtime Environment): A software layer that exists
above the computer's operating system, providing the environment
necessary to run Java programs. The JRE includes the JVM along with
a set of class libraries and other supporting files. If you only need to
run Java applications, installing the JRE is sufficient.
JDK (Java Development Kit): The most comprehensive part of the
Java environment, the JDK is a collection of tools used for both
developing and running Java programs. It includes the JRE, along
with development tools such as the Java compiler (javac), Java
debugger (jdb), and other utilities. For developers and
programmers, the JDK is essential as it provides everything needed
to write, compile, and execute Java code. The hierarchy is JDK > JRE
> JVM.
What is the basic structure of a simple Java program?
A simple Java program typically follows a specific structure, though some
elements are optional:
1. Package Statement (Optional): Defines the package to which the
class belongs. Packages are used to organize classes and provide a
naming convention to avoid conflicts.
2. Import Statement (Optional): Used to import classes, interfaces,
or entire packages from other libraries to be used in the current
program, particularly for input/output operations.
3. Class Definition: Every Java program must have at least one class.
The class acts as a blueprint or template where all program logic
resides. If a class is declared public, its name must match the
filename of the Java source code to avoid compile-time errors.
4. main Method: The entry point of execution for any Java
application. The public static void main(String[] args) signature is
mandatory.
public: An access modifier, making the method accessible from
anywhere.
static: A keyword that allows the main method to be called without
creating an object of the class, saving memory.
void: Indicates that the main method does not return any value.
main: The name of the method recognized by the JVM as the
starting point.
String[] args: An array of String objects used to hold command-line
arguments.
1. System.out.println(): Used to print output to the console.
Anything enclosed in double quotes will be printed literally.
What are data types and variables in Java?
Data Types: Data types specify the different sizes, types, and
values that can be stored in a variable. They classify the kind of
data a variable can hold (e.g., numbers, characters, true/false
values). Java has two main categories of data types:
Primitive Data Types: Predefined by the language. These
are fundamental, built-in data types that represent single,
simple values include
short: 16-bit signed integer.
int: 32-bit signed integer (most commonly used for whole
numbers).
long: 64-bit signed integer (for very large whole numbers).
float: 32-bit single-precision floating-point number (for
fractional numbers with less precision).
double: 64-bit double-precision floating-point number (for
fractional numbers with higher precision).
char: 16-bit Unicode character (for single characters).
Boolean: Represents a logical value, either true or false.
Non-Primitive (Reference) Data Types: These data
types are not predefined by Java but are created by
the programmer or provided by the Java API. They
refer to objects and are used to store more complex
data., such as String, Array, Class, and Interface.
Variables: variables are containers used to store data that can
change during a program's execution. Each variable has a specific
data type and a unique name.. A variable must be declared with a
data type before it can be used (e.g., int age = 20; where int is the
data type, age is the variable name, and 20 is the value). Variable
values can be changed during program execution.
Local Variables: Declared inside a method, constructor,
or block and are only accessible within that scope.
Instance Variables: Declared inside a class but outside
any method, constructor, or block. Their values are unique
to each object of the class.
Static Variables: Declared with the static keyword inside
a class but outside any method. They belong to the class
itself, not to individual objects, and are shared among all
instances of that class.
Control flow statements determine how a program runs in Java.
Control flow statements in Java allow programmers to dictate the order in
which statements are executed, rather than simply following a top-to-
bottom sequence. This enables more complex and dynamic program
behavior. There are three main types:
Decision-Making Statements: Used to make decisions and
execute specific blocks of code based on conditions.
if statement: Evaluates a boolean condition. If true, a block
of code is executed. It has variations like if-else (executes
one block if true, another if false), if-else if-ladder (for
multiple conditions), and nested if (an if statement inside
another if or else block).
switch statement: Allows a variable to be tested for
equality against a list of values (cases). It provides a more
concise way to handle multiple possible execution paths
than a long if-else if chain.
Loop Statements: Used to execute a block of code repeatedly as
long as a certain condition remains true. They are crucial for tasks
requiring repetition without writing redundant code.
for loop: Used when the number of iterations is known
beforehand. It includes initialization, condition, and
increment/decrement.
while loop: An entry-controlled loop that executes a block
of code repeatedly as long as its condition is true. The
condition is checked before entering the loop body.
do-while loop: An exit-controlled loop where the loop body
is executed at least once, and then the condition is checked.
If the condition is true, the loop continues.
Jump Statements: Used to transfer control unconditionally within a
loop or switch statement.
break statement: Terminates the execution of the current
loop or switch statement and transfers control to the
statement immediately following it.
continue statement: Skips the current iteration of a loop
and continues with the next iteration.
What are Classes and Objects in Object-Oriented Programming (OOP)?
Classes and Objects are fundamental building blocks in OOP:
Class: A blueprint or template for creating objects. It describes the
characteristics (data members/variables) and behaviors
(methods/functions) that objects of that type will have. A class itself
is a logical entity and does not occupy memory space until an object
is created from it. Think of a class as the design plan for a house.
Object: An instance of a class. It is a real-world entity that truly
exists and occupies memory. Objects have a "state" (data values
associated with them), "behavior" (actions they can perform or be
performed on them), and "identity" (a unique internal ID managed
by the JVM). Using the house analogy, an object would be the actual
house built from the blueprint, with its specific rooms, bathrooms,
and kitchen.
For example, Vehicle could be a class, and Car, Truck, or Bicycle would be
objects of that Vehicle class. In a university context, B.Tech Second Year
could be a class, and individual students like "Ravi" or "Saloni" would be
objects.
How does Encapsulation work in Java?
Encapsulation is a core OOP pillar in Java that refers to the bundling of
data (variables) and the methods that operate on that data into a single
unit, which is a class. It essentially involves wrapping up the code and
data together within a protective shield.
The primary goal of encapsulation is to hide the implementation details of
a class from outside access, exposing only a public interface for
interaction. This is achieved by:
1. Declaring all variables in a class as private (restricting direct access
from outside the class).
2. Providing public "setter" methods to write (set) values to these
private variables and "getter" methods to read (get) their values.
Think of a medicine capsule: it bundles different medicines inside a single,
protective outer layer. You consume the capsule (the public interface), but
you don't directly interact with or see the individual medicines inside (the
hidden implementation). This promotes data security, code reusability,
and easier maintenance.
What is Polymorphism in Java and its types?
Polymorphism, derived from Greek words "poly" (many) and "morph"
(forms), means "having many forms." In Java, polymorphism is the ability
of an object to take on many forms or for a single action to be performed
in different ways.
A common real-life example is a person: the same person can act as a
son/daughter to their parents, a brother/sister to their siblings, a friend to
their peers, and a student to their teacher – one person, multiple roles.
In Java, polymorphism is primarily achieved through:
1. Compile-Time Polymorphism (Method Overloading): This
occurs when there are two or more methods in the same class with
the same name but different parameters (number, type, or order of
arguments). The compiler decides which method to call at compile
time based on the arguments provided. This is also known as static
polymorphism or early binding.
2. Run-Time Polymorphism (Method Overriding): This occurs
when a subclass declares a method that is already present in its
parent (super) class, with the same name and parameters. The
specific method to be executed is determined at runtime based on
the actual object type. This is also known as dynamic polymorphism
or late binding.
Polymorphism enhances code reusability, improves readability and
maintainability, and enables generic code writing by allowing objects to be
treated as a single type.
convert_to_textConvert to source
Quiz: Short-Answer Questions
Answer each question in 2-3 sentences.
1. Why is Java considered a platform-independent language?
Java is platform-independent because of its "Write Once, Run
Anywhere" (WORA) principle. Code written in Java is compiled into
bytecode, which can then be executed on any operating system or
hardware environment that has a Java Virtual Machine (JVM),
eliminating the need for recompilation across different platforms.
2. What is the primary role of the Java Virtual Machine (JVM)?
The JVM acts as an abstract machine that provides the runtime
environment for Java bytecode execution. It loads, verifies, and
executes Java programs, translating bytecode into machine-specific
instructions, thus enabling Java's platform independence.
3. Differentiate between JRE and JDK. JRE (Java Runtime
Environment) provides the necessary environment to run Java
applications, including the JVM and class libraries. JDK (Java
Development Kit) is a super-set of JRE, containing all the tools
required for developing, compiling, and running Java applications,
such as the Java compiler (javac) and debugger.
4. Explain the significance of the public static void
main(String[] args) method in Java. This method is the entry
point for any standalone Java application. public allows it to be
accessed from anywhere, static means it can be called without
creating an object of the class, void indicates it doesn't return any
value, and main is the method name recognized by the JVM as the
starting point.
5. What are Java comments and why are they used? Java
comments are non-executable statements in a program ignored by
the compiler and interpreter. They are used to add explanatory
notes to the code, improve readability, make code maintenance
easier, and temporarily disable parts of the code during testing
without deleting them.
6. Briefly explain the purpose of Java operators. Java operators
are special symbols used to perform specific operations on variables
and values. These operations can be arithmetic (like addition or
subtraction), relational (for comparisons), logical (for boolean
operations), or assignment, among others, to manipulate data.
7. What is a Java variable, and what is its primary function? A
Java variable is a data container used to store data values during
program execution. Its primary function is to reserve a named
memory location to hold a specific type of data, which can then be
accessed and modified throughout the program.
8. How does the extends keyword relate to Inheritance in Java?
The extends keyword is used in Java to establish an inheritance
relationship between two classes. It signifies that a subclass (child
class) is inheriting properties and behaviors (methods and fields)
from a superclass (parent class), promoting code reusability.
9. What is the core concept behind Encapsulation in Java?
Encapsulation is an OOP concept that involves bundling data
(variables) and the methods that operate on that data into a single
unit, known as a class. It primarily aims to restrict direct access to
some of an object's components, protecting data from external
interference and misuse.
10. Explain the meaning of Polymorphism in the context of
Java. Polymorphism means "many forms." In Java, it refers to the
ability of an object to take on many forms or the ability of a method
to perform different actions based on the object on which it is
invoked. This allows a single action to be performed in different
ways, typically achieved through method overloading and
overriding.
Answer Key
1. Java compiles code into an intermediate bytecode, not
directly into machine-specific code. This bytecode can then
be run on any system equipped with a Java Virtual Machine
(JVM), which translates the bytecode into native machine
instructions for that specific platform.
2. The JVM's primary role is to execute Java bytecode. It acts
as an interpreter, converting the platform-independent
bytecode into platform-specific machine code, thereby
enabling Java programs to run on diverse hardware and
operating systems.
3. JRE is solely for running Java applications and includes the
JVM and necessary libraries. JDK is for developing Java
applications and contains the JRE along with development
tools like the compiler (javac), debugger, and other utilities.
4. This method serves as the starting point for executing a
Java application. public allows universal access, static
means it can be called without an object, void signifies no
return value, and main is the recognized entry method
name for the JVM.
5. Java comments are text within code ignored by the
compiler, serving as explanatory notes. They enhance code
readability, facilitate understanding for other developers (or
the author later), and aid in debugging by allowing
temporary disabling of code sections.
6. Java operators are special symbols that perform specific
computations or actions on operands. They are
fundamental for manipulating data, performing calculations
(arithmetic), making comparisons (relational), combining
conditions (logical), and assigning values.
7. A Java variable is a named storage location in memory used
to hold data values. Its main function is to store and
manage data during a program's execution, allowing for
values to be assigned, retrieved, and modified as needed.
8. The extends keyword is central to implementing inheritance
in Java. It is used in the class declaration to indicate that a
new class (subclass) will derive properties and behaviors
from an existing class (superclass), promoting code reuse
and establishing an "is-a" relationship.
9. Encapsulation in Java is the practice of bundling data and
the methods that operate on that data within a single unit
(a class). Its primary goal is data hiding and protection,
restricting direct access to an object's internal state and
exposing functionality only through well-defined interfaces
(methods).
10. Polymorphism, derived from "many forms," allows
objects to be treated as instances of their parent class or
interface. In Java, it's typically achieved through method
overloading (same method name, different parameters)
and method overriding (subclass providing specific
implementation for a method defined in its superclass),
enabling flexible and dynamic behavior.
Essay Format Questions
1. Discuss Java's "Write Once, Run Anywhere" philosophy, detailing
how the JVM and bytecode contribute to its platform independence,
and compare this to platform-dependent languages.
2. Explain the purpose and components of the Java Development Kit
(JDK), Java Runtime Environment (JRE), and Java Virtual Machine
(JVM). Illustrate their hierarchical relationship and describe how they
interact during the development and execution of a Java program.
3. Describe the fundamental structure of a Java program, including the
purpose of package statements, import statements, and class
definitions. Provide a detailed explanation of the public static void
main(String[] args) method, breaking down each keyword's role.
4. Compare and contrast the four pillars of Object-Oriented
Programming (OOP) in Java: Encapsulation, Inheritance,
Polymorphism, and Abstraction. Provide real-world examples for
each concept and explain how they contribute to building robust
and maintainable software.
5. Elaborate on different types of control flow statements in Java
(decision-making, loop, and jump statements). Provide the syntax
and a simple example for at least one type from each category,
explaining how they alter the normal sequential execution of a
program.
Glossary of Key Terms
Abstraction: An OOP principle that focuses on showing only
essential features and hiding complex implementation details. In
Java, it's achieved using abstract classes and interfaces.
Access Modifier: Keywords in Java that set the accessibility (scope)
of classes, methods, constructors, and fields. Common types include
public, private, protected, and default.
Application Programming Interface (API): A set of predefined
classes, interfaces, and methods that programmers can use to
develop applications.
Array: A data structure that stores a fixed-size sequential collection
of elements of the same data type.
Bytecode: The platform-independent intermediate code generated
by the Java compiler (javac) from Java source code (.java files). It is
executed by the JVM.
Class: A blueprint or template for creating objects. It defines the
structure (data members) and behavior (methods) that objects of
that class will have.
Class Variable (Static Variable): A variable declared with the
static keyword, belonging to the class itself rather than to any
specific instance (object) of the class.
Comments: Non-executable statements in Java code used for
documentation, explanations, or to temporarily disable code.
Compile Time Polymorphism (Method Overloading): A type of
polymorphism where multiple methods in the same class have the
same name but different parameters. The correct method to call is
determined at compile time.
Constructor: A special method in a class that is automatically
called when an object of that class is created. It is used to initialize
the object's state. Its name must be the same as the class name
and it has no return type.
Control Flow Statements: Statements that dictate the order in
which individual statements or blocks of code are executed. Types
include decision-making (if-else, switch), loop (for, while, do-while),
and jump (break, continue).
Data Types: Classifications that determine the type of data a
variable can hold (e.g., integer, character, boolean) and the
operations that can be performed on it. Java has primitive and non-
primitive data types.
Decision-Making Statements: Control flow statements (like if-else
and switch) that execute different blocks of code based on whether
a specified condition evaluates to true or false.
Default Constructor: A constructor automatically provided by the
Java compiler if no constructor is explicitly defined in a class. It has
no parameters.
Default (Package-Private) Access Modifier: If no access
modifier is specified for a member or class, it has default access,
meaning it can be accessed only within the same package.
Encapsulation: An OOP principle of bundling data (variables) and
the methods that operate on the data into a single unit (class), often
accompanied by data hiding (restricting direct access to data).
extends Keyword: Used in class declarations to signify that a class
is inheriting from another class (inheritance).
final Keyword: A non-access modifier used to make entities non-
modifiable. It can be applied to variables (constant), methods
(cannot be overridden), and classes (cannot be inherited).
Inheritance: An OOP principle where a class (subclass/child class)
derives properties and behaviors from another class
(superclass/parent class), promoting code reusability.
Instance Variable: A variable declared inside a class but outside
any method, constructor, or block. Each object (instance) of the
class has its own copy of instance variables.
Instance of Operator: A relational operator in Java used to test if
an object is an instance of a particular class, subclass, or interface.
It returns a boolean value.
Interface: A blueprint of a class that can contain only abstract
methods (methods without a body) and static final fields. It is used
to achieve abstraction and multiple inheritance in Java.
Java Runtime Environment (JRE): A software package that
provides the class libraries and the Java Virtual Machine (JVM)
needed to run Java applications. It does not include development
tools.
Java Virtual Machine (JVM): An abstract machine that provides
the runtime environment for Java bytecode execution. It translates
bytecode into machine-specific instructions and manages memory.
Jump Statements: Control flow statements (break and continue)
that transfer execution control to another part of the program, often
out of or to the next iteration of a loop.
Keywords: Reserved words in Java that have predefined meanings
and cannot be used as identifiers (e.g., class, public, static).
Local Variable: A variable declared inside a method, constructor,
or block. Its scope is limited to that specific block.
Loop Statements: Control flow statements (for, while, do-while)
that execute a block of code repeatedly as long as a certain
condition remains true.
Method: A block of code that performs a specific action. In Java,
methods are always defined within a class. (Equivalent to
"functions" in other languages).
Method Overloading: (See Compile Time Polymorphism)
Method Overriding: A feature of OOP that allows a subclass to
provide a specific implementation for a method that is already
defined in its superclass.
Object: A real-world entity and an instance of a class. It has a state
(data), behavior (methods), and identity.
Object-Oriented Programming (OOP): A programming paradigm
based on the concept of "objects," which can contain data and code
that operates on that data.
Operator: (See Java Operators)
Package: A mechanism in Java to organize classes, interfaces, and
sub-packages into logical groups, preventing naming conflicts and
providing controlled access.
Platform Independence: The ability of Java programs to run on
any operating system or hardware environment without modification
or recompilation, achieved through bytecode and the JVM.
Polymorphism: An OOP principle meaning "many forms." It allows
objects to be treated as instances of their parent class or interface,
enabling a single action to be performed in different ways.
private Access Modifier: Members declared as private are
accessible only within the class where they are declared.
protected Access Modifier: Members declared as protected are
accessible within the class itself, by classes in the same package,
and by subclasses (even if they are in a different package).
public Access Modifier: Members declared as public are
accessible from anywhere.
Run Time Polymorphism (Method Overriding): A type of
polymorphism where the method call is resolved at runtime,
typically achieved through method overriding.
static Keyword: A non-access modifier that makes a member
belong to the class itself, rather than to any specific instance. Static
members can be accessed directly using the class name.
String: In Java, a String is an object that represents a sequence of
characters. It is immutable.
Subclass (Child Class): A class that inherits properties and
behaviors from a superclass.
Superclass (Parent Class): A class whose properties and
behaviors are inherited by a subclass.
Variable: (See Java Variable)
void Keyword: Used in method declarations to specify that the
method does not return any value.
"Write Once, Run Anywhere" (WORA): Java's core philosophy
stating that compiled Java bytecode can be run on any platform that
supports Java without needing to be recompiled for each specific
platform.
JAR (Java Archive) File: A package file format used to aggregate
many Java class files, associated metadata, and resources into one
file, primarily for distribution of software libraries.