0% found this document useful (0 votes)
5 views56 pages

OOPJ (Java) Unit-I

The document outlines the syllabus and course structure for Object Oriented Programming through Java for the academic year 2024-25 at Aditya College of Engineering. It covers key topics such as basic concepts of OOP, Java program structure, data types, control statements, classes and objects, inheritance, interfaces, exception handling, and Java I/O. Additionally, it includes references, textbooks, and course outcomes aimed at equipping students with the skills to analyze problems and implement solutions using OOP principles in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views56 pages

OOPJ (Java) Unit-I

The document outlines the syllabus and course structure for Object Oriented Programming through Java for the academic year 2024-25 at Aditya College of Engineering. It covers key topics such as basic concepts of OOP, Java program structure, data types, control statements, classes and objects, inheritance, interfaces, exception handling, and Java I/O. Additionally, it includes references, textbooks, and course outcomes aimed at equipping students with the skills to analyze problems and implement solutions using OOP principles in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Academic Year : 2024-25


Branch : CSE (II YEAR)
Lecturer Notes
ADITYA COLLEGE OF ENGINEERING
MADANAPALLI

S. Contents Page
No No
1 Academic Calendar 1
2 Syllabus , OOPJ COs and JNTUA Approved Textbooks and Reference Text Books 2-5
3 Theory Syllabus 6-10
4 Laboratory Syllabus
5 Assignment Questions
6 Old Question Papers (JNTUA-R20)
Syllabus & OOPJ COs
UNIT I: Object Oriented Programming: Basic concepts, Principles, Program Structure in Java: Introduction,
Writing Simple Java Programs, Elements or Tokens in Java Programs, Java Statements, Command Line
Arguments, User Input to Programs, Escape Sequences Comments, Programming Style.
Data Types, Variables, and Operators :Introduction, Data Types in Java, Declaration of Variables, Data Types,
Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic Constants, Formatted Output with
printf() Method, Static Variables and Methods, Attribute Final, Introduction to Operators, Precedence and
Associativity of Operators, Assignment Operator (=), Basic Arithmetic Operators, Increment (++) and
Decrement (- -) Operators, Ternary Operator, Relational Operators, Boolean Logical Operators, Bitwise Logical
Operators.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions, Ternary
Operator?:, Switch Statement, Iteration Statements, while Expression, do–while Loop, for Loop, Nested for
Loop, For–Each for Loop, Break Statement, Continue Statement.
UNIT II: Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members, Declaration of
Class Objects, Assigning One Object to Another, Access Control for Class Members, Accessing Private
Members of Class, Constructor Methods for Class, Overloaded Constructor Methods, Nested Classes, Final
Class and Methods, Passing Arguments by Value and by Reference, Keyword this.
Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor Methods, Class
Objects as Parameters in Methods, Access Control, Recursive Methods, Nesting of Methods, Overriding
Methods, Attributes Final and Static.
UNIT III: Arrays:Introduction, Declaration and Initialization of Arrays, Storage of Array in Computer
Memory, Accessing Elements of Arrays, Operations on Array Elements, Assigning Array to Another Array,
Dynamic Change of Array Size, Sorting of Arrays, Search for Values in Arrays, Class Arrays, Two-dimensional
Arrays, Arrays of Varying Lengths, Three-dimensional Arrays, Arrays as Vectors.
Inheritance:Introduction, Process of Inheritance, Types of Inheritances, Universal Super Class-Object Class,
Inhibiting Inheritance of Class Using Final, Access Control and Inheritance, Multilevel Inheritance, Application
of Keyword Super, Constructor Method and Inheritance, Method Overriding, Dynamic Method Dispatch,
Abstract Classes, Interfaces and Inheritance.
Interfaces:Introduction, Declaration of Interface, Implementation of Interface, Multiple Interfaces, Nested
Interfaces, Inheritance of Interfaces, Default Methods in Interfaces, Static Methods in Interface, Functional
Interfaces, Annotations.
UNIT IV: Packages and Java Library:Introduction, Defining Package, Importing Packages and Classes into
Programs, Path and Class Path, Access Control, Packages in Java SE, Java.lang Package and its Classes, Class
Object, Enumeration, class Math, Wrapper Classes, Auto-boxing and Auto-unboxing, Java util Classes and

Object Oriented Programming Through Java Page 2


Interfaces, Formatter Class, Random Class, Time Package, Class Instant (java.time.Instant), Formatting for
Date/Time in Java, Temporal Adjusters Class, Temporal Adjusters Class.
Exception Handling: Introduction, Hierarchy of Standard Exception Classes, Keywords throws and throw, try,
catch, and finally Blocks, Multiple Catch Clauses, Class Throwable, Unchecked Exceptions, Checked
Exceptions.
Java I/O and File: Java I/O API, standard I/O streams, types, Byte streams, Character streams, Scanner class,
Files in Java(Text Book 2)
UNIT V: String Handling in Java:Introduction, Interface Char Sequence, Class String, Methods for
Extracting Characters from Strings,Comparison, Modifying, Searching; Class String Buffer.
Multithreaded Programming:Introduction, Need for Multiple Threads Multithreaded Programming for Multi-
core Processor, Thread Class, Main Thread-Creation of New Threads, Thread States, Thread Priority-
Synchronization, Deadlock and Race Situations, Inter-thread Communication - Suspending, Resuming, and
Stopping of Threads.
Java Database Connectivity:Introduction, JDBC Architecture, Installing MySQL and MySQL Connector/J,
JDBC Environment Setup, Establishing JDBC Database Connections, ResultSet Interface
Java FX GUI: Java FX Scene Builder, Java FX App Window Structure, displaying text and image, event
handling, laying out nodes in scene graph, mouse events (Text Book 3)
Text Books:
1. JAVA one step ahead, Anitha Seth, B.L.Juneja, Oxford.
2. Joy with JAVA, Fundamentals of Object Oriented Programming, DebasisSamanta, MonalisaSarma,
Cambridge, 2023.
3. JAVA 9 for Programmers, Paul Deitel, Harvey Deitel, 4 th Edition, Pearson.
References Books:
1. The complete Reference Java, 11thedition, Herbert Schildt,TMH
2. Introduction to Java programming, 7th Edition, Y Daniel Liang, Pearson
Online Resources:
1. https://nptel.ac.in/courses/106/105/106105191/
2. https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_012880464547618816347_shared/overview
Course Outcomes:After completion of the course, students will be able to
• Analyze problems, design solutions using OOP principles, and implement them efficiently in Java.
(L4)
• Design and implement classes to model real-world entities, with a focus on attributes, behaviors,
and relationships between objects (L4)
• Demonstrate an understanding of inheritance hierarchies and polymorphic behaviour, including
method overriding and dynamic method dispatch. (L3)
• Apply Competence in handling exceptions and errors to write robust and fault-tolerant code. (L3)
• Perform file input/output operations, including reading from and writing to files using Java I/O
classes, graphical user interface (GUI) programming using JavaFX. (L3)
• Choose appropriate data structure of Java to solve a problem (L6)

Object Oriented Programming Through Java Page 3


Index
Unit-I Object Oriented Programming , Data Types, Variables, and Operators , Control Statements

S.No Name of the Topic Page No Date


