0% found this document useful (0 votes)
12 views165 pages

Java Programming Basics and Tools Guide

Java is a class-based, object-oriented programming language designed for portability and ease of use, allowing developers to write once and run anywhere. The document covers the history of Java, the Java Development Kit (JDK), Java Runtime Environment (JRE), and Integrated Development Environments (IDEs) like NetBeans and JCreator for developing Java applications. It also includes instructions for creating, compiling, and executing a simple Java program, along with an overview of identifiers and variables in Java programming.

Uploaded by

raghavcoc1242
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)
12 views165 pages

Java Programming Basics and Tools Guide

Java is a class-based, object-oriented programming language designed for portability and ease of use, allowing developers to write once and run anywhere. The document covers the history of Java, the Java Development Kit (JDK), Java Runtime Environment (JRE), and Integrated Development Environments (IDEs) like NetBeans and JCreator for developing Java applications. It also includes instructions for creating, compiling, and executing a simple Java program, along with an overview of identifiers and variables in Java programming.

Uploaded by

raghavcoc1242
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

1.

1 Introduction, the Java Language Specification, API, JDK, IDE, Creating, Compiling
Introduction:
Java is a class-based, object-oriented programming language that is designed to have as few
implementation dependencies as possible. It is intended to let application developers write
once, and run anywhere (WORA), meaning that compiled Java code can run on all platforms
that support Java without the need for recompilation. Java was first released in 1995 and is
widely used for developing applications for desktop, web, and mobile devices. Java is known
for its simplicity, robustness, and security features, making it a popular choice for enterprise-
level applications.

JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995 and later
acquired by Oracle Corporation. It is a simple programming language. Java makes writing,
compiling, and debugging programming easy. It helps to create reusable code and modular
programs. Java is a class-based, object-oriented programming language and is designed to
have as few implementation dependencies as possible. A general-purpose programming
language made for developers to write once run anywhere that is compiled Java code can
run on all platforms that support Java. Java applications are compiled to byte code that can
run on any Java Virtual Machine.

History:
Java’s history is very interesting. It is a programming language created in 1991. James
Gosling, Mike Sheridan, and Patrick Naughton, a team of Sun engineers known as the Green
team initiated the Java language in 1991. Sun Microsystems released its first public
implementation in 1996 as Java 1.0. It provides no-cost -run-times on popular platforms.
Java1.0 compiler was re-written in Java by Arthur Van Hoff to strictly comply with its
specifications. With the arrival of Java 2, new versions had multiple configurations built for
different types of platforms.

In 1997, Sun Microsystems approached the ISO standards body and later formalized Java, but
it soon withdrew from the process. At one time, Sun made most of its Java implementations
available without charge, despite their proprietary software status. Sun generated revenue
from Java through the selling of licenses for specialized products such as the Java Enterprise
System.

On November 13, 2006, Sun released much of its Java virtual machine as free, open-source
software. On May 8, 2007, Sun finished the process, making all of its JVM’s core code
available under open-source distribution terms.
The principles for creating java were simple, robust, secured, high-performance,
portable, multi-threaded, interpreted, dynamic, etc. In 1995 Java was developed by
James Gosling, who is known as the Father of Java. Currently, Java is used in mobile
devices, internet programming, games, e-business, etc.

 What is API?
Computer languages have strict rules of usage. If you do not follow the rules when writing a
program, the computer will not be able to understand it! An API defines and specifies such rules.

API stands for Application Programming Interface. According to the Wikipedia, an API defines
interactions between multiple software intermediaries. It defines the kinds of calls or requests
that can be made, how to make them, the data formats that should be used, the conventions to
follow, etc. It can also provide extension mechanisms so that users can extend existing
functionality in various ways and to varying degrees.

The Java API is a library of pre-written classes, that are free to use, included in the Java
development [Link] library contains components for managing input, database
programming, and much much more. .

 What is JDK?
The Java Development Kit (JDK) is a basic set of tools used for developing Java applications
and applets. JDK comes from Oracle, the owner of Java, and it contains a compiler, an
interpreter, the Applet Viewer program, other utility programs, the standard Java library,
documentation, and examples.

Java is a very powerful language that can be used in many ways. It comes in three editions:

 Java Standard Edition (Java SE) to develop client – side applications. The applications can
run standalone or as applets running from a web browser.
 Java Enterprise Edition (Java EE) to develop server – side applications.
 Java Micro Edition (Java ME) to develop applications for mobile devices.

In this course, we use Java SE to introduce Java programming. There are many versions of Java
SE. To prepare for the AP Computer Science A exam, we choose to use Java SE 8. You need to
download JDK 1.8, also known as Java 8 or JDK 8.

What is JRE?
The program for running Java program is known as JRE (Java Runtime Environment). The JRE
is a subset of JDK. The following diagram shows the relationship among JDK, JRE and JVM
(Java Virtual Machine, please refer to the previous lesson if you don’t remember it).
 What is IDE?
Once JDK is downloaded and installed, you can enter Java program from a command line,
compile, test and run it. The command line is pretty cool but not so user friendly especially for
beginners. Instead of using the JDK, you can also download and install a Java Development tool
like Eclipse, NetBeans, DrJava and TextPad – software that provides an Integrated Development
Environment (IDE) for developing Java programs quickly. These software provide graphical user
interface (GUI) that greatly enhance user experience.

 Creating compiling and executing a java program


Basically, we save a Java program in a .java file and compile it into a .class file. The .class file is
executed by the Java Virtual Machine.

You can use any text editor or IDE to create and edit a Java source-code file. In this article, I
demonstrate how to create, compile, and run Java programs from a command window.

Step 1: Creating a Java Program


Let's use the command window prompt(cmd) and open a text editor such as Notepad to create
the Java source-code file [Link].

[Link]

Let's create a Java program and name this file to [Link]:

public class Welcome {


public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}

Step 2: Compiling a Java Program


A Java compiler translates a Java source file into a Java bytecode file. Let's use the following
command to compile [Link] file:

javac [Link]

If there aren’t any syntax errors, the compiler generates a bytecode file with a .class extension.
Thus, this command generates a file named [Link].

Step 2: Executing a Java Program


Let's use the following command to execute the bytecode:

java Welcome

The output of the above program displays the message “Welcome to Java!”
1.2 Executing a Java Program Developing Java Programs Using Net Beans/J Creator

1.2.1 Developing Java Programs Using Net Beans

For the first application, HelloWorldApp, will simply display the greeting "Hello World!" To
create this program, we will:

 Create an IDE project

When you create an IDE project, you create an environment in which to build and run
your applications. Using IDE projects eliminates configuration issues normally associated
with developing on the command line. You can build or run your application by choosing
a single menu item within the IDE.

 Add code to the generated source file

A source file contains code, written in the Java programming language, that you and
other programmers can understand. As part of creating an IDE project, a skeleton source
file will be automatically generated. You will then modify the source file to add the
"Hello World!" message.

 Compile the source file into a .class file

The IDE invokes the Java programming language compiler (javac), which takes your
source file and translates its text into instructions that the Java virtual machine can
understand. The instructions contained within this file are known as bytecodes.

 Run the program

The IDE invokes the Java application launcher tool (java), which uses the Java virtual
machine to run your application.

Create an IDE Project

To create an IDE project:

1. Launch the NetBeans IDE.


o On Microsoft Windows systems, you can use the NetBeans IDE item in the Start
menu.
o On Solaris OS and Linux systems, you execute the IDE launcher script by
navigating to the IDE's bin directory and typing ./netbeans.
o On Mac OS X systems, click the NetBeans IDE application icon.
2. In the NetBeans IDE, choose File | New Project....
NetBeans IDE with the File | New Project menu item selected.

3. In the New Project wizard, expand the Java category and select Java Application as
shown in the following figure:

NetBeans IDE, New Project wizard, Choose Project page.

4. In the Name and Location page of the wizard, do the following (as shown in the figure
below):
o In the Project Name field, type Hello World App.
o In the Create Main Class field, type [Link].
NetBeans IDE, New Project wizard, Name and Location page.

5. Click Finish.

The project is created and opened in the IDE. You should see the following components:

 The Projects window, which contains a tree view of the components of the project,
including source files, libraries that your code depends on, and so on.
 The Source Editor window with a file called [Link] open.
 The Navigator window, which you can use to quickly navigate between elements within
the selected class.
NetBeans IDE with the HelloWorldApp project open.

Add JDK 8 to the Platform List (if necessary)

It may be necessary to add JDK 8 to the IDE's list of available platforms. To do this, choose
Tools | Java Platforms as shown in the following figure:
Selecting the Java Platform Manager from the Tools Menu

If you don't see JDK 8 (which might appear as 1.8 or 1.8.0) in the list of installed platforms,
click Add Platform, navigate to your JDK 8 install directory, and click Finish. You should now
see this newly added platform:

The Java Platform Manager


To set this JDK as the default for all projects, you can run the IDE with the --jdkhome switch on
the command line, or by entering the path to the JDK in the netbeans_j2sdkhome property of
your INSTALLATION_DIRECTORY/etc/[Link] file.

To specify this JDK for the current project only, select Hello World App in the Projects pane,
choose File | Project Properties (Hello World App), click Libraries, then select JDK 1.8 in
the Java Platform pulldown menu. You should see a screen similar to the following:

The IDE is now configured for JDK 8.

Add Code to the Generated Source File

When you created this project, you left the Create Main Class checkcbox selected in the New
Project wizard. The IDE has therefore created a skeleton class for you. You can add the "Hello
World!" message to the skeleton code by replacing the line:

// TODO code application logic here

with the line:

[Link]("Hello World!"); // Display the string.


Optionally, you can replace these four lines of generated code:

/**
*
* @author
*/

with these lines:

/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/

These four lines are a code comment and do not affect how the program runs. Later sections of
this tutorial explain the use and format of code comments.

Note: Type all code, commands, and file names exactly as shown. Both the compiler (javac) and
launcher (java) are case-sensitive, so you must capitalize consistently.

HelloWorldApp is not the same as helloworldapp.

Save your changes by choosing File | Save.

The file should look something like the following:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package helloworldapp;

/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
public class HelloWorldApp {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
[Link]("Hello World!"); // Display the string.
}

}
Compile the Source File into a .class File

To compile your source file, choose Run | Build Project (Hello World App) from the IDE's
main menu.

The Output window opens and displays output similar to what you see in the following figure:

Output window showing results of building the HelloWorld project.

If the build output concludes with the statement BUILD SUCCESSFUL, congratulations! You
have successfully compiled your program!

If the build output concludes with the statement BUILD FAILED, you probably have a syntax
error in your code. Errors are reported in the Output window as hyperlinked text. You double-
click such a hyperlink to navigate to the source of an error. You can then fix the error and once
again choose Run | Build Project.

When you build the project, the bytecode file [Link] is generated. You can see
where the new file is generated by opening the Files window and expanding
the Hello World App/build/classes/helloworldapp node as shown in the following figure.
Files window, showing the generated .class file.

Now that you have built the project, you can run your program.

Run the Program

From the IDE's menu bar, choose Run | Run Main Project.

The next figure shows what you should now see.

The program prints "Hello World!" to the Output window (along with other output from the
build script)
1.2.2 Developing Java Programs Using J Creator

1. Start JCreator ...


Click on the Start button -> All Programs -> JCreator

You will then see a window entitled "JCreator - [Start Page]" ...
2. If you see the "Tip of the Day" window, close it.

3. Select File -> New -> Project


4. Click on the Next button to select a Basic Java Application (a regular Java program).
5. In the Name: box, type prog_01

NOTE:
The Location, Source Path and Output paths
will be automatically filled in according to how the
JCreator software was originally set up.
The following screen just shows an example.

[If it is necessary to change any path,


click on the button to the right of the text input box.]
[If it is necessary to change any path,
click on the button to the right of the text input box.]

6. In the window above, click on the Finish button to finish.

7 When the project building is complete,


as shown in the window below,
click on the Finish button to continue to the project window.
Click on the Finish button to continue to the project window.

8. You will then see a window entitled:

prog_01 - JCreator
Close the File View and Package View windows for now,
just leaving the source code (prog_01.java)
and General Output windows open.

You will see the following source code automatically supplied:

/**
* @(#)prog_01.java
*
* prog_01 application
*
* @author
* @version 1.00 2007/9/9
*/

public class prog_01 {

public static void main(String[] args) {

// TODO, add your application code


[Link]("Hello World!");
}
}

The green parts of the source code are comments,


which will not affect how the program runs (executes).
When the program above runs,
it will simply print the words Hello World!
in the General Output window.

Before it can be executed,


the source code must be compiled.
This is explained in the next section...

9. To compile the program,


from the menu, select Build -> Build File.
Wait a few seconds while the program is compiled.
If you made no changes to the source code,
you will get the following message
in the Build Output window
after the code has been successfully compiled...

--------------------Configuration: prog_01 - JDK version 1.6.0_02 <Default> - <Default>-----------


---------

Process completed.

10. To run the compiled program,


from the menu, select Run -> Run File.
In the General Output window,
you will see the following output
after the program prog_01 runs:

--------------------Configuration: prog_01 - JDK version 1.6.0_02 <Default> - <Default>-----------


---------
Hello World!

Process completed.
1.3 Identifiers, Variables, Assignment Statements and Assignment Expressions

1.3.1 Identifiers in Java


In Java programming, identifiers help make different elements inside a program easier to
recognize and use by acting as symbolic names for them. Numerous entities, including classes,
variables, methods, packages, constants, and more, can be represented by these identifiers.
Developers can enhance the readability and maintainability of code by giving these elements
meaningful names.

In Java programming, identifiers are essential because they let programmers efficiently reference
and modify program parts. A class identifier uniquely identifies a class definition to enable the
production of objects and the calling of class methods, for example. In a similar vein, method
IDs designate executable code blocks, and variable identifiers stand in for storage locations
connected to data values.

Identifiers in Java are symbolic names used for identification. It can be a class name, variable
name, method name, package name, constant name, and other names used in programming.
However, in Java, some reserved words cannot be used as an identifier.

For every identifier, some conventions should be used before declaring them. Let's understand it
with a simple Java program:

1. public class HelloJava {


2. public static void main(String[] args) {
3. [Link]("Hello JavaTpoint");
4. }
5. }

In the above example, we have used the following identifiers:

1. HelloJava (Class name)


2. main (main method)
3. String (Predefined Class name)
4. args (String variables)
5. System (Predefined class)
6. out (Variable name)
7. println (method)

 Importance of Identifiers

1. Programme Structure: Classes, variables, methods, packages, and other things are named
by identifiers that are the fundamental building blocks of Java programmes.
2. Readability and Understanding: When well-chosen identifiers improve the readability
and comprehensibility of code, developers can more easily comprehend the function and
goal of various program components.
3. Modifiability: By offering a simple method of referencing and altering program elements,
identifiers aid in code maintenance and change.
4. Communication: Identifiers allow developers to communicate with each other by sharing
details about the purpose and capabilities of certain program pieces.

 Rules for Java Identifiers


There are some rules and conventions for declaring the identifiers in Java. If the identifiers are
not properly declared, we may get a compile-time error. Following are some rules and
conventions for declaring identifiers:

