0% found this document useful (0 votes)
95 views121 pages

Introduction to Java Programming Basics

Java is a high-level, object-oriented programming language known for its platform independence and widespread use in various applications, including mobile, web, and enterprise software. Key features include robustness, security, multithreading, and a large community support. The document also covers Java installation, the Java Development Kit (JDK), and basic syntax, including access modifiers and the structure of Java programs.

Uploaded by

ronnyron225
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)
95 views121 pages

Introduction to Java Programming Basics

Java is a high-level, object-oriented programming language known for its platform independence and widespread use in various applications, including mobile, web, and enterprise software. Key features include robustness, security, multithreading, and a large community support. The document also covers Java installation, the Java Development Kit (JDK), and basic syntax, including access modifiers and the structure of Java programs.

Uploaded by

ronnyron225
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

JAVA INTRODUCTION

JAVA PROGRAMMING INTRODUCTION PART 1


What is Java?
Java is a versatile, high-level, and object-oriented programming language first released by
Sun Microsystems in 1995. Now owned and maintained by Oracle Corporation, Java is one of
the most widely used programming languages globally, with over 3 billion devices running
Java-based applications. It is renowned for its platform independence, achieved through the
Java Virtual Machine (JVM).

Key Features of Java:

●​ Platform Independent: Write Once, Run Anywhere (WORA). Java code is compiled
into platform-agnostic bytecode, executable on any device with a JVM.
●​ Object-Oriented: Follows OOP principles such as encapsulation, inheritance, and
polymorphism.
●​ Robust: Built-in error handling and strong memory management.
●​ Secure: Includes security features like bytecode verification and secure APIs.
●​ Multithreaded: Supports concurrent programming with multithreading capabilities.
●​ Dynamic and Extensible: Classes can be dynamically loaded and extended at
runtime.

What is Java Used For?

Java is versatile and supports the development of a wide range of applications, including:

●​ Mobile Applications: Especially Android apps (via Android Studio and Java SDK).
●​ Desktop Applications: GUI-based applications.
●​ Web Applications: Through frameworks like Spring, Hibernate, and Struts.
●​ Web Servers and Application Servers: Java powers servers such as Apache
Tomcat, WebLogic, and JBoss.
●​ Enterprise Software: Java is widely used in enterprise-level backend systems.
●​ Games: Game development via frameworks like LibGDX.
●​ Database Connections: Used in backend development with tools like JDBC (Java
Database Connectivity).
●​ Internet of Things (IoT): Integration with smart devices like Raspberry Pi.

Why Use Java?


●​ Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
●​ It is one of the most popular programming languages in the world
●​ It has a large demand in the current job market
●​ It is easy to learn and simple to use
●​ It is open-source and free
●​ It is secure, fast and powerful
●​ It has huge community support (tens of millions of developers)
●​ Java is an object oriented language which gives a clear structure to programs and
allows code to be reused, lowering development costs
●​ As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or
vice versa
Java Installation & CMD Check
Some systems may already have Java installed, especially if you're using a computer that previously required
Java for other applications. To check if Java is installed:

Open Command Prompt ([Link]).

Type the following command:cmd ​


java -version
If Java is installed, you’ll see information about the Java version installed on your system, such as:​
java version "23.0.0" 2024-08-21 LTS
Java(TM) SE Runtime Environment 22.9 (build 22.0.0+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 22.9 (build 22.0.0+13-LTS, mixed mode)
If Java is not installed, the system will respond with an error or indicate that the command is not recognized.

Why You Need the JDK


The Java Development Kit (JDK) is essential because:

1.​ Compilation: Converts Java source code (.java files) into bytecode (.class files) using the javac
compiler.
2.​ Execution: Provides the Java Runtime Environment (JRE) to execute Java programs.
3.​ Libraries & Tools: Includes pre-built libraries, APIs, and tools necessary for Java development.

You can download the latest JDK for free from:

●​ Oracle JDK: [Link]


●​ OpenJDK: [Link]

How to Run Java Code

Using NetBeans: ( We will be Using Netbeans IDE )


NetBeans is an Integrated Development Environment (IDE). It is a software application
that provides comprehensive tools to facilitate software development, particularly for Java
programming.
1.​ Install NetBeans (with or without a bundled JDK).

2.​ Create a new Java project:


○​ Open NetBeans.
○​ Click File > New Project.
○​ Choose Java with Ant > Java Application.
○​ Enter the project name and location. Click Finish.
3.​ Write your code in the editor.
4.​ To run the program:
○​ Click the Run button or press Shift + F6.
○​ Output appears in the IDE's console.

JAVA CODE BREAKDOWN - EXPLANATION


public class Main {
public static void main(String[] args) {
[Link]("Hello World");
}
}

public class PrimeFile{


public static void main(String[] args) {
[Link]("Hello to the World");
}
}

public class PrimeFile


1. public:
○​ This is an access modifier.

○​ It means this class is accessible from anywhere, including from outside the package it belongs
to.
●​ Definition: This is the most open access modifier in Java.
●​ Purpose: Allows the class, method, or variable to be accessible from anywhere, even outside the
package.
●​ Usage:
○​ Commonly used for the main class and methods that need to be accessed externally.
○​ Required for the main method, as the JVM must access it to start program execution.

Code Example Below:​

public class PublicExample {


public String message = "Accessible from anywhere!";
public static void main(String[] args) {
PublicExample obj = new PublicExample();
[Link]([Link]);
}
}

2. protected
●​ Definition: This modifier allows limited visibility.
●​ Purpose: Makes the member accessible:
○​ Within the same package.
○​ By subclasses, even if they are in different packages.
●​ Usage: Commonly used in inheritance when you want to provide controlled access to fields or methods
in subclasses.

Code Example Below:​

class Parent {
protected String message = "Accessible in subclasses and the same
package!";
}
public class ProtectedExample extends Parent {
public static void main(String[] args) {
ProtectedExample obj = new ProtectedExample();
[Link]([Link]); // Accessible here because of
inheritance
}
}

3. default (Package-Private) (No Keyword Required)


●​ Definition: The default access level in Java, used when no modifier is specified.

●​ Purpose: Makes the member accessible only within the same package. It is not visible to classes in
other packages, even if they are subclasses.
●​ Usage: Used for internal classes and methods that should not be exposed outside the package.

Code Example Below:


class DefaultExample {
String message = "Accessible only within the same package.";
}
public class TestDefault {
public static void main(String[] args) {
DefaultExample obj = new DefaultExample();
[Link]([Link]); // Works if both classes are in
the same package
}
}

4. private
●​ Definition: The most restrictive access modifier in Java.

●​ Purpose: Makes the member accessible only within the class where it is defined.
●​ Usage:
○​ Used for encapsulation to hide implementation details and protect data.
○​ Commonly applied to fields and helper methods.

Code Example Below:​

public class PrivateExample {


private String message = "Accessible only within this class.";

private void printMessage() {


[Link](message);
}

public static void main(String[] args) {


PrivateExample obj = new PrivateExample();
[Link](); // Works because it’s within the same class
}
}

Comparison of Access Modifiers


Modifier Same Class Same Package Subclass (Different Package) Everywhere

public ✅ ✅ ✅ ✅
protected ✅ ✅ ✅ (only via inheritance) ❌
default ✅ ✅ ❌ ❌
private ✅ ❌ ❌ ❌
Summary on Above Modifiers
●​ public: Accessible everywhere.
●​ protected: Accessible in the same package and subclasses.
●​ default: Accessible only within the same package.
●​ private: Accessible only within the same class.

Understanding these modifiers is key to controlling the visibility and security of your code !

●​ class:
○​ This is a keyword used to define a class in Java.
○​ A class is a blueprint for creating objects and contains code that defines the behavior
and properties of those objects.

Code Example Below:



public class Car {


String model;
int year;
void start() {
[Link]("Car is starting...");
}
}

●​ primefile:
○​ This is the name of the class.
○​ The class name should always start with an uppercase letter by convention. It should match
the file name (e.g., [Link] in this case).
○​ The class name must match the filename (e.g., [Link]) and follow naming
conventions, starting with an uppercase letter.

Code Example Below: If the file is named [Link], then the class name must be:​

public class MyProgram {


public static void main(String[] args) {
[Link]("Hello World");
}
}

2. Curly Braces { and }


●​ Definition: These are used to define a block of code.

●​ Purpose:
○​ { marks the start of a class or method body.
○​ } marks the end.

Code Example Below:​


public class Demo {


public static void main(String[] args) {
{
[Link]("This block is inside main");
}
}
}

3. public static void main(String[] args)


●​ This is the main method.

●​ It is the entry point for any Java program. When the program is run, the main method is
executed first.

Breaking it down:
●​ public:

○​ This makes the method accessible from outside the class.


○​ The JVM (Java Virtual Machine) requires this method to be public so it can be
invoked to start the program.
●​ static:
○​ This means the method belongs to the class, not an instance of the class.
○​ You can call the main method without creating an object of the class.

Code Example Below:

public class StaticExample {


static void displayMessage() {
[Link]("Static method called");
}
public static void main(String[] args) {
displayMessage(); // No need to create an object
}
}

●​ void:

○​ This is the return type of the method.


○​ It means this method does not return any value.
●​ main:
○​ This is the name of the method. It is a special method that serves as the starting point of the
program.
●​ String[] args:
○​ This is an array of String objects.
○​ It is used to pass command-line arguments to the program.

What are args?


●​ args is the name of the parameter, and it represents an array of strings (String[]) that can hold
command-line arguments passed to the program when it is executed.

●​ When you run a Java program from the command line, you can include additional text (arguments) after
the class name. These arguments are captured in the args array.

Breaking (String[] args)Down


String[]
●​ This declares an array of Strings.

○​ An array is a collection of elements of the same type, and String[] specifically means it's an
array of strings.
○​ Each string in this array corresponds to an individual argument passed to the program.

args
●​ This is the name of the array parameter.

●​ It is a conventional name, but you can rename it to something else (e.g., arguments, params), and it
will work the same way.

Purpose of args
●​ The purpose of args is to allow users to pass external data to the program at runtime.

For example, if you run:​



java PrimeFile Hello World

○​ args[0] will contain "Hello".


○​ args[1] will contain "World".

Code Example Below:


Here’s a program to demonstrate the use of args:

public class PrimeFile {


public static void main(String[] args) {
[Link]("Number of arguments: " + [Link]);

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


[Link]("Argument " + i + ": " + args[i]);
}
}
}

Running the Program by :


1.​ Save this code in [Link].

Compile and run it using the following commands:​


javac [Link]
java PrimeFile Hello Java World
Output
Number of arguments: 3
Argument 0: Hello
Argument 1: Java
Argument 2: World

What If No Arguments Are Passed?


If you run the program without any arguments:​
java PrimeFile

●​ Then [Link] will be 0, and the args array will be empty. No arguments will be printed.

Why Use args?


●​ Dynamic Input: It allows the user to pass different inputs without modifying the code.

●​ Configuration: You can pass configuration options (e.g., filenames, environment settings) directly from
the command line.
●​ Automation: Useful for scripting or batch operations where programs need to process different inputs
automatically.

4. { and } (Inside main)


●​ These curly braces define the block of code that belongs to the main method.

5. [Link]("Hello to the World");


●​ This is a statement that prints text to the console.

Breaking it down:
●​ System:

○​ This is a built-in Java class from the [Link] package.


○​ It provides access to system-related features like input and output.
●​ out:
○​ This is a static member of the System class.
○​ It represents the standard output stream, typically the console.
●​ println:
○​ This is a method of the PrintStream class (the type of [Link]).
○​ It prints the specified message followed by a new line.
●​ "Hello to the World":
○​ This is a string literal that will be displayed in the console.
○​ Strings are enclosed in double quotes in Java.

Key Features in the Code


●​ Class: Defines the blueprint of the program.
●​ Main Method: Serves as the entry point.
●​ Curly Braces: Enclose the code blocks for both the class and the method.
●​ Printing: Demonstrates how to display output on the console.