Chapter-I Object Oriented Programming
1.1 Basic concepts, Principles 6-7
1.2 Program Structure in Java 7-9
1.3 Introduction, Writing Simple Java Programs 10-12
1.4 Elements or Tokens in Java Programs 12-14
1.5 Java Statements, Command Line Arguments 14-16
1.6 User Input to Programs 17-18
1.7 Escape Sequences Comments, Programming Style 19-21
Chapter-II Data Types, Variables, and Operators
1.8 Introduction, Data Types in Java 22-24
1.9 Declaration of Variables 25-26
1.10 Data Types 26-27
1.11 Type Casting 28-29
1.12 Scope of Variable Identifier 30-32
1.13 Literal Constants, Symbolic Constants 32-32
1.14 Formatted Output with printf() Method 32-33
1.15 Static Variables and Methods, Attribute Final 33-36
1.16 Precedence and Associativity of Operators 37-38
1.17 Assignment Operator ( = ), Basic Arithmetic Operators, Increment (++) and 38-44
Decrement (- -) Operators, Ternary Operator, Relational Operators, Boolean
Logical Operators, Bitwise Logical Operators.
Chapter-III Control Statements
1.18 Introduction, if Expression, Nested if Expressions, 45-47
1.19 if–else Expressions, Ternary Operator ?: 47-48
1.20 Switch Statement 49-50
1.21 Iteration Statements, while Expression, do–while Loop, for Loop, Nested for 51-54
Loop, For–Each for Loop
1.22 Break Statement, Continue Statement 55-56

Object Oriented Programming Through Java Page 4


Java Introduction

 Java is a high level, object-oriented and a secure and stable programming language but it is not a pure
object-oriented language because it supports primitive data types like int, char etc.
 Java is a platform-independent language because it has runtime environment i.e JRE and API.
Here platform means a hardware or software environment in which an application runs.
Java codes are compiled into byte code or machine-independent code.
 This byte code is run on JVM (Java Virtual Machine).
 Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java.
 Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and
his team changed the name from Oak to Java.

HISTORY OF JAVA

 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
 Originally designed for small, embedded systems in electronic appliances like set-top boxes.
 Firstly, it was called "Greentalk" by James Gosling.After that, it was called Oak
 Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A.,
France, Germany, Romania etc.
 In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
 Java is an island of Indonesia where first coffee was produced (called java coffee).
 Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.

Object Oriented Programming Through Java Page 5


1.1 Basic concepts, Principles
OOPS Basic Concepts
Object-Oriented Programming (OOP) is a programming model that organizes software design around objects
and data rather than actions and logic. Here are some basic concepts of OOP:
1. Class: A blueprint for creating objects (instances) that defines its properties (attributes) and behaviors
(methods).
2. Object: An instance of a class that encapsulates data (attributes or properties) and behaviors (methods).
3. Encapsulation: The bundling of data (attributes) and methods (functions) that operate on the data into a
single unit (class), and restricting direct access to some of the object's components.
4. Abstraction: The process of hiding the difficult implementation details and exposing only the
necessary features of an object. It focuses on what an object does rather than how it does it.
5. Inheritance: The mechanism by which one class (subclass or derived class) can inherit the properties
and behaviors of another class (superclass or base class). It promotes code reusability and allows for
hierarchical classification.
6. Polymorphism: The ability of different objects to respond to the same message or method call in
different ways. It allows objects of different classes to be treated as objects of a common superclass.
7. Method Overriding: A feature that allows a subclass to provide a specific implementation of a method
that is already provided by its superclass. It is used for runtime polymorphism.
8. Constructor: Special methods invoked automatically when an object of a class is instantiated. They are
used to initialize the object's state.
9. Destructor: Special methods invoked automatically when an object is destroyed or goes out of scope.
They are used to release resources used by the object.
10. Message Passing: Objects communicate with each other by sending and receiving information through
method calls.
OOPS Principles
The object-oriented programming paradigm has the following core concepts.
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction
The popular object-oriented programming languages are Smalltalk, C++, Java, PHP, C#, Python, etc.
Encapsulation
 Encapsulation is the process of combining data and code into a single unit (object / class).

 In programming, data is defined as variables and code is defined as methods. In OOP, every object is

associated with its data and code.


 The java programming language uses the class concept to implement encapsulation.

Object Oriented Programming Through Java Page 6


Inheritance
 Inheritance is the process of acquiring properties and behaviors from one object to another object or one
class to another class.
 In the inheritance concept, the class which provides properties is called as parent class or base class or
super class and the class which receives the properties is called as child class or derived class or sub
class.
 In the inheritance, the properties and behaviors of base class extended to its derived class, but the base
class never receive properties or behaviors from its derived class.
 Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Polymorphism
Polymorphism is the process of defining same method with different implementation. That means
creating multiple methods with different behaviors.
 The java uses method overloading and method overriding to implement polymorphism.
 Method overloading - multiple methods with same name but different parameters.
 Method overriding - multiple methods with same name and same parameters but different method body
Abstraction
Abstraction is hiding the internal details and showing only essential functionality.
In the abstraction concept, we do not show the actual implementation to the end user, instead we provide only
essential things.
For example, if we want to drive a car, we does not need to know about the internal functionality like how
wheel system works? how brake system works? how music system works? etc.
1.2 Program Structure in Java
In Java, a program's structure typically follows a specific layout and organization to ensure clarity.
Here’s an overview of the typical structure of a Java program:
1. Package Declaration
Java programs are organized into packages, which help in categorizing classes and interfaces. Packages are
declared at the beginning of each source file to specify the package to which the class or interface belongs.
Example:
package com.example.myproject;
2. Import Statements
Import statements are used to specify other classes or entire packages that are used in the current program. This
allows you to refer to classes by their simple names rather than their fully qualified names throughout the code.
Example:
import java.util.ArrayList;
import java.util.List;

Object Oriented Programming Through Java Page 7


3. Class Declaration
Java programs consist of one or more classes. Each class is declared using the ‘class’ keyword followed by the
class name. The class body contains fields (attributes) and methods (functions).
Example :
public class MyClass
{
// Fields (attributes)
private int myField;

// Constructor
public MyClass(int myField)
{
this.myField = myField;
}
// Methods
public void myMethod()
{
// Method implementation
}
}
4. Main Method
Every Java application must have a ‘main’ method as its entry point, which is declared as follows:
Example:
public static void main(String[] args)
{
// Application logic
}
5. Comments
Comments are used to explain the code and make it more understandable. Java supports both single-line and
multi-line comments.
Example
// This is a single-line comment
/*
* This is a multi-line comment.
* It can span multiple lines.
*/
6. Access Modifiers
Java provides several access modifiers (‘public’, ‘private’, ‘protected’, default) to control the visibility and
accessibility of classes, methods, and fields.

Object Oriented Programming Through Java Page 8


Example
public class MyClass
{
private int privateField; // Private field
public void publicMethod()
{
// Public method
// Method implementation
}
}
7. Class Structure
The structure inside a class naturally includes fields (variables), constructors, methods, and nested classes or
interfaces.
Methods can also include control flow statements such as loops (‘for’, ‘while’, ‘do-while’) and conditional
statements (‘if’, ‘else’, ‘switch’).
8. Java Documentation
Java supports documentation comments using the ‘/** ... */’ syntax, which can be used to generate API
documentation using tools like Javadoc.
Example:
/**
* This class represents a simple example class.
* It demonstrates the structure of a Java class.
*/
public class MyClass
{
// Fields, constructors, methods, etc.
}
Example Program Structure
package com.example.myproject;

import java.util.ArrayList;
import java.util.List;
/**
* This class demonstrates a simple Java program structure.
*/

public class SampleCode


{
public static void main(String[] args)
{
System.out.println("Hello, world!");
}
}

Object Oriented Programming Through Java Page 9


1.3 Introduction, Writing Simple Java Programs
Introduction
Java Terminology
JVM (Java Virtual Machine)
 It is a software and that provides runtime environment in which java bytecode can be executed.
 It not physically exists and JVMs are not same for all hardware and software, for example for window
OS JVM is different and for Linux JVM is different.
 JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is
platform independent .
Operation of JVM
JVM mainly performs following operations.
 Allocating sufficient memory space for the class properties.
 Provides runtime environment in which java bytecode can be executed
 Converting byte code instruction into machine level instruction.
JVM is separately available for every Operating System while installing java software so that JVM is
platform dependent.
Note: Java is platform Independent but JVM is platform dependent because every Operating system have
different-different JVM which is install along with JDK Software.

What is Java Bytecode?


 As soon as a java program is compiled, java bytecode is generated. In more suitable terms, java