o A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore
(_) or a dollar sign ($). For example, @javatpoint is not a valid identifier because it
contains a special character @.
o There should not be any space in an identifier. For example, java tpoint is an invalid
identifier.
o An identifier should not contain a number at the starting. For example, 123javatpoint is
an invalid identifier.
o An identifier should be of length 4-15 letters only. However, there is no limit on its
length. But, it is good to follow the standard conventions.
o We cannot use the Java reserved keywords as an identifier such as int, float, double, char,
etc. For example, int double is an invalid identifier in Java.
o An identifier should not be any query language keywords such as SELECT, FROM,
COUNT, DELETE, etc.

1.3.2 Variables in Java

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
 boolean - stores values with two states: true or false

 Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax

type variableName = value;

Where type is one of Java's types (such as int or String), and variableName is the name of the
variable (such as x or name). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

Example

Create a variable called name of type String and assign it the value "John".
Then we use println() to print the name variable:

String name = "John";

[Link](name);

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;

[Link](myNum);

You can also declare a variable without assigning the value, and assign the value later:

Example

int myNum;

myNum = 15;

[Link](myNum);

Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example

Change the value of myNum from 15 to 20:

int myNum = 15;

myNum = 20; // myNum is now 20

[Link](myNum);

 Final Variables

If you don't want others (or yourself) to overwrite existing values, use the final keyword (this
will declare the variable as "final" or "constant", which means unchangeable and read-only):

Example

final int myNum = 15;

myNum = 20; // will generate an error: cannot assign a value to a final variable

 Other Types

A demonstration of how to declare variables of other types:

Example

int myNum = 5;

float myFloatNum = 5.99f;

char myLetter = 'D';

boolean myBool = true;

String myText = "Hello";


1.3.3. Assignment Statements and Assignment Expressions in Java

An assignment statement designates a value for a variable. An assignment statement can be used
as an expression in Java.

After a variable is declared, you can assign a value to it by using an assignment statement. In
Java, the equal sign = is used as the assignment operator. The syntax for assignment statements is
as follows:

variable = expression;

An expression represents a computation involving values, variables, and operators that, when
taking them together, evaluates to a value. For example, consider the following code:

int y = 1; // Assign 1 to variable y


double radius = 1.0; // Assign 1.0 to variable radius
int x = 5 * (3/2); // Assign the value of the expression to x
x = y + 1; // Assign the addition of y and 1 to x
double area = radius * radius * 3.14; // Compute the area

You can use a variable in an expression. A variable can also be used on both sides of
the = operator. For example:

x=x+1

In the above assignment statement, the result of x + 1 is assigned to the variable x. Let’s say
that x is 1 before the statement is executed, and so becomes 2 after the statement execution.

To assign a value to a variable, you must place the variable name to the left of the assignment
operator. Thus the following statement is wrong:

1 = x; // Wrong

Note that the math equation x = 2 * x + 1 ≠ the Java expression x = 2 * x + 1

In Java, an assignment statement is an expression that evaluates a value, which is assigned to the
variable on the left side of the assignment operator. Whereas an assignment expression is the
same, except it does not take into account the variable.
That’s why the following statements are legal:

[Link](x = 1);

Which is equivalent to:

x=1;
[Link](x);

And this statement

//If a value is assigned to multiple variables, you can use this syntax:
i = j = k = 1;

is equivalent to:

k = 1;
j = k;
i = j;

Note: The data type of a variable on the left must be compatible with the data type of a value on
the right. For example, int x = 1.0 would be illegal, because the data type of x is int (integer) and
does not accept the double value 1.0 without Type Casting.
1.4 Named Constants, Naming Conventions. Numeric Data Types and Operations, Numeric
Literals
1.4.1 Named Constants
A named constant is an identifier that represents a permanent value. The value of a variable may
change during the execution of a program, but a named constant, or simply constant, represents
permanent data that never changes. For example, pie of a circle is a constant. If you use it
frequently, you don’t want to keep typing 3.14159; instead, you can declare a constant for pie.
Here is the syntax for declaring a constant:

final datatype CONSTANTNAME = value;

A constant must be declared and initialized in the same statement. The word final is a Java
keyword for declaring a constant.

There are three benefits of using constants:

 You don’t have to repeatedly type the same value if it is used multiple times;
 If you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you need to
change it only in a single location in the source code;
 A descriptive name for a constant makes the program easy to read.

1.4.2 Naming Conventions


Java naming convention is a rule to follow as you decide what to name your identifiers such as
class, package, variable, constant, method, etc.

But, it is not forced to follow. So, it is known as convention not rule. These conventions are
suggested by several Java communities such as Sun Microsystems and Netscape.

All the classes, interfaces, packages, methods and fields of Java programming language are given
according to the Java naming convention. If you fail to follow these conventions, it may generate
confusion or erroneous code.

 Advantage of Naming Conventions in Java


By using standard Java naming conventions, you make your code easier to read for yourself and
other programmers. Readability of Java program is very important. It indicates that less time is
spent to figure out what the code does.

 Naming Conventions of the Different Identifiers


The following table shows the popular conventions used for the different identifiers.

Identifiers Type Naming Rules Examples

It should start with the uppercase public class Employee


letter. {
Class
It should be a noun such as //code snippet
Color, Button, System, Thread, }
etc.
Use appropriate words, instead
of acronyms.

It should start with the uppercase


letter.
interface Printable
It should be an adjective such as
{
Interface Runnable, Remote,
//code snippet
ActionListener.
}
Use appropriate words, instead
of acronyms.

It should start with lowercase class Employee


letter. {
It should be a verb such as // method
main(), print(), println(). void draw()
Method
If the name contains multiple {
words, start it with a lowercase //code snippet
letter followed by an uppercase }
letter such as actionPerformed(). }

It should start with a lowercase


letter such as id, name.
It should not start with the
special characters like &
class Employee
(ampersand), $ (dollar), _
{
(underscore).
// variable
Variable If the name contains multiple
int id;
words, start it with the lowercase
//code snippet
letter followed by an uppercase
}
letter such as firstName,
lastName.
Avoid using one-character
variables such as x, y, z.

It should be a lowercase letter //package


such as java, lang. package [Link];
If the name contains multiple class Employee
Package
words, it should be separated by {
dots (.) such as [Link], //code snippet
[Link]. }

It should be in uppercase letters class Employee


Constant such as RED, YELLOW. {
If the name contains multiple //constant
words, it should be separated by static final int MIN_AGE = 18;
an underscore(_) such as //code snippet
MAX_PRIORITY. }
It may contain digits but not as
the first letter.

1.4.3 Numeric Data Types and Operations

Java has six numeric types for integers and floating-point numbers with operators +, -, *, /, and
%.

 Numeric Types

Every data type has a range of values. The compiler allocates memory space for each variable or
constant according to its data type. Java provides eight primitive data types for numeric values,
characters, and Boolean values.

Java uses four types for integers: byte, short, int, and long. Choose the type that is most
appropriate for your variable. For example, if you know an integer stored in a variable is within a
range of a byte, declare the variable as a byte.

Java uses two types for floating-point numbers: float and double. The double type is twice as big
as float, so the double is known as double precision and float as single precision. Normally, you
should use the double type, because it is more accurate than the float type.
 Reading Numbers from the Keyboard

Methods for Scanner Objects

Here are examples for reading values of various types from the keyboard:

Scanner input = new Scanner([Link]);


[Link]("Enter a byte value: ");
byte byteValue = [Link]();

[Link]("Enter a short value: ");


short shortValue = [Link]();

[Link]("Enter an int value: ");


int intValue = [Link]();

[Link]("Enter a long value: ");


long longValue = [Link]();

[Link]("Enter a float value: ");


float floatValue = [Link]();

If you enter a value with an incorrect range or format, a runtime error would occur.

 Numeric Operators

The operators for numeric data types include the standard arithmetic operators: addition (+),
subtraction (–), multiplication (****), division (/), and remainder (%*).

When both operands of a division are integers, the result of the division is the quotient and the
fractional part is truncated. For example, 5 / 2 yields 2, not 2.5, and –5 / 2 yields -2, not –2.5. To
perform a float-point division, one of the operands must be a floating-point number. For
example, 5.0 / 2 yields 2.5.

The % operator, known as remainder or modulo operator, yields the remainder after division.
The operand on the left is the dividend and the operand on the right is the divisor. Therefore, 7 %
3 yields 1, 3 % 7 yields 3, 12 % 4 yields 0, 26 % 8 yields 2, and 20 % 13 yields 7.

The % operator is often used for positive integers, but it can also be used with negative integers
and floating-point values. The remainder is negative only if the dividend is negative. For
example, -7 % 3 yields -1, -12 % 4 yields 0, -26 % -8 yields -2, and 20 % -13 yields 7.

Remainder is very useful in programming. For example, an even number % 2 is always 0 and an
odd number % 2 is always 1. Thus, you can use this property to determine whether a number is
even or odd. If today is Saturday, it will be Saturday again in 7 days. Suppose you and your
friends are going to meet in 10 days. What day is in 10 days? You can find that the day is
Tuesday using the following expression:

(6 + 10) % 7 is 2

The program obtains minutes and remaining seconds from an amount of time in seconds. For
example, 500 seconds contains 8 minutes and 20 seconds.

The + and - operators can be both unary and binary. A unary operator has only one operand;
a binary operator has two. For example, the - operator in -5 is a unary operator to negate
number 5, whereas the - operator in 4 - 5 is a binary operator for subtracting 5 from 4.

 Exponent Operations

The [Link](a, b) method can be used to compute a^b. The pow method is defined in
the Math class in the Java API. You invoke the method using the syntax [Link](a,
b) (e.g., [Link](2, 3)), which returns the result of a^b (2^3). Here, a and b are parameters for
the pow method and the numbers 2 and 3 are actual values used to invoke the method. For
example,

[Link]([Link](2, 3)); // Displays 8.0


[Link]([Link](4, 0.5)); // Displays 2.0
[Link]([Link](2.5, 2)); // Displays 6.25
[Link]([Link](2.5, -2)); // Displays 0.16

1.4.4 Numeric Literals


In Java, literals are the constant values that appear directly in the program. It can be assigned
directly to a variable. Java has various types of literals. The following figure represents a literal.

Types of Literals in Java


There are the majorly four types of literals in Java:

1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal

 Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:

o Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may
have a positive (+) or negative (-) Note that between numbers commas and non-digit
characters are not permitted. For example, 5678, +657, -89, etc.
1. int decVal = 26;
o Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0. For
example, 045, 026,
1. int octVal = 067;

o Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as


hexadecimal integers. It may also include a character from a to f or A to F that represents
numbers from 10 to 15, respectively. For example, 0xd, 0xf,
1. int hexVal = 0x1a;

o Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create
binary literals in Java SE 7 and later). Prefix 0b represents the Binary system. For
example, 0b11010.
1. int binVal = 0b11010;
 Real Literals
The numbers that contain fractional parts are known as real literals. We can also represent real
literals in exponent form. For example, 879.90, 99E-3, etc.

 Backslash Literals
Java supports some special backslash character literals known as backslash literals. They are
used in formatted output. For example:

\n: It is used for a new line

\t: It is used for horizontal tab

\b: It is used for blank space

\v: It is used for vertical tab

\a: It is used for a small beep

\r: It is used for carriage return

\': It is used for a single quote

\": It is used for double quotes

 Character Literals
A character literal is expressed as a character or an escape sequence, enclosed in a single quote
('') mark. It is always a type of char. For example, 'a', '%', '\u000d', etc.

 String Literals
String literal is a sequence of characters that is enclosed between double quotes ("") marks. It
may be alphabet, numbers, special characters, blank space, etc. For example, "Jack", "12345",
"\n", etc.

 Floating Point Literals


The vales that contain decimal are floating literals. In Java, float and double primitive types fall
into floating-point literals. Keep in mind while dealing with floating-point literals.
Advertisement

o Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc. It is
a 32-bit float literal.
o Floating-point literals for double type end with D or d. It is optional to write D or d. For
example, 6d, 8.354D, etc. It is a 64-bit double literal.
o It can also be represented in the form of the exponent.
Floating:

1. float length = 155.4f;


Decimal:

1. double interest = 99658.445;


Decimal in Exponent form:

1. double val= 1.234e2;

Boolean Literals
Boolean literals are the value that is either true or false. It may also have values 0 and 1. For
example, true, 0, etc.

1. boolean isEven = true;


 Null Literals
Null literal is often used in programs as a marker to indicate that reference type object is
unavailable. The value null may be assigned to any variable, except variables of primitive types.

1. String stuName = null;


2. Student age = null;
 Class Literals
Class literal formed by taking a type name and appending .class extension. For
example, [Link]. It refers to the object (of type Class) that represents the type itself.

1. class classType = [Link];


Invalid Literals
There is some invalid declaration of literals.

1. float g = 6_.674f;
2. float g = 6._674F;
3. long phoneNumber = 99_00_99_00_99_L;
4. int x = 77_;
5. int y = 0_x76;
6. int z = 0X_12;
7. int z = 0X12_;
1.5 Evaluating Expressions and Operator Precedence, Increment and Decrement
Operators, Numeric Type Conversions

1.5.1 Evaluating Expressions and Operator Precedence

In real life when we solve an expression containing multiple operators we follow some rules. For
example in an expression 2+3*4, we do the multiplication first before addition because the
multiplication operator has higher precedence than addition operator. The same applies in java as
well.

In java, operator precedence is a rule that tells us the precedence of different operators. Operators
with higher precedence are evaluated before operators with lower precedence. For example in
expression a+b*c, the operator * will be evaluated before + operator, because operator * has
higher precedence than + operator.

Table bellow shows the precedence of operators in decreasing order, the operators appearing first
in table have higher precedence than operators appearing later. Operators appearing in same row
of table have equal precedence. When operators of equal precedence appears in the same
expression, a rule governs the evaluation order which says that all binary operators except for the
assignment operator are evaluated from left to right while assignment operator is evaluated from
right to left. For example in expression 2+3-4, 2 and 3 is added first then 4 is subtracted from it.
Consider a and b as two operands for the examples given in below table.

Java operator precedence table

Operators Precedence Example

Postfix expr++ expr-- a++ , a--

Unary ++expr --expr +expr -expr ~ ! ++a , --a , !a

Multiplicative */% a*b , a/b , a%b

Additive +- a+b , a-b

Shift << >> >>> a<<2 , a>>1

Relational < > <= >= instanceof a<2 , a>1

Equality == != a==b , a!=b


Bitwise AND & a&b

Bitwise exclusive OR ^ a^b

Bitwise inclusive OR | a|b

Logical AND && a&&b

Logical OR || a||b

Ternary ?: a = a>2 ? a : b

Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>= a=b, a+=b, a/=b, a>>=2

Which operator has highest precedence in java ?

The postfix operator(eg. a++, a--) has the highest precedence in java.

Which operator has lowest precedence in java ?

Assignment operator and it's different forms has the lowest precedence in java.

A programmer should remember bellow rules while evaluating an expression in java.

 The operands of operators are evaluated from left to right. For example in expression ++a + b--,
the operand ++a is evaluated first then b-- is evaluated.

 Every operand of an operator (except the conditional operators &&, ||, and ? :) are evaluated
completely before any part of the operation itself is performed. For example in expression ++a
+ b--, the addition operation will take place only after ++a and b-- is evaluated.

 The left-hand operand of a binary operator are evaluated completely before any part of the