Complete Code Flow


1.​ The JVM starts by looking for the main method in the specified class.
2.​ The main method is executed, and the statement inside it is run.
3.​ The [Link] method outputs "Hello to the World" to the console.

Java Syntax
Java programs follow a specific syntax structure that must be adhered to for successful
compilation and execution.

Every line of code that runs in Java must be inside a class. And the class name should
always start with an uppercase first letter. In our example, we named the class Main.

Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.

The name of the java file must match the class name. When saving the file, save it using the
class name and add ".java" to the end of the filename. To run the example above on your
computer, make sure that Java is properly installed:

Sample Example Code:


public class Main {
public static void main(String[] args) {
[Link]("Hello World");
}
}

●​ Every Line Inside a Class:


○​ All code in Java must be inside a class.
○​ The class name must start with an uppercase letter and match the file name.
●​ Case Sensitivity:
○​ Java is case-sensitive. For instance, Main and main are treated differently.
●​ File Naming:
○​ Save the file with the same name as the class name (e.g., [Link]).

The main Method is the entry point of every Java application and every Java program has a
class name which must match the filename, and that every program must
contain the main() method.
public static void main(String[] args)

●​ public: Accessible to all.


●​ static: Belongs to the class, not an instance of the class.
●​ void: No return value.
●​ String[] args: Accepts command-line arguments as an array of strings.

Printing to the Console


(To the View for you to see Output )
Inside the main method, the [Link]() statement is used to display output for you to see:

[Link]("Hello World");

●​ System: Built-in Java class that contains useful members, such as out, which is short for "output". The
println() method, short for "print line", is used to print a value to the screen (or a file).
●​ out: Static member of the System class for output.
●​ println(): Prints text followed by a new line.

The println() Method


println() method to output values or print text in Java:

Sample Example Code:


public class Main {
public static void main(String[] args) {
[Link]("Hello World");
[Link]("I am Learning JAva");
[Link]("It is very Awesome !");
}
}

The print() Method


The only difference is that it does not insert a new line at the end of the output:
Sample Example Code:

public class Main {


public static void main(String[] args) {
[Link]("This will Print");
[Link]("On a Single Line");
[Link]("Continuously !");
}
}

By the End of This Section You Should be Able To :

1. Understand the Fundamentals of Java

●​ Explain what Java is, its history, and why it is widely used.
●​ Describe the types of applications that can be built with Java (mobile, web,
desktop, games, etc.).
●​ Discuss the features that make Java a popular programming language (e.g.,
platform independence, object-oriented nature).

2. Set Up a Java Development Environment

●​ Check for Java installation and verify the version using the command line.
●​ Understand the purpose of the Java Development Kit (JDK) and how to install it.
●​ Install and set up NetBeans IDE to write, compile, and run Java programs.

3. Write, Compile, and Execute Java Code

●​ Create, structure, and run Java programs using an IDE (NetBeans).


●​ Understand the syntax and structure of a basic Java program.
●​ Write simple programs that output text to the console (e.g., "Hello World").

4. Comprehend Java Code Syntax and Structure

●​ Understand the role of classes, methods, and the main method in Java
programs.
●​ Utilize curly braces {} to define code blocks.
●​ Write and interpret code with proper naming conventions for classes, methods,
and variables.

5. Use Access Modifiers Effectively

●​ Understand and apply the four access modifiers (public, protected,


default, and private).
●​ Control the visibility and accessibility of classes, methods, and variables.
●​ Understand the differences between modifiers and their impact on code security
and reusability.

6. Work with Command-Line Arguments (Terminal, CMD )

●​ Use String[] args to capture and process command-line arguments in Java


programs.
●​ Create dynamic programs that take user input through command-line arguments.
●​ Handle cases with and without arguments effectively.

The Introduction Section Ends Here ,


WE will Proceed Now To Java Fundamental Concepts !
FUNDAMENTAL CONCEPTS
JAVA PROGRAMMING FUNDAMENTALS PART 2
1. Reserved Words in Java ( Key Words )
Any programming language reserves some words to represent functionalities defined by that
language. These words are called reserved words. They can be briefly categorized into two parts:
keywords(50) and literals(3). Keywords define functionalities and literals define value. Identifiers are
used by symbol tables in various analyzing phases(like lexical, syntax, and semantic) of a compiler
architecture.

Keyword Usage

abstract Specifies that a class or method will be implemented later, in a


subclass

assert Assert describes a predicate placed in a Java program to indicate that


the developer thinks that the predicate is always true at that place.

boolean A data type that can hold True and False values only

break A control statement for breaking out of loops.

byte A data type that can hold 8-bit data values

case Used in switch statements to mark blocks of text

catch Catches exceptions generated by try statements

char A data type that can hold unsigned 16-bit Unicode characters

class Declares a new class

continue Sends control back outside a loop

default Specifies the default block of code in a switch statement

do Starts a do-while loop

double A data type that can hold 64-bit floating-point numbers

else Indicates alternative branches in an if statement

enum A Java keyword is used to declare an enumerated type. Enumerations


extend the base class.

extends Indicates that a class is derived from another class or interface

final Indicates that a variable holds a constant value or that a method will
not be overridden
finally Indicates a block of code in a try-catch structure that will always be
executed

float A data type that holds a 32-bit floating-point number

for Used to start a for loop

if Tests a true/false expression and branches accordingly

implements Specifies that a class implements an interface

import References other classes

instanceof Indicates whether an object is an instance of a specific class or


implements an interface

int A data type that can hold a 32-bit signed integer

interface Declares an interface

long A data type that holds a 64-bit integer

native Specifies that a method is implemented with native (platform-specific)


code

new Creates new objects

null This indicates that a reference does not refer to anything

package Declares a Java package

private An access specifier indicating that a method or variable may be


accessed only in the class it’s declared in

protected An access specifier indicating that a method or variable may only be


accessed in the class it’s declared in (or a subclass of the class it’s
declared in or other classes in the same package)

public An access specifier used for classes, interfaces, methods, and


variables indicating that an item is accessible throughout the
application (or where the class that defines it is accessible)

return Sends control and possibly a return value back from a called method

short A data type that can hold a 16-bit integer

static Indicates that a variable or method is a class method (rather than being
limited to one particular object)
strictfp A Java keyword is used to restrict the precision and rounding of
floating-point calculations to ensure portability.

super Refers to a class’s base class (used in a method or class constructor)

switch A statement that executes code based on a test value

synchronized Specifies critical sections or methods in multithreaded code

this Refers to the current object in a method or constructor

throw Creates an exception

throws Indicates what exceptions may be thrown by a method

transient Specifies that a variable is not part of an object’s persistent state

try Starts a block of code that will be tested for exceptions

void Specifies that a method does not have a return value

volatile This indicates that a variable may change asynchronously

while Starts a while loop

sealed The sealed keyword is used to declare a class as “sealed,” meaning it


restricts which classes can extend it.

permits The permits keyword is used within a sealed class declaration to


specify the subclasses that are permitted to extend it.

📌 Java Comments
Comments can be used to explain Java code, and to make it more readable. It can
also be used to prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not be
executed).
This example uses a single-line comment before a line of code:
// This is a comment in Java and will not be executed
[Link]("Hello World");

Java Multi-line Comments


Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by Java.

/* The code below will print the words Hello World


to the screen, and it is amazing */
[Link]("Hello World");

📌 Java Variables
Variables are containers for storing data values.
A variable provides us with named storage that our programs can
manipulate
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

// Main class
public class Main {

public static void main(String[] args) {


// Declare and initialize integer variables
int a, b, c; // Declares three integers: a, b, and c.
a = 10; // Assigns a value to a.
b = 10; // Assigns a value to b.

// Declare and initialize a byte variable


byte B = 22; // Initializes a byte variable B with a value of 22.

// Declare and initialize a double variable for pi


double pi = 3.14159; // Declares and assigns the value of pi.

// Declare and initialize a char variable


char letter = 'a'; // Initializes the char variable with the value 'a'.

// Declare and initialize various types of variables


int myNum = 5; // Integer variable initialized with 5.
float myFloatNum = 5.99f; // Float variable initialized with 5.99.
char myLetter = 'D'; // Char variable initialized with 'D'.
boolean myBool = true; // Boolean variable initialized with true.
String myText = "Hello"; // String variable initialized with "Hello".

// Print out the variables


[Link]("Integer a: " + a);
[Link]("Integer b: " + b);
[Link]("Byte B: " + B);
[Link]("Value of Pi: " + pi);
[Link]("Character letter: " + letter);
[Link]("Integer myNum: " + myNum);
[Link]("Float myFloatNum: " + myFloatNum);
[Link]("Character myLetter: " + myLetter);
[Link]("Boolean myBool: " + myBool);
[Link]("String myText: " + myText);
}
}

Sample Code 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);

Printing the Variables to the Console !


String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
[Link](fullName);

int x = 5;
int y = 6;
[Link](x + y); // Print the value of x + y

int x = 5;
int y = 6;
int z = 50;
[Link](x + y + z);
📌 Java Identifiers
All Java variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
Note: It is recommended to use descriptive names in order to create
understandable and maintainable code:
// Main class
public class StudentInfo {

public static void main(String[] args) {


// Declare and initialize a descriptive variable
int minutesPerHour = 60; // Good: Descriptive variable name
makes it easy to understand.

// Declare and initialize a less descriptive variable (not


recommended)
int m = 60; // OK, but the variable name 'm' is not
self-explanatory.

// Student details
String studentName = "John Doe"; // Stores the name of the
student.
int studentID = 15; // Stores the student's ID.
int studentAge = 23; // Stores the age of the student.
float studentFee = 75.25f; // Stores the fee paid by the
student.
char studentGrade = 'B'; // Stores the student's grade.

// Print descriptive variable


[Link]("Minutes per hour: " + minutesPerHour);

// Print less descriptive variable


[Link]("Minutes (m): " + m); // Not recommended for
production code.

// Print student details


[Link]("Student name: " + studentName);
[Link]("Student ID: " + studentID);
[Link]("Student age: " + studentAge);
[Link]("Student fee: " + studentFee);
[Link]("Student grade: " + studentGrade);
}
}

📌 Java Data Types


Data types specify the different sizes and values that can be stored in the variable. The
data type tells the compiler about the type of data to be stored and the required
memory
Data types are divided into two groups:
●​ Primitive data types - includes byte, short, int, long, float,
double, boolean and char
●​ Non-primitive data or Object Data types - such as String, Arrays
and Classes (you will learn more about these in a later chapter)

Primitive types start with a lowercase letter (like int), while non-primitive types
typically starts with an uppercase letter (like String).

Primitive types always hold a value, whereas non-primitive types can be null.

📌 Primitive Data Types in Java


Primitive data are only single values and have no special capabilities. There are 8 primitive
data types. They are depicted below in tabular format below as follows:

Type Description Default Size Example Literals Range of Values


Value

boolea Represents true or FALSE 1 bit true, false true, false


n false.

byte Small integer 0 8 10, -25 -128 to 127


values. bits

char A single 16-bit \u0000 16 'A', '\\', '\n', '\u0041' 0 to 65,535 (Unicode
Unicode character. bits range)

short Small integer 0 16 1000, -500 -32,768 to 32,767


values. bits

int Integer values 0 32 100000, -2000 -2,147,483,648 to


(default). bits 2,147,483,647
long Large integer 0L 64 10000000000L, -9,223,372,036,854,775,
values. bits -1000L 808 to
9,223,372,036,854,775,8
07

float Floating-point 0.0f 32 3.14f, -0.001f, Up to 7 decimal digits


numbers bits 1.23e5f precision.
(single-precision).

double Floating-point 0.0d 64 3.14159d, -0.001d, Up to 16 decimal digits


numbers bits 1.23e10d precision.
(double-precision).

📌 Java Non-Primitive (Reference/Object) Data Types


The following are the non-primitive (reference/object) data types −

​ String: The string is a class in Java, and it represents the sequences of