bytecode is the machine code in the form of a .class file.
How does it works?
 When we write a program in Java, firstly, the compiler compiles that program and a bytecode is
generated for that piece of code.
 When we wish to run this .class file on any other platform, we can do so. After the first compilation, the
bytecode generated is now run by the Java Virtual Machine and not the processor in consideration.
 This essentially means that we only need to have basic java installation on any platforms that we want to
run our code on.
 Resources required to run the bytecode are made available by the Java Virtual Machine, which calls the
processor to allocate the required resources.
Java Development Kit(JDK):
 As the name suggests, it is a complete Java development kit that includes everything including compiler,
Java Runtime Environment (JRE), java debuggers, java docs, etc.
 For the program to execute in java, we need to install JDK on our computer in order to create, compile
and run the java program.

Object Oriented Programming Through Java Page 10


Java Runtime Environment (JRE):
For running the java program, a computer needs JRE.
Writing Simple programs
Example 1: Calculate Area of a Circle
import java.util.Scanner;

public class CircleAreaCalculator


{
public static void main(String[] args)
{
final double PI = 3.14159;

Scanner scanner = new Scanner(System.in); // Create a Scanner object for user input
System.out.print("Enter the radius of the circle: "); // Ask the user to enter the radius
double radius = scanner.nextDouble();

double area = PI * radius * radius; // Calculate the area of the circle

System.out.println("The area of the circle with radius " + radius + " is: " + area);
scanner.close(); // Close the Scanner
}
}
Explanation:
1. Import Statement: The ‘import java.util.Scanner;’ statement imports the ‘Scanner’ class from the ‘java.util’

package, which is used for reading user input.

2. Class Declaration: The ‘CircleAreaCalculator’ class is declared with the ‘public’ access modifier.

3. Main Method: The ‘main’ method is where the execution of the program begins.

4. Scanner Initialization: A ‘Scanner’ object named ‘scanner’ is created to read input from the user.

‘System.in’ specifies that input will be read from the standard input stream (typically the keyboard).

5. User Input: The program prompts the user to enter the radius of the circle using ‘System.out.print("Enter the

radius of the circle: ");’, and then reads the double input using ‘scanner.nextDouble();’.

6. Area Calculation: The area of the circle is calculated using the formula \( \text{area} = \pi \times

\text{radius}^2 \), where \( \pi \) is approximated as ‘3.14159’.

7. Result Output: After calculating the area, the program prints the result using ‘System.out.println("The area

of the circle with radius " + radius + " is: " + area);’.

8. Closing Scanner: The ‘scanner.close();’ statement closes the ‘Scanner’ object to release its resources.

Object Oriented Programming Through Java Page 11


Example 2: Calculate Sum of Even Numbers
public class SumOfEvenNumbers
{
public static void main(String[] args)
{
int n = 10; // Number of even numbers to sum
int sum = 0;

for (int i = 2; i <= 2 * n; i += 2) {


sum += i;
}
System.out.println("Sum of the first " + n + " even numbers is: " + sum);
}
}
Explanation:
1. Class Declaration: The ‘SumOfEvenNumbers’ class is declared with the ‘public’ access modifier.

2. Main Method: The ‘main’ method is where the execution of the program begins.

3. Sum Calculation: In this example, we calculate the sum of the first ‘n’ even numbers. We iterate over even

numbers starting from 2 up to ‘2 * n’ (inclusive), incrementing by 2 in each iteration (‘i += 2’). Inside the loop,

we add each even number ‘i’ to the ‘sum’.

4. Result Output: After calculating the sum, the program prints the result using ‘System.out.println("Sum of

the first " + n + " even numbers is: " + sum);

1.4 Elements or Tokens in Java Programs


In Java programming, tokens are the smallest units of a program that are meaningful to the compiler.
Here are the main types of tokens found in Java programs:
1. Keywords 2. Identifiers 3. Literals
4.Operators 5. Separators 6. Comments
1. Keywords
Keywords are predefined reserved words that have special meanings in Java. They cannot be used as
identifiers (such as variable names or method names).
Examples include:
‘class’ ‘public’ ‘static’ ‘void’ ‘if’ ‘else’ ‘for’
‘while’ ‘return’ ‘try’ ‘catch’

Object Oriented Programming Through Java Page 12


2. Identifiers
Identifiers are names given to variables, methods, classes, and other user-defined components in a Java
program. They must follow certain rules:
Must begin with a letter (A-Z or a-z), dollar sign ‘$’, or underscore ‘_’.
Subsequent characters may be letters, digits (0-9), dollar signs, or underscores.
Cannot be a Java keyword.
Case-sensitive (‘myVariable’ is different from ‘MyVariable’).
Example identifiers:
- ‘myVariable’
- ‘calculateArea’
- ‘Person’
- ‘MAX_VALUE’
3. Literals
Literals are constant values that are directly written into the code.
They can be of various types:
Integer literals: Examples include ‘10’, ‘0’, ‘-15’.
Floating-point literals: Examples include ‘3.14’, ‘0.1’, ‘-2.5’.
Boolean literals: ‘ true’ and ‘false’.
Character literals: Enclosed in single quotes, such as ‘'a'‘, ‘'1'‘, ‘'!'‘.
String literals: Enclosed in double quotes, such as ‘ "Hello"‘, ‘"Java"‘, ‘"123"‘.
4. Operators
Operators perform operations on variables and values.
They are categorized into different types:
Arithmetic operators: ‘+’, ‘-’, ‘*’, ‘/’, ‘%’.
Relational operators: ‘==‘, ‘!=‘, ‘<‘, ‘>‘, ‘<=‘, ‘>=‘.
Logical operators: ‘&&’ (AND), ‘||’ (OR), ‘!’ (NOT).
Assignment operators: ‘=‘, ‘+=‘, ‘-=‘, ‘*=‘, ‘/=‘, ‘%=‘.
5. Separators
Separators are characters used to separate tokens in Java programs. Common separators include:
Semicolon (‘;’): Ends statements.
Comma (‘,’): Separates elements in a list or parameters in a method call.
Parentheses (‘(‘ and ‘)’): Used in method declarations and method calls.
Braces (‘{‘ and ‘}’): Define code blocks (e.g., class body, method body, loops).
Square brackets (‘[‘ and ‘]’): Used in array declarations and access.

Object Oriented Programming Through Java Page 13


6. Comments
Comments are not part of the executable code but are used to document the code and improve its readability.
Java supports three types of comments:
**Single-line comments**: Begin with ‘//’ and continue to the end of the line.
Example: // This is a single-line comment
Multi-line comments: Enclosed between ‘/*’ and ‘*/’. Can span multiple lines.
Example /*
* This is a multi-line comment.
* It can span multiple lines.
*/
Documentation comments: Begin with ‘/**’ and are used by tools like Javadoc to generate
documentation.
Example:
/**
* This method calculates the area of a circle.
* @param radius The radius of the circle.
* @return The area of the circle.
*/
1.5 Java Statements, Command Line Arguments
In Java programming, statements are the building blocks of a program.
They are executed sequentially unless control flow statements (such as loops or conditionals) alter the execut ion
order.
Here are the main types of statements in Java:
1. Declaration Statements
2. Expression Statements
3.Control Flow Statements
4. Block Statements
1. Declaration Statements
Declaration statements declare variables and allocate memory for them. They specify the type and name of the
variable:
int age; // Declaration statement for an integer variable named 'age'
double pi = 3.14; // Declaration statement with initialization
String message = "Hello, Java!"; // Declaration statement for a String variable with initialization
2. Expression Statements
Expression statements are the most common type of statement.
They include assignments and method calls that produce a value:

int x = 10; // Assignment statement


System.out.println("Value of x: " + x); // Method call as a statement

Object Oriented Programming Through Java Page 14


3. Control Flow Statements
Control flow statements alter the flow of execution based on specified conditions.
They include:
Conditional Statements (‘if’, ‘else’, ‘else if’): Execute statements based on a boolean condition.
if (x > 0)
{
System.out.println("x is positive");
}
else
{
System.out.println("x is non-positive");
}

Loop Statements (‘for’, ‘while’, ‘do-while’): Repeatedly execute statements based on a condition.
Example:
for (int i = 0; i < 5; i++)
{
System.out.println("Iteration: " + i);
}
Branching Statements (‘break’, ‘continue’, ‘return’): Change the flow of control.
Example:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exit the loop
}
if (i % 2 == 0)
{
continue; // Skip current iteration
}
System.out.println(i);
}

public int add(int a, int b)


{
return a + b; // Return statement
}
4. Block Statements
A block is a group of zero or more statements enclosed in curly braces ‘{ }’.
It creates a scope for local variables and allows multiple statements to be treated as a single unit:
Example:
{
int localVar = 10; // Local variable inside a block
System.out.println("Local variable: " + localVar);
}
Object Oriented Programming Through Java Page 15
Command Line Arguments
 The java command-line argument is an argument i.e. passed at the time of running the java program.
 The arguments passed from the console can be received in the java program and it can be used as an
input.
So, it provides a convenient way to check the behavior of the program for the different values.
 You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java

In this example, we are receiving only one argument and printing it.
To run this java program, you must pass at least one argument from the command prompt.

class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
Example of command-line argument that prints all the values

In this example, we are printing all the arguments passed from the command-line.
For this purpose, we have traversed the array using for loop.

class A
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc

Object Oriented Programming Through Java Page 16


1.6 User Input to Programs
In Java, user input can be obtained using the ‘Scanner’ class from the ‘java.util’ package.
This class allows you to read various types of user input, such as integers, floating-point numbers, strings, and
characters.
Here's how you can use ‘Scanner’ to handle user input in Java programs:
1. Importing Scanner Class
First, you need to import the ‘Scanner’ class at the beginning of your Java file:
import java.util.Scanner;
2. Creating a Scanner Object
Next, create a ‘Scanner’ object to read input from the user.
You typically create this object using ‘System.in’, which represents the standard input stream
Scanner scanner = new Scanner(System.in);
3. Reading Different Types of Input
Use methods provided by the ‘Scanner’ class to read user input of different data types:
‘nextInt()’ : Reads an integer input.
‘nextDouble()’ : Reads a double input.
‘nextLine()’ : Reads a line of text input.
‘next()’ : Reads the next token (word) of input as a string.
‘nextBoolean()’ : Reads a boolean input.
‘nextChar()’ : Reads a single character input.
Example: Reading Integer Input
import java.util.Scanner;

public class UserInputExample


{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in); // Create a Scanner object

System.out.print("Enter an integer: "); // Prompt the user to enter an integer


int number = scanner.nextInt(); // Read the integer input

System.out.println("You entered: " + number); // Output the entered number


scanner.close(); // Close the Scanner object to prevent resource leak
}
}

