0% found this document useful (0 votes)
14 views

UNIT 1 - APJ (1)

The document provides an overview of Object-Oriented Programming (OOP) principles and their application in Java, highlighting features such as encapsulation, inheritance, and polymorphism. It discusses the advantages of OOP, including modularity, reusability, and ease of maintenance, along with Java's unique buzzwords that emphasize its design principles. Additionally, the document includes basic Java programming concepts, including class and object definitions, control statements, and sample code demonstrating these concepts.

Uploaded by

jesudosss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

UNIT 1 - APJ (1)

The document provides an overview of Object-Oriented Programming (OOP) principles and their application in Java, highlighting features such as encapsulation, inheritance, and polymorphism. It discusses the advantages of OOP, including modularity, reusability, and ease of maintenance, along with Java's unique buzzwords that emphasize its design principles. Additionally, the document includes basic Java programming concepts, including class and object definitions, control statements, and sample code demonstrating these concepts.

Uploaded by

jesudosss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

CSPC404 ADVANCED PROGRAMMING IN JAVA

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.

Features / advantages of Object Oriented Programming :-

1.It emphasis in own data rather than procedure.

2. It is based on the principles of inheritance, polymorphism, encapsulation and data abstraction.

3. Programs are divided into objects.

4. Data and the functions are wrapped into a single unit called class so that data is hidden and is safe from accidental
alternation.

5. Objects communicate with each other through functions.

6. New data and functions can be easily added whenever necessary.

7. Employs bottom-up approach in program design.

PROCEDURE-ORIENTED PROGRAMMING [POP]:

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.

Example: A program may involve the following operations:

Collecting data from user (Reading)

Calculations on collected data (Calculation)


1
Displaying the result to the user (Printing)

1.2 Object-Oriented Programming Paradigms

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

OOP is used in various domains, such as:

 Game development
 Web applications
 User interface design
 Mobile applications

By embracing these paradigms, developers can create structured, efficient, and adaptable programs.

1.3 Features of Object Oriented Programming

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.

Advantages of OOP Features

1. Code Reusability: Inheritance and modularity reduce duplicate code.


2. Maintainability: Encapsulation ensures that updates in one area have minimal impact elsewhere.
3. Scalability: Easier to expand functionality using objects and classes.
4. Efficiency: Polymorphism and abstraction improve program design and usability.

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.4 Java Buzzwords

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

 Java is designed to be easy for experienced programmers to learn and use.


 If you already know object-oriented programming, learning Java will be even simpler.
 For C++ programmers, switching to Java is easy since Java uses similar syntax and object-oriented features.

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

1.5 An Overview of Java

Object-Oriented Programming (OOP) is a fundamental part of Java, and all Java programs are based on its principles.

1.5.1 Two Paradigms

Programs have two main ways of organizing: process-oriented and object-oriented.

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.

1.5.2 The Three OOP Principles

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:

 Inheritance allows one object to take on properties


from another.
 For example, a dog inherits traits from the animal
class, like size and intelligence, while adding unique
traits like breed.

Polymorphism

 Polymorphism means using a single method or


interface to handle different types of data.
 For example, in Java, you can use the same set of
instructions to create stacks for integers, decimals, or
characters, and Java program will automatically choose
the right action based on what type of data you are
working with.

1.5.3 A First Simple Program

Entering the Program

 In Java, the name of the source file is very important.


 The file name must match the class name inside it and end with .java.
 For example, if your class is named Example, the file must be named Example.java.
 Java is case-sensitive, so the capitalization must match exactly.
 Following this rule helps keep programs organized and easy to manage.

Compiling the Program

 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

The program begins with the following lines

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.

1.5.4 Two Control Statements


The if Statement
The Java if statement works much like the IF statement in any other language.
Syntax :
if(condition) statement;

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

1.5.5 Using Blocks of Code


 Java allows two or more statements to be grouped into blocks of code, also called code blocks.
 Once a block of code has been created, it becomes a logical unit that can be used any place that a
single statement can.