characters.
​ Arrays: Arrays are created with the help of primitive data types and store
multiple values of the same type.
​ Classes: The classes are the user-defined data types and consist of
variables and methods.
​ Interfaces: The interfaces are abstract types that are used to specify a
set of methods.

Syntax: Declaring a string


// Main class
public class StringExample {

public static void main(String[] args) {


// Declare a String without using the 'new' operator
String sent = "We have a New String which is actually a
sentence!";

// Declare a String using the 'new' operator


String sent1 = new String("The New String is actually a
sentence!");

// Print both Strings


[Link]("String declared without 'new' operator: " +
sent);
[Link]("String declared using 'new' operator: " +
sent1);

// Check if both strings are equal in content


boolean isEqual = [Link](sent1);
[Link]("Are the contents of the two strings equal?
" + isEqual);

// Check if both strings reference the same object


boolean isSameReference = (sent == sent1);
[Link]("Do the two strings reference the same
object? " + isSameReference);
}
}

2. Java Type Casting


Type casting is a technique that is used either by the compiler or a
programmer to convert one data type to another in Java. Type casting is
also known as type conversion. For example, converting int to double,
double to int, short to int, etc.

In Java, there are two types of casting:


●​ Widening Casting (automatically) - converting a smaller type to a
larger type size​
byte -> short -> char -> int -> long -> float -> double​

●​ Narrowing Casting (manually) - converting a larger type to a smaller


size type​
double -> float -> long -> int -> char -> short -> byte
Example Code : In this example, we are adding an integer and a double
number, storing the result in a double variable to display the sum,
implicitly casting the integer to a double during the addition:

public class Tester {


// Main driver method
public static void main(String[] args) {
// Define int variables
int num1 = 5004;
double num2 = 2.5;
double sum = num1 + num2;
// show output
[Link]("The sum of " + num1 + " and " + num2 + " is
" + sum);
}
}

We can also get an error when the compiler tries to convert a large data
type to a small data type. ( for Example if sum above is stored in Int )

But you can resolve this issue by :


int myInt = (int) myDouble; // Manual casting: double to int

Example code Below


public class Main {
public static void main(String[] args) {
double myDouble = 93.78d;
int myInt = (int) myDouble; // Manual casting: double to int

[Link](myDouble); // Outputs 9.78


[Link](myInt); // Outputs 9
}
}

3. Java Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
int sumOne = 100 + 50; // 150 (100 + 50)
int sum2 = sumOne + 250; // 400 (150 + 250)
int totalSum = sum2 + sum2; // 800 (400 + 400)

Java divides the operators into the following groups:

●​ Arithmetic operators
●​ Assignment operators
●​ Comparison operators
●​ Logical operators
●​ Bitwise operators

📌 Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two x+y


values

- Subtraction Subtracts one value x-y


from another

* Multiplication Multiplies two values x*y

/ Division Divides one value by x/y


another

% Modulus Returns the division x%y


remainder

++ Increment Increases the value of a ++x


variable by 1

-- Decrement Decreases the value of --x


a variable by 1

📌 Java Assignment Operators


Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
int x = 10;
x += 5;

Operator Example Same As Explanation

= x=5 x=5 Assigns the value 5 to the variable x.

+= x += 3 x=x+3 Adds 3 to the current value of x and assigns the


result back to x.

-= x -= 3 x=x-3 Subtracts 3 from the current value of x and


assigns the result back to x.

*= x *= 3 x=x*3 Multiplies the current value of x by 3 and


assigns the result back to x.

/= x /= 3 x=x/3 Divides the current value of x by 3 and assigns


the result back to x.

%= x %= 3 x=x%3 Calculates the remainder of x divided by 3 and


assigns the result back to x.

&= x &= 3 x=x&3 Performs a bitwise AND operation between x


and 3 and assigns the result to x.

` =` `x = 3`

^= x ^= 3 x=x^3 Performs a bitwise XOR operation between x


and 3 and assigns the result to x.

>>= x >>= 3 x = x >> 3 Shifts the bits of x to the right by 3 positions and
assigns the result to x.

<<= x <<= 3 x = x << 3 Shifts the bits of x to the left by 3 positions and
assigns the result to x.

Code Example to Demonstrate the above Assignment operators


public class AssignmentOperators {

public static void main(String[] args) {


// Initialize variable x with a value
int x = 12;

// Using the addition assignment operator


x += 5; // x = x + 5
[Link]("x after += 5: " + x); // Output: x = 17

// Using the subtraction assignment operator


x -= 7; // x = x - 7
[Link]("x after -= 7: " + x); // Output: x = 10

// Using the multiplication assignment operator


x *= 4; // x = x * 4
[Link]("x after *= 4: " + x); // Output: x = 40

// Using the division assignment operator


x /= 8; // x = x / 8
[Link]("x after /= 8: " + x); // Output: x = 5

// Using the modulus assignment operator


x %= 3; // x = x % 3
[Link]("x after %= 3: " + x); // Output: x = 2

// Resetting x for bitwise operations


x = 14;

// Using the bitwise AND assignment operator


x &= 7; // x = x & 7
[Link]("x after &= 7: " + x); // Output: x = 6

// Using the bitwise OR assignment operator


x |= 3; // x = x | 3
[Link]("x after |= 3: " + x); // Output: x = 7

// Using the bitwise XOR assignment operator


x ^= 5; // x = x ^ 5
[Link]("x after ^= 5: " + x); // Output: x = 2
// Resetting x for shift operations
x = 16;

// Using the right shift assignment operator


x >>= 2; // x = x >> 2
[Link]("x after >>= 2: " + x); // Output: x = 4

// Using the left shift assignment operator


x <<= 3; // x = x << 3
[Link]("x after <<= 3: " + x); // Output: x = 32
}
}

📌 Java Comparison Operators


Comparison operators are used to compare two values (or variables).
This is important in programming, because it helps us to find answers
and make decisions.
The return value of a comparison is either true or false. These values
are known as Boolean values,

Operato Name Example Explanation


r
== Equal to x == y Returns true if the value of x is
equal to the value of y.
!= Not equal x != y Returns true if the value of x is
to not equal to the value of y.
> Greater x > y Returns true if the value of x is
than greater than the value of y.
< Less than x < y Returns true if the value of x is
less than the value of y.
>= Greater x >= y Returns true if the value of x is
than or greater than or equal to the value
equal to of y.
<= Less than x <= y Returns true if the value of x is
or equal less than or equal to the value of
to y.

Java code to demo the above ​

public class RelationalOperatorsDemo {


public static void main(String[] args) {
int x = 10; // Assigning value to x
int y = 20; // Assigning value to y

// == Equal to
if (x < y) {
//
[Link]("x is less than y");
} else {
//
[Link]("x is not equal to y");
}
// != Not equal to
if (x != y) {
[Link]("x is not equal to y");
} else {
[Link]("x is equal to y");
}
// > Greater than
if (x > y) {
[Link]("x is greater than y");
} else {
[Link]("x is not greater than y");
}
// < Less than
if (x < y) {
[Link]("x is less than y");
} else {
[Link]("x is not less than y");
}
// >= Greater than or equal to
if (x >= y) {
[Link]("x is greater than or equal to y");
} else {
[Link]("x is not greater than or equal to y");
}
// <= Less than or equal to
if (x <= y) {
[Link]("x is less than or equal to y");
} else {
[Link]("x is not less than or equal to y");
}
}
}

📌 Java Logical Operators


You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical Returns true if both x < 5 && x < 10


and statements are true

|| Logical or Returns true if one of the x < 5 || x < 4


statements is true

! Logical Reverse the result, !(x < 5 && x <


not returns false if the result 10)
is true

Code to demo Logical Operators


public class LogicalOperatorsDemo {
public static void main(String[] args) {
int x = 15; // Assigning a value to x
// Logical AND (&&)
// Both conditions must be true for the result to be true
if (x > 10 && x < 20) {
[Link]("x is greater than 10 AND less than
20");
} else {
[Link]("x does not satisfy both conditions for
AND");
}
// Logical OR (||)
// At least one condition must be true for the result to be
true
if (x < 10 || x > 12) {
[Link]("x is less than 10 OR greater than 12");
} else {
[Link]("x does not satisfy either condition for
OR");
}
// Logical NOT (!)
// Reverses the result of the condition
if (!(x > 5 && x < 20)) {
[Link]("NOT: x is NOT greater than 5 AND less
than 20");
} else {
[Link]("NOT: x is greater than 5 AND less than
20");
}
}
}

4. Java Strings
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double
quotes:

String txt = "Hello World";


[Link]([Link]()); // Outputs "HELLO WORLD"
[Link]([Link]()); // Outputs "hello world"

📌 String Concatenation
The + operator can be used between strings to combine them. This is called
concatenation:

public class StringConcatenationDemo {


public static void main(String[] args) {
// Example 1: Using the + operator for concatenation
String firstName = "Emily";
String lastName = "Smith";
String fullName = firstName + " " + lastName; // Concatenating
first and last name with a space
[Link]("Full name using + operator: " + fullName);

// Example 2: Using the concat() method for concatenation


String greeting = "Hello, ";
String name = "World!";
String message = [Link](name); // Concatenating strings
using concat method
[Link]("Message using concat(): " + message);

// Example 3: Concatenating multiple strings


String intro = "My name is ";
String ageInfo = " and I am ";
int age = 25;
String completeIntro = intro + firstName + " " + lastName +
ageInfo + age + " years old.";
[Link]("Introduction using concatenation: " +
completeIntro);

// Example 4: Combining string literals directly


[Link]("Hello" + ", " + "how are you today?");
}
}

5. Java Math

The Java Math class has many methods that allow you to perform
mathematical tasks on numbers.

public class MathMethodsDemo {


public static void main(String[] args) {
// Finding the maximum value between two numbers
int maxValue = [Link](25, 42); // Compares 25 and 42
[Link]("Maximum value: " + maxValue);

// Finding the minimum value between two numbers


int minValue = [Link](25, 42); // Compares 25 and 42
[Link]("Minimum value: " + minValue);

// Calculating the square root of a number


double squareRoot = [Link](81); // Square root of 81
[Link]("Square root: " + squareRoot);

// Getting the absolute value of a number


double absoluteValue = [Link](-12.3); // Converts -12.3 to
12.3
[Link]("Absolute value: " + absoluteValue);

// Generating a random number between 0 (inclusive) and 1


(exclusive)
double randomValue = [Link]();
[Link]("Random value between 0 and 1: " +
randomValue);

// Generating a random integer between 0 (inclusive) and 10


(exclusive)
int randomZeroToNine = (int) [Link]([Link]() * 10);
[Link]("Random value between 0 and 9: " +
randomZeroToNine);

// Generating a random integer between 1 (inclusive) and 10


(inclusive)
int randomOneToTen = (int) [Link]([Link]() * 10) + 1;
[Link]("Random value between 1 and 10: " +
randomOneToTen);

// Generating a random integer between two values (e.g., min=5,


max=15)
int min = 5, max = 15;
int randomBetweenRange = (int) [Link]([Link]() * (max
- min + 1)) + min;
[Link]("Random value between " + min + " and " +
max + ": " + randomBetweenRange);
// Rounding a number to the nearest integer
long roundedValue = [Link](7.5); // Rounds 7.5 to 8
[Link]("Rounded value: " + roundedValue);

// Rounding a number down to the nearest integer


double roundedDownValue = [Link](7.8); // Rounds 7.8 down
to 7
[Link]("Rounded down value: " + roundedDownValue);

// Rounding a number up to the nearest integer


double roundedUpValue = [Link](7.2); // Rounds 7.2 up to 8
[Link]("Rounded up value: " + roundedUpValue);
}
}

6. Java Boolean
A boolean is a primitive data type that can hold only two values: Very
often, in programming, you will need a data type that can only have one of
two values, like:

●​ YES / NO
●​ ON / OFF
●​ TRUE / FALSE

For this, Java has a boolean data type, which can store true or false
values.

public class BooleanDemo {


public static void main(String[] args) {
// Boolean examples with descriptive variables
boolean isCodingExciting = true; // Indicates if coding is
exciting
boolean isPizzaHealthy = false; // Indicates if pizza is
healthy
[Link]("Is coding exciting? " + isCodingExciting);
// Outputs true
[Link]("Is pizza healthy? " + isPizzaHealthy); //
Outputs false

// Comparing two numbers


int numA = 15;
int numB = 20;
[Link]("Is numA greater than numB? " + (numA >
numB)); // Outputs false
[Link]("Is numA less than numB? " + (numA < numB));
// Outputs true

// Checking eligibility with comparison


int personAge = 21;
int legalDrinkingAge = 21; // Legal drinking age in some
countries
[Link]("Is the person old enough to drink? " +
(personAge >= legalDrinkingAge)); // Outputs true

// Equality check
int favoriteNumber = 7;
int guessedNumber = 7;
[Link]("Is the guessed number correct? " +
(favoriteNumber == guessedNumber)); // Outputs true

// Logical AND and OR with booleans


boolean isSunny = true;
boolean isWeekend = true;
[Link]("Is it sunny and the weekend? " + (isSunny
&& isWeekend)); // Outputs true
[Link]("Is it sunny or the weekend? " + (isSunny ||
isWeekend)); // Outputs true

// Logical NOT
boolean isRaining = false;
[Link]("Is it NOT raining? " + (!isRaining)); //
Outputs true
}
}

7. Java If ... Else


Java Conditions and If Statements
As you know Java supports the usual logical conditions from mathematics:
●​ Less than: a < b
●​ Less than or equal to: a <= b
●​ Greater than: a > b
●​ Greater than or equal to: a >= b
●​ Equal to a == b
●​ Not Equal to: a != b
You can use these conditions to perform different actions for different
decisions.
Java has the following conditional statements:
●​ Use if to specify a block of code to be executed, if a specified
condition is true
●​ Use else to specify a block of code to be executed, if the same
condition is false
●​ Use else if to specify a new condition to test, if the first condition is
false
●​ Use switch to specify many alternative blocks of code to be executed
public class ConditionalDemo {
public static void main(String[] args) {
// If-else example
int x = 20;
int y = 18;

// Check if x is greater than y


if (x > y) {
[Link]("x is greater than y"); // Outputs this
block since x > y
} else {
[Link]("x is not greater than y");
}

// If-else if-else example


int age = 25;
if (age < 13) {
[Link]("You are a child.");
} else if (age >= 13 && age < 20) {
[Link]("You are a teenager.");
} else if (age >= 20 && age < 60) {
[Link]("You are an adult."); // Outputs this
block since age = 25
} else {
[Link]("You are a senior citizen.");
}

// Another example combining conditions


int number = -5;

if (number > 0) {
[Link]("The number is positive.");
} else if (number < 0) {
[Link]("The number is negative."); // Outputs
this block since number = -5
} else {
[Link]("The number is zero.");
}
}
}

8. Java Switch
Java Switch Statements
Instead of writing many if..else statements, you can use the switch
statement.
The switch statement selects one of many code blocks to be executed:

public class ConditionalDemo {


public static void main(String[] args) {

// Switch example
int day = 5; // Represents the day of the week (1 = Monday, ...,
7 = Sunday)

switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday"); // Outputs this block since
day = 5
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day");
}
}
}

9 . Java While Loop


The while loop loops through a block of code as long as a specified condition
is true:
public class WhileLoopDemo {
public static void main(String[] args) {
// Example 1: Counting up from 0 to 4
int i = 0;
[Link]("Example 1: Counting up from 0 to 4");
while (i < 5) {
[Link](i); // Prints the current value of i
i++; // Increments i by 1
}

// Example 2: Countdown from 10 to 6


int count = 10;
[Link]("\nExample 2: Countdown from 10 to 6");
while (count > 5) {
[Link](count); // Prints the current value of
count
count--; // Decrements count by 1
}

// Example 3: Printing only even numbers between 1 and 10


int num = 2; // Start with the first even number
[Link]("\nExample 3: Printing even numbers between 1
and 10");
while (num <= 10) {
[Link](num); // Prints the current value of num
num += 2; // Increments num by 2 to get the next even number
}

// Example 4: Infinite loop with a break condition


[Link]("\nExample 4: Infinite loop with break");
int infinite = 0;
while (true) { // Infinite loop
[Link]("Infinite loop iteration: " + infinite);
infinite++;
if (infinite == 3) { // Exit the loop when infinite equals 3
[Link]("Breaking the infinite loop!");
break;
}
}
}
}

10. The Do While Loop


The do while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat
the loop as long as the condition is true.

public class DoWhileLoopDemo {


public static void main(String[] args) {
// Example 1: Counting up from 0 to 4
int i = 0;
[Link]("Example 1: Counting up from 0 to 4");
do {
[Link](i); // Prints the current value of i
i++; // Increments i by 1
} while (i < 5); // Loop runs while i is less than 5

// Example 2: Countdown from 3 to 0


int countdown = 3;
[Link]("\nExample 2: Countdown from 3 to 0");
do {
[Link](countdown); // Prints the current value of
countdown
countdown--; // Decrements countdown by 1
} while (countdown >= 0); // Loop runs while countdown is greater
than or equal to 0

// Example 3: Printing odd numbers between 1 and 9


int num = 1; // Start with the first odd number
[Link]("\nExample 3: Printing odd numbers between 1
and 9");
do {
[Link](num); // Prints the current value of num
num += 2; // Increments num by 2 to get the next odd number
} while (num <= 9); // Loop runs while num is less than or equal
to 9

// Example 4: Infinite loop with a break condition


[Link]("\nExample 4: Infinite loop with break");
int infinite = 0;
do {
[Link]("Infinite loop iteration: " + infinite);
infinite++;
if (infinite == 3) { // Exit the loop when infinite equals 3
[Link]("Breaking the infinite loop!");
break;
}
} while (true); // Infinite loop condition
}
}

11. Java For Loop


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

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.

Statement 3 increases a value (i++) each time the code block in the loop has been
executed2. Nested Loop Example

1. Single Loop Example

public class SingleLoopExample {


public static void main(String[] args) {
// Let's say we have a basket of apples, and we want to count
them.
int totalApples = 5; // Total number of apples in the basket
// Loop through each apple in the basket
for (int appleNumber = 1; appleNumber <= totalApples;
appleNumber++) {
[Link]("Counting apple #" + appleNumber);
}
// After the loop, print the final message
[Link]("All apples have been counted! " +
totalApples + " apples have been counted.");
}
}

Explanation:
totalApples: Represents the total number of apples in the basket.
appleNumber: This is the loop variable. It starts at 1 and increments by 1
(appleNumber++) until it reaches totalApples.
Loop Execution:
The loop runs 5 times because totalApples is 5.
In each iteration, it prints the current apple number.
OUTPUT:
Counting apple #1
Counting apple #2
Counting apple #3
Counting apple #4
Counting apple #5
All apples have been counted! 5 apples have been counted.

2. Nested Loop Example


public class NestedLoopExample {
public static void main(String[] args) {
// Let's say we have 3 shelves in a library, and each shelf can
hold 4 books.
int totalShelves = 3; // Total number of shelves
int booksPerShelf = 4; // Number of books each shelf can hold

// Outer loop: Iterate through each shelf


for (int shelfNumber = 1; shelfNumber <= totalShelves;
shelfNumber++) {
[Link]("Organizing books on shelf #" +
shelfNumber);
// Inner loop: Iterate through each book on the current shelf
for (int bookNumber = 1; bookNumber <= booksPerShelf;
bookNumber++) {
[Link](" Placing book #" + bookNumber + " on
shelf #" + shelfNumber);
}
}

[Link]("All books have been organized!");


}
}

Explanation
totalShelves: Represents the total number of shelves in the library.
booksPerShelf: Represents the number of books each shelf can hold.
Outer Loop (shelfNumber):
This loop runs 3 times because there are 3 shelves.
For each shelf, it prints a message indicating which shelf is being organized.
Inner Loop (bookNumber):
This loop runs 4 times for each shelf because each shelf can hold 4 books.
For each book, it prints a message indicating which book is being placed on the
current shelf.
Total Iterations:
The outer loop runs 3 times, and the inner loop runs 4 times for each outer loop
iteration.
So, the inner loop's [Link] executes a total of 12 times (3 shelves * 4
books per shelf).
Output:
Organizing books on shelf #1
Placing book #1 on shelf #1
Placing book #2 on shelf #1
Placing book #3 on shelf #1
Placing book #4 on shelf #1
Organizing books on shelf #2
Placing book #1 on shelf #2
Placing book #2 on shelf #2
Placing book #3 on shelf #2
Placing book #4 on shelf #2
Organizing books on shelf #3
Placing book #1 on shelf #3
Placing book #2 on shelf #3
Placing book #3 on shelf #3
Placing book #4 on shelf #3
All books have been organized!

12. Java For Each Loop


public class ForEachExample {
public static void main(String[] args) {
// Array of car brands
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

// For-each loop to iterate through the array


for (String i : cars) {
[Link](i);
}
}
}

Explanation:

1.​ Array Declaration:


○​ String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
■​ This creates an array of strings named cars with four elements:
"Volvo", "BMW", "Ford", and "Mazda".
2.​ For-Each Loop:
○​ for (String i : cars) { ... }
■​ This is the for-each loop syntax.
■​ It reads as: "For each element i in the array cars, do the following."
■​ The variable i represents the current element of the array during each
iteration.
3.​ Loop Execution:
○​ The loop iterates over each element in the cars array.
○​ In each iteration:
■​ The value of i is set to the current element of the array.
■​ The [Link](i); statement prints the value of i.
4.​ Output:
○​ The loop will print each element of the cars array on a new line:

Volvo
BMW
Ford
Mazda
13. Java Break
The break statement is used to exit a loop or a switch statement prematurely

The break statement can also be used to jump out of a loop.

public class BreakInForLoop {


public static void main(String[] args) {
// Loop from 1 to 10
for (int i = 1; i <= 10; i++) {
[Link]("Current number: " + i);

// Exit the loop if i equals 5


if (i == 5) {
[Link]("Breaking the loop at i = 5");
break;
}
}
[Link]("Loop ended!");
}
}

Explanation:
The loop runs from i = 1 to i = 10.
When i equals 5, the break statement is executed, and the loop terminates immediately.
The program continues executing the code after the loop.

Output:
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5
Breaking the loop at i = 5
Loop ended!

14. Java Continue


The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
This example skips the value of 4: and prints 0 to 9

public class ContinueExample {


public static void main(String[] args) {
// Loop from 0 to 9
for (int i = 0; i < 10; i++) {
// Skip the iteration if i equals 4
if (i == 4) {
continue;
}
// Print the current value of i
[Link](i);
}
}
}

Explanation:

1.​ For Loop Initialization:


○​ for (int i = 0; i < 10; i++) { ... }
■​ The loop starts with i = 0.
■​ It continues as long as i < 10.
■​ After each iteration, i is incremented by 1 (i++).
2.​ Condition Check:
○​ if (i == 4) { continue; }
■​ Inside the loop, there’s an if statement that checks if the
current value of i is 4.
■​ If the condition is true (i.e., i == 4), the continue
statement is executed.
3.​ Continue Statement:
○​ The continue statement skips the rest of the code in the current
iteration and moves to the next iteration of the loop.
○​ When i equals 4, the continue statement is executed, and the
program skips the [Link](i); statement for that
iteration.
4.​ Output Statement:
○​ [Link](i);
■​ This statement prints the current value of i during each
iteration of the loop.
■​ However, it will not execute when i == 4 because the
continue statement skips the rest of the loop body for that
iteration.

15. Java Arrays


Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.

To declare an array, define the variable type with square brackets:

public class TwoArraysExample {


public static void main(String[] args) {
// Declare and initialize two arrays
String[] names = {"Alice", "Bob", "Charlie", "Diana"};
int[] ages = {25, 30, 22, 28};

// Check if both arrays have the same length


if ([Link] != [Link]) {
[Link]("Error: The arrays must have the same
length.");
return;
}

// Access and print values from both arrays using indexes


[Link]("Name\tAge");
[Link]("------------");
for (int i = 0; i < [Link]; i++) {
[Link](names[i] + "\t" + ages[i]);
}
}
}

Explanation:

1.​ Two Arrays:


○​ names: A String array containing names.
○​ ages: An int array containing ages corresponding to the names.
2.​ Length Check:
○​ Before accessing the arrays, the program checks if both arrays have the
same length using [Link] != [Link].
○​ If the lengths are not equal, it prints an error message and exits.
3.​ Accessing Elements:
○​ A for loop is used to iterate through the arrays using the index i.
○​ Inside the loop:
■​ names[i] accesses the i-th element of the names array.
■​ ages[i] accesses the i-th element of the ages array.
4.​ Output:
○​ The program prints the values from both arrays in a tabular format.

Name Age
------------
Alice 25
Bob 30
Charlie 22
Diana 28
PRIMITIVE DATA TYPES
PRIMITIVE DATA TYPES
JAVA DATA TYPES CODE

// This is a Java program that demonstrates different data types and


their operations.
public class JavaTester {
public static void main(String args[]) {

// Byte: Used for small integer values (Range: -128 to 127)


// Suitable for saving memory in large arrays of small numbers.
byte smallNumber1 = 2; // Declaring a byte variable with value 2
byte smallNumber2 = 4; // Declaring another byte variable with
value 4
byte byteSum = (byte) (smallNumber1 + smallNumber2); // Explicit
cast required because the result of addition defaults to int
[Link]("Byte: " + byteSum); // Output the sum of two
byte values

// Short: Used for slightly larger integers than byte (Range:


-32,768 to 32,767)
// Useful when memory is constrained and the range of values is
small.
short shortNumber1 = 2; // Declaring a short variable with value 2
short shortNumber2 = 4; // Declaring another short variable with
value 4
short shortSum = (short) (shortNumber1 + shortNumber2); //
Explicit cast required for addition
[Link]("Short: " + shortSum); // Output the sum of two
short values

// Int: The most commonly used integer type (Range: -2,147,483,648


to 2,147,483,647)
// Default type for whole numbers if no suffix is provided.
int wholeNumber1 = 2; // Declaring an int variable with value 2
int wholeNumber2 = 4; // Declaring another int variable with value
4
int intSum = wholeNumber1 + wholeNumber2; // No casting required
for addition
[Link]("Int: " + intSum); // Output the sum of two int
values

// Long: Used for very large integer values (Range: Very large, up
to 19 digits)
// Requires an 'L' suffix to differentiate from int.
long largeNumber1 = 2L; // Declaring a long variable with value 2
long largeNumber2 = 4L; // Declaring another long variable with
value 4
long longSum = largeNumber1 + largeNumber2; // Adding two long
values
[Link]("Long: " + longSum); // Output the sum of two
long values

// Float: Used for single-precision decimal numbers (Up to 7


decimal digits)
// Requires an 'f' suffix to differentiate from double.
float decimalNumber1 = 2.0f; // Declaring a float variable with
value 2.0
float decimalNumber2 = 4.0f; // Declaring another float variable
with value 4.0
float floatSum = decimalNumber1 + decimalNumber2; // Adding two
float values
[Link]("Float: " + floatSum); // Output the sum of two
float values

// Double: Used for double-precision decimal numbers (Up to 16


decimal digits)
// Default type for decimal numbers.
double preciseDecimal1 = 2.0; // Declaring a double variable with
value 2.0
double preciseDecimal2 = 4.0; // Declaring another double variable
with value 4.0
double doubleSum = preciseDecimal1 + preciseDecimal2; // Adding
two double values
[Link]("Double: " + doubleSum); // Output the sum of
two double values

// Boolean: Represents a true or false value


// Commonly used in conditions and loops.
boolean isJavaFun = true; // Declaring a boolean variable with
value true
[Link]("Boolean: " + isJavaFun); // Output the boolean
value

// Char: Represents a single character (e.g., letters, digits, or


symbols)
// Always enclosed in single quotes ('').
char letter = 'A'; // Declaring a char variable with the value 'A'
[Link]("Char: " + letter); // Output the char value
}
}
NON-PRIMITIVE DATA TYPES
NON-PRIMITIVE DATA TYPES

Non-primitive data types are called reference types because they refer to
[Link] used to store complex objects rather than simple values.

1. Class Example
// Class Example: Demonstrates how to create and use a class in Java
public class ClassExample {
public static void main(String[] args) {
// Creating an object of the Person class
// The 'new' keyword is used to create an instance (object) of
the class.
// We are passing "Alice" and 30 as arguments to the Person class
constructor.
Person person = new Person("Alice", 30);

// Accessing the object's methods to get the name and age


// The getName() and getAge() methods are called to retrieve the
object's data.
[Link]([Link]() + " is " + [Link]() +
" years old.");
}
}

// Defining the Person class


// A class is like a blueprint for creating objects.
// It contains fields (data) and methods (behavior).
class Person {
// Declaring private fields (variables) for the class
// These fields store the name and age of a person.
// The 'private' keyword means these fields can only be accessed
within this class.
private String name; // Field for the person's name
private int age; // Field for the person's age

// Constructor to initialize the Person object


// A constructor is a special method that is called when an object is
created.
// It is used to assign values to the fields of the object.
public Person(String name, int age) {
[Link] = name; // Assign the passed name to the 'name' field
[Link] = age; // Assign the passed age to the 'age' field
}

// Getter method for name


// This method allows other classes to access the private 'name'
field.
public String getName() {
return name; // Return the value of the 'name' field
}

// Getter method for age


// This method allows other classes to access the private 'age'
field.
public int getAge() {
return age; // Return the value of the 'age' field
}
}

2. Array Example
// Array Example: Demonstrates how to use arrays in Java
public class ArrayExample {
public static void main(String[] args) {
// Declaring and initializing an array of integers
int[] numbers = {1, 2, 3, 4, 5};

// Accessing and printing elements of the array


[Link]("First number is: " + numbers[0]);
[Link]("All numbers: ");
for (int num : numbers) {
[Link](num + " ");
}
[Link]();
}
}

3. String Example

// String Example: Demonstrates how to work with Strings in Java


public class StringExample {
public static void main(String[] args) {
// Creating and using a String
String message = "Hello, Java Learners!";
[Link]("Original String: " + message);

// Using some String methods


[Link]("String Length: " + [Link]());
[Link]("Uppercase: " + [Link]());
[Link]("Substring (6-10): " + [Link](6,
10));
}
}

4. Enum Example
// Enum Example: Demonstrates how to use enums in Java
public class EnumExample {
public static void main(String[] args) {
// Assigning a value to the enum variable
Day today = [Link];

// Printing the current day


[Link]("Today is " + today);

// Checking if today is a weekend or weekday


if (today == [Link] || today == [Link]) {
[Link]("It's a weekend!");
} else {
[Link]("It's a weekday.");
}
}
}

// Defining the Day enum


enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

5. Interface Example
// Interface Example: Demonstrates how to use an interface in Java
public class InterfaceExample {
public static void main(String[] args) {
// Creating an object of the Dog class
Dog dog = new Dog();
[Link](); // Calls the speak method defined in Dog
}
}

// Defining the Animal interface


interface Animal {
void speak(); // Method to be implemented by classes that use this
interface
}

// Defining the Dog class that implements the Animal interface


class Dog implements Animal {
@Override
public void speak() {
[Link]("The dog says: Woof!");
}
}
Instructions for Running the Code:

1.​ Copy and paste each code section into its own .java file.
2.​ Compile and run each file separately to see the output for each concept.
3.​ The names of the files should match the public class names (e.g.,
[Link], [Link]).
JAVA SCANNER CLASS
How the Scanner Class Works:
The Scanner class in Java, part of the [Link] package, is a versatile tool for parsing
input. It can be read from various sources, including keyboard input, files, and strings.

1. Key Features of the Scanner Class


1.​ Read Data: You can read various types of data like strings, integers, doubles, etc.
2.​ Delimiters: It allows you to specify delimiters for tokenizing input.
3.​ Error Handling: Provides methods to handle exceptions like
InputMismatchException.

2. Importing the Scanner Class


Before using the Scanner class, you must import it:

import [Link];

3. Creating a Scanner Object


To use the Scanner class, you must create an object of the class.

Scanner sc = new Scanner([Link]); // For reading input from the keyboard

●​ [Link] tells the program to get input from the user (keyboard).
●​ sc is the variable name that holds the Scanner object.

4. Common Methods of the Scanner Class


●​ nextInt(): Reads an integer.
●​ nextDouble(): Reads a double.
●​ nextLine(): Reads a full line (including spaces).
●​ next(): Read a single word (no spaces).
●​ nextBoolean(): Reads a boolean value (true or false).
●​ nextByte(): Reads a byte.
●​ nextFloat(): Reads a float.
5. Example: Reading Different Data Types
import [Link];

public class ScannerExample {


public static void main(String[] args) {
// Create a Scanner object for keyboard input
Scanner sc = new Scanner([Link]);

// Reading an integer
[Link]("Enter an integer:");
int num = [Link](); // Reads an integer input

// Reading a double
[Link]("Enter a double:");
double price = [Link](); // Reads a double input

// Reading a string
[Link]("Enter a word:");
String word = [Link](); // Reads a word

// Reading a full line


[Link](); // Consume the newline character
[Link]("Enter a full sentence:");
String sentence = [Link](); // Reads a full line

// Print the values


[Link]("Integer: " + num);
[Link]("Double: " + price);
[Link]("Word: " + word);
[Link]("Sentence: " + sentence);

[Link](); // Close the scanner object


}
}
6. Handling Input Mismatch
If the user enters an incorrect type of input (e.g., entering a string when an integer is
expected), it can throw an InputMismatchException. To handle this, you can use a
try-catch block:

import [Link];

public class InputMismatchExample {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter an integer: ");
// Will throw InputMismatchException if input is not an integer
int num = [Link]();
[Link]("You entered: " + num);
} catch (Exception e) {
[Link]("Invalid input! Please enter an integer.");
}
[Link]();
}
}

6. More Sample Codes Below


Initialization:
To use the Scanner class, you first need to create an instance of it by passing an appropriate
input source to its constructor.

import [Link];

public class ScannerInitialization {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Your code goes here !
}
}
Here, [Link] represents the standard input stream, typically the keyboard.
Reading Input:

The Scanner class provides various methods to read different types of input:

●​ nextInt(): Reads an int value.


●​ nextDouble(): Reads a double value.
●​ nextLine(): Reads a line of text as a String.
●​ next(): Reads the next token as a String.

Other methods include nextFloat(), nextLong(), nextBoolean(), etc.

For example, to read an integer input from the user:

import [Link];

public class ReadInteger {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter an integer: ");
int number = [Link]();
[Link]("You entered: " + number);
[Link]();
}
}

To read a full line of text:

import [Link];

public class ReadLine {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a line of text: ");
String line = [Link]();
[Link]("You entered: " + line);
[Link]();
}
}
Tokenization:

The Scanner class breaks the input into tokens using a delimiter pattern. By default, this
delimiter is whitespace. However, you can change the delimiter to any regular expression
using the useDelimiter() method.

For example, to use a comma as a delimiter:

import [Link];

public class CommaDelimiter {


public static void main(String[] args) {
String input = "apple,banana,cherry";
Scanner scanner = new Scanner(input);
[Link](",");
while ([Link]()) {
[Link]([Link]().trim());
}
[Link]();
}
}

This is particularly useful when parsing data from files or strings with specific delimiters.

Input Validation:

Before reading a specific type of input, it's good practice to check if the next token matches
the expected type using methods like hasNextInt(), hasNextDouble(), etc.