Object Oriented Programming Through Java Page 17


Explanation:

Import Statement: ‘import java.util.Scanner;’ imports the ‘Scanner’ class from the ‘java.util’ package.
Creating Scanner Object:
Scanner scanner = new Scanner(System.in);
creates a new ‘Scanner’ object to read from the standard input (‘System.in’).
Prompting User: ‘System.out.print("Enter an integer: ");’ displays a message to prompt the user for input.
Reading Input: ‘int number = scanner.nextInt();’ reads an integer entered by the user.
Output: ‘System.out.println("You entered: " + number);’ displays the entered number.
Closing Scanner: ‘scanner.close();’ closes the ‘Scanner’ object to release resources.

Example:
Reading String Input

import java.util.Scanner;
public class StringInputExample
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in); // Create a Scanner object

System.out.print("Enter your name: "); // Prompt the user to enter a string


String name = scanner.nextLine(); // Read the string input
System.out.println("Hello, " + name + "!"); // Output the entered name
scanner.close(); // Close the Scanner object
}
}
Explanation:
Reading String Input:
‘String name = scanner.nextLine();’ reads a line of text input (including spaces) entered by the user.
Output:
‘System.out.println("Hello, " + name + "!");’ displays a personalized greeting using the entered name.

Object Oriented Programming Through Java Page 18


