UNIT 1 - APJ (1)
UNIT 1 - APJ (1)
UNIT I
INTRODUCTION TO OOP AND JAVA: Overview of OOP – Object oriented programming paradigms, Features of
Object Oriented Programming, Java Buzzwords- Overview of Java - Data Types, Variables and Arrays, Operators,
Control Statements, Programming Structures in Java, Defining classes in Java, Constructors- Methods -Access
specifiers
1.1Overview of OOP
Object-Oriented Programming System (OOPs) is a programming paradigm based on the concept of ―objects that
contain data and methods, instead of just functions and procedures.
Objects are instances of classes that represent real-world entities with attributes (data) and behaviors (functions).
OOP organizes programs into reusable, modular, and maintainable components, making it ideal for solving complex
problems.
4. Data and the functions are wrapped into a single unit called class so that data is hidden and is safe from accidental
alternation.
Procedure-Oriented Programming is a conventional programming which consists of writing a list of instructions for
the computer to follow and organizing these instructions into groups known as Functions (or) Procedures (or)
subroutines (or) Modules.
Object-Oriented Programming (OOP) is a programming style that organizes software design around objects rather
than actions or logic. Objects represent real-world entities and their attributes and behavior. OOP makes software
easier to design, maintain, and scale. The key principles of the OOP paradigm are:
1. Encapsulation
Encapsulation means bundling data (attributes) and methods (functions) that operate on the data into a single unit,
called a class. It also restricts direct access to some of an object's components to protect its internal state.
Example: A car's engine details are hidden; you only use the "start" button to operate it.
2. Abstraction
Abstraction simplifies complex systems by highlighting only the important details and hiding unnecessary ones.
Example: When you use a smartphone, you just press icons without knowing the internal working of each
application.
3. Inheritance
Inheritance enables a new class (child class) to reuse, extend, or modify behaviors and properties of an existing class
(parent class). This promotes code reusability and reduces redundancy.
Example: A car class can inherit properties like "wheels" and "engine" from a general vehicle class.
4. Polymorphism
Polymorphism allows the same method or action to perform differently depending on the context or object. This
could be achieved through method overriding or overloading.
Example: The "drive" function works differently for a car, a bike, or a truck, even though the function name
is the same.
2
Benefits of OOP
1. Modularity: Code is organized into classes and objects, making it easier to read and manage.
2. Reusability: Inheritance and modular design allow for reusing existing code in new applications.
3. Scalability: OOP handles increasing complexity more effectively with objects and classes.
4. Ease of Maintenance: Encapsulation ensures that code changes in one part don't affect other parts
unnecessarily.
Applications of OOP
Game development
Web applications
User interface design
Mobile applications
By embracing these paradigms, developers can create structured, efficient, and adaptable programs.
OOP provides a structured approach to software design through its unique features. These features simplify complex
systems, promote code reusability, and enhance scalability. The core features are:
1. Class
A class is a blueprint for creating objects. It defines a set of attributes (data) and methods (functions) that
represent the characteristics and behaviors of an entity.
Example: A "Car" class can have attributes like color, model, and speed, and methods like start() and stop().
2. Object
An object is an instance of a class. It represents a specific real-world entity and interacts with other objects
to perform tasks.
Example: A "Toyota" car is an object of the "Car" class.
3. Encapsulation
Encapsulation bundles data (attributes) and methods into a single unit (class) and hides the internal details
from the outside. This ensures controlled access to the data using access specifiers like public, private, and
protected.
Example: A car engine is hidden from the driver, and you control it using the accelerator and brakes.
4. Abstraction
Abstraction focuses on showing only the essential details of an object while hiding the internal
implementation. This reduces complexity and improves usability.
3
Example: You use a TV remote without knowing the internal circuit connections.
5. Inheritance
Inheritance allows a class (child class) to acquire properties and methods of another class (parent class). This
promotes code reuse and hierarchical design.
Example: A "Truck" class can inherit properties like wheels and engine from a "Vehicle" class.
6. Polymorphism
Polymorphism means "many forms" and allows methods or operations to behave differently based on the
object or context.
o Method Overloading: Same method name with different parameters.
o Method Overriding: A child class redefines a method from the parent class.
Example: The "+" operator is used for addition with numbers and concatenation with strings.
7. Dynamic Binding
Dynamic binding (or late binding) means the method to be called is determined at runtime rather than
compile-time.
Example: A method in a parent class is overridden in the child class, and the actual method called depends
on the object type during runtime.
8. Message Passing
Objects communicate with each other by sending and receiving messages (method calls). This interaction
allows for cooperation among objects to achieve a task.
Example: An "order" object can send a message to an "inventory" object to check stock availability.
9. Modularity
Code is organized into classes and objects, making it modular. Modularity allows developers to focus on one
part of the system without affecting others.
OOP features are widely adopted in programming languages like Java, C++, Python, and more, providing a powerful
paradigm for building complex and maintainable software systems.
1. Simple
2. Secure
3. Portable
4
4. Object-oriented
5. Robust
6. Multithreaded
7. Architecture-neutral
8. Interpreted
9. High performance
10. Distributed
11. Dynamic
Simple
Secure
Java makes sure that downloaded programs don't harm your computer by keeping them within a safe
environment.
It stops them from accessing private information or important parts of the system, making it safer to run
programs from the internet.
Portable
Portability means a Java program can run on any computer or operating system without needing separate
versions.
This is achieved through a mechanism that allows the same code to work across different devices, ensuring
ease of use and compatibility.
Object-oriented
Java was designed independently to make object-oriented programming simple and practical.
It uses objects for most things but keeps basic types like integers for fast and easy to use.
Robust
Java is robust because it ensures programs run reliably on different systems by detecting errors early during
both compilation and runtime.
It simplifies memory management with automatic garbage collection and handles run-time errors effectively
using object-oriented exception handling.
Multithreaded
Java supports multithreading, enabling programs to perform multiple tasks at the same time, which is ideal for
interactive and networked applications.
It provides an efficient way to manage multiple processes, allowing developers to focus on their program's behavior
rather than complex multitasking details.
Architecture-neutral
Java was designed to ensure that programs remain functional over time, regardless of operating system or hardware
changes. The goal of "write once; run anywhere, anytime, forever" was largely achieved through decisions made in
the Java language and its Virtual Machine.
5
Interpreted
Java programs are compiled into an intermediate form called bytecode, which can run on any system with a Java
Virtual Machine, enabling cross-platform functionality.
High Performance
Java uses a just-in-time compiler to convert bytecode into native machine code, ensuring very high performance
without losing platform independence.
Distributed
Java is built for the Internet's distributed environment, as it can handle TCP/IP protocols and access resources using
URLs, similar to accessing files. It also supports Remote Method Invocation (RMI), allowing programs to run methods
over a network.
Dynamic
Java can check and manage objects while the program runs. This lets parts of the code be updated easily without
affecting the whole system
Object-Oriented Programming (OOP) is a fundamental part of Java, and all Java programs are based on its principles.
In the process-oriented approach, the program is focused on a series of steps (code) that act on data,
In object-oriented programming, the program is centered around data (objects) and how it interacts with code
through well-defined interfaces. The object-oriented approach helps manage complex programs by giving more
control to the data.
Abstraction :
Abstraction helps manage complexity by treating something as a whole instead of focusing on all its individual parts.
For example, when driving a car, we don't think about its many parts but use it as one object.
In programming, abstraction breaks complex systems into smaller, manageable parts, allowing each part (or object)
to have its own behavior and respond to messages. This concept is key in object-oriented programming, making it
easier to maintain and evolve software.
Object-oriented programming languages help you use three key concepts: encapsulation inheritance, and
polymorphism These concepts are essential for building programs in an
object-oriented way.
Encapsulation:
Encapsulation is the concept of keeping data and the methods that
manipulate it together in a "wrapper" to protect them from outside
interference. In Java, this is done using classes, where data (variables) and
6
actions (methods) are combined, and only specific parts of the code (public methods) are accessible to others, while
the rest is hidden (private) to prevent misuse and maintain control.
Inheritance:
Polymorphism
To compile a Java program, use the javac command followed by the file name:
C:\>javac Example.java
This creates a Example.class file, which contains bytecode (not directly executable).
To run the program, use the java command with the class name (without .class)
C:\>java Example
This runs the program, displaying the output
This is a simple Java program.
7
A Closer Look at the First Sample Program
1. Comments: The program starts with comments that explain what the program does. These are just notes for
the programmer and don’t affect how the program runs.
2. Class Definition: The program creates a class called Example, which is where the code goes.
3. Main Method: The main method is where the program starts. It's like the starting point for Java programs.
4. Print Statement: System.out.println("This is a simple Java program."); prints a message to the screen.
5. Closing Braces: The curly braces ({}) mark where sections of code begin and end.
This program is a basic example showing how Java programs are structured.
Example
if(num< 100)
System.out.println("num is less than 100");
/*
Demonstrate the if.
Call this file "IfSample.java".
*/
class IfSample {
public static void main(String args[]) {
int x, y;
x = 10;
y = 20;
if(x < y) System.out.println("x is less than y");
x = x * 2;
if(x == y) System.out.println("x now equal to y");
x = x * 2;
if(x > y) System.out.println("x now greater than y");
// this won't display anything
if(x == y) System.out.println("you won't see this");
}
}
The output generated by this program is shown here:
x is less than y
x now equal to y
x now greater than y
8
The for Loop
The simplest form of the for loop is shown here:
for(initialization; condition; iteration) statement;
/*
Demonstrate the for loop.
Call this file "ForTest.java".
*/
class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);
}
}
This program generates the following output:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9
/*
Demonstrate a block of code.
Call this file "BlockTest.java"
*/
class BlockTest {
public static void main(String args[]) {
int x, y;
y = 20;
// the target of this loop is a block
for(x = 0; x<10; x++) {
System.out.println("This is x: " + x);
System.out.println("This is y: " + y);
y = y - 2;
}
}
9
}
Whitespaces
Java is called a free-form language because it doesn’t force you to write the code in a specific layout.
You can write everything on one line or across multiple lines as long as the code is clear for the computer to
read.
Spaces, tabs, or newlines are used to separate words or symbols when needed, but how you arrange them is
up to you.
However, organizing your code neatly makes it easier to read and understand.
Identifiers
Identifiers are used to name things, such as classes, variables, and methods.
An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters.
Literals
A constant value in Java is created by using a literal representation of it.
For example, here are some literals:
10
Separators
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon.
Primitive Data Type: byte, short, int, long, char, float, double, and boolean.
Non-Primitive Data Type: String, Array, etc.
11
public static void main(String[] args) {
byte smallNumber = 100;
short mediumNumber = 30000;
int largeNumber = 100000;
long veryLargeNumber = 10000000000L;
float decimalNumber = 3.14f;
double preciseDecimal = 3.141592653;
char letter = 'A';
boolean isJavaFun = true;
Data
Example Explanation
Type
String String name = "Java"; Stores a sequence of characters (text).
Array int[] arr = {1, 2, 3}; Stores multiple values of the same type.
Defines objects with properties and
Class class Car { }
methods.
Interface interface Vehicle { } Defines a blueprint for classes to follow.
Integer Literals
In Java, integer literals are whole numbers like 1, 42, or 123, and they can be written in different number systems
12
Floating-Point Literals
Floating-point literals in Java represent numbers with decimal points, such as 2.0, 3.14159, or 0.6667.
Boolean Literals
Boolean literals are simple. There are only two logical values that a Boolean value can have, true and false.
Character Literals
In Java, character literals are single characters written in single quotes, like 'a' or '@', and are based on the 16-bit
Unicode system.
String Literals
String literals in Java are specified like they are in most other languages—by enclosing a
sequence of characters between a pair of double quotes. Examples of string literals are"Hello World"
17.4 Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a
type, and an optional initializer.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
type identifier [ = value ][, identifier [= value ] …];
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the variable
is declared.
For example, here is a short program that computes the length of the hypotenuse of a right triangle given the lengths
of its two opposing sides:
14
System.out.println(d); // Output: 10.0
Example:
double d = 9.99;
int num = (int) d; // Explicit type conversion (casting) from double to int
System.out.println(num); // Output: 9 (fractional part is lost)
1.7.6 .Arrays
An array is a group of like-typed variables that are referred to by a common name.
Arrays of any type can be created and may have one or more dimensions.
A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables.
Create an Array
Declare an array variable, e.g., int myArray[];
Allocate memory using new,
e.g., myArray = new int[10];
15
To calculate the average of numbers:
1. First way: You can place the square brackets after the variable name:
int[] a = new int[3];
2. Second way: You can place the square brackets after the type:
int a[] = new int[3];
Both of these ways are the same and can be used interchangeably.
Multidimensional Arrays
16
A Few Words About Strings
For now, a string can be declared using the String type, and you can assign a text (like a sentence or word) to a string
variable.
You can then display the string using methods like println().
For example, the line of code String str = "this is a test"; creates a string called str with the value "this is a test", and
System.out.println(str); prints it out.
1.8 Operators
Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Modulus: 0
Program
public class RelationalOperatorExample {
public static void main(String[] args) {
int a = 10, b = 5;
Output:
a == b: false
a != b: true
a > b: true
a < b: false
a >= b: true
a <= b: false
// Logical OR (||)
System.out.println("a || b: " + (a || b)); // true (true OR false)
Output:
a && b: false
a || b: true
!a: false
!b: true
a += 5; // a = a + 5
System.out.println("After a += 5: " + a);
a -= 3; // a = a - 3
18
System.out.println("After a -= 3: " + a);
a *= 2; // a = a * 2
System.out.println("After a *= 2: " + a);
a /= 4; // a = a / 4
System.out.println("After a /= 4: " + a);
a %= 3; // a = a % 3
System.out.println("After a %= 3: " + a);
}
}
Output:
Initial value of a: 10
After a += 5: 15
After a -= 3: 12
After a *= 2: 24
After a /= 4: 6
After a %= 3: 0
// Pre-increment
System.out.println("Pre-Increment: " + (++x)); // x = 6
// Post-increment
System.out.println("Post-Increment: " + (x++)); // Prints 6, then x becomes 7
System.out.println("After Post-Increment, x: " + x); // x = 7
// Pre-decrement
System.out.println("Pre-Decrement: " + (--x)); // x = 6
// Post-decrement
System.out.println("Post-Decrement: " + (x--)); // Prints 6, then x becomes 5
System.out.println("After Post-Decrement, x: " + x); // x = 5
}
}
Output
Pre-Increment: 6
Post-Increment: 6
After Post-Increment, x: 7
Pre-Decrement: 6
Post-Decrement: 6
After Post-Decrement, x: 5
19
6. Conditional (Ternary) Operator: Used for conditional expressions.
Example: condition ? true_expression : false_expression
Program:
public class TernaryExample {
public static void main(String[] args) {
int a = 10, b = 20;
Output
The maximum value is: 20
// Increment Operator
System.out.println("Incremented a: " + (++a));
// Conditional Operator
int max = (a > b) ? a : b;
System.out.println("Max value: " + max);
}
}
20
1.9 Control Statements
Control statements in Java are used to control the flow of execution based on conditions.
They allow you to make decisions, repeat actions, and branch the program’s execution.
1. Decision-Making Statements
Syntax
if (condition) {
// code to be executed
}
Program
public class Main {
public static void main(String[] args) {
int number = 10;
if (number > 5) {
System.out.println("Number is greater than 5");
}
}
}
Output:
Number is greater than 5
if-else statement: Executes one block of code if the condition is true, and another block if it's false.
Syntax
if (condition) {
// code to be executed if true
} else {
// code to be executed if false
}
Program
public class Main {
public static void main(String[] args) {
int num = -5;
if (num > 0)
System.out.println("Positive");
else
System.out.println("Negative");
}
}
Output
Negative
21
Syntax
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else {
// code if no condition is true
}
Program
Output
switch statement: A more efficient alternative to multiple if-else statements when you need to check a
variable against multiple possible values.
Syntax
switch (variable) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// code if no case matches
}
Program:
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
String dayName;
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
default: dayName = "Invalid day"; break;
22
}
System.out.println(dayName);
}
}
Output:
Wednesday
2. Looping Statements
Syntax
for (int i = 0; i < 5; i++) {
// code to be executed
}
Program:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++)
System.out.println("Hello, Java! " + i);
}
}
Output
Hello, Java! 1
Hello, Java! 2
Hello, Java! 3
Hello, Java! 4
Hello, Java! 5
while loop:
Syntax
while (condition) {
// code to be executed
}
Program
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1; // Initialize the variable
while (i <= 5) { // Condition to check
System.out.println(i); // Print the value of i
i++; // Increment i by 1
}
}
23
}
Output
1
2
3
4
5
do-while loop: Similar to the while loop, but it checks the condition after executing the loop, ensuring the
block of code runs at least once.
Syntax
do {
// code to be executed
} while (condition);
Program
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
}
}
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
3. Jump Statements
These statements allow you to alter the flow of control in a loop or block of code.
Syntax
break; // Exits the nearest enclosing loop
Program:
24
}
Output
1
2
3
4
Continue: Skips the current iteration of the loop and moves to the next iteration.
Syntax
continue;
Program
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // Skip iteration when i is 3
System.out.println(i);
}
}
}
Output
1
2
4
5
Summary:
These control statements provide the flexibility to make decisions and repeat operations, making them essential for
developing logic in Java programs.
Class:
It defines the properties (variables) and behaviors (methods) that the objects of this class will have.
Object:
25
Example: Simple Class with Objects
1. Defining a Class:
Box is a class.
It has three properties: width, height, and depth.
The object mybox is created with its own set of width, height, and depth.
These properties can store specific values for this object.
Constructors
Purpose: Constructors automatically initialize an object when it is created, making it more concise and convenient
than manually initializing variables.
Key Features:
2. No Return Type: Not even void, as it implicitly returns the object of the class.
3. Automatic Call: Invoked as soon as the object is created, before new completes.
class Box {
double width;
26
double height;
double depth;
Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
Output:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
A parameterized constructor allows you to create objects with different initial values, unlike a default constructor
that assigns the same value to all objects.
27
Parameterized Constructor:
Box(double w, double h, double d) allows you to specify the dimensions of the box when creating it.
Volume is 3000.0
Volume is 162.0
Methods
28
type: the type of data the method will return (for example, int, double, etc.). If the method doesn't return a
value, the return type should be void.
name: the method’s name, which is a valid identifier.
parameter-list: the parameters are values the method can take when called. If the method doesn't require
any, the parameter list will be empty.
If the method returns a value, it uses the return keyword to send a result back, like so:
return value;
For example, a Box class might have instance variables like width, height, and depth. A volume() method can
compute the box's volume:
This volume() method is invoked on a Box object, like mybox1.volume(), which then computes the volume of
the box using its dimensions (width, height, depth).
Methods can be more flexible by returning values. For example, the volume() method can return the
computed value rather than just printing it:
The volume() method can now be used to return the volume value to
the calling code, for example:
Methods can also take parameters to make them more generalized. For example, a method that returns the
square of a number can accept any number as input:
29
Using Methods to Set Data
Methods can also be used to set the values of instance variables. Instead of directly assigning values to them,
a method can be used for setting these values. For example, a setDim() method can be used to set the dimensions of
a Box object:
Understanding methods, their parameters, and return values is crucial for effective Java programming.
Methods let you control actions within classes and make your programs more flexible and organized.
Access specifiers
Definition: Access specifiers are used to specify the visibility and accessibility of a class constructors, member
variables and methods.
Java classes, fields, constructors and methods can have one of four different access modifiers:
1. Public
2. Private
3. Protected
4. Default (package)
30
The default access modifier is friendly. This is similar to public modifier except only the classes belonging to a
particular package knows the variables and methods.
Program
class Example {
private int privateVar = 10;
protected int protectedVar = 20;
public int publicVar = 30;
void display() {
System.out.println("Private: " + privateVar);
System.out.println("Protected: " + protectedVar);
System.out.println("Public: " + publicVar);
}
}
Output:
Private: 10
Protected: 20
Public: 30
31