right-hand operand is evaluated.

 Order of evaluation given by parenthesis () get's preference over operator precedence.

 The prefix version of ++ or -- evaluates/uses the incremented value in an expression while


postfix version of ++ or -- evaluates the current value, then increases/decreases the operand
value.

 All binary operators are evaluated from left to right except assignment operator.

What changes the precedence of the operators in Java ?

Parentheses "()" are used to alter the order of evaluation. For example in an expression a+b*c, if
you want the addition operation to take place first, then rewrite the expression as (a+b)*c.

Java Program of Operator Precedence

class OperatorPrecedence {

public static void main (String[] args) {

int result = 0;

result = 5 + 2 * 3 - 1;

[Link]("5 + 2 * 3 - 1 = " +result);

result = 5 + 4 / 2 + 6;

[Link]("5 + 4 / 2 + 6 = " +result);

result = 3 + 6 / 2 * 3 - 1 + 2;

[Link]("3 + 6 / 2 * 3 - 1 + 2 = " +result);

result = 6 / 2 * 3 * 2 / 3;

[Link]("6 / 2 * 3 * 2 / 3 = " +result);

int x = 2;

result = x++ + x++ * --x / x++ - --x + 3 >> 1 | 2;

[Link]("result = " +result);

Output:

5 + 2 * 3 - 1 = 10
5 + 4 / 2 + 6 = 13
3 + 6 / 2 * 3 - 1 + 2 = 13
6 / 2 * 3 * 2 / 3 = 6
result = 2

Let's understand how the last expression x++ + x++ * --x / x++ - --x + 3 >> 1 | 2 is evaluated
step by step.

operands are evaluated first, left to right

2 + 3 * 3 / 3 - 3 + 3 >> 1 | 2

* and / have higher preference than other, * evaluated first as it comes in left

2 + 9 / 3 - 3 + 3 >> 1 | 2

/ have higher preference than others

2 + 3 - 3 + 3 >> 1 | 2

+ and - have higher preference than others

5 >> 1 | 2

>> have higher preference than |

2|2

Output

2
1.5.2 Increment and Decrement Operators

Java programming language is well known for its simplicity and readability. One of the features
that contribute to this simplicity is the use of various operators. Among these operators are the
increment (++) and decrement (–) operators, which are used to increase or decrease the value of
a variable by 1. In this blog post, we will discuss these operators in detail and explore their use
cases with examples. Whether you are a beginner or an intermediate developer, this post will
help you understand the concept of increment and decrement operators in Java.

 Introduction to Increment and Decrement Operators

The increment (++) and decrement (–) operators are unary operators in Java, which means they
operate on a single operand. They are used to increase or decrease the value of an integer,
floating-point, or character variable by 1. These operators can be applied in two ways: prefix and
postfix.

 Prefix Increment and Decrement Operators

In the prefix form, the operator is placed before the operand. The value of the operand is
incremented or decremented first, and then the result is used in the expression. The syntax for
prefix increment and decrement operators is as follows:

++variable;
--variable;

 Postfix Increment and Decrement Operators

In the postfix form, the operator is placed after the operand. The value of the operand is used in
the expression first, and then it is incremented or decremented. The syntax for postfix increment
and decrement operators is as follows:

variable++;
variable--;

Now, let's dive deeper into these operators and see how they work with examples.

Examples of Increment and Decrement Operators

 Prefix Increment Operator

Let's start with a simple example to understand the prefix increment operator.

int a = 5;
int b = ++a;
[Link]("a: " + a + ", b: " + b);

In this example, the value of a is incremented by 1, and then the result is assigned to b. The
output will be:

a: 6, b: 6

 Postfix Increment Operator

Now, let's look at an example of the postfix increment operator.

int a = 5;
int b = a++;
[Link]("a: " + a + ", b: " + b);

In this example, the value of a is used in the expression first, and then it is incremented by 1. The
output will be:

a: 6, b: 5

 Prefix Decrement Operator

Here's an example of the prefix decrement operator.

int a = 5;
int b = --a;
[Link]("a: " + a + ", b: " + b);

In this example, the value of a is decremented by 1, and then the result is assigned to b. The
output will be:

a: 4, b: 4

 Postfix Decrement Operator

Lastly, let's see an example of the postfix decrement operator.

int a = 5;
int b = a--;
[Link]("a: " + a + ", b: " + b);

In this example, the value of a is used in the expression first, and then it is decremented by 1.
The output will be:

a: 4, b: 5

Use Cases of Increment and Decrement Operators

Increment and decrement operators are commonly used in loops and other control structures.
They can simplify the code and make it more readable.
Using Increment Operator in a Loop

For instance, you can use the increment operator in a for loop to iterate through an array.

int[] numbers = {1, 2, 3, 4, 5};


for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}

In this example, the variable i is incremented by 1 in each iteration of the loop until it reaches the
length of the array.

Using Decrement Operator in a Loop

Similarly, you can also use the decrement operator in a loop to iterate through an array in reverse
order.

int[] numbers = {1, 2, 3, 4, 5};


for (int i = [Link] - 1; i >= 0; i--) {
[Link](numbers[i]);
}

In this example, the variable i is decremented by 1 in each iteration of the loop until it reaches 0.
1.5.3 Numeric Type Conversions

Floating-point numbers can be converted into integers using explicit casting. If an integer and a
floating-point number are involved in a binary operation, Java automatically converts the integer
to a floating-point value. So, 3 * 4.5 is same as 3.0 * 4.5.

You can always assign a value to a numeric variable whose type supports a larger range of
values; thus, for instance, you can assign a long value to a float variable. You cannot, however,
assign a value to a variable of a type with a smaller range unless you use type casting. Casting is
an operation that converts a value of one data type into a value of another data type. Casting a
type with a small range to a type with a larger range is known as widening a type. Casting a type
with a large range to a type with a smaller range is known as narrowing a type. Java will
automatically widen a type, but you must narrow a type explicitly.

The syntax for casting a type is to specify the target type in parentheses, followed by the
variable’s name or the value to be cast. For example, the following statement

[Link]((int)1.7);

displays 1. When a double value is cast into an int value, the fractional part is truncated. The
following statement

[Link]((double)1 / 2);

displays 0.5, because 1 is cast to 1.0 first, then 1.0 is divided by 2. However, the statement

[Link](1 / 2);

displays 0, because 1 and 2 are both integers and the resulting value should also be an integer.

Casting is necessary if you are assigning a value to a variable of a smaller type range, such as
assigning a double value to an int variable. A compile error will occur if casting is not used in
situations of this kind. However, be careful when using casting, as loss of information might lead
to inaccurate results.

Casting does not change the variable being cast. For example, d is not changed after casting in
the following code:

double d = 4.5;
int i = (int)d; // i becomes 4, but d is still 4.5

To assign a variable of the int type to a variable of the short or byte type, explicit casting must
be used. For example, the following statements have a compile error:

int i = 1;
byte b = i; // Error because explicit casting is required

However, so long as the integer literal is within the permissible range of the target variable,
explicit casting is not needed to assign an integer literal to a variable of the short or byte type
UGCSA117 : Object-Oriented Programming(OOP)
in Java
(BCA 2nd Sem)

Unit-2

Module2.1:
2.1.1 Boolean Data Type
The Boolean data type is used to store logic values i.e. truth values which are true
or false. It takes only 1 byte of space to store logic values. Here, true means 1,
and false means 0. In the Boolean data type any value other than ‘0’ is considered
as ‘true’. Boolean values are most commonly used in data structures to decide the
flow of control of a program and decision statements. In programming languages,
we have various data types to store different data types. The most used data types
are integer, string, float, and Boolean. The Boolean data type is a type of data that
stores only two types of values i.e. True or False. These values are not case-
sensitive depending upon programming languages. The name Boolean comes
from the branch of mathematics called Boolean algebra, named after George Bool
the mathematician.

Example of Declaration of Boolean Data Type


import [Link].*;

class GFG { public static void main


(String[] args) { boolean a = true;
boolean b = false;
//boolean c = 1; this will give error
//Because in Java only true and false
//can be used in boolean

[Link]("a: "+a);
[Link]("b: "+b);

}
}
2.1.2Difference Between Boolean and Other Data Types
In programming languages, there are three types of data which are Booleans, Text,
and Numbers. It is important to understand the differences between them and some
basics about them.
Booleans: They are either true (1) or false (0) and take only 1 byte of space in
memory. while other data types take 2 to 8 bytes depending on the machine.
Numbers: Numbers can be negative, positive, and zero or decimal numbers. The data
type used to store numbers such as short, int, and double can take 2 to 8 bytes of
space in memory.
Text: Text includes characters, alphabets, numbers, and a collection of them. Text can
be of character or string type. The size of 1 character is 2 bytes.
2.1.3 If Else Statement in Programming
An if else statement in programming is a basic programming technique
that allows you to make decisions based on certain conditions. It allows
your program to execute different pieces of code depending on whether
the specified condition evaluates to true or false. This capability is
crucial in building dynamic and functional applications.
2.1.4 Importance of If Else Statement:
The importance of if-else statements lies in their ability to control the execution
of a program. Using if-else statements allows developers to apply logic that
responds to situations, making programs more versatile and powerful. Whether
manipulating user statements, manipulating data, or controlling program flow, if-
else statements play an important role in programming.
2.1.5 Basic Syntax of If Else Statement:
Generally, the basic syntax of if false statements follow this pattern: if
(condition) {
// Code block to execute if condition is true }
else {
// Code block to execute if condition is false }

In this syntax:
The `if` keyword begins a conditional statement.
The condition is enclosed in parentheses `()`.
If the condition evaluates to true, the code block immediately following the `if`
statement is executed.
If the condition evaluates to false, the code block is executed in the `else`
statement.
2.1.6 If Else Statement in Java:
Here is the implementation of if-else statement in Java language:

public class Main {

public static void main(String[] args) {


// Declare and initialize the variable num

int num = 10;

// Check if num is greater than 0

if (num > 0)

// If num is greater than 0, print "Number is positive."

[Link]("Number is positive.");

} else {

// If num is not greater than 0, print "Number is non-positive."

[Link]("Number is non-positive.");

} }
}

2.1.7 Nested If Else Statement in Programming

Nested If Else Statements are a fundamental concept in programming.


They allow us to create more complex decision-making structures by
placing one if-else statement inside another. In this article, we will
discuss the Nested if else statement.
• What is Nested If Else Statement?
Nested if-else statements allow for more complex decision-making within the
program. You can nest if-else statements with other if-else statements, creating
conditions at multiple levels.
• Syntax of Nested If Else Statement:
if (condition1) {
// Code block for condition1 being true if
(condition2) {
// Code block for condition1 and condition2 both being true
} else {
// Code block for condition1 being true and condition2 being false
}}
else {
// Code block for condition1 being false }
• Nested If Else Statement in Java:
Here is the implementation of Nested if else statement in Java language:

public class Main {

public static void main(String[] args) {

// Declare and initialize the variable num

int num = 10;

// Outer if-else statement to check if num is greater than 0

if (num > 0) {

[Link]("Number is positive.");
// Nested if-else statement to check if num is even or odd

if (num % 2 == 0) {

[Link]("Number is even.");

} else {

[Link]("Number is odd.");

} else {

// Execute if num is not greater than 0

[Link]("Number is non-positive.");

} }

2.1.8 Java Nested if

Nested if in Java refers to having one if statement inside another if statement. If


the outer condition is true the inner conditions are checked and executed
accordingly. Nested if condition comes under decision-making statement in Java,
enabling multiple branches of execution.
Note:
Normal if condition checks condition independently which means each condition
works on its own.
Whereas nested if checks conditions that depend on each other, which means one
condition is only checked if another condition is true.

Syntax of Nested if
if (condition1) { if
(condition2) { if
(condition3) {
// statements;
}
}
}
Note: If the outer condition satisfies then only the inner condition will be checked.
Along with if condition, else condition can also be executed.
UGCSA117 : Object-Oriented Programming(OOP)
in Java
(BCA 2nd Sem)

Unit-2

Module2:

2.2 Logical Operators


Logical operators are used to perform logical “AND”, “OR” and “NOT”
operations, i.e. the function similar to the AND gate and OR gate in digital
electronics. They are used to combine two or more conditions/constraints or to
complement the evaluation of the original condition under particular
consideration. One thing to keep in mind is, that while using the AND operator,
the second condition is not evaluated if the first one is false. Whereas while using
the OR operator, the second condition is not evaluated if the first one is true, i.e.
the AND and OR operators have a short-circuiting effect. Used extensively to test
for several conditions for making a decision.
AND Operator ( && ) – if( a && b ) [if true execute else don’t]
OR Operator ( || ) – if( a || b) [if one of them is true to execute else don’t] NOT
Operator ( ! ) – !(a<b) [returns false if a is smaller than b]
Example For Logical Operator in Java
Here is an example depicting all the operators where the values of variables a, b,
and c are kept the same for all the situations.
a = 10, b = 20, c = 30 For
AND operator:
Condition 1: c > a
Condition 2: c > b
Output:
True [Both Conditions are true]

For OR Operator:
Condition 1: c > a
Condition 2: c > b
Output:
True [Both Conditions are true]

For OR Operator:
Condition 1: c > a
Condition 2: c > b
Output:
True [One of the Condition if true]

For NOT Operator:


Condition 1: c > a
Condition 2: c > b
Output:
2.2.1 Switch Statements in Java
The switch statement in Java is a multi-way branch statement. In simple
words, the Java switch statement executes one statement from multiple
conditions.
It is an alternative to an if-else-if ladder statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
The expression can be of type byte, short, char, int, long, enums, String, or
wrapper classes (Integer, Short, Byte, Long).

Note: Java switch expression must be of byte, short, int, long(with its Wrapper
type), Enums, and string. Beginning with JDK7, it also works with enumerated
types (Enums in Java), the String class, and Wrapper classes.
Syntax: switch(expression)
{ case value1 :
// Statements
break; // break is optional

case value2 : //
Statements break; //
break is optional
....
....
....
default :
// default Statement
}
2.2.1.1Some Important Rules for Java Switch Statements
Case values must be constants or literals and of the same type as the switch
expression.
Duplicate case values are not allowed.
The break statement is used to exit from the switch block. It is optional but
recommended to prevent fall-through.
The default case is optional and executes if no case matches the switch
expression. It can appear anywhere within the switch block.
Note: Starting from Java 7, switch statements can use String-type values.
They can also handle wrapper classes like Integer, Short, Byte, Long.
Flowchart of Switch-Case Statement
This flowchart shows the control flow and working of switch statements:

Note: Java switch statement is a fall-through statement that means it executes all
statements if break keyword is not used, so it is highly essential to use break
keyword inside each case.

[Link] Conditional Operator in Programming


Conditional Operator, often referred to as the ternary operator, is a concise
way to express a conditional (if-else) statement in many programming
languages. It is represented by the "?" symbol and is sometimes called the
ternary operator because it takes three operands.

2.2.2 Syntax of Conditional Operator:


The syntax of conditional operators, often referred to as the ternary operator, is
as follows:
condition? expression_if_true: expression_if_false condition: A Boolean
expression that evaluates to either true or false. expression_if_true: The value or
expression to be returned if the condition is true. expression_if_false: The value
or expression to be returned if the condition is
false.

2.2.3 Operator Precedence and Associativity in Programming


We have many types of operators in a programming language. Operators serve
many purposes. But when we have many operators within the same statement,
Operator Precedence and Associativity come into the picture. They define which
operator should be taken into account first. It is similar to the BODMAS rule we
have learned in our school mathematics. In this article, we will see what is
Operator Precedence and Associativity.
Operators Precedence:

Op
Prece era Descri Assoc
dence tor ption iativity
1 () Parenth Left-
eses toRight
(functi
on call)

When various operators are used within the same statement a problem arises which
is which operation should be performed first. To solve this problem there is the
concept of operator precedence. Operator Precedence is a set of rules that defines
the priority for all the operators present in a programming language. The operation
which has an operator with the highest priority will be executed first. Operator
Associativity:
If we have operators which have same precedence in the same statement then we
use associativity to figure out which operation should be performed first.
Associativity defines whether you should go from left to right or you should go
to right to left. If Associativity says that you should go left to right then
operation on the left side should be performed first and then only, we should
move to right side.

Operator Precedence and Associativity Table:


The following tables list the operator precedence from highest to lowest and the
associativity for each of the operators:
Op
Prece era Descri Assoc
dence tor ption iativity

[] Array
Subscri
pt
(Square
Bracket
s)

. Dot
Operat
or

-> Structu
re
Pointer
Operat
or

++ , Postfix
— increm
ent,
decrem
ent
2 ++ / Prefix Rightto-
— increm Left
ent,
decrem
ent
Op
Prece era Descri Assoc
dence tor ption iativity

+/ Unary
– plus,
minus

!,~ Logical
NOT,
Bitwise
comple
ment

Cast
(typ
Operat
e)
or

* Derefer
ence
Operat
or
& Addres
sof
Operat
or

size Determ
of ine size
in bytes
Op
Prece era Descri Assoc
dence tor ption iativity

3 *,/, Multipl Left-


% ication, toRight
divisio
n,
modulu
s

4 +/- Additio Left-


n, toRight
subtrac
tion

Bitwise
<< , shift Left-
>> left, toRight
5
Bitwise
shift
right
6 <, Relatio Left-
<= nal less toRight
than,
less
than or
equal
to

Relatio
>,
nal
>=
greater
Op
Prece era Descri Assoc
dence tor ption iativity

than,
greater
than, or
equal
to

7 == , Relatio Left-
!= nal is toRight
equal
to, is
not
equal
to

8 & Bitwise Left-


AND toRight

9 ^ Bitwise Left-
exclusi toRight
ve OR
10 | Bitwise Left-
inclusi toRight
ve OR

11 && Logical Left-


AND toRight
Op
Prece era Descri Assoc
dence tor ption iativity

12 || Logical Left-
OR toRight

13 Ternary Rightto-
?:
conditi Left
onal

14 = Assign Rightto-
ment Left

+= , - Additio
= n,
subtrac
tion
assign
ment
Multipl
ication,
*= , divisio
/= n
assign
ment

%= Modulu
, s,
&= bitwise
AND
Op
Prece era Descri Assoc
dence tor ption iativity

assign
ment

Bitwise
exclusi
^= , ve,
|= inclusi
ve OR
assign
ment

<<= Bitwise
, shift
>>= left,
right
assign
ment

15 , comma Left-
(expres toRight
sion
separat
or)
UGCSA117 : Object-Oriented Programming(OOP)
in Java (BCA 2nd Sem)

Unit-2

Module2:
2.3 Java Math Class
[Link] Class methods help to perform numeric operations like square, square root,
cube, cube root, exponential, and trigonometric operations.
Methods of Math Class in Java
Math class consists of methods that can perform mathematical operations and
can make long calculations a bit easier. Let us check the method provided in the
Math class.

Method Description

sin Returns the trigonometric value of the sine


of an angle.
Method Description

cos Returns the trigonometric value of the


cosine of an angle.

tan Returns the trigonometric value of the


tangent of an angle.

Returns the trigonometric value of the arc


asin
sine of an angle.

acos Returns the trigonometric value of the arc


cosine of an angle.

atan Returns the trigonometric value of the arc


tangent of an angle.

toRadians Convert value in degrees to value in radians

toDegrees Convert value in radians to value in degrees

exp Returns Euler’s number e raised to the


power of a double value

log Returns the natural logarithm (base e) of a


double value
log10 Returns the base 10 logarithms of a double
value

sqrt Returns the correct rounded positive square


root of a double value
Method Description

cbrt Returns the cube root of a double value

IEEEremainder Computes the remainder operation on two


arguments as instructed by the IEEE 754
standard.

Returns the smallest double value that is


ceil greater than or equal to the argument. It is a
fixed mathematical integer

floor Returns the smallest double value that is


less than or equal to the argument. It is a
fixed mathematical integer.

rint Returns the double value that is closest in


value to the argument and is equal to a
mathematical integer

atan2 Returns the angle theta from the conversion


of rectangular coordinates (x, y) to polar
coordinates (r, theta)

pow Returns(pow(a,b)) the value of ab.

round Returns the closest int to the argument, with


ties rounding to positive infinity
random Returns a double value with a positive sign,
in the range [0.0, 1.0).
Method Description

addExact Returns the sum of its arguments, throwing


an exception if the result overflows a value.

subtractExact Returns the difference of its arguments,


throwing an exception if the result
overflows a value.

multiplyExact Returns the product of the arguments,


throwing an exception if the result
overflows a value.

incrementExact Returns the argument value incremented by


1 and throws an exception if the value
overflows.

Returns the argument value decremented by


decrementExact 1 and throws an exception if the value
overflows.

negateExact Returns the negation of the argument and


throws an exception if the value overflows.

toIntExact Returns the value of the long argument and


throws an exception if the int overflows.
floorDiv Returns the largest (closest to positive
infinity) long value that is less than or equal
to the algebraic quotient

floorMod Returns the floor modulus of the arguments


Method Description

abs Return the absolute value

max Returns the maximum out of the two


arguments

min Returns the minimum out of the two


arguments

ulp Returns the size of an ulp of the argument.

signum Returns value 0,1 and -1 depending upon if


the argument is equal, greater, or less than
zero respectively.

sinh Returns the hyperbolic sine of the value.

cosh Returns the hyperbolic cosine of the value.

tanh Returns the hyperbolic sine of the value.

hypot Returns the hyperbolic tangent of the value.

expm1 Returns ex-1


log1p Returns the natural logarithm of the sum of
the argument and 1

copySign Returns the first value argument with the


sign of the second value argument
Method Description

getExponent Returns the unbiased exponent used in the


representation of a value

nextAfter Returns the floating-point number adjacent


to the first argument in the direction of the
second argument.

nextUp Returns the floating-point value adjacent to


d in the direction of positive infinity.

nextDown Returns the floating-point value adjacent to


d in the direction of negative infinity.

scalb Returns f × 2scaleFactor rounded as if


performed by a single correctly rounded
floating-point multiplied to a member of the
value set.
UGCSA117 : Object-Oriented Programming(OOP)
in Java (BCA 2nd Sem)

MODULE-2:
2.4 Character Class in Java
Java provides a wrapper class Character in [Link] package. An object of type
Character contains a single field, whose type is char. The Character class offers
several useful class (i.e., static) methods for manipulating characters. You can
create a Character object with the Character constructor.

2.4.1 Creating a Character object:


Character ch = new Character('a');
The above statement creates a Character object which contains ‘a’ of type char.
Only one constructor in the Character class expects an argument of char data type.
If we pass a primitive char into a method that expects an object, the compiler
automatically converts the char to a Character class object. This feature is called
Autoboxing and Unboxing.
Note: The Character class is immutable like String class i.e once it’s object is
created, it cannot be changed.
2.3.2 Methods in Character Class

The methods of Character class are as follows:


1. boolean isLetter(char ch): This method is used to determine whether the
specified char value(ch) is a letter or not. The method will return true if it is a
letter([A-Z],[a-z]), otherwise return false. In place of character, we can also pass
ASCII value as an argument as char to int is implicitly typecasted in Java.
Syntax:
boolean isLetter(char ch)
Parameters:
• ch – a primitive character
Returns: It returns true if ch is an alphabet, otherwise, returns false

2. boolean isDigit(char ch): This method is used to determine whether the


specified char value(ch) is a digit or not. Here also we can pass the ASCII value
as an argument. Syntax:
boolean isDigit(char ch)
Parameters:
• ch – a primitive character
Returns: It returns true if ch is a digit, otherwise, returns false

3. boolean isWhitespace(char ch): It determines whether the specified char


value(ch) is white space. Whitespace includes space, tab, or newline. Syntax:
boolean isWhitespace(char ch)
Parameters:
• ch – a primitive character
Returns: It returns true if ch is whitespace, otherwise, returns false.

4. boolean isUpperCase(char ch): It determines whether the specified char


value(ch) is uppercase or not. Syntax:
boolean isUpperCase(char ch)
Parameters:
• ch – a primitive character
Returns: It returns true if ch is upper case, otherwise, returns false.

5. boolean isLowerCase(char ch): It determines whether the specified char


value(ch) is lowercase or not. Syntax:
boolean isLowerCase(char ch)
Parameters:
• ch – a primitive character
Returns: It returns true if ch is lowercase, otherwise, returns false.
6. char toUpperCase(char ch): It returns the uppercase of the specified char
value(ch). If an ASCII value is passed, then the ASCII value of its uppercase will
be returned. Syntax:
char toUpperCase(char ch)
Parameters:
• ch – a primitive character
Returns: It returns the uppercase form of the specified char value.
7. char toLowerCase(char ch): It returns the lowercase of the specified char
value(ch). Syntax:
char toLowerCase(char ch)
Parameters:
• ch – a primitive character
Returns: It returns the lowercase form of the specified char value.
8. toString(char ch): It returns a String class object representing the specified
character value(ch) i.e a one-character string. Here we cannot pass ASCII value.
Syntax:
String toString(char ch)
Parameters:
• ch – a primitive character Returns: It returns a String object.
2.4.3 Java Strings
In Java, String is the type of objects that can store the sequence of characters
enclosed by double quotes and every character is stored in 16 bits i.e using UTF
16-bit encoding. A string acts the same as an array of characters. Java provides a
robust and flexible API for handling strings, allowing for various operations
such as concatenation, comparison, and manipulation.
Ways of Creating a Java String
There are two ways to create a string in Java:
• String Literal
• Using new Keyword Syntax:
<String_Type> <string_variable> = “<sequence_of_string>”;
1. String literal (Static Memory)
To make Java more memory efficient (because no new objects are created if it
exists already in the string constant pool).
2. Using new keyword (Heap Memory)
• String s = new String(“Welcome”);
• In such a case, JVM will create a new string object in normal (nonpool)
heap memory and the literal “Welcome” will be placed in the string
constant pool. The variable s will refer to the object in the heap (non-
pool)
In the given example only one object will be created. Firstly JVM will not find
any string object with the value “Welcome” in the string constant pool, so it will
create a new object. After that it will find the string with the value “Welcome” in
the pool, it will not create a new object but will return the reference to the same
instance.
UGCSA117 : Object-Oriented Programming(OOP)
in Java (BCA 2nd Sem)

MODULE-2:
2.5 Java Do While Loop
Java do-while loop is an Exit control loop. Unlike for or while loop, a do-while
check for the condition after executing the statements of the loop body.

Practical Application of Do While Loop


Suppose you are implementing a game where you show some options to the user,
press 1 to do this, press 2 to do this. etc and press ‘Q’ to quit the game. So here
you want to show the game menu to the user at least once, so you write the code
for the game menu inside the do-while loop.

Syntax :
do
{
// Loop Body
Update_expression
}

// Condition check
while (test_expression );
Note: The test_expression for the do -while loop must return a boolean
n value ,
else we would get a compile-time error.

2.5.1 Java while Loop

Java while loop is a control flow statement used to execute the block of
statements repeatedly until the given condition evaluates to false. Once the
condition becomes false, the line immediately after the loop in the program is
executed.

Syntax of while loop in Java


while (test_expression) {
// statements update_expression;
}
Note: If we do not provide the curly braces ‘{‘ and ‘}’ after while( condition ),
then by default while statement will consider the immediate one statement to be
inside its block.
Parts of Java While Loop
• Test Expression: This condition is evaluated before each iteration. If it
returns true, then the loop executes; otherwise, the loop exits. For
Example: i<=5

• Update Expression: After executing the loop body, this expression


increments/decrements the loop variable by some value. For Example:
i++

Execution of While Loop in Java


Now, let’s understand the execution flow of while loop with the below diagram:

1. Control enters the while loop.


2. The condition is tested.
3. If true, execute the body of the loop.
4. If false, exit the loop.
5. After executing the body, update the loop variable.
6. Repeat from step-2 until the condition is false.
3.1 Defining a Method, calling a Method, Passing Arguments by
Values
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
• Create a Method
A method must be declared within a class. It is defined with the name of the method,
followed by parentheses (). Java provides some pre-defined methods, such
as [Link](), but you can also create your own methods to perform certain
actions:
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}

Example Explained
• myMethod() is the name of the method
• static means that the method belongs to the Main class and not an object of the
Main class. You will learn more about objects and how to access methods
through objects later in this tutorial.
• void means that this method does not have a return value. You will learn more
about return values later in this chapter
• Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;
In the following example, myMethod() is used to print a text (the action), when it is
called:
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}

// Outputs "I just got executed!"

A method can also be called multiple times:


Example
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}

public static void main(String[] args) {


myMethod();
myMethod();
myMethod();
}
}

// I just got executed!


// I just got executed!
// I just got executed!
• Parameters and Arguments
Information can be passed to methods as a parameter. Parameters act as variables
inside the method.
Parameters are specified after the method name, inside the parentheses. You can add
as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as parameter.
When the method is called, we pass along a first name, which is used inside the method
to print the full name:
ExampleGet your own Java Server
public class Main {
static void myMethod(String fname) {
[Link](fname + " Refsnes");
}

public static void main(String[] args) {


myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

When a parameter is passed to the method, it is called an argument. So, from the
example above: fname is a parameter, while Liam, Jenny and Anja are arguments.
Multiple Parameters
You can have as many parameters as you like:
Example
public class Main {
static void myMethod(String fname, int age) {
[Link](fname + " is " + age);
}

public static void main(String[] args) {


myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}

// Liam is 5
// Jenny is 8
// Anja is 31

Note that when you are working with multiple parameters, the method call must have
the same number of arguments as there are parameters, and the arguments must be
passed in the same order.

A Method with If...Else


It is common to use if...else statements inside methods:
Example
public class Main {

// Create a checkAge() method with an integer variable called age


static void checkAge(int age) {
// If age is less than 18, print "access denied"
if (age < 18) {
[Link]("Access denied - You are not old enough!");

// If age is greater than, or equal to, 18, print "access granted"


} else {
[Link]("Access granted - You are old enough!");
}

public static void main(String[] args) {


checkAge(20); // Call the checkAge method and pass along an age of 20
}
}

// Outputs "Access granted - You are old enough!"


3.2 Modularizing Code, Overloading Methods, The Scope of Variables
1. Modularizing Code in Java

Modularization refers to breaking a large program into smaller, reusable, and


manageable parts (modules). In Java, modularization is achieved through:

• Methods – Reusable blocks of code that perform a specific task.


• Classes – Grouping related methods and variables.
• Packages – Organizing related classes into folders.
• Modules (Java 9+) – A higher level of organization that encapsulates classes
and packages.

Example:

// Class in a package (modularizing by functionality)


package [Link];

public class MathUtils {


public static int add(int a, int b) {
return a + b;
}
}

Then in another file:

import [Link];

public class Main {


public static void main(String[] args) {
[Link]([Link](5, 10));
}
}

Benefits:

• Improves code reusability.


• Enhances readability and maintainability.
• Supports team collaboration.

2. Method Overloading in Java

Method overloading allows multiple methods in the same class to have the same name
but different parameters (either in number, type, or both).
Example:

class OverloadExample {
// Method with two int parameters
int add(int a, int b) {
return a + b;
}

// Method with three int parameters (different number of parameters)


int add(int a, int b, int c) {
return a + b + c;
}

// Method with double parameters (different parameter types)


double add(double a, double b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
OverloadExample obj = new OverloadExample();
[Link]([Link](5, 10)); // Calls int add(int, int)
[Link]([Link](5, 10, 15)); // Calls int add(int, int, int)
[Link]([Link](5.5, 10.5)); // Calls double add(double, double)
}
}

Key Points:

• Overloaded methods must have different method signatures (parameter list).


• Return type does not affect method overloading.
• Improves code readability and reusability.

3. Scope of Variables in Java

Variable scope determines where a variable can be accessed in a program. Java has
different types of variable scope:

1. Local Scope

• A variable declared inside a method or block.


• Accessible only within that method or block.
• Not accessible outside.
public class ScopeExample {
public void show() {
int localVar = 10; // Local variable
[Link](localVar);
}
// [Link](localVar); // Error: localVar not accessible here
}

2. Instance Scope

• Declared inside a class but outside any method.


• Belongs to an instance of the class.
• Accessible throughout the class via an instance.

class Person {
String name; // Instance variable (different for each object)

void setName(String n) {
name = n;
}

void showName() {
[Link](name);
}
}

public class Main {


public static void main(String[] args) {
Person p1 = new Person();
[Link]("Alice");
[Link](); // Alice

Person p2 = new Person();


[Link]("Bob");
[Link](); // Bob
}
}

3. Static (Class) Scope

• Declared with static keyword inside a class.


• Shared across all instances of the class.

class Counter {
static int count = 0; // Static variable (shared across all objects)

Counter() {
count++;
}

void showCount() {
[Link]("Count: " + count);
}
}

public class Main {


public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

[Link](); // Count: 3 (Shared variable)


}
}

4. Block Scope

• Declared inside a loop or block ({}).


• Exists only within the block.

public class LoopScope {


public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
[Link](i); // i is accessible here
}
// [Link](i); // Error: i is out of scope
}
}

Summary Table

Scope Type Declared In Accessible In Example


Only inside the
Local Scope Inside a method/block int x = 10; inside main()
method/block
Instance Inside a class (no String name; inside class
Accessible via object
Scope static) Person
Inside a class (static Shared across all static int count; inside
Static Scope
keyword) objects class Counter
Inside {} (loops, if
Block Scope Only inside the block for (int i=0; i<5; i++)
statements)
3.3 Method Abstraction and Stepwise Refinement. Array Basics,
Copying Arrays.

1. Method Abstraction and Stepwise Refinement

Method Abstraction

• Method abstraction means hiding the implementation details and exposing only
the functionality.
• In Java, this is achieved using methods: the caller only needs to know the
method signature (name, parameters, return type) and not how it works
internally.
• This improves code readability, reusability, and maintainability.

Example of Method Abstraction

class Calculator {
// Abstracting the logic inside a method
public int add(int a, int b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
int sum = [Link](5, 10); // The user doesn't need to know how add() works
[Link](sum);
}
}

• Here, add(int a, int b) abstracts the logic of addition.

Stepwise Refinement

• Stepwise refinement is a top-down approach where a complex problem is


broken into smaller, manageable steps.
• Each step is refined further until it becomes a simple, implementable method.

Example of Stepwise Refinement

Let's say we want to calculate the area of a rectangle, but we refine it into smaller steps:

1. Get user input.


2. Calculate area.
3. Display the result.

import [Link];

class Rectangle {
// Step 2: Calculate the area
public int calculateArea(int length, int width) {
return length * width;
}
}

public class Main {


// Step 1: Get user input
public static int getInput(String prompt) {
Scanner sc = new Scanner([Link]);
[Link](prompt);
return [Link]();
}

// Step 3: Display result


public static void displayResult(int area) {
[Link]("The area of the rectangle is: " + area);
}

public static void main(String[] args) {


int length = getInput("Enter length: ");
int width = getInput("Enter width: ");

Rectangle rect = new Rectangle();


int area = [Link](length, width);

displayResult(area);
}
}

Advantages of Stepwise Refinement:

• Breaks down complex problems into smaller, easier-to-handle steps.


• Each method has a single responsibility.
• Improves code readability and maintainability.

2. Array Basics in Java


An array in Java is a collection of elements of the same data type stored in contiguous
memory.

Declaring and Initializing an Array

// Declaration
int[] numbers;

// Initialization
numbers = new int[5]; // Array of size 5

// Declaration + Initialization
int[] values = {10, 20, 30, 40, 50}; // Directly assign values

Accessing and Modifying Elements

int[] arr = new int[3];

arr[0] = 5; // Assigning values


arr[1] = 10;
arr[2] = 15;

[Link](arr[1]); // Output: 10

Iterating Over an Array

int[] nums = {2, 4, 6, 8, 10};

// Using a for loop


for (int i = 0; i < [Link]; i++) {
[Link](nums[i] + " ");
}
// Output: 2 4 6 8 10

// Using an enhanced for loop


for (int num : nums) {
[Link](num + " ");
}

Key Array Properties

Property Description
length Returns the number of elements in the array
Zero-based index Arrays in Java start at index 0
Fixed size Once created, the array size cannot change
3. Copying Arrays in Java

There are different ways to copy an array in Java:

1. Using a Loop (Manual Copy)

int[] original = {1, 2, 3, 4, 5};


int[] copy = new int[[Link]];

for (int i = 0; i < [Link]; i++) {


copy[i] = original[i];
}

// Verifying the copy


[Link]([Link](copy)); // Output: [1, 2, 3, 4, 5]

2. Using [Link]()

• More efficient than a loop.

int[] original = {1, 2, 3, 4, 5};


int[] copy = new int[[Link]];

[Link](original, 0, copy, 0, [Link]);

[Link]([Link](copy)); // Output: [1, 2, 3, 4, 5]

• Parameters:
1. Source array
2. Start index in the source array
3. Destination array
4. Start index in the destination array
5. Number of elements to copy

3. Using [Link]()

• Copies and resizes the array.

import [Link];

int[] original = {1, 2, 3, 4, 5};


int[] copy = [Link](original, [Link]);

[Link]([Link](copy)); // Output: [1, 2, 3, 4, 5]


4. Using clone()

• Creates a shallow copy of the array.

int[] original = {1, 2, 3, 4, 5};


int[] copy = [Link]();

[Link]([Link](copy)); // Output: [1, 2, 3, 4, 5]

• Shallow copy means that for non-primitive types (objects), only references are
copied, not actual objects.

5. Using [Link]()

• Copies a portion of an array.

import [Link];

int[] original = {1, 2, 3, 4, 5};


int[] copy = [Link](original, 1, 4); // Copies elements from index 1 to 3

[Link]([Link](copy)); // Output: [2, 3, 4]

Summary Table

Concept Explanation Example


Method Hiding implementation details public int add(int a, int b) { return a +
Abstraction and exposing only functionality b; }
Stepwise Breaking a complex problem into Methods for input, calculation, and
Refinement smaller methods display
A collection of elements of the
Array Basics int[] arr = {1, 2, 3};
same type
Copying [Link](original, 0, copy,
Creating a duplicate of an array
Arrays 0, [Link]);
3.4 Passing Arrays to Methods, Returning an Array from a Method.

1. Passing Arrays to Methods

• In Java, arrays are passed by reference to methods. This means any


modifications made to the array inside the method will reflect outside the method
as well.

Example: Passing an Array to a Method

class ArrayExample {
// Method that modifies the array
public static void modifyArray(int[] arr) {
for (int i = 0; i < [Link]; i++) {
arr[i] *= 2; // Doubling each element
}
}

public static void main(String[] args) {


int[] numbers = {1, 2, 3, 4, 5};

[Link]("Before modification: " + [Link](numbers));

modifyArray(numbers); // Passing array to the method

[Link]("After modification: " + [Link](numbers));


}
}

Output:

Before modification: [1, 2, 3, 4, 5]


After modification: [2, 4, 6, 8, 10]

Key Point: Since arrays are passed by reference, changes made in modifyArray()
affect the original array.

2. Returning an Array from a Method

• A method can return an array, just like it returns any other data type.

Example: Returning an Array from a Method

class ArrayReturnExample {
// Method that generates an array of even numbers
public static int[] generateEvenNumbers(int size) {
int[] evens = new int[size];
for (int i = 0; i < size; i++) {
evens[i] = (i + 1) * 2; // Filling with even numbers
}
return evens; // Returning the array
}

public static void main(String[] args) {


int[] evenNumbers = generateEvenNumbers(5); // Calling the method

[Link]("Generated Array: " + [Link](evenNumbers));


}
}

Output:

Generated Array: [2, 4, 6, 8, 10]

Key Point: The method generateEvenNumbers() creates an array, fills it with


values, and then returns it.

3. Passing and Returning Multidimensional Arrays

Java also allows passing and returning 2D arrays.

Example: Passing and Returning a 2D Array

class MatrixOperations {
// Method to multiply a 2D matrix by a scalar and return the result
public static int[][] multiplyMatrix(int[][] matrix, int scalar) {
int rows = [Link];
int cols = matrix[0].length;
int[][] result = new int[rows][cols];

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
result[i][j] = matrix[i][j] * scalar;
}
}
return result; // Returning the modified matrix
}

public static void main(String[] args) {


int[][] matrix = {
{1, 2},
{3, 4}
};

int[][] modifiedMatrix = multiplyMatrix(matrix, 2); // Passing 2D array

// Printing the modified matrix


for (int[] row : modifiedMatrix) {
[Link]([Link](row));
}
}
}