For example:

import [Link];

public class InputValidation {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter an integer: ");
if ([Link]()) {
int number = [Link]();
[Link]("You entered: " + number);
} else {
[Link]("Input is not an integer.");
}
[Link]();
}
}

Closing the Scanner:

After completing the input operations, it's important to close the Scanner to free up
system resources:

[Link]();

However, be cautious when closing a Scanner that's tied to [Link], as closing it will
also close the underlying input stream, which may not be desirable in all cases.

Example Usage:

Here's a comprehensive example demonstrating the use of the Scanner class:

import [Link];

public class ScannerExample {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Hello, " + name + ". You are " + age + " years old.");

[Link]();
}
}

In this example, the program prompts the user to enter their name and age, then outputs a
greeting message including the provided information.
JAVA METHODS
JAVA METHODS
Java Methods are blocks of code that perform a specific task. A method allows us to reuse
code, improving both efficiency and organization. All methods in Java must belong to a
class. Methods are similar to functions and expose the behavior of objects.

1. Why Use Java Methods?


●​ Improves code reusability
●​ Enhances readability
●​ Reduces redundancy
●​ Supports modular programming

2. Syntax of a Java Method


access_modifier return_type method_name(parameter_list) {
// Method body
// Code to execute
return value; // (if return type is not void)
}