/*
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
}

The output generated by this program is shown here:


This is x: 0
This is y: 20
This is x: 1
This is y: 18
This is x: 2
This is y: 16
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2
In this case, the target of the for loop is a block of code and not just a single statement.
1.5.6 Lexical issues

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.

Someexamples of valid identifiers are

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.

The Java Keywords


There are 50 keywords currently defined in the Java language

The Java Class Libraries


 Java provides built-in methods like println() and print() through System.out, where System is a predefined
class included in all programs.
 Java comes with class libraries that handle tasks like input/output, working with strings, networking,
graphics, and creating graphical user interfaces (GUIs).
 These libraries add powerful features to Java.
 Learning Java also involves understanding how to use these standard libraries.

1.7 Data Types, Variables, and Arrays

Java supports several types of data.

1.7.1 Java is a strongly typed language


 Every variable and expression has a specific, well-defined type.

1.7.2 The Primitive Types

Primitive Data Type: byte, short, int, long, char, float, double, and boolean.
Non-Primitive Data Type: String, Array, etc.

Example Program for Primitive Data Types:


public class PrimitiveExample {

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;

System.out.println("Byte: " + smallNumber);


System.out.println("Short: " + mediumNumber);
System.out.println("Int: " + largeNumber);
System.out.println("Long: " + veryLargeNumber);
System.out.println("Float: " + decimalNumber);
System.out.println("Double: " + preciseDecimal);
System.out.println("Char: " + letter);
System.out.println("Boolean: " + isJavaFun);
}
}
Non-Primitive Data Types (Stores complex values, like objects)

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.

Example Program for Non Primitive Data Types:

public class NonPrimitiveExample {


public static void main(String[] args) {
String name = "Java Programming";
int[] numbers = {10, 20, 30, 40}; // Array
System.out.println("String: " + name);
System.out.println("Array first element: " + numbers[0]);
}
}

1.7.3 A Closer Look at Literals

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 ] …];

Here are several examples of variable declarations of various types.


int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

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:

// Demonstrate dynamic initialization.


class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
13
}
}
The Scope and Lifetime of Variables

 Each block creates a new scope, which controls:


o Visibility: What parts of the program can access variables.
o Lifetime: How long the variables exist.
 Java's scopes are different from traditional global and local scopes in other languages:
o Java mainly uses class scope and method scope. Class scope has unique properties.
 Variables within a method (including its parameters) are only accessible within the method's scope.
 Variables inside a scope:
o Cannot be accessed outside that scope.
o Are localized for security and protection.
 Scopes can nest:
o Inner scopes can access variables from their outer scope.
o Outer scopes cannot access variables from inner scopes.
This setup supports encapsulation and safe programming.

// Demonstrate block scope.


class Scope {
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{
// start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}

1.7.5 Type Conversion and Casting


In Java, Type Conversion refers to the process of converting one data type to another, either implicitly or explicitly.

There are two types of type conversion in Java:


1. Implicit Type Conversion (Widening)
 It is done automatically by the Java compiler when you assign a smaller data type to a larger data type.
 No data is lost in this process, and the conversion happens without the need for explicit syntax.
Example
int num = 10;
double d = num; // Implicit type conversion from int to double

14
System.out.println(d); // Output: 10.0

2.Explicit Type Conversion (Narrowing)


 This requires explicit casting by the programmer to convert from a larger data type to a smaller data type.
 It may lead to data loss if the value is too large for the target type.

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];

Accessing Array Elements:


 Access elements using their index in square brackets,
 e.g., myArray[0] for the first element.

Java Array Safety:


 Java checks if you're accessing indexes within the array's range (e.g., 0 to size-1). If you access outside this
range, it throws an error.
Examples:
 To store the number of days in each month

15
To calculate the average of numbers:

In Java, arrays can be declared in two different ways.

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

In Java, multidimensional arrays are actually arrays of arrays.

For multi-dimensional arrays, there are two forms:

char[][] a = new char[3][4]; // 2D array


OR
char a[][] = new char[3][4]; // 2D array

// Demonstrate a two-dimensional array.


class TwoDArray {
public static void main(String args[]) This program generates the following
{ output:
int twoD[][]= new int[4][5]; 0 1 2 3 4
5 6 7 8 9
int i, j, k = 0; 10 11 12 13 14
15 16 17 18 19
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

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

Java provides a rich operator environment.


Most of its operators can be divided into the following four groups: arithmetic, bitwise, relational, and logical.

Types of Operators in Java:


1. Arithmetic Operators: Used to perform basic arithmetic operations.
 Example: +, -, *, /, %
Program
public class ArithmeticOperatorsExample {
public static void main(String[] args) {
int a = 10, b = 5;

// Performing arithmetic operations


System.out.println("Addition: " + (a + b)); // 10 + 5 = 15
System.out.println("Subtraction: " + (a - b)); // 10 - 5 = 5
System.out.println("Multiplication: " + (a * b)); // 10 * 5 = 50
System.out.println("Division: " + (a / b)); // 10 / 5 = 2
System.out.println("Modulus: " + (a % b)); // 10 % 5 = 0 (remainder)
}

Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Modulus: 0

2. Relational Operators: Used to compare two values.


 Example: ==, !=, <, >, <=, >=

Program
public class RelationalOperatorExample {
public static void main(String[] args) {
int a = 10, b = 5;

// Using relational operators to compare 'a' and 'b'


System.out.println("a == b: " + (a == b)); // Check if a is equal to b
System.out.println("a != b: " + (a != b)); // Check if a is not equal to b
17
System.out.println("a > b: " + (a > b)); // Check if a is greater than b
System.out.println("a < b: " + (a < b)); // Check if a is less than b
System.out.println("a >= b: " + (a >= b)); // Check if a is greater than or equal to b
System.out.println("a <= b: " + (a <= b)); // Check if a is less than or equal to b
}
}

Output:
a == b: false
a != b: true
a > b: true
a < b: false
a >= b: true
a <= b: false

3. . Logical Operators: Used to perform logical operations.


 Example: &&, ||, !
Program
public class LogicalOperatorsExample {
public static void main(String[] args) {
boolean a = true;
boolean b = false;

// Logical AND (&&)


System.out.println("a && b: " + (a && b)); // false (true AND false)

// Logical OR (||)
System.out.println("a || b: " + (a || b)); // true (true OR false)

// Logical NOT (!)


System.out.println("!a: " + (!a)); // false (NOT true)
System.out.println("!b: " + (!b)); // true (NOT false)
}
}

Output:
a && b: false
a || b: true
!a: false
!b: true

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


Example: =, +=, -=, *=, /=
Program
public class AssignmentOperatorExample {
public static void main(String[] args) {
int a = 10; // Simple assignment
System.out.println("Initial value of a: " + a);

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

5. Increment and Decrement Operators: Used to increase or decrease a value.


Example: ++, --
Program:
public class IncrementDecrementExample {
public static void main(String[] args) {
int x = 5;

// 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;

// Using the ternary operator to find the maximum number


int max = (a > b) ? a : b;

// Display the result


System.out.println("The maximum value is: " + max);
}
}

Output
The maximum value is: 20

Simple Example Program:

public class OperatorExample {


public static void main(String[] args) { Output
int a = 10, b = 5;
Sum: 15
// Arithmetic Operator
System.out.println("Sum: " + (a + b)); a == b: false

a > b AND b < 10: true


// Relational Operator
System.out.println("a == b: " + (a == b)); Updated a: 15

// Logical Operator Incremented a: 16


System.out.println("a > b AND b < 10: " + (a > b && b < 10));
Max value: 16
// Assignment Operator
a += 5; // a = a + 5
System.out.println("Updated a: " + a);

// 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

These statements help in making decisions in the program by evaluating conditions.

 if statement: Executes a block of code if a condition is true.

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

 if-else-if ladder: Used to check multiple conditions.

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

public class IfElseIfLadder {


public static void main(String[] args) {
int num = 25;
if (num > 30) {
System.out.println("Number is greater than 30");
} else if (num > 20) {
System.out.println("Number is greater than 20 but less than or equal to 30");
} else {
System.out.println("Number is 20 or less");
}
}
}

Output

Number is greater than 20 but less than or equal to 30

 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

These statements are used to repeat a block of code multiple times.

 for loop: Used when the number of iterations is known.

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:

 Executes the block of code as long as the condition is true.


 The condition is checked before entering the 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.

 break: Exits from the current loop or switch statement.

Syntax
break; // Exits the nearest enclosing loop

Program:

public class BreakExample {


public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) break; // Exit loop when i is 5
System.out.println(i);
}
}

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:

 Decision-making: if, if-else, switch.


 Looping: for, while, do-while.
 Jump: break, continue.

These control statements provide the flexibility to make decisions and repeat operations, making them essential for
developing logic in Java programs.

1.10 Defining classes in Java

Class:

 A class is a blueprint or template for creating objects.

 It defines the properties (variables) and behaviors (methods) that the objects of this class will have.

Object:

 An object is an instance of a class.

 It has its own copy of the properties defined in the class.

General Form of a Class

25
Example: Simple Class with Objects

1. Defining a Class:

 Box is a class.
 It has three properties: width, height, and depth.

Using the Class:

 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:

1. Name: Same as the class name.

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.

Example with Constructor:

/* Here, Box uses a constructor to initialize the dimensions of a box.*/