Output:

[2, 4]

[6, 8]

Key Point: Just like 1D arrays, 2D arrays are also passed by reference, and we
can return them from methods.

Summary Table

Concept Explanation Example


Arrays are passed by modifyArray(int[] arr) modifies the
Passing an Array
reference original array
Returning an A method can return an int[] generateNumbers() returns an
Array array array
Passing 2D
Works just like 1D arrays multiplyMatrix(int[][] matrix, int scalar)
Arrays
Returning 2D A method can return a 2D
return result;
Arrays array
3.5 Searching Arrays, Sorting Arrays, Two-Dimensional Array Basics,
Multi-dimensional Arrays.

1. Searching Arrays in Java

Searching means finding an element's index in an array. The two common search
techniques are:

• Linear Search (for unsorted arrays)


• Binary Search (for sorted arrays)

1.1 Linear Search (Unsorted Array)

• Time Complexity: O(n)


• Searches for an element one by one.

class LinearSearchExample {
public static int linearSearch(int[] arr, int key) {
for (int i = 0; i < [Link]; i++) {
if (arr[i] == key) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}

public static void main(String[] args) {


int[] numbers = {5, 3, 8, 2, 7, 6};
int key = 7;

int index = linearSearch(numbers, key);


[Link](index != -1 ? "Found at index: " + index : "Not found");
}
}

Output:

Found at index: 4

1.2 Binary Search (Sorted Array)

• Time Complexity: O(log n)


• Works only on sorted arrays by dividing the search range in half.

import [Link];
class BinarySearchExample {
public static int binarySearch(int[] arr, int key) {
int left = 0, right = [Link] - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
left = mid + 1;
else
right = mid - 1;
}
return -1; // Not found
}

public static void main(String[] args) {


int[] numbers = {2, 3, 5, 6, 7, 8}; // Sorted array
int key = 7;

int index = binarySearch(numbers, key);


[Link](index != -1 ? "Found at index: " + index : "Not found");
}
}