Key Components of a Method Declaration


access_modifier: Defines the visibility of the method (e.g., public, private, protected, or
default).
return_type: The data type of the value returned by the method. Use void if the method
does not return anything.
method_name: The name of the method (should follow Java naming conventions).
parameter_list: A list of input parameters (optional).
method_body: The code that defines the functionality of the method.
return: Used to return a value (if the return type is not void).

3. Types of Java Methods


●​ Predefined Methods: Methods provided by Java libraries (e.g., [Link]()).
●​ User-defined Methods: Methods created by the programmer.
Example of Predefined Methods: Using Built-in Methods

public class BuiltInMethods {


public static void main(String[] args) {
double squareRoot = [Link](25); // Built-in method from Math
class
[Link]("Square Root of 25: " + squareRoot); //
Output: 5.0

String text = "Hello, Java!";


[Link]("Uppercase: " + [Link]()); //
Output: HELLO, JAVA!
}
}

Example of User-defined Methods: Methods created by the programmer to perform


specific tasks.

// Method Without Parameters and Without Return Type


public class Greetings {
public static void sayHello() { // No parameters, no return type
[Link]("Hello, welcome to Java!");
}

public static void main(String[] args) {


sayHello(); // Calling the method
}
}

// Method With Parameters and With Return Type


public class Calculator {
public static int multiply(int x, int y) { // Parameters and return
type
return x * y;
}

public static void main(String[] args) {


int result = multiply(5, 4); // Calling method and storing
return value
[Link]("Multiplication: " + result);
}
}

What are Parameters and Arguments in Java ?

●​ Parameters: These are variables defined in the method signature.


They act as placeholders for the values that will be passed to the
method when it is called.
●​ Arguments: These are the actual values that are passed to the
method when it is called. Arguments are assigned to the corresponding
parameters.

public void greetUser(String name) { // 'name' is a parameter


[Link]("Hello, " + name + "!");
}
greetUser("Liam"); // "Liam" is an argument

You can define a method with multiple parameters. Separate them


with a comma.

public class Calculator {


// Method with two parameters
public void add(int num1, int num2) {
int sum = num1 + num2;
[Link]("Sum: " + sum);
}

public static void main(String[] args) {


Calculator smartCalc = new Calculator(); // Create an object

// Calling the method with arguments


[Link](5, 10); // Arguments: 5 and 10
[Link](15, 20); // Arguments: 15 and 20
}
}
Java Method Return Values

What is a Return Value?

In Java, a method can return a value using the return statement. The return
value is the output of the method, which can be used by the caller.

●​ If a method returns a value, it must specify a return type (e.g., int,


double, String).
●​ If a method does not return a value, it must use void as the return
type.

Example: Returning an Integer

// Define a class named Calculator


public class Calculator {
// Method that returns the sum of two numbers
public int addNumbers(int firstNumber, int secondNumber) {
return firstNumber + secondNumber; // Returning the sum of
firstNumber and secondNumber
}

// Main method - Entry point of the program


public static void main(String[] args) {
// Create an object (instance) of the Calculator class
Calculator calculatorInstance = new Calculator();

// Call the addNumbers() method using the object and pass two
integers (5, 7)
// Store the returned sum in the variable 'sumResult'
int sumResult = [Link](5, 7);

// Print the sum to the console


[Link]("Sum: " + sumResult);
}
}
4. Java Methods Overloading
Method Overloading in Java allows multiple methods with the same name but different
parameters in the same class. This helps make the code more readable and efficient.

🔹 Why use Method Overloading?


●​ Makes the program cleaner by avoiding multiple method names.
●​ Helps in code reusability by allowing different types of inputs for the same method.
●​ Increases flexibility by handling different cases with a single method name.

Rules for Method Overloading

✅ The method name must be the same.​


✅ The method must have different parameters (different types, order, or number).​
✅ The return type can be the same or different, but it does not affect overloading.
❌ Method Overloading DOES NOT depend on the return type alone.
Example 1: Overloading a Method with Different Parameters

// Class to demonstrate method overloading


public class MathCalculator {

// Method to add two integers


public int add(int num1, int num2) {
return num1 + num2;
}

// Overloaded method: adds three integers


public int add(int num1, int num2, int num3) {
return num1 + num2 + num3;
}

public static void main(String[] args) {


// Creating an instance of the MathCalculator class
MathCalculator calculator = new MathCalculator();

// Calling the add method with two numbers


int sumTwoNumbers = [Link](5, 10);
[Link]("Sum of 2 numbers: " + sumTwoNumbers); //
Output: 15
// Calling the add method with three numbers
int sumThreeNumbers = [Link](5, 10, 15);
[Link]("Sum of 3 numbers: " + sumThreeNumbers); //
Output: 30
}
}
Explanation

●​ We created two methods named add().


●​ The first add() method takes two parameters and returns their sum.
●​ The second add() method takes three parameters and returns their sum.
●​ Java automatically calls the correct method based on the number of arguments
provided.

Example 2: Overloading with Different Order of Parameters

public class OrderExample {

// Method with (int, String) order


public void show(int num, String text) {
[Link]("Integer: " + num + ", Text: " + text);
}

// Overloaded method with (String, int) order


public void show(String text, int num) {
[Link]("Text: " + text + ", Integer: " + num);
}

public static void main(String[] args) {


// Creating an instance of OrderExample class
OrderExample obj = new OrderExample();

// Calling the overloaded methods


[Link](5, "Apple"); // Calls show(int, String)
[Link]("Banana", 10); // Calls show(String, int)
}
}
Key Takeaways 🚀
1.​Method Overloading allows multiple methods with the same name but different
parameters.
2.​Overloaded methods must differ in parameter type, order, or count.
3.​The return type does not matter in method overloading.
4.​Overloading makes programs cleaner, reusable, and flexible.

5. Java Scope
Scope in Java refers to where a variable or method can be accessed in a
program. It defines the visibility and lifetime of a variable.

In Java, there are four main types of scope:

1.​ Local Scope (Method-Level Scope)


2.​ Instance Scope (Object-Level Scope)
3.​ Static Scope (Class-Level Scope)
4.​ Block Scope (Loop or Conditional Scope)

1️⃣ Local Scope (Method-Level Scope)

A variable declared inside a method is local to that method. It cannot be accessed


outside the method.

🔹 Example of Local Scope


public class LocalScopeExample {
public void showMessage() {
String message = "Hello, Java!"; // Local variable
[Link](message);
}

public static void main(String[] args) {


LocalScopeExample localObj = new LocalScopeExample();
[Link]();

// [Link](message); ❌ ERROR: Cannot access local


variable outside its method.
}
}

📝 Key Points
✅ Local variables must be initialized before use.​
✅ They cannot be accessed outside the method where they are declared.​
✅ Their lifetime is only during method execution.

2️⃣ Instance Scope (Object-Level Scope)

Instance variables are declared inside a class but outside methods. They belong to an object
of the class and can be accessed through that object.

🔹 Example of Instance Scope


public class InstanceScopeExample {
int age = 25; // Instance variable (Object-level scope)

public void showAge() {


[Link]("Age: " + age); // Can be accessed within
methods
}

public static void main(String[] args) {


InstanceScopeExample person = new InstanceScopeExample();
[Link](); // Output: Age: 25
}
}

📝 Key Points
✅ Instance variables belong to an object, so each object has its own copy.​
✅ They can be accessed by all methods in the class.​
✅ Their lifetime is as long as the object exists.

3️⃣ Static Scope (Class-Level Scope)


Static variables belong to the class itself rather than a specific object. These variables are
shared by all instances of the class.

🔹 Example of Static Scope


public class StaticScopeExample {
static int count = 0; // Static variable (Class-level scope)

public void increaseCount() {


count++; // Shared across all objects
}

public static void main(String[] args) {


StaticScopeExample obj1 = new StaticScopeExample();
StaticScopeExample obj2 = new StaticScopeExample();

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

[Link]("Count: " + count); // Output: Count: 2


}
}

📝 Key Points
✅ Static variables belong to the class, not objects.​
✅ Shared among all objects of the class.​
✅ Access using
✅ Lifetime: Until the program ends.
[Link] (e.g., [Link]).​

4️⃣ Block Scope (Loop or Conditional Scope)

Variables declared inside a loop, if, or switch block are limited to that block.

🔹 Example of Block Scope


public class BlockScopeExample {
public static void main(String[] args) {
if (true) {
int num = 100; // Block-scoped variable
[Link]("Number: " + num);
}

// [Link](num); ❌ ERROR: Cannot access 'num'


outside the block
}
}

📝 Key Points
✅ Variables inside {} (loops, if, switch) are only accessible within that block.​
✅ Cannot be accessed outside the block where they were declared.
📝 Quick Summary Table
Scope Type Declared Inside Accessible Inside Lifetime
Local Scope Method Only inside the method Until method execution
ends
Instance Class (outside All methods of the class (using As long as the object
Scope methods) objects) exists
Static Scope Class (with static) All objects (shared variable) Until program ends

Block Scope {} (loops, if, switch) Only inside the block Until block execution
ends

🔹 When to Use Each Scope?


●​ Local variables → When data is needed only within a single method.
●​ Instance variables → When each object needs its own unique copy of the variable.
●​ Static variables → When a variable needs to be shared across all objects.
●​ Block-scoped variables → When a variable is needed only inside a loop or condition.

6. Java Recursion
Recursion is a programming technique where a method calls itself to solve a problem.
A recursive method must have:

1.​ Base Case → A condition that stops the recursion.


2.​ Recursive Case → A condition where the method calls itself with a modified
parameter.

🔹 Example of Recursion (Printing Numbers)


public class RecursionExample {
// Recursive method to print numbers from n to 1
public static void printNumbers(int n) {
if (n <= 0) { // Base case: Stop when n reaches 0
return;
}
[Link](n); // Print the number
printNumbers(n - 1); // Recursive call with n-1
}

public static void main(String[] args) {


printNumbers(5); // Output: 5 4 3 2 1
}
}

🔹 Factorial Using Recursion


public class FactorialExample {
// Recursive method to calculate factorial
public static int factorial(int n) {
if (n == 0 || n == 1) { // Base case: Factorial of 0 or 1 is 1
return 1;
}
return n * factorial(n - 1); // Recursive call
}

public static void main(String[] args) {


int result = factorial(5);
[Link]("Factorial of 5: " + result); // Output: 120
}
}
JAVA OOP PRINCIPLES
OOPs (Object-Oriented Programming)
Simula is considered the first object-oriented programming language. The
programming paradigm where everything is represented as an object is
known as a pure object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

OOPs (Object-Oriented Programming)


Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and
maintenance by providing some concepts:
○​ Object
○​ Class
○​ Inheritance
○​ Polymorphism
○​ Abstraction
○​ Encapsulation