class Box {
double width;
26
double height;
double depth;

// This is the constructor for Box.

Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Output:

Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0

Parameterized Constructors in Java

A parameterized constructor allows you to create objects with different initial values, unlike a default constructor
that assigns the same value to all objects.

Example: Box Class with Parameterized Constructor

27
Parameterized Constructor:

Box(double w, double h, double d) allows you to specify the dimensions of the box when creating it.

The output from this program is shown here:

Volume is 3000.0

Volume is 162.0

Methods

 Methods are key components of a class.


 A class typically consists of two main elements: instance variables (or fields) and methods.
 Methods define actions that objects of the class can perform.

General Form of a Method

A method's structure is:

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;

Adding a Method to the Box Class

In Java, methods allow classes to interact and manipulate data internally.

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).

Returning a Value from a Method

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:

Adding Parameters to a Method

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:

This setDim() method is called to set the dimensions of a box:

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)

1. Public (anything declared as public can be accessed from anywhere):


A variable or method declared/defined with the public modifier can be accessed anywhere in the program through
its class objects, through its subclass objects and through the objects of classes of other packages also.
2. Private (anything declared as private can’t be seen outside of the class):
The instance variable or instance methods declared/initialized as private can be accessed only by its class. Even its
subclass is not able to access the private members.
3. Protected (anything declared as protected can be accessed by classes in the same package and subclasses in the
other packages):
The protected access specifier makes the instance variables and instance methods visible to all the classes,
subclasses of that package and subclasses of other packages.
4. Default (can be accessed only by the classes in the same 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);
}
}

public class Main {


public static void main(String[] args) {
Example obj = new Example();
obj.display();
}
}

Output:

Private: 10
Protected: 20
Public: 30

31

You might also like