Output:

Found at index: 4

Java Built-in [Link]() Method:

import [Link];

public class Main {


public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10};
int key = 6;
int index = [Link](arr, key);
[Link](index >= 0 ? "Found at index: " + index : "Not found");
}
}

2. Sorting Arrays in Java

Sorting arranges elements in ascending or descending order.


2.1 Bubble Sort (Basic Sorting Algorithm)

• Time Complexity: O(n²)

class BubbleSortExample {
public static void bubbleSort(int[] arr) {
int n = [Link];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

public static void main(String[] args) {


int[] numbers = {5, 2, 9, 1, 5, 6};
bubbleSort(numbers);
[Link]("Sorted Array: " + [Link](numbers));
}
}

2.2 Java Built-in Sorting ([Link]())

• Uses Dual-Pivot QuickSort for primitives (int[]) → O(n log n)


• Uses MergeSort for Objects (Integer[], String[]).

import [Link];

public class Main {


public static void main(String[] args) {
int[] arr = {5, 3, 8, 1, 2};
[Link](arr);
[Link]("Sorted Array: " + [Link](arr));
}
}

Output:

Sorted Array: [1, 2, 3, 5, 8]


3. Two-Dimensional Array Basics

A 2D array is an array of arrays, forming a matrix-like structure.

3.1 Declaring and Initializing a 2D Array

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

3.2 Accessing Elements

[Link](matrix[1][2]); // Output: 6

3.3 Looping Through a 2D Array

public class Main {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

for (int i = 0; i < [Link]; i++) {


for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}

Output:

123
456
789

4. Multi-Dimensional Arrays in Java

A multi-dimensional array is an extension of a 2D array, meaning arrays inside


arrays.
4.1 3D Array Example

int[][][] threeDArray = {
{
{1, 2}, {3, 4}
},
{
{5, 6}, {7, 8}
}
};

4.2 Accessing Elements in a 3D Array

[Link](threeDArray[1][0][1]); // Output: 6

4.3 Looping Through a Multi-Dimensional Array

public class MultiDimArray {


public static void main(String[] args) {
int[][][] arr = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};

for (int i = 0; i < [Link]; i++) {


for (int j = 0; j < arr[i].length; j++) {
for (int k = 0; k < arr[i][j].length; k++) {
[Link](arr[i][j][k] + " ");
}
[Link]();
}
[Link]();
}
}
}

Output:

12
34

56
78
Summary Table

Concept Explanation Example


Linear Search Searches one by one for (i=0; i<[Link]; i++)
Binary Search Works on sorted arrays [Link](arr, key);
Bubble Sort Basic sorting algorithm Nested loops for swapping
[Link]() Efficient built-in sorting [Link](arr);
2D Arrays Arrays of arrays int[][] matrix = new int[3][3];
Multi-D Arrays More than two dimensions int[][][] threeDArray = new int[2][2][2];
3.6 Recursion, writing recursive codes in Java

Recursion in Java

Recursion is a programming technique where a method calls itself to solve smaller


instances of a problem until it reaches a base case. It is commonly used for problems
that can be broken down into smaller subproblems, such as factorial computation,
Fibonacci series, and tree traversals.

1. Structure of a Recursive Method

Every recursive function should have:

1. Base Case → The condition that stops recursion.


2. Recursive Case → The function calls itself with a smaller problem.

java
CopyEdit
void recursiveMethod() {
if (base_condition) {
return; // Base Case (Stops recursion)
} else {
recursiveMethod(); // Recursive Case
}
}

2. Example 1: Factorial Using Recursion

Factorial Formula:

n!=n×(n−1)!n! = n \times (n-1)!n!=n×(n−1)!

Base Case: 1!=11! = 11!=1

Recursive Java Code for Factorial

class FactorialExample {
public static int factorial(int n) {
if (n == 0) { // Base Case
return 1;
}
return n * factorial(n - 1); // Recursive Call
}
public static void main(String[] args) {
int num = 5;
[Link]("Factorial of " + num + " is: " + factorial(num));
}
}

Output:

Factorial of 5 is: 120

3. Example 2: Fibonacci Series Using Recursion

Fibonacci Formula:

F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)F(n)=F(n−1)+F(n−2)

