Projava Ebook 1
Projava Ebook 1
Learning Outcomes:
Students will be able to iden fy and describe the key features of Java, such as
its pla orm independence, object-oriented nature, and automa c memory
management.
Students will be able to differen ate between Java and C++ by comparing their
syntax, memory management, and pla orm dependence.
Students will be able to demonstrate the ability to construct Java program
structures, including class declara ons, main methods, and the use of packages
and comments.
Students will be able to explain the role and func onality of the JVM, including
bytecode execu on and pla orm independence.
Students will be able to apply various control structures (like loops and
condi onals) and effec vely use arrays in Java programming to solve problems.
Structure:
1.1 Java features
1.2 How Java differs from C++
1.3 Java Program Structure
1.4 Java Tokens
1.5 Java virtual machine
1.6 Constants, variables and data types
1.7 Operators & expressions
1.8 Control structures
1.9 Arrays
Knowledge Check 1
Outcome-Based Ac vity 1
1.10 class & object
1.11 garbage collec on
1.12 finalize() method
1.13 Inheritance
1.14 method overriding
1.15 Abstract class
1.16 Interfaces, Extending Interfaces & Accessing Interface variables.
Knowledge Check 2
Outcome-Based Ac vity 2
1.17 Summary
1.18 Keywords
1.19 Self-Assessment Ques ons
1.20 References / Reference Reading
1.1Java Features:
Portability:
The WORA principle states that Java code is turned into bytecode, an intermediate
form that may run on any device that has a Java Virtual Machine (JVM).
Object-Oriented:
Java is fundamentally object-oriented, promo ng the use of classes and objects.
Encapsula on, inheritance, and polymorphism are integral concepts in Java.
Pla orm Independence:
Java applica ons can run on any pla orm with a compa ble JVM.
Reduces dependency on the underlying hardware and opera ng system.
Automa c Memory Management:
Garbage Collec on automa cally manages memory, freeing developers from
manual memory alloca on and dealloca on.
Security:
Built-in security features to create secure applica ons.
The bytecode verifier ensures that code running on the JVM is safe.
Mul threading:
Java supports concurrent execu on with built-in support for mul threading.
Allows the crea on of responsive and efficient applica ons.
Keywords
Special Indentifiers
Symbols
Modifiers Literals
Tokens
in Java
White
Operators
Spaces
Comments Separators
Keywords:
Reserved words with predefined meanings.
Examples: `class`, `public`, `sta c`, `void`, etc.
Iden fiers:
Names given to variables, methods, classes, etc., by the programmer.
Must start with a le er, underscore (_), or dollar sign ($) and can be followed by
le ers, digits, underscores, or dollar signs.
Literals:
Represent constant values.
Examples: Numeric literals (e.g., `12`, `3.14`), character literals (`'A'`), string
literals (`"Hello"`), boolean literals (`true` or `false`).
Operators:
Symbols that perform opera ons on variables and values.
Examples: Arithme c operators (`+`, `-`, ``, `/`), rela onal operators (`<`, `>`, `==`,
`!=`), logical operators (`&&`, `||`).
Separators:
Characters used to separate statements and define the structure of the program.
Examples: Semicolon (`;`), comma (`,`), parentheses (`()`), curly braces (`{}`),
square brackets (`[]`).
Comments:
Not treated as a part of the program but are useful for documenta on.
Mul -line comments are encapsulated between {/} and {/}, while single-line
comments begin with {//}.
White Spaces:
Spaces, tabs, and line breaks that separate tokens.
Ignored by the compiler but enhance code readability.
Modifiers:
Keywords that define the scope and behavior of variables, methods, and classes.
Examples: `public`, `private`, `sta c`, `final`.
Special Symbols:
Symbols with special meanings in Java.
Examples: `@` (used in annota ons), `::` (method reference), `...` (varargs).
1.8Control structures
Condi onal Statements:
1 `if` Statement:
A block of code can only be executed by the `if` statement if a par cular condi on
is met.
if (condi on) { // Code to be run in the event that the condi on is sa sfied }
2 `if-else` Statement:
If the condi on is true, you can run one block of code using the `if-else` statement;
if it is false, you can run an other chunk of code.
if (condi on) { // Code to be run in the event that the condi on is sa sfied } If the
condi on is false, then else { // Code to be executed }
An illustra on would be as follows: int y = 3; if (y % 2 == 0) { System.out.println("y
is even"); } else { System.out.println("y is odd");
3 `switch` Statement:
The `switch` statement is used to select one of many code blocks to be executed.
switch (variable) {
case value1:
// Code to be executed if variable equals value1
break;
case value2:
// Code to be executed if variable equals value2
break;
// addi onal cases...
default:
// Code to be executed if none of the cases match
}
Example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// addi onal cases...
default:
System.out.println("Invalid day");
}
Looping Statements:
1 `for` Loop:
The `for` loop is used to iterate a block of code a specific number of mes.
Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Itera on " + i);
}
2 `while` Loop:
The `while` loop con nues to execute a block of code as long as the specified
condi on is true.
while (condi on) {
// Code to be executed as long as the condi on is true
}
Example:
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
3 `do-while` Loop:
The `do-while` loop is similar to the `while` loop, but it ensures that the code block
is executed at least once, even if the condi on is ini ally false.
do {
// Code to be executed at least once
} while (condi on);
Example:
int num = 1;
do {
System.out.println("Number: " + num);
num++;
} while (num <= 3);
1.9Arrays
1. Arrays in Java:
In Java, an array is a form of data structure that lets you have several values of the
same kind stored under one variable name. Data collec ons are easier to maintain
and work with when arrays are used.
2. Declara on and Ini aliza on:
Declara on:
The data type of each element that the array will contain must be specified before
the array name and square brackets {[]} are used to declare the array.
dataType[] arrayName;
Example:
int[] numbers;
Example:
int[] numbers = {1, 2, 3, 4, 5};
Using `new` Keyword:
dataType[] arrayName = new dataType[size];
Example:
int[] numbers = new int[5];
Example:
int thirdElement = numbers[2]; // Accessing the third element (index 2) of the
'numbers' array.
4. Array Length:
The length of an array, indica ng the number of elements it can hold, can be
obtained using the `length` property.
Example:
int length = numbers.length; // Returns the length of the 'numbers' array.
5. Itera ng Through an Array:
`for` Loop:
for (int i = 0; i < arrayName.length; i++) {
// Access and process array elements using arrayName[i]
}
Example:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Example:
for (int num : numbers) {
System.out.println(num);
}
Declara on:
dataType[][] arrayName;
Example:
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Knowledge Check 1
Fill in the Blanks
1. Java is known for its __________ programming paradigm. (Object-
Oriented/Procedural)
2. Unlike C++, Java does not support explicit __________. (Memory
Management/Pointers)
3. The _________method is a mandatory entry point for the execu on of a Java
program. (Main/Start)
4. Iden fiers in Java must start with a ______ or underscore. (Le er/Number)
5. The JVM interprets Java source code and translates it into __________ for
execu on on the host system. (Bytecode/Machine Code)
Outcomes-Based Ac vity 1
Implement a Java program that simulates a library system. U lize object-
oriented principles to create classes for books, library users, and transac ons.
Showcase pla orm independence by running the program on different
opera ng systems.
1.10 Class & Object
1. Classes in Java:
Defini on:
In Java, a class is an object crea on blueprint or template. It combines behavior
and data into one cohesive unit. The building blocks of object-oriented
programming are classes.
Syntax:
// Class Declara on
public class ClassName {
// Fields (a ributes/variables)
dataType fieldName;
Example:
public class Car {
// Fields
String make;
String model;
int year;
// Methods
void startEngine() {
System.out.println("Engine started!");
}
}
2. Objects in Java:
Defini on:
An instance of a class is called an object. It is constructed from a class defini on and
represents an actual thing. The class defines the state and behavior of an
object.Object Crea on:
// Syntax
ClassName objectName = new ClassName();
Example:
Car myCar = new Car();
// Invoking Methods
objectName.methodName(parameters);
Example:
// Accessing Fields
myCar.make = "Toyota";
myCar.model = "Camry";
myCar.year = 2022;
// Invoking Methods
myCar.startEngine();
3. Constructors:
Defini on:
When an object is formed, a class's constructor—a unique method—is called. It sets
the object's state to ini al.
Default and Parameterized Constructors:
// Default Constructor
public ClassName() {
// Ini aliza on code
}
// Parameterized Constructor
public ClassName(parameterType param1, parameterType param2, ...) {
// Ini aliza on code using parameters
}
Example:
public class Student {
String name;
int age;
// Default Constructor
public Student() {
name = "Unknown";
age = 0;
}
// Parameterized Constructor
public Student(String studentName, int studentAge) {
name = studentName;
age = studentAge;
}
}
4. Encapsula on:
Defini on:
Combining data (fields) and methods that work with the data into a single unit
(class) is known as encapsula on. It aids in data concealing and safeguards the
object's integrity.
• Modifiers of Access:
- {public}: Reachable from any loca on.
- {private}: Only available inside the class.
- {protected}: Available only within this class and any of its child classes.
- (default): Available inside the same bundle.
Example:
public class BankAccount {
private double balance; // private field
Program
// Define the class
class Car {
// Fields
String make;
String model;
int year;
// Constructor
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
// Main class
public class CarExample {
public sta c void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car("Toyota", "Camry", 2022);
In this program:
1. The `Car` class is defined with fields (`make`, `model`, `year`), a constructor, and
a method (`displayInfo`) to display car informa on.
2. The `CarExample` class is the main class that contains the `main` method.
3. An object `myCar` of the `Car` class is created in the `main` method.
4. The fields of the `myCar` object are set using the constructor.
5. The `displayInfo` method is called to print the car informa on to the console.
This simple program illustrates the basic concepts of classes and objects in Java. The
`Car` class serves as a blueprint for crea ng car objects, and the `CarExample` class
demonstrates the crea on and usage of an object of the `Car` class.
3. `finalize()` Method:
Defini on:
The `finalize()` method is part of the `Object` class and is called by the garbage
collector before an object is reclaimed.
Syntax:
protected void finalize() throws Throwable {
// Cleanup code before object is garbage collected
}
Example:
public class MyClass {
// Class members...
protected void finalize() throws Throwable {
// Cleanup code
super.finalize();
}
}
Program
class MyClass {
// Class members...
// Constructor
public MyClass() {
System.out.println("Object created");
}
// Finalize method
protected void finalize() throws Throwable {
System.out.println("Object is being garbage collected");
// Cleanup code (if needed)
super.finalize();
}
}
Please note that while using `System.gc()` suggests garbage collec on, the actual
execu on of garbage collec on is managed by the Java Virtual Machine (JVM), and
there's no guarantee that it will happen immediately. The `finalize()` method is
called before an object is garbage collected, and it can be used for any necessary
cleanup opera ons.
1.12 Inheritance
1. Inheritance in Java:
Defini on:
A key idea in object-oriented programming is inheritance, which permits a class
(subclass or derived class) to take on characteris cs and traits from another class
(superclass or base class). It creates a "is-a" link between classes and encourages
code reuse.
Syntax:
// Superclass (Base Class)
class Superclass {
// Fields and methods of the superclass
}
// Constructor
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}
// Method
public void displayInfo() {
System.out.println("Vehicle Informa on:");
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}
Subclass (Car):
// Subclass
class Car extends Vehicle {
// Addi onal fields
String model;
// Constructor
public Car(String brand, String model, int year) {
// Call the superclass constructor using 'super'
super(brand, year);
this.model = model;
}
In this example:
- The `Vehicle` class is the superclass with fields and a method to display vehicle
informa on.
- The `Car` class is the subclass that extends `Vehicle`. It has addi onal fields and a
method.
- The `InheritanceExample` class demonstrates the crea on of a `Car` object and
the use of inherited methods from both the superclass and the subclass.
The Java inheritance link between the `Car` and `Vehicle` classes is demonstrated
by this program. In addi on to inheri ng fields and methods from the
superclass, the subclass is also allowed to have its own fields and methods.
1. Single Inheritance:
Defini on:
A class that inherits from only one superclass is said to have single inheritance.
Syntax:
// Superclass
class Superclass {
// Fields and methods of the superclass
}
Example:
// Single Inheritance Example
class Animal {
void eat() {
System.out.println("Animal is ea ng");
}
}
// Interface 2
interface Interface2 {
// Methods of Interface2
}
Example:
// Mul ple Inheritance Example through Interfaces
interface Walkable {
void walk();
}
interface Swimmable {
void swim();
}
3. Hierarchical Inheritance:
Defini on:
When several classes derive from a single superclass, this is known as
hierarchical inheritance.
Syntax:
// Superclass
class Animal {
// Fields and methods of the superclass
}
Example:
// Hierarchical Inheritance Example
class Animal {
void eat() {
System.out.println("Animal is ea ng");
}
}
// Constructor
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}
// Method
public void displayInfo() {
System.out.println("Vehicle Informa on:");
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}
// Constructor
public Bicycle(String brand, int gears, int year) {
// Call the superclass constructor using 'super'
super(brand, year);
this.gears = gears;
}
// Addi onal method
public void pedal() {
System.out.println("The bicycle is now pedaling.");
}
}
// Main class
public class InheritanceProgram {
public sta c void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car("Toyota", "Camry", 2022);
In this program:
- The `Vehicle` class is the superclass with fields and a method to display vehicle
informa on.
- The `Car` class is a subclass of `Vehicle` with addi onal fields and a method.
- The `Bicycle` class is another subclass of `Vehicle` with its own set of addi onal
fields and a method.
- The `InheritanceProgram` class demonstrates the crea on of objects of both the
`Car` and `Bicycle` classes, showcasing the inheritance rela onship.
Subclass (Circle):
// Subclass
class Circle extends Shape {
double radius;
// Constructor
public Circle(double radius) {
this.radius = radius;
}
3. Complete Program:
Here is the complete Java program that demonstrates method overriding:
// Superclass
class Shape {
double calculateArea() {
return 0; // Default implementa on (to be overridden)
}
}
// Subclass
class Circle extends Shape {
double radius;
// Constructor
public Circle(double radius) {
this.radius = radius;
}
// Main class
public class MethodOverridingExample {
public sta c void main(String[] args) {
// Create an object of the subclass (Circle)
Circle myCircle = new Circle(5.0);
2. Abstract Method:
Defini on:
A method expressed in an abstract class but lacking a body is called an abstract
method. Abstract methods require an implementa on, which subclasses must
supply.
Syntax:
// Abstract class with an abstract method
abstract class AbstractClass {
abstract void abstractMethod();
}
// Concrete method
void display() {
System.out.println("This is a shape.");
}
}
Subclass (Circle):
// Subclass extending the abstract class
class Circle extends Shape {
double radius;
// Constructor
public Circle(double radius) {
this.radius = radius;
}
// Constant(s)
dataType CONSTANT_NAME = value;
}
2. Extending Interfaces:
Defini on:
In Java, an interface can extend another interface, inheri ng its abstract methods
and constants. This allows for the crea on of a hierarchy of interfaces.
Syntax:
// Interface extending another interface
interface MyExtendedInterface extends AnotherInterface {
// Addi onal abstract method(s) and constant(s)
}
// Constant
String COLOR = "Red";
}
Using Interfaces:
// Class implemen ng the interfaces
class Shape implements Resizable {
// Implementa on of draw method
@Override
public void draw() {
System.out.println("Drawing a shape with color: " + COLOR);
}
In this example:
- The `Drawable` interface defines an abstract method `draw` and a constant
`COLOR`.
- The `Resizable` interface extends `Drawable` and adds an abstract method `resize`.
- The `Shape` class implements the interfaces and provides implementa ons for the
abstract methods.
- The `color` variable is accessed directly from the interface.
Knowledge Check 2
State True or False
1. "In Java, an object is an instance of a class." (True)
2. "Garbage collec on in Java is a manual process where the developer has to
explicitly deallocate memory." (False)
3. "The `finalize()` method is called by the programmer to ini ate garbage
collec on." (False)
4. "In Java, a subclass can inherit both a ributes and methods from mul ple
superclasses simultaneously." (False)
5. "Method overriding in Java allows a subclass to provide a specific
implementa on for a method that is already defined in its superclass." (True)
Outcomes-Based Ac vity 2
Apply and demonstrate understanding of key Java concepts such as classes,
objects, inheritance, method overriding, abstract classes, interfaces, garbage
collec on, and finalize() method. For Design a program that represents different
geometric shapes, u lizing class hierarchy, inheritance, and interfaces.
1.16 Summary
A feature-rich language with Object-Oriented paradigm, pla orm
independence, simple syntax, robust security, mul threading, and support for
distributed compu ng.
Differen ates from C++ through pla orm independence, no explicit pointers,
automa c garbage collec on, avoidance of operator overloading, and use of
interfaces for mul ple inheritance.
Program structure includes class declara on, main method, package
organiza on, and comments for documenta on.
Tokens encompass keywords, iden fiers, literals, operators, separators, and
comments for code clarity.
The Java Virtual Machine (JVM) provides a pla orm-independent execu on
environment, interpre ng bytecode, managing memory, and enforcing security.
Constants, variables, and data types define the founda on for storing and
manipula ng data.
Operators and expressions handle opera ons on variables and literals.
Control structures, including condi onal and looping statements, govern
program flow.
Arrays act as a data structure, allowing the collec on and indexing of elements.
Classes and objects form the core of Java, with constructors ini alizing object
proper es.
Garbage collec on automa cally manages memory by reclaiming unused
objects.
Inheritance involves the crea on of subclasses inheri ng proper es from a
superclass.
Method overriding allows specific implementa ons in subclasses.
Abstract classes feature abstract and concrete methods for structured code.
Interfaces combine abstract methods and constants, suppor ng extension and
direct access to interface variables.
1.17 Keywords
Java Features: This keyword refers to the dis nc ve characteris cs of the Java
programming language. Java is known for its portability, object-oriented nature,
pla orm independence, automa c memory management (garbage collec on),
robust security features, and support for mul threading. These features make
Java a versa le and widely-used programming language.
Java vs. C++: This sec on highlights the differences between Java and C++. Key
differences include Java's pla orm independence through bytecode and the
Java Virtual Machine (JVM), automa c memory management (garbage
collec on) as opposed to C++'s manual memory management, and Java's
simpler syntax. Java also avoids explicit use of pointers and mul ple inheritance,
which are features present in C++.
Java Program Structure: This keyword encompasses the essen al components
of a Java program's structure. It includes class declara ons, the main method,
the use of packages for organiza on, and the importance of comments for
documenta on. Understanding these elements is fundamental to wri ng well-
organized Java programs.
Java Virtual Machine (JVM): The JVM is a crucial component of Java's
architecture. It's responsible for execu ng Java bytecode, providing a pla orm-
independent run me environment. The JVM plays a key role in memory
management, security enforcement, and ensuring Java's pla orm
independence.
Garbage Collec on: This term refers to Java's process of automa c memory
management. The garbage collector in Java automa cally iden fies and discards
objects that are no longer in use, thus preven ng memory leaks and op mizing
memory usage. Understanding garbage collec on is important for efficient Java
programming.