Apart from these concepts, there are some other terms which are used in
Object-Oriented design:
○​ Coupling
○​ Cohesion
○​ Association
○​ Aggregation
○​ Composition

○​
Java Object
Any entity that has state and behavior is known as an object. For example, a chair, pen,
table, keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. It contains an address and takes up


some space in memory. Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of message accepted and the type
of response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.

Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object.
Class does not consume any space.

Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism in Java
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.

Abstraction
Hiding internal implementation and showing functionality only to the user is known as
abstraction. For example, phone call, we do not know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation in Java OOPs Concepts


Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.

A Java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises
when classes are aware of each other. If a class has the details information of another class,
there is strong coupling. In Java, we use private, protected, and public modifiers to display
the visibility level of a class, method, and field. We can use interfaces for the weaker
coupling because there is no concrete implementation.

Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A
single well-defined task is done by a highly cohesive method. The weakly cohesive method
will split the task into separate parts. The [Link] package is a highly cohesive package
because it has I/O related classes and interface. However, the [Link] package is a weakly
cohesive package because it has unrelated classes and interfaces.

Association
Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association between
the objects:

One to One
One to Many
Many to One, and
Many to Many
Let's understand the relationship with real-time examples. For example, a country can have
one prime minister (one to one), and a prime minister can have many ministers (one to
many). Also, many MP's can have one prime minister (many to one), and many ministers
can have many departments (many to many).

Association can be unidirectional or bidirectional.

Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where
one object contains other objects as a part of its state. It represents the weak relationship
between objects. It is also termed as a has-a relationship in Java. Like, inheritance
represents the is-a relationship. It is another way to reuse objects.

Composition
The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a strong
relationship between the containing object and the dependent object. It is the state where
containing objects do not have an independent existence. If we delete the parent object, all
the child objects will be deleted automatically.

// Demonstrating Java OOP Concepts above

// 1. Encapsulation: Wrapping data and methods into a single unit


class Animal {
private String name;
private String sound;

// Constructor
public Animal(String name, String sound) {
[Link] = name;
[Link] = sound;
}

// Getter methods (Encapsulation)


public String getName() {
return name;
}

public String getSound() {


return sound;
}

// Behavior method
public void makeSound() {
[Link](name + " says " + sound);
}
}

// 2. Inheritance: Dog class inherits from Animal class


class Dog extends Animal {
public Dog(String name) {
super(name, "Woof");
}
}

// 3. Polymorphism: Method Overriding


class Cat extends Animal {
public Cat(String name) {
super(name, "Meow");
}
}

// 4. Abstraction: Abstract class with an abstract method


abstract class Vehicle {
abstract void move();
}
// Subclass providing implementation
class Car extends Vehicle {
public void move() {
[Link]("Car moves on wheels");
}
}

// 5. Association: Person and Car have a relationship (Person owns a


Car)
class Person {
private String name;
private Car car; // One-to-One Association

public Person(String name, Car car) {


[Link] = name;
[Link] = car;
}

public void drive() {


[Link](name + " is driving the car.");
[Link]();
}
}

// 6. Aggregation: Company has employees, but they can exist


independently
class Employee {
private String name;

public Employee(String name) {


[Link] = name;
}

public void showDetails() {


[Link]("Employee Name: " + name);
}
}

class Company {
private String companyName;
private Employee[] employees;

public Company(String companyName, Employee[] employees) {


[Link] = companyName;
[Link] = employees;
}

public void showCompanyDetails() {


[Link]("Company: " + companyName);
for (Employee e : employees) {
[Link]();
}
}
}

// 7. Composition: Library contains Books, and Books cannot exist


without Library
class Book {
private String title;

public Book(String title) {


[Link] = title;
}

public void showTitle() {


[Link]("Book Title: " + title);
}
}

class Library {
private Book[] books; // Strong Relationship (Composition)

public Library(Book[] books) {


[Link] = books;
}

public void showLibraryBooks() {


for (Book book : books) {
[Link]();
}
}
}

// Main Class to demonstrate OOP Concepts


public class OOPDemo {
public static void main(String[] args) {
// Demonstrate Object and Class
Animal dog = new Dog("Buddy");
[Link]();

Animal cat = new Cat("Whiskers");


[Link]();

// Demonstrate Abstraction
Vehicle car = new Car();
[Link]();

// Demonstrate Association
Person person = new Person("John", new Car());
[Link]();

// Demonstrate Aggregation
Employee emp1 = new Employee("Alice");
Employee emp2 = new Employee("Bob");
Company company = new Company("TechCorp", new Employee[]{emp1,
emp2});
[Link]();

// Demonstrate Composition
Book book1 = new Book("Java Programming");
Book book2 = new Book("Data Structures");
Library library = new Library(new Book[]{book1, book2});
[Link]();
}
}
JAVA CLASS
JAVA CLASS
A class in Java is a blueprint for creating objects. It defines:

●​ Attributes (Instance Variables) → Data that each object holds.


●​ Methods (Behaviors) → Actions that objects can perform.

In the Code Above:

1.​ Class Definition (Person)


○​ String name; → Stores the person's name.
○​ int age; → Stores the person's age.
○​ Person(String personName, int personAge) { ... } → A
constructor to initialize objects.
○​ void introduce() { ... } → A method that prints a greeting.
2.​ Creating Objects (Main class)
○​ Inside main(), two objects (person1 and person2) are created using new
Person(...).
○​ Each object stores different data but uses the same class structure.

Class vs. Object

●​ Class → A template (like a blueprint for making houses).


●​ Objects → The actual things built using the template (actual houses with different
colors, sizes, etc.).

Example Code of a Class


// Defining a simple class
class Car {
// Attributes (state)
String brand;
int speed;
}

Class with Methods (No Objects)


// Defining a class with methods
class Car {
// Attributes
String brand;
int speed;
// Method to display car details
void showDetails() {
[Link]("Brand: " + brand);
[Link]("Speed: " + speed + " km/h");
}
}

The class has a method, but since no objects are created, the method will not execute.

Class with Constructor (No Objects)


// Class with a constructor
class Car {
String brand;
int speed;

// Constructor to initialize attributes


Car(String brandX, int speedX) {
[Link] = brandX;
[Link] = speedX;
}
}

The constructor is ready to initialize objects, but no object is created yet.

Class with Static Method (No Objects)


// Class with a static method
class Car {
// Static method that belongs to the class
static void carInfo() {
[Link]("A car is a vehicle for transportation.");
}
}

What is a Static Method in Java?


A static method in Java is a method that belongs to the class itself, rather than to any
specific object of the class. This means:

●​ You can call it without creating an object of the class.


●​ It shares the same memory for all instances.
●​ It cannot access non-static (instance) variables or methods directly.

// Class with a static method


class Car {
// Static method that belongs to the class
static void carInfo() {
[Link]("A car is a vehicle for transportation.");
}
}

// Main class to execute the program


public class Main {
public static void main(String[] args) {
// Calling the static method without creating an object
[Link]();
}
}

Demonstrating void, int, String,Return Return Types


// Defining a class to demonstrate method types
class Car {
String brand;
int speed;

// 1. Method with `void` (Performs an action but returns


nothing)
void showDetails() {
[Link]("Brand: " + brand);
[Link]("Speed: " + speed + " km/h");
}

// 2. Method that returns an `int` (Returns the car's speed)


int getSpeed() {
return speed; // Returning an integer value
}

// 3. Method that returns a `String` (Returns formatted car


details)
String getDetails() {
return "Brand: " + brand + ", Speed: " + speed + " km/h";
}

// 4. Method that returns an `Object` (Returns the car itself


for chaining)
Car increaseSpeed(int value) {
[Link] += value; // Increasing speed
return this; // Returning the current object
}
}

// Main// Main class to execute the program class to run the program
public class Main {
public static void main(String[] args) {
// Creating a car object
Car myCar = new Car();
[Link] = "Toyota";
[Link] = 120;

// Calling the `void` method (prints directly, no return


value)
[Link]("Calling showDetails():");
[Link]();

// Calling the method that returns an `int` (stores the


value)
int carSpeed = [Link]();
[Link]("\nCalling getSpeed(): Car speed is " +
carSpeed + " km/h");

// Calling the method that returns a `String` (stores and


prints)
String details = [Link]();
[Link]("\nCalling getDetails(): " + details);

// Calling the method that returns an Object (allows method


chaining)
[Link]("\nCalling increaseSpeed(30):");
[Link](30).showDetails(); // Increases speed
and shows details
}
}

📌 Output of the Code above


Calling showDetails():
Brand: Toyota
Speed: 120 km/h

Calling getSpeed(): Car speed is 120 km/h

Calling getDetails(): Brand: Toyota, Speed: 120 km/h

Calling increaseSpeed(30):
Brand: Toyota
Speed: 150 km/h
JAVA OBJECTS
JAVA OBJECTS
Object-Oriented Programming or Java OOPs concept refers to programming languages that
use objects in programming.

In Java, an object is an instance of a class that contains both state (attributes/fields) and
behavior (methods/functions). Objects are the fundamental building blocks of Java's
Object-Oriented Programming (OOP) paradigm.

Key Characteristics of Java Objects:

1.​ State (Attributes/Fields) – Objects have data stored in fields (variables within a
class).
2.​ Behavior (Methods) – Objects have functions (methods) that define their behavior.
3.​ Identity – Each object is uniquely identified by its memory address.

Creating an Object in Java

Objects are created from classes using the new keyword.

Example 1

// Defining a class named Person