Base Cases:

• F(0)=0F(0) = 0F(0)=0
• F(1)=1F(1) = 1F(1)=1

Recursive Java Code for Fibonacci

class FibonacciExample {
public static int fibonacci(int n) {
if (n == 0) return 0; // Base Case 1
if (n == 1) return 1; // Base Case 2

return fibonacci(n - 1) + fibonacci(n - 2); // Recursive Call


}

public static void main(String[] args) {


int num = 7;
[Link]("Fibonacci of " + num + " is: " + fibonacci(num));
}
}

Output:

Fibonacci of 7 is: 13

4. Example 3: Sum of Digits Using Recursion

Given a number, recursively sum its digits.


Example:
Input: 1234
Output: 1 + 2 + 3 + 4 = 10

Recursive Java Code

class SumOfDigitsExample {
public static int sumOfDigits(int n) {
if (n == 0) return 0; // Base Case
return (n % 10) + sumOfDigits(n / 10); // Recursive Call
}

public static void main(String[] args) {


int num = 1234;
[Link]("Sum of digits: " + sumOfDigits(num));
}
}

Output:

Sum of digits: 10

5. Example 4: Reverse a String Using Recursion

Example:
Input: "hello"
Output: "olleh"

Recursive Java Code

class ReverseStringExample {
public static String reverseString(String str) {
if ([Link]()) return str; // Base Case
return reverseString([Link](1)) + [Link](0); // Recursive Call
}

public static void main(String[] args) {


String str = "hello";
[Link]("Reversed: " + reverseString(str));
}
}

Output:

Reversed: olleh
6. Example 5: Finding GCD (Greatest Common Divisor) Using Recursion

Euclidean Algorithm:

GCD(a,b)=GCD(b,amod b)GCD(a, b) = GCD(b, a \mod b)GCD(a,b)=GCD(b,amodb)

Base Case: If b==0b == 0b==0, return aaa.

Recursive Java Code

class GCDExample {
public static int gcd(int a, int b) {
if (b == 0) return a; // Base Case
return gcd(b, a % b); // Recursive Call
}

public static void main(String[] args) {


[Link]("GCD of 48 and 18: " + gcd(48, 18));
}
}

Output:

GCD of 48 and 18: 6

7. Example 6: Tower of Hanoi (Classic Recursion Problem)

Problem: Move n disks from Source (A) to Target (C) using Auxiliary (B).
Base Case: If only 1 disk, move it directly.
Recursive Case:

1. Move n-1 disks from A → B.


2. Move the nth disk from A → C.
3. Move n-1 disks from B → C.

Recursive Java Code

class TowerOfHanoi {
public static void solveHanoi(int n, char source, char auxiliary, char target) {
if (n == 1) {
[Link]("Move disk 1 from " + source + " to " + target);
return;
}
solveHanoi(n - 1, source, target, auxiliary);
[Link]("Move disk " + n + " from " + source + " to " + target);
solveHanoi(n - 1, auxiliary, source, target);
}
public static void main(String[] args) {
int disks = 3;
solveHanoi(disks, 'A', 'B', 'C');
}
}

Output:

Move disk 1 from A to C


Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

8. Summary Table

Problem Base Case Recursive Call

Factorial n == 0 → return 1 n * factorial(n-1)