1.7 Escape Sequences Comments, Programming Style
In Java, escape sequences and comments are two separate concepts that serve different purposes in a program.
Let's discuss each of them separately:
Escape Sequences
Escape sequences in are special sequences of characters that are used to represent characters that are
difficult or impossible to represent directly in a string literal.
They typically begin with a backslash (‘\’) followed by a specific character or code:
1. Newline (‘\n’): Moves the cursor to the beginning of the next line.
System.out.println("Hello,\nWorld!");
Output:
Hello,
World!
2. Tab (‘\t’): Moves the cursor to the next tab stop.
System.out.println("Hello,\tJava!");
Output:
Hello, Java!
3. Backslash (‘\\’): Represents a literal backslash character.
System.out.println("C:\\Users\\John\\Documents");
Output:
C:\Users\John\Documents
4. Single Quote (‘\'‘) and Double Quote (‘\"‘): Represent single and double quote characters inside string
literals, respectively.
System.out.println("She said, \"Hello!\"");
Output:
She said, "Hello!"
Comments in Java
Comments in Java are text that is ignored by the compiler but can be used to explain and document code. They
improve code readability and are categorized into three types:
1. Single-line comments: Begin with ‘//’ and extend to the end of the line.
// This is a single-line comment
int x = 10; // This comment explains the purpose of the variable
2. Multi-line comments: Begin with ‘/*’ and end with ‘*/’. They can span multiple lines.
/*
* This is a multi-line comment.
* It can span multiple lines.
*/

Object Oriented Programming Through Java Page 19


3. Documentation comments: Begin with ‘/’ and are used to generate API documentation using tools like
Javadoc.
/*
This method calculates the area of a circle.
@param radius The radius of the circle.
@return The area of the circle.
*/
public double calculateArea(double radius)
{
return Math.PI * radius * radius;
}
Programming Style in java
 Programming style in Java, often referred to as code style or coding conventions, includes guidelines
and practices that developers follow to write clean, readable, and maintainable code.
 Consistent coding style not only improves code readability but also promotes teamwork among team
members.
 Here are some important aspects of programming style in Java:
1. Naming Conventions
Classes: Start with an uppercase letter and use CamelCase.
Example: ‘MyClass’, ‘UserInterface’.
Methods and Variables: Start with a lowercase letter and use CamelCase.
Example: ‘calculateArea()’, ‘firstName’.
Constants: Use all uppercase letters with underscores separating words.
Example: ‘MAX_CAPACITY’, ‘PI_VALUE’.

2. Indentation and Braces


Use consistent indentation (usually 4 spaces per level).
Curly braces ‘{}’ should always be used, even for single-line statements after control flow keywords
(‘if’, ‘else’, ‘for’, ‘while’, ‘do’).
Example:
if (condition)
{
// Statements
}
else
{
// Statements
}

Object Oriented Programming Through Java Page 20


3. Comments
Use comments to explain complex algorithms, decisions, or any non-obvious code.
Follow consistent grammar and style in comments.
Avoid redundant comments that only repeat the code.
Example:
public class Calculator
{
// Calculates the sum of two numbers
public int add(int num1, int num2) {
return num1 + num2;
}
4. White Spaces
Use spaces consistently around operators (‘=‘, ‘+’, ‘-’, ‘*’, ‘/’, etc.) for improved readability.
Avoid excessive white spaces that might clutter the code.
Example:
int sum = 10 + 5;
int product = 3 * (7 - 2);
5. Error Handling
Always handle exceptions appropriately using ‘try-catch’ blocks or propagate them using ‘throws’ clause.
Provide meaningful error messages to aid in debugging.
Example:
try
{
// Code to read the file
}
catch (IOException e)
{
System.err.println("Error reading file: " + e.getMessage());
}
7. Use of JavaDoc
Use JavaDoc comments to document classes, methods, and fields for automatic generation of API
documentation.
Provide descriptions, parameters, return values, and exceptions in JavaDoc comments.
8. Code Organization
Organize classes, methods, and fields logically.
Group related methods and fields together.
Use packages to organize related classes.
Conclusion : It ensures that your code is easier to understand for both yourself and others who may work with
or maintain it in the future.
Object Oriented Programming Through Java Page 21
Chapter-II Data Types, Variables, and Operators
1.8 Data Types in Java
In java, there are two types of data types
 primitive data types
 non-primitive data types

Data Type Default Value Default size


boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
byte
 byte data type is a 8-bit signed two's complement integer
 Minimum value is : -128 (-2^7)
 Maximum value is : 127 (inclusive)(2^7 -1)
 Default value is : 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte
is four times smaller than an int
Syntax :
byte Variable_Name = Value;
short
 Short data type is a 16-bit signed two's complement integer
 Minimum value is : -32,768 (-2^15)
 Maximum value is : 32,767(inclusive) (2^15 -1)
 Default value is : 0
 Short data type can also be used to save memory. A short is 2 times smaller than an int
Syntax : short Variable_Name = Value;

Object Oriented Programming Through Java Page 22


int
 Int data type is a 32-bit signed two's complement integer
 Minimum value is : -2,147,483,648.(-2^31)
 Maximum value is : 2,147,483,647(inclusive).(2^31 -1)
 Default value is : 0
 int is generally used as the default data type for integral values unless there is a concern
about memory
Syntax :
int Variable_Name = Value;
long
 Long data type is a 64-bit signed two's complement integer
 Minimum value is : -9,223,372,036,854,775,808.(-2^63)
 Maximum value is : 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 Default value is : 0L
 This type is used when a wider range than int is needed
Syntax :
long Variable_Name = Value_L;
float
 float data type is a single-precision 32-bit IEEE 754 floating point
 Default value is : 0.0f
 Float data type is never used for precise values such as currency
 Float is mainly used to save memory in large arrays of floating point numbers
Syntax :
float Variable_Name = (float) Value;
double

 double data type is a double-precision 64-bit IEEE 754 floating point


 Default value is : 0.0d
 Double data type should never be used for precise values such as currency
 This data type is generally used as the default data type for decimal values. generally the
default choice
Syntax :
double Variable_Name = Value;
boolean

 boolean data type represents one bit of information


 There are only two possible values : true and false
 This data type is used for simple flags that track true/false conditions
 Default value is : false
Syntax :
boolean Variable_Name = Value (true/false);
char
 char data type is a single 16-bit Unicode character
 Minimum value is : '\u0000' (or 0)
 Maximum value is : '\uffff' (or 65,535 inclusive)
 Char data type is used to store any character

Note:
It is because java uses Unicode system not ASCII code system.
The \u0000 is the lowest range of Unicode system. Unicode is a 16-bit character encoding standard.
Syntax :
char Variable_Name = Value;

Object Oriented Programming Through Java Page 23


Example: (Lab-1)
public class DefaultValuesDemo
{
static byte b;
static short s;
static int i;
static long l;
static float f;
static double d;
static char c;
static boolean bv;

public static void main(String[] args)


{
// Displaying default values

System.out.println("Default values of primitive data types in Java:");


System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("int: " + i);
System.out.println("long: " + l);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("char: " + c);
System.out.println("boolean: " + bv);
}
}

/* Output:

D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>javac DefaultValuesDemo.java


D:\acem 2024-25 OOPJ CSE A&B\oopj_prc>java DefaultValuesDemo

Default values of primitive data types in Java:

byte: 0
short: 0
int: 0
long: 0
float: 0.0
double: 0.0
char:
boolean: false

*/

Object Oriented Programming Through Java Page 24


1.9 Declaration of Variables
 Variable is a name of memory location.
 A variable is a container which holds the value while the Java program is executed.
 It is a combination of "vary + able" which means its value can be changed.
Syntax-declaration:
dataType variableName;
Example
int data=50; //Here data is variable

Types of Variable

There are three types of variables in java

Local Variable
A variable that is declared inside the method is called local variable.
//local Variable Example

class LocalVariable
{
public static void main(String args[])
{
int a=10;
System.out.println(a);
}
}
Instance Variable

A variable that is declared inside the class but outside the method is called instance variable . It is not
declared as static.
//Instance variable Example
class InstanceVariable
{
int a=10;

public static void main(String args[])


{
InstanceVariable d = new InstanceVariable();
System.out.println(d.a);
}
}

Object Oriented Programming Through Java Page 25


Static variable
A variable that is declared as static is called static variable. It cannot be local.
//Static variable Example
class StaticVariable
{
static int a = 1;
public static void main(String args[])
{
System.out.println(a);
}
}
1.10 Data Types (Refer 1.8) & 1.11 Type Casting (or) Type conversion
Type casting
Convert a value from one data type to another data type is known as type casting.
Types of Type Casting
There are two types of type casting:
 Widening Type Casting(Type Conversion)
 Narrowing Type Casting(Type Casting)
Widening Type Casting
 Converting a lower data type into a higher one is called widening type casting.
 It is also known as implicit conversion or casting down.
 It is done automatically. It is safe because there is no chance to lose data.
It takes place when:
 Both data types must be compatible with each other.

 The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done automatically.
Also, the char and Boolean data types are not compatible with each other.
WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
long y = x; //automatically converts the integer type into long type
float z = y; //automatically converts the long type into float type

System.out.println("Before conversion, int value "+x);


System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Object Oriented Programming Through Java Page 26
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0

Narrowing Type Casting

 Converting a higher data type into a lower one is called narrowing type casting.
 It is also known as explicit conversion or casting up and it is done manually by the programmer.
 If we do not perform casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type casting two times. First, we have
converted the double type into long data type after that long data type is converted into int type.

NarrowingTypeCastingExample.java
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
long l = (long)d; //converting double data type into long data type
int I = (int)l; //converting long data type into int data type

System.out.println("Before conversion: "+d);


System.out.println("After conversion into long type: "+l); //fractional part lost
System.out.println("After conversion into int type: "+i); //fractional part lost

}
}
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166

Object Oriented Programming Through Java Page 27


1.12 Scope of Variable Identifier
In Java, the scope of a variable refers to the region of the program where the variable can be accessed or
referenced.
The scope of a variable is determined by where it is declared within the code and affects its visibility and
lifetime.
Understanding variable scope is crucial for writing efficient and bug-free Java programs. Here are the main
types of variable scopes in Java:

1. Local Variables
Local variables are declared within a method, constructor, or block of code (denoted by ‘{}’). They are only
accessible within the method, constructor, or block where they are declared.
Scope: Begins when the declaration is encountered and ends when the method, constructor, or block completes
execution or when the block's curly braces ‘{}’ are exited.
Example:
public class ScopeExample
{
public void exampleMethod()
{
int localVar = 10; // localVar is a local variable
System.out.println(localVar); // Accessible within exampleMethod()
// Other code
// localVar is not accessible outside of exampleMethod()
}
2. Instance Variables (Non-Static Fields)
Instance variables are declared within a class but outside any method, constructor, or block.
Each instance (object) of the class has its own copy of instance variables.
Scope: Exists as long as the object (instance of the class) to which it belongs exists.
In other words, it exists for the lifetime of the object.
Example:
public class ScopeExample
{
private int instanceVar; // instanceVar is an instance variable
public void exampleMethod()
{
instanceVar = 10; // Accessing instanceVar within a method
System.out.println(instanceVar);
}
// instanceVar can be accessed and modified in other methods of this class
}

Object Oriented Programming Through Java Page 28


3. Class Variables (Static Fields)
Class variables, also known as static fields, are declared with the ‘static’ keyword within a class but outside any
method, constructor, or block.
They are shared among all instances of the class.
Scope: Exists for the entire duration of the program (i.e., as long as the class is loaded into memory).
public class ScopeExample
{
private static int classVar; // classVar is a class variable

public static void main(String[] args)


{
classVar = 100; // Accessing classVar in a static method (main method)
System.out.println(classVar);
}
// classVar can be accessed and modified in other static methods of this class
}
4. Block Variables (Local Variables within Blocks)
Variables declared within a block of code (within ‘{}’) inside a method, constructor, or other block are block-
level variables. They have scope limited to that block and any nested blocks.
Scope: Begins when the block is entered and ends when the block completes execution or when the block's
curly braces ‘{}’ are exited.
Example:
public class ScopeExample
{
public void exampleMethod()
{
{
int blockVar = 20; // blockVar is a block-level variable
System.out.println(blockVar); // Accessible within this block
}
// blockVar is not accessible here
}
}

Object Oriented Programming Through Java Page 29


1.13 Literal Constants , Symbolic Constants
In Java, literal constants (often just called literals) are fixed values that are directly written in the code and
represent themselves.
They are used to initialize variables or provide data directly within expressions. Java supports various types of
literals for different data types:
1. Integer Literals
Integer literals represent whole numbers without any fractional or decimal parts. They can be in several formats:
Decimal (Base 10): Standard format without any prefix. Example: ‘100’, ‘-42’.
Binary (Base 2): Prefix ‘0b’ or ‘0B’ followed by binary digits (‘0’ and ‘1’). Example: ‘0b1010’, ‘0B111’.
Octal (Base 8): Prefix ‘0’ followed by octal digits (‘0’ to ‘7’). Example: ‘075’, ‘021’.
Hexadecimal (Base 16): Prefix ‘0x’ or ‘0X’ followed by hexadecimal digits (‘0’ to ‘9’, ‘A’ to ‘F’ or ‘a’ to ‘f’).
Examples:
int decimal = 100; // Decimal integer literal
int binary = 0b1010; // Binary integer literal (decimal 10)
int octal = 075; // Octal integer literal (decimal 61)
int hex = 0xFF; // Hexadecimal integer literal (decimal 255)
2. Floating-Point Literals
Floating-point literals represent numbers with a fractional part or an exponent.
They can be specified in either standard (decimal) form or scientific notation (exponential form):
Standard (Decimal) Form: Includes a decimal point and optionally a sign (‘+’ or ‘-’).
Scientific (Exponential) Notation: Uses ‘E’ or ‘e’ to indicate the exponent part of the number.
Examples:
double standard = 3.14; // Standard floating-point literal
double scientific = 2.5E3; // Scientific notation (2500.0)
float f = 0.1f; // Floating-point literal with suffix 'f'
3. Character Literals
Character literals represent individual characters enclosed in single quotes (‘'‘).
Single Characters: Directly represented by the character itself. Example: ‘'A'‘, ‘'7'‘, ‘'%'‘.
Escape Sequences: Special characters represented by an escape sequence starting with ‘\’. Example: ‘'\n'‘
(newline), ‘'\t'‘ (tab), ‘'\\'‘ (backslash).
Examples:
char ch = 'A'; // Character literal
char newline = '\n'; // Escape sequence (newline)
char tab = '\t'; // Escape sequence (tab)

Object Oriented Programming Through Java Page 30


4. String Literals:
String literals represent sequences of characters enclosed in double quotes (‘"‘). They can include escape
sequences similar to character literals:

Simple Text: Directly represented within double quotes. Example: ‘"Hello, Java!"‘.
Escape Sequences: Special characters and formatting represented by escape sequences.
Examples:
String message = "Hello, Java!"; // String literal
String path = "C:\\Users\\John"; // String with escape sequence for backslash
5. Boolean Literals
Boolean literals represent the two boolean values: ‘true’ and ‘false’.
They are keywords in Java and cannot be converted into any other type.
Examples:
boolean isJavaFun = true; // Boolean literal true
boolean isWorking = false; // Boolean literal false
6. Null Literal
The ‘null’ literal represents a reference that does not refer to any object.
It is often used to indicate that a reference variable does not currently refer to an object.
Examples:
String str = null; // Null literal representing no reference
Note:Literals in Java provide a straightforward way to represent fixed values of various data types directly
within your code.
Symbolic Constants in Java
In Java, symbolic constants refer to named identifiers that represent constant values which do not change during
the execution of a program.
They are typically defined using the ‘final’ keyword to indicate that their value cannot be altered once
initialized.
Using ‘final’ for Symbolic Constants
To define a symbolic constant in Java, you declare a ‘final’ variable and assign it a value.
By convention, the name of symbolic constants is usually written in uppercase letters with underscores
separating words
Examples :
1. Integer Constants
public static final int MAX_VALUE = 100;
public static final int INITIAL_COUNT = 0;

Object Oriented Programming Through Java Page 31


2. Floating-Point Constants
public static final double PI = 3.14159;
public static final float GRAVITY = 9.81f;
3. String Constants
public static final String DEFAULT_USERNAME = "guest";
public static final String ERROR_MESSAGE = "An error occurred.";
1.14 Formatted Output with printf() Method
In Java, the ‘printf()’ method (from ‘PrintStream’ and ‘PrintWriter’ classes) is used to format and display text in
a specified format.
It provides a way to control the output format by specifying formatting instructions, such as width, precision,
and alignment.
This method is particularly useful for generating formatted output, especially when dealing with numbers and
strings that require specific formatting.
Syntax of ‘printf()’ :
The ‘printf()’ method has a syntax similar to the ‘printf()’ function in C programming language:
System.out.printf(format, arg1, arg2, ...);
Where:
’format’: A string that specifies the format of the output.
’arg1, arg2, ...’: Arguments to be formatted according to the format string.
Format Specifiers:
Format specifiers start with a percent sign ‘%’ followed by a conversion character that specifies the type of
formatting to be applied.
Examples:
’%d’: Format specifier for integers (‘int’, ‘long’).
’%f’: Format specifier for floatingpoint numbers (‘float’, ‘double’).
’%s’: Format specifier for strings.
’%c’: Format specifier for characters.
’%b’: Format specifier for booleans.
’%n’: Platformspecific line separator.
Examples of ‘printf()’ Usage
1. Formatting Integers:
int number = 42;
System.out.printf("The number is: %d%n", number);
Output: The number is: 42

Object Oriented Programming Through Java Page 32


2. Formatting Floating-Point Numbers:
Double pi = 3.14159;
System.out.printf("Pi is approximately: %.2f%n", pi); // Rounds to 2 decimal places
Output:
Pi is approximately: 3.14
3. Formatting Strings:
String name = "Alice";
System.out.printf("Hello, %s!%n", name);
Output:
Hello, Alice!
4. Specifying Field Width and Alignment:
String product = "Apple";
Double price = 1.25;
int quantity = 10;
System.out.printf("Product: %-10s Price: $%5.2f Quantity: %d%n", product, price, quantity);
Output:
Product: Apple Price: $ 1.25 Quantity: 10
‘-10s’ left-aligns the string ‘product’ within a 10-character width.
‘5.2f’ specifies a floating-point number with a width of 5 characters, including 2 decimal places.
1.15 Static Variables and Methods, Attribute Final
In Java, ‘static’ is a keyword that can be applied to variables, methods, and nested classes.
When applied to variables and methods, it changes their behavior and usage compared to non-static (instance)
variables and methods.
Here’s an explanation of ‘static’ variables and methods in Java:
Static Variables (Class Variables):
Static variables, also known as class variables, belong to the class rather than any instance of the class.
There is only one copy of a static variable regardless of how many instances (objects) of the class are created.
They are initialized only once, at the start of the execution, and are shared among all instances of the class.
Declaration and Initialization:
public class MyClass
{
public static int count = 0; // Static variable
public MyClass() {
count++; // Increment count each time a new instance is created
}
}

Object Oriented Programming Through Java Page 33


//Accessing Static Variables: Static variables can be accessed using the class name or an instance of the class:
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();

System.out.println(MyClass.count); // Access using class name


System.out.println(obj1.count); // Access using instance (not recommended)
System.out.println(obj2.count); // Access using instance (not recommended)
Static Methods:
 Static methods belong to the class rather than any instance of the class.
 They can be called directly using the class name without creating an instance of the class.
 Static methods cannot access instance variables directly because they do not belong to any instance.
Declaration and Usage:
public class MathUtils
{
public static int add(int a, int b)
{
return a + b;
}
}
Calling Static Methods:
Static methods are called using the class name:
int result = MathUtils.add(10, 20); // Calling static method directly
Characteristics of Static Variables and Methods:
1. Single Copy: There is only one copy of static variables per class, regardless of how many objects of the class
are created.
2. Memory Allocation: Static variables are allocated memory when the class is loaded into memory and are
destroyed when the class is unloaded.
3. Initialization: Static variables are initialized only once, at the start of the execution, before the initialization
of any instance variables.
4. Direct Access: Static methods can directly access other static variables and static methods. They cannot
directly access instance variables or instance methods (unless through an object reference).
Notes:
Thread Safety: Static variables and methods are shared across all threads, so proper synchronization may be
needed if they are modified concurrently.
Static Block: You can also use a static block to initialize static variables or perform other initialization tasks
when the class is loaded.

Object Oriented Programming Through Java Page 34


Attribute final in Java
 The final keyword in java is used to restrict the user.
 The java final keyword can be used in many context.
 final can be used for variables or methods or classes
Java final variable
If you make any variable as final, you cannot change the value of final variable (It will be constant).
Example:
class Bike9
{
final int speedlimit = 90; //final variable
void run()
{
speedlimit = 400;
}
public static void main(String args[])
{
Bike9 obj = new Bike9();
obj.run();
}
}
Output: Compile Time Error

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.
Java final method

If you make any method as final, you cannot override it.

Example :
class Bike
{
final void run()
{
System.out.println("running");
}
}

Object Oriented Programming Through Java Page 35


class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda honda = new Honda();
honda.run();
}
}
Output: Compile Time Error

Java final class


If you make any class as final, you cannot extend it.
Example
final class Bike
{
}
class Honda1 extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda1 honda = new Honda1();
honda.run();
}
}
Output: Compile Time Error