class Person {
// Attributes (Instance variables)
String name;
int age;

// Constructor to initialize the object


Person(String personName, int personAge) {
[Link] = personName; // Assigning the parameter value to the
instance variable
[Link] = personAge;
}

// Method to display details


void introduce() {
[Link]("Hello! My name is " + name + " and I am " +
age + " years old.");
}
}
// Main class to run the program
public class Main {
public static void main(String[] args) {
// Creating four objects of the Person class
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Prime", 300);
Person person2 = new Person("YY", 70);
Person person2 = new Person("Bob", 80);

// Calling the method to display details for all objects


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

Output

Hello! My name is Alice and I am 25 years old.


Hello! My name is Prime and I am 300 years old.
Hello! My name is YY and I am 70 years old.
Hello! My name is Bob and I am 80 years old.

Example 2

// Defining a class named Car


class Car {
// Attributes (State) - These store the properties of the car
String brand; // The brand of the car (e.g., Toyota, BMW)
int speed; // The speed of the car in km/h

// Parameterized Constructor to initialize the object with given


brand and speed
Car(String brandX, int speedX) {
[Link] = brandX; // '[Link]' refers to the instance
variable, 'brandX' is the constructor parameter
[Link] = speedX; // '[Link]' refers to the instance
variable, 'speedX' is the constructor parameter
}

// Method (Behavior) - This function increases the speed of the car


void accelerate() {
speed += 10; // Increases speed by 10 km/h
[Link](brand + " is moving at " + speed + "
km/h."); // Prints updated speed
}
}

// Main class - This is where the program starts execution


public class Main {
public static void main(String[] args) {
// Creating an object of the Car class with brand "Toyota" and
initial speed of 50 km/h
Car myCar = new Car("Toyota", 50);

// Accessing object properties and printing them


[Link]("Brand: " + [Link]); // Displays the
brand of the car
[Link]("Speed: " + [Link]); // Displays the
initial speed

// Calling a method to accelerate the car


[Link](); // Increases the speed and prints the
updated speed
}
}

Output
Brand: Toyota
Speed: 50
Toyota is moving at 60 km/h.
Instance Variable Belongs to the object ([Link]). Used across the class.
brandX is a Local Parameter and Only exists inside the constructor.

What is a Constructor in Java?

A constructor is a special method in Java that is used to initialize objects. It is automatically


called when an object of a class is created. The constructor's main purpose is to set initial
values for an object’s attributes.

Key Features of a Constructor:

1.​ Same Name as Class – A constructor must have the same name as the class.
2.​ No Return Type – Unlike methods, constructors do not have a return type (not even
void).
3.​ Called Automatically – It is called when an object is instantiated using the new
keyword.
4.​ Types of Constructors:
○​ Default Constructor (No parameters)
○​ Parameterized Constructor (With parameters)
○​ Constructor Overloading (Multiple constructors in the same class)

Why Use Constructors?

●​ Automatically initializes objects when created.


●​ Avoids manually setting values for every new object.
●​ Helps in enforcing required fields when creating an object.

Example : Constructor Overloading (Multiple Constructors)


class Car {
String brand;
int speed;

// Default Constructor
Car() {
brand = "Unknown";
speed = 0;
}

// Parameterized Constructor
Car(String bb, int ss) {
brand = bb;
speed = ss;
}

void display() {
[Link]("Brand: " + brand + ", Speed: " + speed + " km/h");
}
}

public class Main {


public static void main(String[] args) {
Car car1 = new Car(); // Calls default constructor
Car car2 = new Car("Mercedes", 80); // Calls parameterized
constructor

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

OutPut :
Brand: Unknown, Speed: 0 km/h
Brand: Mercedes, Speed: 80 km/h
JAVA INHERITANCE
JAVA INHERITANCE
1. What is Inheritance?

Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows


one class to inherit the properties and behaviors of another class. The class that is inherited
from is called the parent (superclass/base class), and the class that inherits is called the
child (subclass/derived class).

2. Benefits of Inheritance

●​ Code Reusability: Avoids redundancy by reusing existing code.


●​ Method Overriding: Allows modifying behavior of inherited methods.
●​ Extensibility: New functionalities can be added easily.
●​ Better Organization: Helps structure code hierarchically.

Types of Inheritance in Java


Java supports the following types of inheritance:

1. Single Inheritance
A class inherits from only one superclass.
// Parent class (SuperClass)
class Animal {
void makeSound() {
[Link]("Animals make different sounds.");
}
}

// Child class (SubClass)


class Dog extends Animal {
void bark() {
[Link]("Dog barks.");
}
}

// Main Class
public class SingleInheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Inherited method
[Link](); // Own method
}

}
Explanation:
Dog class inherits the makeSound() method from Animal, so it can use it along with its
own method bark().

Output:
Animals make different sounds.
Dog barks.

2. Multilevel Inheritance

A chain of inheritance where a class is derived from another derived class.

// Parent class
class Animal {
void eat() {
[Link]("Animals eat food.");
}
}

// Child class inheriting Animal


class Mammal extends Animal {
void warmBlooded() {
[Link]("Mammals are warm-blooded.");
}
}

// Grandchild class inheriting Mammal


class Human extends Mammal {
void speak() {
[Link]("Humans can speak.");
}
}

// Main class
public class MultilevelInheritanceExample {
public static void main(String[] args) {
Human person = new Human();
[Link](); // Inherited from Animal
[Link](); // Inherited from Mammal
[Link](); // Own method
}
}

Explanation: The Human class inherits from Mammal, which in turn inherits from Animal.
This demonstrates multilevel inheritance.
Output

Animals eat food.


Mammals are warm-blooded.
Humans can speak.

3. Hierarchical Inheritance

Multiple child classes inherit from the same parent class.

// Parent class
class Vehicle {
void start() {
[Link]("Vehicle is starting...");
}
}

// Child class 1
class Car extends Vehicle {
void speedUp() {
[Link]("Car is speeding up.");
}
}

// Child class 2
class Bike extends Vehicle {
void wheelie() {
[Link]("Bike is doing a wheelie.");
}
}

// Main class
public class HierarchicalInheritanceExample {
public static void main(String[] args) {
Car myCar = new Car();
[Link](); // Inherited method
[Link](); // Own method

Bike myBike = new Bike();


[Link](); // Inherited method
[Link](); // Own method
}
}

Explanation: Both Car and Bike inherit the start() method from Vehicle but also have
their unique behaviors.

Output:
Vehicle is starting...
Car is speeding up.
Vehicle is starting...
Bike is doing a wheelie.

4. Multiple Inheritance (via Interfaces)

Java does not support multiple inheritance with classes to avoid the diamond problem.
However, multiple inheritance is possible using interfaces.

// First interface
interface Flyable {
void fly();
}

// Second interface
interface Swimmable {
void swim();
}

// Class implementing multiple interfaces


class Duck implements Flyable, Swimmable {
public void fly() {
[Link]("Duck can fly.");
}

public void swim() {


[Link]("Duck can swim.");
}
}

// Main class
public class MultipleInheritanceExample {
public static void main(String[] args) {
Duck duck = new Duck();
[Link]();
[Link]();
}
}

Explanation: The Duck class implements two interfaces, Flyable and Swimmable,
demonstrating multiple inheritance.

Output:

Duck can fly.


Duck can swim.
Method Overriding in Inheritance
When a subclass provides a specific implementation of a method that is already defined in
its superclass, it is called method overriding.

// Parent class
class Animal {
void makeSound() {
[Link]("Animals make sounds.");
}
}

// Child class overriding method


class Cat extends Animal {
@Override
void makeSound() {
[Link]("Cat meows.");
}
}

// Main class
public class MethodOverridingExample {
public static void main(String[] args) {
Animal myAnimal = new Animal();
[Link](); // Calls the parent class method

Cat myCat = new Cat();


[Link](); // Calls the overridden method in the child
class
}
}

Explanation: The Cat class provides its own version of the makeSound() method,
overriding the one in Animal.

Output:

Animals make sounds.


Cat meows.
Using super Keyword in Inheritance
The super keyword is used to refer to the immediate parent class.

// Parent class
class Animal {
void makeSound() {
[Link]("Animal makes a sound.");
}
}

// Child class
class Dog extends Animal {
void makeSound() {
[Link](); // Calls the parent method
[Link]("Dog barks.");
}
}

// Main class
public class SuperKeywordExample {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
}
}

Explanation: The [Link]() calls the parent class’s makeSound() method


before executing its own implementation.

Output:

Animal makes a sound.


Dog barks.

Conclusion
●​ Inheritance allows code reuse and better organization.
●​ Different types of inheritance include single, multilevel, hierarchical, and multiple (via
interfaces).
●​ Method overriding allows modifying inherited methods.
●​ The super keyword helps access parent class methods and constructors.
JAVA POLYMORPHISM
JAVA POLYMORPHISM
What is Polymorphism?
Polymorphism is an important concept in Object-Oriented Programming (OOP) that allows a
single interface to be used for different data types. In Java, polymorphism enables a single
method, function, or operator to perform different tasks based on the object that calls it.

Types of Polymorphism in Java

1.​ Compile-time Polymorphism (Method Overloading)


2.​ Runtime Polymorphism (Method Overriding)

1. Compile-time Polymorphism (Method Overloading)


Compile-time polymorphism occurs when multiple methods in the same class have the same
name but different parameters (method signatures). The method to be executed is
determined at compile time.

Example: Method Overloading


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

// Method with three integer parameters


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

// Method with double parameters


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

public class MethodOverloadingExample {


public static void main(String[] args) {
MathOperations math = new MathOperations();

[Link]("Sum of 2 and 3: " + [Link](2, 3));


[Link]("Sum of 2, 3, and 4: " + [Link](2, 3, 4));
[Link]("Sum of 2.5 and 3.5: " + [Link](2.5,
3.5));
}
}

Explanation:
●​ The add() method is overloaded with different parameters.
●​ The appropriate method is selected at compile time based on the number and type
of arguments.

Output:
Sum of 2 and 3: 5
Sum of 2, 3, and 4: 9
Sum of 2.5 and 3.5: 6.0

2. Runtime Polymorphism (Method Overriding)


Runtime polymorphism occurs when a subclass provides a specific implementation of a
method that is already defined in its superclass. The method to be executed is determined at
runtime.

Example: Method Overriding


// Parent class
class Animal {
void makeSound() {
[Link]("Animals make sounds.");
}
}

// Child class overriding the method


class Dog extends Animal {
@Override
void makeSound() {
[Link]("Dog barks.");
}
}

// Another child class overriding the method


class Cat extends Animal {
@Override
void makeSound() {
[Link]("Cat meows.");
}
}

// Main class
public class MethodOverridingExample {
public static void main(String[] args) {
Animal myAnimal; // Reference of parent class

myAnimal = new Dog();


[Link](); // Calls Dog's method

myAnimal = new Cat();


[Link](); // Calls Cat's method
}
}

Explanation:
●​ The makeSound() method is overridden in Dog and Cat.
●​ The method call is resolved at runtime based on the actual object.

Output:
Dog barks.
Cat meows.

Key Differences Between Overloading & Overriding

Feature Method Overloading Method Overriding

Definition Multiple methods with the same A method in a child class with the
name but different parameters in same signature as in the parent
the same class. class.
Binding Compile-time (Static binding) Runtime (Dynamic binding)

Parameters Must be different (either in Must be the same


number, type, or order)

Return Type Can be different Must be the same or covariant

Access No restrictions Cannot reduce visibility (e.g.,


Modifiers public method in parent cannot
become private in child)
Final/Static Can be overloaded Cannot be overridden
Methods
Polymorphism and Interfaces
Java interfaces also support polymorphism by allowing different classes to implement the
same interface in their own way.

Example: Polymorphism with Interfaces


// Interface
interface Animal {
void makeSound();
}

// Dog implements Animal interface


class Dog implements Animal {
public void makeSound() {
[Link]("Dog barks.");
}
}

// Cat implements Animal interface


class Cat implements Animal {
public void makeSound() {
[Link]("Cat meows.");
}
}

// Main class
public class InterfacePolymorphismExample {
public static void main(String[] args) {
Animal myAnimal;

myAnimal = new Dog();


[Link]();

myAnimal = new Cat();


[Link]();
}
}

Explanation:

●​ The Animal interface provides a contract for different classes.


●​ Both Dog and Cat implement makeSound() differently, demonstrating polymorphism.

Output:
Dog barks.
Cat meows.
Polymorphism and Upcasting
Upcasting refers to treating a subclass object as an instance of its superclass.

Example: Upcasting
class Animal {
void makeSound() {
[Link]("Animal makes a sound.");
}
}

class Dog extends Animal {


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

public class UpcastingExample {


public static void main(String[] args) {
Animal myAnimal = new Dog(); // Upcasting
[Link](); // Calls Dog's overridden method
}
}

Explanation:
●​ Even though myAnimal is of type Animal, it refers to a Dog object.
●​ Method Overriding ensures that Dog’s makeSound() is called instead of
Animal’s.

Output:
Dog barks.

Polymorphism in Java Collections


Java collections often use polymorphism to store different types of objects in a generic way.

Example: Using Polymorphism in an ArrayList


import [Link];

class Animal {
void makeSound() {
[Link]("Some animal sound.");
}
}

class Dog extends Animal {


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

class Cat extends Animal {


void makeSound() {
[Link]("Cat meows.");
}
}

public class CollectionPolymorphismExample {


public static void main(String[] args) {
ArrayList<Animal> animals = new ArrayList<>();
[Link](new Dog());
[Link](new Cat());

for (Animal animal : animals) {


[Link]();
}
}
}

Explanation:
●​ The ArrayList<Animal> stores different types of Animal objects.
●​ Polymorphism ensures that the correct method is called at runtime.

Output:
Dog barks.
Cat meows.

Advantages of Polymorphism

✅ Code Reusability – The same method can work with different types of objects.​

✅ Scalability – New classes can be easily added with minimal changes.​

✅ Flexibility – Methods can behave differently based on object type.​


Better Maintainability – Enhances code readability and organization.
Conclusion
●​ Polymorphism allows methods to have multiple implementations based on
context.
●​ Method Overloading happens at compile-time, while Method Overriding
happens at runtime.
●​ Interfaces and Upcasting support polymorphism in Java.
●​ Polymorphism enhances flexibility and maintainability of code.
JAVA ABSTRACTION
JAVA ENCAPSULATION

You might also like