Fibonacci `n == 0

Sum of Digits n == 0 → return 0 (n%10) + sumOfDigits(n/10)

Reverse String [Link]() → return str reverse([Link](1)) + [Link](0)

GCD b == 0 → return a gcd(b, a % b)

Tower of Hanoi n == 1 → Move disk Move n-1 disks twice


4.1 Class Abstraction and Encapsulation

1. Abstraction in Java

Abstraction is a principle of hiding implementation details and showing only the


essential features of an object. It helps in reducing complexity and increasing
reusability.

Achieved using:
Abstract classes (abstract keyword)
Interfaces (interface keyword)

Example: Abstraction using an Abstract Class

java
CopyEdit
abstract class Vehicle {
abstract void start(); // Abstract method (no body)
}

class Car extends Vehicle {


@Override
void start() {
[Link]("Car starts with a key");
}
}

class Bike extends Vehicle {


@Override
void start() {
[Link]("Bike starts with a button");
}
}

public class Main {


public static void main(String[] args) {
Vehicle myCar = new Car();
[Link](); // Output: Car starts with a key

Vehicle myBike = new Bike();


[Link](); // Output: Bike starts with a button
}
}
Why use Abstraction?

• Hides unnecessary implementation details


• Reduces code duplication
• Encapsulates behaviors in a structured way

2. Encapsulation in Java

Encapsulation is the process of wrapping data (variables) and methods within a class
and restricting direct access to them. It helps in data hiding and data protection.

Achieved using:
Declaring variables as private
Providing public getter and setter methods

Example: Encapsulation in Java

java
CopyEdit
class Person {
private String name; // Private variable

// Getter method
public String getName() {
return name;
}

// Setter method
public void setName(String newName) {
[Link] = newName;
}
}

public class Main {


public static void main(String[] args) {
Person p = new Person();
[Link]("Alice"); // Setting value using setter
[Link]([Link]()); // Getting value using getter
}
}

Why use Encapsulation?

• Protects data from unauthorized access


• Provides controlled access via getters and setters
• Improves code maintainability
3. Abstraction vs. Encapsulation

Feature Abstraction Encapsulation


Purpose Hides implementation details Hides data (variables)
How? Using abstract classes & interfaces Using private variables & getters/setters
Focus What an object does How data is controlled
abstract class Vehicle with start() private String name with getName() and
Example
method setName()

4. Combining Abstraction and Encapsulation

You can use both concepts together to create robust and secure applications.

Example: Combining Abstraction and Encapsulation

java
CopyEdit
abstract class BankAccount {
private double balance; // Encapsulated variable

public BankAccount(double initialBalance) {


[Link] = initialBalance;
}

public double getBalance() {


return balance;
}

public void deposit(double amount) {


balance += amount;
}

abstract void withdraw(double amount); // Abstract method


}

class SavingsAccount extends BankAccount {


public SavingsAccount(double initialBalance) {
super(initialBalance);
}

@Override
void withdraw(double amount) {
if (amount <= getBalance()) {
deposit(-amount);
[Link]("Withdrawal successful. New balance: " + getBalance());
} else {
[Link]("Insufficient balance.");
}
}
}

public class Main {


public static void main(String[] args) {
BankAccount account = new SavingsAccount(1000);
[Link](500);
[Link](700);
}
}

Output:

sql
CopyEdit
Withdrawal successful. New balance: 500.0
Insufficient balance.
4.2 Thinking in Objects, Processing Primitive Data Type Values as
Objects, Types, The Big Integer, and Big Decimal Classes.

1. Thinking in Objects

Object-Oriented Programming (OOP) is a fundamental approach in Java, focusing on


objects instead of procedural logic.
Core OOP Concepts:
✔ Encapsulation – Hiding data using access modifiers (private, public, etc.)
✔ Abstraction – Hiding implementation details using abstract classes & interfaces
✔ Inheritance – Allowing new classes to reuse properties and methods of existing
classes
✔ Polymorphism – Enabling methods to behave differently based on the object

Example: Thinking in Objects

java
CopyEdit
class Car {
String brand;
int speed;

Car(String brand, int speed) {


[Link] = brand;
[Link] = speed;
}

void accelerate() {
speed += 10;
[Link](brand + " is now running at " + speed + " km/h");
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car("Toyota", 50);
[Link](); // Output: Toyota is now running at 60 km/h
}
}
Why think in objects?

• Helps in modular design


• Enhances code reusability
• Makes software easier to maintain and extend

2. Processing Primitive Data Type Values as Objects

Java provides wrapper classes to treat primitive data types as objects.


Why use Wrapper Classes?
✔ Allow storing primitives in collections (e.g., ArrayList<Integer>)
✔ Provide utility methods (e.g., [Link]())
✔ Enable autoboxing (automatic conversion between primitive and wrapper types)

Wrapper Classes in Java

Primitive Type Wrapper Class


Int Integer
Double Double
Char Character
Boolean Boolean

Example: Autoboxing & Unboxing

java
CopyEdit
public class WrapperExample {
public static void main(String[] args) {
Integer num = 10; // Autoboxing (int → Integer)
int primitiveNum = num; // Unboxing (Integer → int)
[Link]("Integer object: " + num);
[Link]("Primitive int: " + primitiveNum);
}
}

Output:

pgsql
CopyEdit
Integer object: 10
Primitive int: 10
3. Types in Java

Java has two main categories of data types:

A) Primitive Data Types

These are basic types stored directly in memory.


byte, short, int, long (for integers)
float, double (for decimal values)
char (for characters)
boolean (for true/false values)

B) Reference Data Types

These store addresses of objects in memory.


String, Array, Class, Interface, etc.

4. The BigInteger Class

Since int and long have limited range, BigInteger is used for large integer calculations.
✔ Found in [Link]
✔ Supports arbitrary precision
✔ Provides methods for arithmetic operations, GCD, primality testing, etc.

Example: Using BigInteger

java
CopyEdit
import [Link];

public class BigIntegerExample {


public static void main(String[] args) {
BigInteger num1 = new BigInteger("123456789123456789");
BigInteger num2 = new BigInteger("987654321987654321");

// Perform arithmetic operations


BigInteger sum = [Link](num2);
BigInteger product = [Link](num2);

[Link]("Sum: " + sum);


[Link]("Product: " + product);
}
}

Output:
makefile
CopyEdit
Sum: 1111111111111111110
Product: 121932631356500531347203169112635269

5. The BigDecimal Class

Since double and float cannot precisely store decimal values, BigDecimal is used for
high-precision decimal calculations.
✔ Found in [Link]
✔ Useful for financial applications (avoids rounding errors)
✔ Supports arithmetic operations, rounding modes, and scale setting

Example: Using BigDecimal

java
CopyEdit
import [Link];

public class BigDecimalExample {


public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("10.25");
BigDecimal num2 = new BigDecimal("3.14");

// Perform arithmetic operations


BigDecimal sum = [Link](num2);
BigDecimal division = [Link](num2, 2, BigDecimal.ROUND_HALF_UP);

[Link]("Sum: " + sum);


[Link]("Division (Rounded to 2 decimals): " + division);
}
}

Output:

vbnet
CopyEdit
Sum: 13.39
Division (Rounded to 2 decimals): 3.27
4.3 The String Class, The String Builder and String Buffer Class,
Super-Class and Sub-Classes.

1. The String Class

• In Java, String is an immutable sequence of characters.


• Defined in [Link] package.
• Once created, a String object cannot be changed (immutable).

Creating Strings

java
CopyEdit
public class StringExample {
public static void main(String[] args) {
String s1 = "Hello"; // String literal
String s2 = new String("World"); // Using new keyword
[Link](s1 + " " + s2); // Output: Hello World
}
}

Important String Methods

Method Description
length() Returns length of string
charAt(index) Returns character at the given index
concat(str) Joins two strings
toUpperCase() Converts to uppercase
toLowerCase() Converts to lowercase
substring(start, end) Extracts a substring
equals(str) Checks if two strings are equal
compareTo(str) Compares two strings lexicographically
trim() Removes leading and trailing spaces

Example: String Methods

java
CopyEdit
public class StringMethods {
public static void main(String[] args) {
String str = " Java Programming ";

[Link]("Length: " + [Link]()); // 18


[Link]("Trimmed: '" + [Link]() + "'"); // "Java Programming"
[Link]("Uppercase: " + [Link]()); // " JAVA PROGRAMMING
"
[Link]("Substring: " + [Link](5, 14)); // "Programmi"
[Link]("Character at index 3: " + [Link](3)); // 'a'
}
}

Key Takeaways:

• String is immutable (cannot be modified after creation).


• Methods like toUpperCase(), concat() create a new string instead of modifying
the existing one.

2. StringBuilder and StringBuffer Classes

Since String is immutable, modifications create new objects in memory, which can be
inefficient.
To solve this, Java provides mutable alternatives:

• StringBuilder (Not thread-safe but faster)


• StringBuffer (Thread-safe but slower)

StringBuilder Class

✔ Faster and more efficient than StringBuffer (not synchronized).


✔ Used when only one thread is accessing the string.

Example: Using StringBuilder

java
CopyEdit
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // Modifies the same object
[Link](sb); // Output: Hello World
}
}

StringBuffer Class

✔ Thread-safe (synchronized), but slower than StringBuilder.


✔ Used in multi-threaded environments.

Example: Using StringBuffer


java
CopyEdit
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
[Link](" World"); // Modifies the same object
[Link](sb); // Output: Hello World
}
}

Comparison: String vs. StringBuilder vs. StringBuffer

Feature String StringBuilder StringBuffer


Mutable? No (Immutable) Yes Yes
Slow (creates new Slower (due to
Performance Fast
object) synchronization)
Thread
Not required Not thread-safe Thread-safe
Safety
If the string won’t When performance is When multi-threading is
Usage
change important needed

3. Super-Class and Sub-Classes in Java

Super-Class (Parent Class)

A super-class (or base class) is a generalized class that other classes inherit from.
It contains common attributes and methods that can be reused in sub-classes.

Sub-Class (Child Class)

A sub-class (or derived class) inherits properties and behaviors from a super-class
using the extends keyword.

Key Features of Inheritance:


✔ Code Reusability – Common functionality is defined in the super-class.
✔ Method Overriding – A sub-class can modify the inherited method.
✔ Super Keyword – Used to call the super-class constructor or methods.

Example: Super-Class and Sub-Class

java
CopyEdit
// Super-Class (Parent)
class Animal {
String name;
void eat() {
[Link](name + " is eating");
}
}

// Sub-Class (Child)
class Dog extends Animal {
void bark() {
[Link](name + " is barking");
}
}

public class InheritanceExample {


public static void main(String[] args) {
Dog dog = new Dog();
[Link] = "Buddy";
[Link](); // Inherited from Animal class
[Link](); // Defined in Dog class
}
}

Output:

csharp
CopyEdit
Buddy is eating
Buddy is barking

Super Keyword

The super keyword is used to:

• Call the super-class constructor


• Access super-class methods
• Access super-class fields

Example: Using super Keyword

java
CopyEdit
// Super-Class
class Vehicle {
int speed = 50;

void display() {
[Link]("Vehicle is moving at speed: " + speed);
}
}

// Sub-Class
class Car extends Vehicle {
int speed = 100; // Overriding speed variable

void display() {
[Link](); // Calls super-class method
[Link]("Car is moving at speed: " + speed);
}
}

public class SuperExample {


public static void main(String[] args) {
Car c = new Car();
[Link]();
}
}

Output:

csharp
CopyEdit
Vehicle is moving at speed: 50
Car is moving at speed: 100

Types of Inheritance in Java

Type Description Example


One class inherits from
Single Inheritance class Dog extends Animal
another
A sub-class inherits from
Multilevel Inheritance class Puppy extends Dog
another sub-class
Multiple classes inherit from a class Cat extends Animal, class
Hierarchical Inheritance
single super-class Dog extends Animal
Multiple Inheritance A class implements multiple class Bird implements Flyable,
(via interfaces) interfaces Singable
4.4 Using the super Keyword, Overriding Methods, Overriding vs.
Overloading. The Object Class and String() Method.

1. Using the super Keyword

The super keyword in Java is used to refer to the immediate parent class (superclass).

Uses of super

• Access Parent Class Methods


• Access Parent Class Fields
• Call Parent Class Constructor

Example 1: Using super to Call Superclass Methods

java
CopyEdit
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


void makeSound() {
[Link](); // Calls the method from Animal class
[Link]("Dog barks");
}
}

public class SuperMethodExample {


public static void main(String[] args) {
Dog dog = new Dog();
[Link]();
}
}

Output:

css
CopyEdit
Animal makes a sound
Dog barks
Example 2: Using super to Access Superclass Fields

java
CopyEdit
class Vehicle {
int speed = 50;
}

class Car extends Vehicle {


int speed = 100;

void displaySpeed() {
[Link]("Car speed: " + speed);
[Link]("Vehicle speed: " + [Link]); // Accesses the speed
variable from Vehicle
}
}

public class SuperVariableExample {


public static void main(String[] args) {
Car car = new Car();
[Link]();
}
}

Output:

yaml
CopyEdit
Car speed: 100
Vehicle speed: 50

Example 3: Using super to Call Superclass Constructor

java
CopyEdit
class Animal {
Animal() {
[Link]("Animal Constructor");
}
}

class Dog extends Animal {


Dog() {
super(); // Calls the constructor of Animal class
[Link]("Dog Constructor");
}
}

public class SuperConstructorExample {


public static void main(String[] args) {
Dog dog = new Dog();
}
}

Output:

nginx
CopyEdit
Animal Constructor
Dog Constructor

2. Overriding Methods in Java

Method overriding allows a subclass to provide a specific implementation of a


method that is already defined in its superclass.

Rules for Method Overriding

✔ The method must have the same name and same parameters as the parent class
method.
✔ The method must be in a subclass (inheritance is required).
✔ Access level cannot be more restrictive (e.g., if the parent method is public, the
overridden method cannot be private).
✔ The method cannot be overridden if it is static, final, or private.

Example: Overriding a Method

java
CopyEdit
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
}
}

class Cat extends Animal {


@Override
void makeSound() { // Overriding the method
[Link]("Cat meows");
}
}

public class OverridingExample {


public static void main(String[] args) {
Cat cat = new Cat();
[Link]();
}
}

Output:

nginx
CopyEdit
Cat meows

Explanation: The makeSound() method in Cat overrides the method in Animal.

3. Overriding vs. Overloading

Overriding: Redefining a method in a subclass with the same signature.


Overloading: Defining multiple methods with the same name but different
parameters in the same class.

Feature Overriding Overloading

Method with the same name but


Definition Method redefinition in a subclass
different parameters

Where it
Between superclass & subclass Within the same class
occurs

Parameters Must be the same Must be different

Must be the same or a covariant


Return Type Can be different
type

Access Cannot be more restrictive than


No restriction
Modifier the parent class

Example: Overriding vs. Overloading

java
CopyEdit
class MathOperations {
// Method Overloading
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
class AdvancedMath extends MathOperations {
// Method Overriding
@Override
int add(int a, int b) { return a + b + 10; }
}

public class OverridingVsOverloading {


public static void main(String[] args) {
MathOperations math = new MathOperations();
[Link]("Overloading: " + [Link](5, 10)); // Calls overloaded method

AdvancedMath advMath = new AdvancedMath();


[Link]("Overriding: " + [Link](5, 10)); // Calls overridden method
}
}

Output:

makefile
CopyEdit
Overloading: 15
Overriding: 25

4. The Object Class and toString() Method

Every class in Java implicitly extends the Object class, which is the parent of all classes.

Important Methods of the Object Class

Method Description

toString() Returns a string representation of an object

equals(Object obj) Checks if two objects are equal

hashCode() Returns the hash code of an object

getClass() Returns the runtime class of the object

clone() Creates a copy of the object (if the class implements Cloneable)

The toString() Method


✔ By default, toString() returns the class name + hash code.
✔ It is often overridden to return meaningful information about an object.

Example: Default toString() Behavior

java
CopyEdit
class Person {
String name;

Person(String name) {
[Link] = name;
}
}

public class ToStringExample {


public static void main(String[] args) {
Person p = new Person("Alice");
[Link](p); // Calls toString() method
}
}

Output:

less
CopyEdit
Person@15db9742 (Default output: className@hashCode)

Example: Overriding toString()

java
CopyEdit
class Person {
String name;
int age;

Person(String name, int age) {


[Link] = name;
[Link] = age;
}

@Override
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
}
public class OverriddenToString {
public static void main(String[] args) {
Person p = new Person("Alice", 25);
[Link](p); // Calls overridden toString()
}
}

Output:

css
CopyEdit
Person[name=Alice, age=25]

Explanation: Overriding toString() makes objects print in a readable format instead of


showing the default class@hashCode output.
4.5 Polymorphism, Dynamic Binding, Casting Objects and the
instance of Operator, The Object’s equals Method, The Array List
Class.

1. Polymorphism in Java

Polymorphism allows one interface to be used for multiple implementations.


It enables a single method, operator, or object to behave differently in different contexts.

Types of Polymorphism

• Compile-time Polymorphism (Method Overloading)


• Runtime Polymorphism (Method Overriding)

Example of Compile-time Polymorphism (Method Overloading)

java
CopyEdit
class MathOperations {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}

public class OverloadingExample {


public static void main(String[] args) {
MathOperations math = new MathOperations();
[Link]("Addition of integers: " + [Link](5, 10));
[Link]("Addition of doubles: " + [Link](5.5, 2.5));
}
}

Output:

yaml
CopyEdit
Addition of integers: 15
Addition of doubles: 8.0

Example of Runtime Polymorphism (Method Overriding)


java
CopyEdit
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
[Link]("Dog barks");
}
}

public class OverridingExample {


public static void main(String[] args) {
Animal myPet = new Dog(); // Upcasting
[Link](); // Calls Dog's makeSound() due to polymorphism
}
}

Output:

nginx
CopyEdit
Dog barks

✔ Explanation: Even though myPet is of type Animal, the overridden method in Dog is
called due to dynamic method dispatch.

2. Dynamic Binding in Java

Dynamic binding (late binding) means that method calls are resolved at runtime, not
compile-time.
It is used in method overriding to determine which method to call based on the
actual object type.

Example of Dynamic Binding

java
CopyEdit
class Parent {
void display() {
[Link]("Parent class method");
}
}
class Child extends Parent {
@Override
void display() {
[Link]("Child class method");
}
}

public class DynamicBindingExample {


public static void main(String[] args) {
Parent obj = new Child(); // Upcasting
[Link](); // Calls Child's display() method
}
}

Output:

kotlin
CopyEdit
Child class method

✔ Explanation: The display() method in the Child class is executed due to dynamic
binding.

3. Casting Objects and the instanceof Operator

Casting is used to convert objects from one type to another.

Upcasting: Converting a subclass object to a superclass reference (implicit).


Downcasting: Converting a superclass reference back to a subclass reference
(explicit).

Example of Upcasting & Downcasting

java
CopyEdit
class Animal {
void makeSound() {
[Link]("Animal sound");
}
}

class Cat extends Animal {


void purr() {
[Link]("Cat purrs");
}
}
public class CastingExample {
public static void main(String[] args) {
Animal a = new Cat(); // Upcasting (Implicit)
[Link]();

if (a instanceof Cat) {
Cat c = (Cat) a; // Downcasting (Explicit)
[Link]();
}
}
}

Output:

nginx
CopyEdit
Animal sound
Cat purrs

✔ Explanation:

• Upcasting: Animal a = new Cat(); (Implicit)


• Downcasting: (Cat) a; (Explicit)

4. The equals() Method in Java

The equals() method in the Object class compares object references by default.
It should be overridden to compare object data instead of memory addresses.

Example of Default equals() Behavior

java
CopyEdit
class Person {
String name;

Person(String name) {
[Link] = name;
}
}

public class EqualsExample {


public static void main(String[] args) {
Person p1 = new Person("Alice");
Person p2 = new Person("Alice");
[Link]([Link](p2)); // False (different memory locations)
}
}

Output:

arduino
CopyEdit
false

Example of Overriding equals() Method

java
CopyEdit
class Person {
String name;

Person(String name) {
[Link] = name;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != [Link]()) return false;
Person person = (Person) obj;
return [Link]([Link]);
}
}

public class OverriddenEqualsExample {


public static void main(String[] args) {
Person p1 = new Person("Alice");
Person p2 = new Person("Alice");

[Link]([Link](p2)); // True (same name)


}
}

Output:

arduino
CopyEdit
true

✔ Explanation:
• equals() now compares names, not memory addresses.

5. The ArrayList Class in Java

ArrayList is a resizable array implementation of the List interface.


It allows dynamic resizing, unlike arrays.
Elements can be added/removed easily.

Basic ArrayList Operations

java
CopyEdit
import [Link];

public class ArrayListExample {


public static void main(String[] args) {
// Creating an ArrayList of Strings
ArrayList<String> fruits = new ArrayList<>();

// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

// Accessing elements
[Link]("First fruit: " + [Link](0));

// Modifying elements
[Link](1, "Blueberry");

// Removing an element
[Link]("Cherry");

// Iterating through the list


[Link]("Fruits:");
for (String fruit : fruits) {
[Link](fruit);
}

// Checking size
[Link]("Size of ArrayList: " + [Link]());
}
}

Output:
yaml
CopyEdit
First fruit: Apple
Fruits:
Apple
Blueberry
Size of ArrayList: 2
5.1 Exception-Handling Overview, Exception Types, the Finally
Clause, Defining Custom Exception Classes

Exception handling is a mechanism in Java to handle runtime errors so that normal


program execution is maintained. It is achieved using try, catch, finally, throw, and
throws keywords.

1. Exception Handling Overview

An exception is an event that disrupts the normal flow of a program. Java provides a
structured way to handle exceptions to prevent crashes and ensure stability.

Basic Syntax of Exception Handling

try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Handle the exception
} finally {
// Optional block, always executes
}

2. Exception Types

Exceptions in Java are categorized into Checked, Unchecked, and Errors.

A) Checked Exceptions (Compile-time)

• Must be handled using try-catch or throws.


• Examples:
o IOException
o SQLException
o FileNotFoundException

Example: Handling a Checked Exception

import [Link].*;

public class CheckedExceptionExample {


public static void main(String[] args) {
try {
FileReader file = new FileReader("[Link]");
BufferedReader br = new BufferedReader(file);
[Link]([Link]());
} catch (IOException e) {
[Link]("File not found or unable to read: " + [Link]());
}
}
}

B) Unchecked Exceptions (Runtime)

• Occur at runtime and do not require mandatory handling.


• Examples:
o NullPointerException
o ArrayIndexOutOfBoundsException
o ArithmeticException

Example: Handling an Unchecked Exception

public class UncheckedExceptionExample {


public static void main(String[] args) {
try {
int num = 10 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
}
}
}

C) Errors

• Indicate serious system problems (not handled by normal programs).


• Examples:
o OutOfMemoryError
o StackOverflowError

Example: StackOverflowError (infinite recursion)

public class StackOverflowExample {


public static void recursiveMethod() {
recursiveMethod(); // Infinite recursion causes StackOverflowError
}

public static void main(String[] args) {


recursiveMethod();
}
}
3. The finally Clause

• The finally block executes regardless of whether an exception occurs or not.


• Used for cleanup operations like closing database connections or releasing
resources.

Example: Using finally

public class FinallyExample {


public static void main(String[] args) {
try {
int a = 10 / 0; // Exception occurs
} catch (ArithmeticException e) {
[Link]("Exception handled: " + [Link]());
} finally {
[Link]("This block always executes.");
}
}
}

Output:

Exception handled: / by zero


This block always executes.

4. Defining Custom Exception Classes

Java allows you to create custom exceptions by extending the Exception class.

Steps to Create a Custom Exception

1. Extend the Exception class.


2. Provide a constructor with a custom message.
3. Throw the exception using throw in a method.

Example: Custom Exception for Age Validation

// Step 1: Create Custom Exception


class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}

// Step 2: Use Custom Exception


public class CustomExceptionExample {
public static void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age must be 18 or older!");
} else {
[Link]("Access granted.");
}
}

public static void main(String[] args) {


try {
checkAge(16); // This will throw AgeException
} catch (AgeException e) {
[Link]("Exception: " + [Link]());
}
}
}

Output:

Exception: Age must be 18 or older!


5.2 Abstract Classes, Interfaces, The Comparable Interface, Interfaces vs.
Abstract Classes. Text I/O Handled in Java

1. Abstract Classes in Java

An abstract class is a class that cannot be instantiated and may contain abstract
methods (methods without a body). It serves as a base class for other classes.

Key Features of Abstract Classes

Can have both abstract and concrete methods.


Used for partial implementation of a class.
Can have constructors, instance variables, and static methods.
Uses the abstract keyword.

Example of an Abstract Class

abstract class Animal {


String name;

// Abstract method (no implementation)


abstract void makeSound();

// Concrete method
void sleep() {
[Link](name + " is sleeping.");
}
}

// Subclass providing implementation for the abstract method


class Dog extends Animal {
Dog(String name) {
[Link] = name;
}

@Override
void makeSound() {
[Link](name + " barks!");
}
}

public class AbstractExample {


public static void main(String[] args) {
Dog myDog = new Dog("Buddy");
[Link](); // Output: Buddy barks!
[Link](); // Output: Buddy is sleeping.
}
}

2. Interfaces in Java

An interface in Java defines a contract that a class must follow but does not contain any
concrete implementations.

Key Features of Interfaces

Contains only abstract methods (before Java 8).


Uses the interface keyword.
A class implements an interface using the implements keyword.
Supports multiple inheritance (unlike abstract classes).
From Java 8 onwards, interfaces can have default and static methods.

Example of an Interface

interface Vehicle {
void start();
}

// Implementing the interface


class Car implements Vehicle {
@Override
public void start() {
[Link]("Car engine starts...");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Vehicle myCar = new Car();
[Link](); // Output: Car engine starts...
}
}

3. The Comparable Interface

The Comparable interface is used for sorting objects in Java. It allows a class to define
a natural ordering by implementing the compareTo method.

Key Features
Single-method interface: int compareTo(T obj).
Used for sorting objects in collections (TreeSet, TreeMap, [Link](), etc.).
Returns:

• Negative value if this < obj


• Zero if this == obj
• Positive value if this > obj

Example of Comparable Interface

import [Link].*;

class Student implements Comparable<Student> {


String name;
int age;

Student(String name, int age) {


[Link] = name;
[Link] = age;
}

// Implement compareTo for sorting by age


@Override
public int compareTo(Student s) {
return [Link]([Link], [Link]);
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

public class ComparableExample {


public static void main(String[] args) {
List<Student> students = new ArrayList<>();
[Link](new Student("Alice", 22));
[Link](new Student("Bob", 20));
[Link](new Student("Charlie", 25));

// Sort list of students by age


[Link](students);
[Link](students);
}
}

Output: [Bob (20), Alice (22), Charlie (25)]


4. Interfaces vs. Abstract Classes

Feature Abstract Class Interface


Usage Partial implementation Fully abstract (before Java 8)
Methods Both abstract & concrete methods Only abstract methods (before Java 8)
Variables Can have instance variables Only public static final constants
Inheritance Supports single inheritance Supports multiple inheritance
Constructors Can have constructors Cannot have constructors

✔ Use an abstract class when: You want to share code among related classes.
✔ Use an interface when: You want multiple classes to follow a common contract.

5. Text I/O Handling in Java

Java provides multiple ways to handle text input/output, including File Handling.

Reading from a File (Using BufferedReader)

import [Link].*;

public class FileReadExample {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}
}
}

Writing to a File (Using BufferedWriter)

import [Link].*;

public class FileWriteExample {


public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"))) {
[Link]("Hello, Java File Handling!");
[Link]();
[Link]("This is a second line.");
} catch (IOException e) {
[Link]("Error writing file: " + [Link]());
}
}
}
5.3 Text I/O vs. Binary I/O, Binary I/O Classes Motivations and
Benefits Defining Generic Classes and Interfaces

1. Text I/O vs. Binary I/O

Java provides two main ways to handle file input and output: Text I/O and Binary I/O.
Feature Text I/O Binary I/O
Data Type Reads/writes text (characters) Reads/writes raw bytes
Uses character encoding (e.g.,
Encoding No encoding, stores raw binary data
UTF-8)
Slower (encoding/decoding
Speed Faster (direct byte storage)
overhead)
Usage For text files (e.g., .txt, .csv) For binary files (e.g., .jpg, .mp3, .exe)
Java BufferedReader, BufferedWriter, FileInputStream, FileOutputStream,
Classes FileReader, FileWriter ObjectInputStream, ObjectOutputStream

Example of Text I/O

import [Link].*;

public class TextIOExample {


public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"))) {
[Link]("Hello, this is a text file.");
[Link]();
[Link]("Second line of text.");
} catch (IOException e) {
[Link]("Error writing file: " + [Link]());
}

try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {


String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}
}
}
Output (from file):
Hello, this is a text file.
Second line of text.
Example of Binary I/O
import [Link].*;

public class BinaryIOExample {


public static void main(String[] args) {
// Writing binary data
try (FileOutputStream fos = new FileOutputStream("[Link]")) {
[Link](100); // Writes a single byte (value 100)
[Link](200); // Writes another byte
} catch (IOException e) {
[Link]("Error writing binary file: " + [Link]());
}

// Reading binary data


try (FileInputStream fis = new FileInputStream("[Link]")) {
int value;
while ((value = [Link]()) != -1) {
[Link](value + " ");
}
} catch (IOException e) {
[Link]("Error reading binary file: " + [Link]());
}
}
}
Output (raw binary data read from file):
100 200

2. Binary I/O Classes: Motivation and Benefits

Motivation for Using Binary I/O


✔ Efficient storage – No encoding overhead, direct byte storage.
✔ Faster processing – No need for character conversion.
✔ Handles all types of data – Can store text, images, audio, and video files.
✔ Preserves data integrity – No risk of encoding corruption.
Key Binary I/O Classes
Class Description
FileInputStream / FileOutputStream Reads/writes raw byte streams from/to files.
Reads/writes primitive data types (e.g., int,
DataInputStream / DataOutputStream
double).
ObjectInputStream /
Reads/writes Java objects (serialization).
ObjectOutputStream

Example of Object I/O (Serialization)


import [Link].*;
// A serializable class
class Person implements Serializable {
String name;
int age;

Person(String name, int age) {


[Link] = name;
[Link] = age;
}
}

public class ObjectIOExample {


public static void main(String[] args) {
// Writing object to file
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("[Link]"))) {
Person p = new Person("Alice", 25);
[Link](p);
} catch (IOException e) {
[Link]("Error writing object: " + [Link]());
}

// Reading object from file


try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("[Link]"))) {
Person p = (Person) [Link]();
[Link]("Person: " + [Link] + ", Age: " + [Link]);
} catch (IOException | ClassNotFoundException e) {
[Link]("Error reading object: " + [Link]());
}
}
}
Output:
Person: Alice, Age: 25

3. Defining Generic Classes and Interfaces


Generics allow writing flexible and type-safe code by defining classes and interfaces
with type parameters.
Advantages of Generics
✔ Type safety – Prevents ClassCastException at runtime.
✔ Code reusability – Single class for multiple data types.
✔ Performance – Eliminates need for explicit casting.

Example of a Generic Class


// Generic class with a type parameter <T>
class Box<T> {
private T value;
void setValue(T value) {
[Link] = value;
}

T getValue() {
return value;
}
}

public class GenericClassExample {


public static void main(String[] args) {
Box<Integer> intBox = new Box<>();
[Link](10);
[Link]("Integer Value: " + [Link]());

Box<String> strBox = new Box<>();


[Link]("Hello");
[Link]("String Value: " + [Link]());
}
}
Output:
vbnet
CopyEdit
Integer Value: 10
String Value: Hello

4. Generic Interfaces
A generic interface defines a contract that multiple classes can follow.
Example of a Generic Interface
// Generic interface
interface Computable<T> {
T compute(T a, T b);
}

// Implementation for Integer


class IntegerAdder implements Computable<Integer> {
@Override
public Integer compute(Integer a, Integer b) {
return a + b;
}
}

// Implementation for String


class StringConcatenator implements Computable<String> {
@Override
public String compute(String a, String b) {
return a + b;
}
}

public class GenericInterfaceExample {


public static void main(String[] args) {
Computable<Integer> intAdder = new IntegerAdder();
[Link]("Sum: " + [Link](5, 10));

Computable<String> strConcat = new StringConcatenator();


[Link]("Concatenation: " + [Link]("Hello, ", "World!"));
}
}
Output:
Sum: 15
Concatenation: Hello, World!
5.4 Generic Methods. Processes and Threads
1. Generic Methods in Java

A generic method is a method that uses type parameters to allow flexible and reusable
code. These methods enable type safety and can work with multiple data types without
explicit casting.

Defining a Generic Method


A generic method has a type parameter (inside < >) before the return type.
// Generic method example
class Utility {
// Generic method with type parameter <T>
public static <T> void printArray(T[] array) {
for (T element : array) {
[Link](element + " ");
}
[Link]();
}
}

public class GenericMethodExample {


public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"Hello", "World"};

// Calling the generic method


[Link](intArray); // Output: 1 2 3 4 5
[Link](strArray); // Output: Hello World
}
}
Output:
12345
Hello World

Generic Method with Multiple Type Parameters


A generic method can have multiple type parameters.
class PairUtil {
// Generic method with two type parameters <K, V>
public static <K, V> void printPair(K key, V value) {
[Link]("Key: " + key + ", Value: " + value);
}
}

public class MultipleGenericsExample {


public static void main(String[] args) {
[Link](1, "One");
[Link]("Name", "Alice");
}
}
Output:
Key: 1, Value: One
Key: Name, Value: Alice

Bounded Type Parameters in Generic Methods


A generic method can be restricted to work only with a specific type hierarchy.
// Bounded type parameter (T extends Number)
class MathUtil {
public static <T extends Number> double square(T num) {
return [Link]() * [Link]();
}
}

public class BoundedGenericExample {


public static void main(String[] args) {
[Link]([Link](5)); // Works with Integer
[Link]([Link](3.14)); // Works with Double
}
}
Output:
25.0
9.8596
Note: T extends Number ensures the method only accepts Integer, Double, Float,
etc.

2. Processes and Threads in Java


What is a Process?
A process is an independent program running on a computer. Each process has its own
memory space.

Example of Running an External Process in Java

import [Link];

public class ProcessExample {


public static void main(String[] args) {
try {
Process process = [Link]().exec("[Link]"); // Opens
Notepad
[Link]("Notepad started...");
} catch (IOException e) {
[Link]();
}
}
}
This will open Notepad (on Windows).

What is a Thread?
A thread is a lightweight process that shares memory with other threads of the same
process.
🛠 Java supports multithreading using the Thread class and Runnable interface.

Creating Threads in Java


1. Using the Thread Class
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread: " + i);
}
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link](); // Starts the thread
}
}
Output:
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5

2. Using the Runnable Interface (Preferred)


java
CopyEdit
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Runnable Thread: " + i);
}
}
}

public class RunnableExample {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
[Link]();
}
}
Output: Similar to the previous example.
Multithreading with Multiple Threads

class PrintNumbers extends Thread {


private String name;

PrintNumbers(String name) {
[Link] = name;
}

public void run() {


for (int i = 1; i <= 3; i++) {
[Link](name + ": " + i);
}
}
}

public class MultiThreadExample {


public static void main(String[] args) {
PrintNumbers t1 = new PrintNumbers("Thread-1");
PrintNumbers t2 = new PrintNumbers("Thread-2");

[Link]();
[Link]();
}
}
Output (Order may vary due to concurrency):
Thread-1: 1
Thread-2: 1
Thread-1: 2
Thread-2: 2
Thread-1: 3
Thread-2: 3

3. Thread Synchronization
When multiple threads share resources, data inconsistency can occur. Synchronization
helps avoid this.

Example of a Synchronized Method


class Counter {
private int count = 0;

// Synchronized method
public synchronized void increment() {
count++;
}

public int getCount() {


return count;
}
}

public class SynchronizationExample {


public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();

// Creating two threads that increment the counter


Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) [Link]();
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) [Link]();
});

[Link]();
[Link]();
[Link]();
[Link]();

[Link]("Final Count: " + [Link]());


}
}
Output (Consistent due to synchronization):
Final Count: 2000
5.5 Thread Objects, Defining and Starting a Thread

Threads allow concurrent execution of tasks in Java, improving application


performance. Java provides two ways to create and start threads:

1. Extending the Thread class


2. Implementing the Runnable interface (Recommended for better flexibility)

1. Creating a Thread by Extending the Thread Class

We create a thread by extending the Thread class and overriding the run() method.

Example:

class MyThread extends Thread {


public void run() { // Overriding run() method
for (int i = 1; i <= 5; i++) {
[Link]("Thread running: " + i);
try {
[Link](500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
[Link]();
}
}
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread t1 = new MyThread(); // Creating thread object
[Link](); // Starting the thread
}
}

Output (Runs independently from main() thread):

Thread running: 1
Thread running: 2
Thread running: 3
Thread running: 4
Thread running: 5

Key Points:

• run() method contains the code executed by the thread.


• start() method starts the execution of a new thread.
• [Link](milliseconds) pauses execution for a while.

2. Creating a Thread by Implementing the Runnable Interface (Recommended)

The Runnable interface is preferred because it allows multiple threads to share the
same object.

Example:

class MyRunnable implements Runnable {


public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Runnable Thread: " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link]();
}
}
}
}

public class RunnableExample {


public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable(); // Create Runnable object
Thread t1 = new Thread(myRunnable); // Create Thread with Runnable
[Link](); // Start the thread
}
}

Output:

Runnable Thread: 1
Runnable Thread: 2
Runnable Thread: 3
Runnable Thread: 4
Runnable Thread: 5

Advantages of Runnable:

• Better flexibility (allows multiple threads to share the same task).


• Avoids single inheritance limitation (since Java does not support multiple
inheritance).
• Improved resource sharing.
3. Running Multiple Threads

We can create multiple threads that run simultaneously.

Example:

class MyTask implements Runnable {


private String name;

MyTask(String name) {
[Link] = name;
}

public void run() {


for (int i = 1; i <= 3; i++) {
[Link](name + " - Count: " + i);
try {
[Link](300);
} catch (InterruptedException e) {
[Link]();
}
}
}
}

public class MultiThreadExample {


public static void main(String[] args) {
Thread t1 = new Thread(new MyTask("Thread-1"));
Thread t2 = new Thread(new MyTask("Thread-2"));

[Link]();
[Link]();
}
}

Output (May vary due to concurrent execution):

Thread-1 - Count: 1
Thread-2 - Count: 1
Thread-1 - Count: 2
Thread-2 - Count: 2
Thread-1 - Count: 3
Thread-2 - Count: 3

Key Points:
• Multiple threads execute simultaneously.
• Execution order is unpredictable (depends on CPU scheduling).

4. Thread Lifecycle in Java

A thread in Java goes through several states:

State Description
NEW Thread is created but not started (new Thread()).
RUNNABLE Thread is started and ready to run.
RUNNING Thread is currently executing (run() method).
BLOCKED Thread is waiting for a resource (e.g., lock).
WAITING Thread is waiting indefinitely for another thread’s signal.
TIMED_WAITING Thread is waiting for a specific amount of time ([Link]()).
TERMINATED Thread has finished execution.

5. Using join() to Wait for Thread Completion

The join() method ensures that the main thread waits for another thread to finish before
continuing.

Example:

class Worker extends Thread {


private String name;

Worker(String name) {
[Link] = name;
}

public void run() {


for (int i = 1; i <= 3; i++) {
[Link](name + " is working... " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link]();
}
}
}
}

public class JoinExample {


public static void main(String[] args) {
Worker t1 = new Worker("Worker-1");
Worker t2 = new Worker("Worker-2");
[Link]();
try {
[Link](); // Main thread waits until t1 finishes
} catch (InterruptedException e) {
[Link]();
}

[Link](); // t2 starts only after t1 completes


}
}

Output (t2 starts only after t1 finishes):

Worker-1 is working... 1
Worker-1 is working... 2
Worker-1 is working... 3
Worker-2 is working... 1
Worker-2 is working... 2
Worker-2 is working... 3

Key Points:

• join() ensures Worker-2 starts only after Worker-1 completes.

6. Thread Priorities

Java threads have priority levels (1 to 10):

• Thread.MIN_PRIORITY = 1
• Thread.NORM_PRIORITY = 5 (Default)
• Thread.MAX_PRIORITY = 10

Example:

class PriorityThread extends Thread {


PriorityThread(String name) {
super(name);
}

public void run() {


[Link](getName() + " Priority: " + getPriority());
}
}

public class ThreadPriorityExample {


public static void main(String[] args) {
PriorityThread t1 = new PriorityThread("Low Priority");
PriorityThread t2 = new PriorityThread("High Priority");

[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);

[Link]();
[Link]();
}
}

Output (Thread with higher priority may execute first):

High Priority Priority: 10


Low Priority Priority: 1

Key Point: Priority does not guarantee execution order (depends on OS scheduling).

7. Daemon Threads

A daemon thread runs in the background (e.g., Garbage Collector).


Use setDaemon(true) before starting the thread.

class DaemonTask extends Thread {


public void run() {
while (true) {
[Link]("Daemon Thread Running...");
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
}

public class DaemonExample {


public static void main(String[] args) {
DaemonTask daemon = new DaemonTask();
[Link](true);
[Link]();

[Link]("Main thread finishes...");


}
}

You might also like