Object Oriented Programming Through Java Page 36


1.16 Precedence and Associativity of Operators
In Java operators have precedence and associativity rules that determine the order of evaluation in expressions.
Precedence
Precedence determines the order of evaluation of operators in an expression.
Operators with higher precedence are evaluated before operators with lower precedence.
If operators have the same precedence, their associativity determines the order of evaluation.
Common Operator Precedence (from highest to lowest):
1. Postfix operators: ‘expr++’, ‘expr--’
2. Unary operators: ‘++expr’, ‘--expr’, ‘+expr’, ‘-expr’, ‘!expr’, ‘~expr’
3. Multiplicative operators: ‘*’, ‘/’, ‘%’
4. Additive operators: ‘+’, ‘-’
5. Shift operators: ‘<<‘, ‘>>‘, ‘>>>‘
6. Relational operators: ‘<‘, ‘<=‘, ‘>‘, ‘>=‘, ‘instanceof’
7. Equality operators: ‘==‘, ‘!=‘
8. Bitwise AND: ‘&’
9. Bitwise XOR: ‘^’
10. Bitwise OR: ‘|’
11. Logical AND: ‘&&’
12. Logical OR: ‘||’
13. Conditional operator: ‘? :’
14. Assignment operators: ‘=‘, ‘+=‘, ‘-=‘, ‘*=‘, ‘/=‘, ‘%=‘ etc.
Associativity:
Associativity determines the grouping of operators with the same precedence.
It specifies whether an expression is evaluated from left to right (‘left-associative’) or right to left
(‘right-associative’) when operators have the same precedence.
Operator Associativity:
Left-associative: Operators group from left to right.
For example, ‘a + b + c’ is evaluated as ‘(a + b) + c’.
Right-associative: Operators group from right to left.
For example, assignment operators like ‘=‘ are right- associative, so ‘a = b = c’ is evaluated as ‘a = (b = c)’.
Examples:
1+ 2 * 3;
Here, multiplication (‘*’) has higher precedence than addition (‘+’), so ‘2 * 3’ is evaluated first, resulting in ‘6’.
Then, ‘10 + 6’ is evaluated, resulting in ‘16’.
Associativity Example:
int result = 10 - 5 - 2;
Subtraction (‘-’) is left-associative, so ‘10 - 5’ is evaluated first, resulting in ‘5’. Then, ‘5 - 2’ is evaluated,
resulting in ‘3’.

Object Oriented Programming Through Java Page 37


3. Mixed Operators:
int result = 10 + 5 * 2 - 3 / 2;
Following operator precedence (‘*’ and ‘/’ have higher precedence than ‘+’ and ‘-’):
‘5 * 2’ evaluates to ‘10’.
‘3 / 2’ evaluates to ‘1’.
Then, ‘10 + 10 - 1’ evaluates to ‘19’.
1.17 Operators
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
 Unary Operator,
 Arithmetic Operator,
 Shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator.

Operator Type Category Precedence

Unary Postfix expr++ expr--

Prefix ++expr --expr +expr -expr

Arithmetic Multiplicative  / %

Additive + -

Shift Shift << >>

Relational Comparison < > <= >=

Equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary Ternary ?:

Assignment Assignment = += -= *= /= %=

Object Oriented Programming Through Java Page 38


Java Unary Operator (increment /Decrement Operators)
The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:
 incrementing/decrementing a value by one
 negating an expression
 inverting the value of a Boolean

Java Unary Operator Example: ++ and --

public class OperatorExample


{
public static void main(String args[])
{
int x=10;
System.out.println(x++); //10 (11)
System.out.println(++x); //12
System.out.println(x--); //12 (11)
System.out.println(--x); //10
}
}
Output:
10
12
12
10
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as
basic mathematical operations.
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b); //15
System.out.println(a-b); //5
System.out.println(a*b); //50
System.out.println(a/b); //2
System.out.println(a%b); //0
}
}

Object Oriented Programming Through Java Page 39


Output:
15
5
50
2
0
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of
times.
public class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}
}
Output:
40
80
80
240
Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left operand to right by the number of bits
specified by the right operand.
Java Right Shift Operator Example
public OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}
}
Output:
2
5
2

Object Oriented Programming Through Java Page 40


Java AND Operator Example: Logical && and Bitwise &
 The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.
 The bitwise & operator always checks both conditions whether first condition is true or false.
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c); //false && true = false
System.out.println(a<b&a<c); //false & true = false
}
}
Output:
false
false
Java Ternary Operator
 Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example
public class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min = (a<b) ? a : b;
System.out.println(min);
}
}
Output:
2

Object Oriented Programming Through Java Page 41


Bitwise Logical Operators
Bitwise Operators
Bitwise operators are used to performing the manipulation of individual bits of a number. They can be used
with any integral type (char, short, int, etc.). They are used when performing update and query operations of
the Binary indexed trees.
Now let’s look at each one of the bitwise operators in Java:
1. Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e., if either of the
bits is 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)
2. Bitwise AND (&)
This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of input values, i.e., if both bits
are 1, it gives 1, else it shows 0.
Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)
3. Bitwise XOR (^)
This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input values, i.e., if
corresponding bits are different, it gives 1, else it shows 0.

Object Oriented Programming Through Java Page 42


Example:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
______
0010 = 2 (In decimal)
4. Bitwise Complement (~)
This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement representation of the input
value, i.e., with all bits inverted, which means it makes every 0 to 1, and every 1 to 0.
Example:
a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5


~ 0101
______
1010 = 10 (In decimal)
Note: Compiler will give 2’s complement of that number, i.e., 2’s complement of 10 will be -6.
Boolean Logical Operators
The logical operators are used when we want to form compound conditions by combining two or more
relations.
example : a > b && X == 25
The following logical operators are supported for boolean type.

Object Oriented Programming Through Java Page 43


The below boolean logical table shows the results of various operators. This table is important and needs to be
remembered for future.

Example:
class BoolLogic
{
public static void main(String arg[])
{
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;

System.out.println(" a = " + a);


System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}
OUTPUT:

a = true
b = false
a|b = true
a&b = false
a^b = true
!a&b|a&!b = true
!a = false

Object Oriented Programming Through Java Page 44


Chapter-III Control Statements
1.18 Introduction, if Expression, Nested if Expressions,
 The control statements are used to control the order of execution according to our requirements.

Types of Control Statements


In java, the control statements are classified as follows.
 Selection Control Statements ( Decision Making Statements )
 Iterative Control Statements ( Looping Statements )
 Jump Statements
Selection Control Statements or Decision-Making statements:
 As the name suggests, decision-making statements decide which statement to execute
 when Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided.
 There are two types of decision-making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition.
The control of the program is diverted depending upon the specific condition.
The condition of the If statement gives a Boolean value, either true or false. In Java,
there are four types of if-statements given below.
1. Simple if statement
2. Nested if-statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition)
{
//code to be executed
}

Object Oriented Programming Through Java Page 45


Example: //Java Program to demonstrate the use of if statement.
public class IfExample
{
public static void main(String[] args)
{
int age=20;
if(age>18) //checking the age
{
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18

Java Nested if statement

The nested if statement represents the if block within another if block.


Here, the inner if block condition executes only when outer if block condition is true.
Syntax:

if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}

Example: //Java Program to demonstrate the use of Nested If Statement.


public class JavaNestedIfExample
{
public static void main(String[] args)
{
//Creating two variables for age and weight
int age=20;
int weight=80;

Object Oriented Programming Through Java Page 46


if(age>=18) //applying condition on age and weight
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
}
}
}
Output:
You are eligible to donate blood
1.19 if–else Expressions, Ternary Operator ?:
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
Example: //It is a program of odd and even number.
public class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0) //Check if the number is divisible by 2 or not
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}
}
}
Output: odd number

Object Oriented Programming Through Java Page 47


Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
else
{
//code to be executed if all the conditions are false
}

//Program to check POSITIVE, NEGATIVE or ZERO:


public class PositiveNegativeExample
{
public static void main(String[] args)
{
int number=-13;
if(number>0)
{
System.out.println("POSITIVE");
}
else
if(number<0)
{
System.out.println("NEGATIVE");
}
else
{
System.out.println("ZERO");
}
}
}
Output: NEGATIVE
Ternary Operator ?: (Refer page No:47)

Object Oriented Programming Through Java Page 48


1.20 Java Switch Statement

 The Java switch statement executes one statement from multiple conditions.
 It is like if-else-if ladder statement.
 The switch statement works with byte, short, int, long, enum types, String and some wrapper types like
Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
Points to Remember

 There can be one or N number of case values for a switch expression.


 The case value must be of switch expression type only. The case value must be literal or constant. It
doesn't allow variables.
 The case values must be unique. In case of duplicate value, it renders compile-time error.
 The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and
string.
 Each case statement can have a break statement which is optional. When control reaches to the break
statement, it jumps the control after the switch expression. If a break statement is not found, it
executes the next case.
 The case value can have a default label which is optional.

Syntax:

switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
case value3:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

Object Oriented Programming Through Java Page 49


SwitchExample.java
public class SwitchExample
{
public static void main(String[] args)
{
int number=20; //Declaring a variable for switch expression
switch(number) //Switch expression
{
case 10:
System.out.println("10");
break;
case 20:
System.out.println("20");
break;
case 30:
System.out.println("30");
break;
default:
System.out.println("Not in 10, 20 or 30");
}
}
}
Output: 20

Object Oriented Programming Through Java Page 50


1.21 Iteration Statements, while, do–while Loop, for Loop, Nested for Loop, For–Each for Loop

 In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true.
 However, loop statements are used to execute the set of instructions in a repeated order.
 The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly.

1. for loop
2. while loop
3. do-while loop
Java Simple for Loop
A simple for loop is the same as C/C++.
We can initialize the variable, check condition and increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It must return boolean value either true or false. It is an
optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
4. Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization; condition; increment/decrement)
{
//statement or code to be executed
}
ForExample.java ///which prints table of 1
public class ForExample
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
System.out.print(i);
}
}
}
Output: 1 2 3 4 5

Object Oriented Programming Through Java Page 51


Java Nested for Loop
If we have a for loop inside the another loop, it is known as nested for loop.
The inner loop executes completely whenever outer loop executes.
NestedForExample.java
public class NestedForExample
{
public static void main(String[] args)
{
for(int i=1;i<=3;i++) //loop of i
{
for(int j=1;j<=3;j++) //loop of j
{
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}
Output:
11
12
13
21
22
23
31
32
33
Java for-each Loop
 It is easier to use than simple for loop because we don't need to increment value and use subscript
notation.
 It works on the basis of elements and not the index. It returns element one by one in the defined variable.
Syntax:
for(data_type variable : array_name)
{
//code to be executed
}

Object Oriented Programming Through Java Page 52


ForEachExample.java //Java For-each loop example which prints the elements of the array

public class ForEachExample


{
public static void main(String[] args)
{
int arr[]={12,23,44,56,78}; //Declaring an array
for(int i:arr) //Printing array using for-each loop
{
System.out.print(i);
}
}
}
Output:
12 23 44 56 78
Java While Loop
 The while loop is used to iterate a part of the program repeatedly until the specified condition is true.
 As soon as the Boolean condition becomes false, the loop automatically stops.
 If the number of iteration is not fixed, it is recommended to use the while loop.
Syntax:
while (condition)
{
//code to be executed
Increment / decrement statement
}
Example:
Unlike the for loop, we separately need to initialize and increment the variable used in the condition
(here, i). Otherwise, the loop will execute infinitely.
WhileExample.java
public class WhileExample
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
{
System.out.print(i);
i++;
}
}
}
Output: 1 2 3 4 5

Object Oriented Programming Through Java Page 53


Java do-while Loop
 The do-while loop is used to iterate a part of the program repeatedly, until the specified condition is true.
 If the number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use a do-while loop.
 Java do-while loop is called an exit control loop.
Syntax:
do{
//code to be executed / loop body
//update statement
}while (condition);
Note: The do block is executed at least once, even if the condition is false.
Example:
Unlike the for loop, we separately need to initialize and increment the variable used in the condition
(here, i). Otherwise, the loop will execute infinitely.
DoWhileExample.java //In the below example, we print integer values from 1 to 10.
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.print(i);
i++;
}while(i<=5);
}
}
Output:
1 2 3 4 5

Object Oriented Programming Through Java Page 54


1.22 Break Statement,Continue Statement(Jump Statements/ Unconditional Control Statements)

 Jump statements are used to transfer the control of the program to the specific statements.
 In other words, jump statements transfer the execution control to the other part of the program.
 There are two types of jump statements in Java, i.e., break and continue.
Java Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
jump-statement;
break;
BreakExample.java //Java Program to demonstrate the use of break statement inside the for loop.
public class BreakExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++) //using for loop
{
if(i==5) //breaking the loop
{
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Java Continue Statement
 The continue statement is used in loop control structure when you need to jump to the next iteration of
the loop immediately.
 The Java continue statement is used to continue the loop.
 It continues the current flow of the program and skips the remaining code at the specified condition.
 In case of an inner loop, it continues the inner loop only.
 We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.

Object Oriented Programming Through Java Page 55


Syntax:
jump-statement;
continue;

ContinueExample.java //Java Program to demonstrate the use of continue statement inside the for loop.
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5 || i==7 || i==3)
{
continue; //it will skip the rest statement
}
System.out.println(i);
}
}
}
Output:
1
2
4
6
8
9
10
As you can see in the above output, 5 is not printed on the console. It is because the loop is continued when it
reaches to 5.

Object Oriented Programming Through Java Page 56

You might also like