Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 121

Java Concepts

Objects

Objects are instances of classes. They have state


and behavior.

For example, a car object can have a color, a


model, and a speed, and it can perform actions
such as accelerating or braking.
Classes
Classes are blueprints or templates for creating
objects. They define the properties and methods
that objects of that class will have.

For example, a car class can define the properties of


a car, such as its color and model, and the methods
that it can perform, such as accelerating or braking.
Abstraction
Abstraction is the process of hiding the
implementation details of a system and only
exposing the essential features to the user.

In OOP, abstraction is achieved using abstract


classes or interfaces. For example, a vehicle class
can be abstract, and its subclasses, such as car
or truck, can provide the specific
implementation details.
Encapsulation
Encapsulation is the practice of hiding the internal
details of an object and only exposing a public
interface that can be used to interact with the
object.

In OOP, encapsulation is achieved by defining


private and public methods and properties. For
example, a car object can have private properties
such as the engine type and public methods such as
accelerating or braking.
Inheritance
Inheritance is the mechanism by which a subclass
can inherit properties and methods from its
superclass.

It enables code reuse and promotes modularity. In


OOP, inheritance is achieved by using the "extends"
keyword to create a subclass of a superclass.

For example, a car class can inherit properties and


methods from a vehicle superclass.
Polymorphism
Polymorphism is the ability of an object to take on
many forms. In OOP, polymorphism is achieved by
using overriding methods.

For example, a car object can have a "drive"


method that can be overridden by its subclasses to
provide different implementations.

This enables the car object to take on different


forms, such as a sports car or a family sedan.
Introduction to OOPs in Java
Object-Oriented Programming (OOP) is a
programming paradigm that focuses on
organizing code into objects that have data and
behavior.

Java is a popular programming language that


supports OOP concepts.
Introduction to OOPs in Java
In Java, everything is an object, including
classes, methods, and variables.
A class is a blueprint or a template that
describes the properties and behaviors of an
object.
A method is a collection of instructions that
perform a specific task.
A variable is a container that holds a value.
Introduction to OOPs in Java

To create an object in Java, you first need to


define a class.

Here is an example of a simple class definition:


Introduction to OOPs in Java
public class Person {
private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public String getName() {


return this.name;
}

public int getAge() {


return this.age;
}
}
Introduction to OOPs in Java
In the above example, we have defined a class called
Person. The class has two private instance variables,
name and age. We have also defined a constructor, which
is a special method that is called when an object is
created. The constructor takes two parameters, name and
age, and sets the values of the instance variables.

We have also defined two getter methods, getName and


getAge, which allow us to access the values of the
instance variables from outside the class.
Introduction to OOPs in Java
To create an object of the Person class, we can use
the new keyword

Person person = new Person("John", 30);

In the above example, we have created a new


Person object and assigned it to the variable
person. We have passed the values "John" and 30
to the constructor, which sets the name and age
instance variables of the Person object.
Introduction to OOPs in Java
We can now use the getName and getAge
methods to access the values of the instance
variables

System.out.println(person.getName()); // Output: John


System.out.println(person.getAge()); // Output: 30

This is just a basic example of how OOP works in Java


Characteristics of Java
Object-oriented:
Java is an object-oriented programming
language. Everything in Java is an object, which
simplifies programming and makes it easier to
maintain code.
Characteristics of Java
Platform independent:
Java code is compiled into an intermediate
bytecode that can run on any platform that has
a Java Virtual Machine (JVM) installed, which
makes Java programs platform independent.
Characteristics of Java
Memory management:
Java provides automatic memory management,
which means that the programmer doesn't have
to worry about memory allocation and
deallocation. The JVM takes care of allocating
and deallocating memory as needed.
Characteristics of Java
Robustness:
Java is designed to be robust and fault-tolerant.
It has a strict type checking system that prevents
many programming errors at compile time, and
it also includes features like exception handling
and garbage collection that help prevent crashes
and memory leaks.
Characteristics of Java
Security:
Java includes a number of built-in security
features that make it a popular choice for
building secure applications. For example, Java's
sandbox security model allows untrusted code
to run securely within a restricted environment.
Characteristics of Java
Multi-threading:
Java supports multi-threading, which allows
multiple threads of execution to run
simultaneously within a single program.
Characteristics of Java
Large standard library:
Java comes with a large standard library of
classes and methods that make it easy to
perform many common programming tasks
without having to write custom code.
Characteristics of Java
Overall, Java's combination of platform
independence, automatic memory
management, robustness, and security make it a
popular choice for building a wide range of
applications, from web and mobile apps to
enterprise software and embedded systems.
Java Environment
The Java environment refers to the software and
tools necessary for developing and running Java
applications.

It includes three main components: the Java


Development Kit (JDK), the Java Runtime
Environment (JRE), and the Java Virtual Machine
(JVM).
Java Environment
1. Java Development Kit (JDK): The JDK is a
software package that provides the necessary
tools, libraries, and compilers for Java
development.
It includes the Java compiler (javac) for
compiling Java source code into bytecode, as
well as various development utilities and
libraries.
Java Environment
2. Java Runtime Environment (JRE): The JRE is a
runtime environment that allows you to run Java
applications.
It includes the JVM, libraries, and other
components necessary to execute Java
bytecode.
Java Environment
3. Java Virtual Machine (JVM): The JVM is an
integral part of the Java platform. It is
responsible for executing Java bytecode and
providing a runtime environment for Java
applications.
The JVM translates bytecode into machine-
specific instructions and handles memory
management, garbage collection, and other
runtime tasks.
Java Environment
The Java environment also includes additional
tools and frameworks, such as Integrated
Development Environments (IDEs) like Eclipse,
IntelliJ IDEA, and NetBeans, which provide
advanced features for Java development,
debugging, and testing.
Overall, the Java environment provides
developers with the necessary tools and
infrastructure to write, compile, and run Java
applications across different platforms.
Java Source File Structure and
Compilation
The compilation process in Java involves several
steps:

Writing the code: The first step is to write the


Java code using a text editor or an Integrated
Development Environment (IDE).

Saving the code: The next step is to save the


code with a .java extension.
Java Source File Structure and
Compilation
Compilation:
The code is then compiled using the Java
compiler, which converts the source code into
bytecode.
The bytecode is a platform-independent
representation of the code that can be run on
any machine that has a Java Virtual Machine
(JVM) installed.
Java Source File Structure and
Compilation
Bytecode generation: The compiled bytecode is
saved in a .class file.

Execution: Finally, the bytecode is executed by


the JVM, which converts it into machine code
and runs it on the host system.
Java Source File Structure and
Compilation
To compile the program, type the following
command and press Enter:

javac filename.java

Replace filename with the actual name of your Java


file.
This will create a .class file in the same directory as
your .java file.
Java Source File Structure and
Compilation
To execute the program, type the following
command and press Enter:

java filename

Replace filename with the actual name of your Java


file (without the .java or .class extension).

This will run your Java program and output the


results to the terminal/command prompt.
Java Source File Structure and
Compilation
Package declaration (optional): The package declaration is
the first line of a Java source file, which specifies the
name of the package to which the class belongs. The
package name should be a unique identifier that reflects
the organization or the project structure.

Import statements (optional): The import statements are


used to import classes from other packages into the
current source file. These statements come after the
package declaration and before the class declaration.
Java Source File Structure and
Compilation
Class declaration (required): A Java source file can
contain only one public class declaration. The class
name should match the file name (excluding the
".java" extension).

A class declaration consists of the keyword "class"


followed by the class name, and the class body,
which contains the class variables and methods.
Java Source File Structure and
Compilation
Class variables (optional): The class variables are declared
within the class body and are accessible to all methods of
the class.

Methods (optional): The methods are declared within the


class body and define the behavior of the class.

Comments (optional): Comments can be added to the


Java source code to document the code, explain its
behavior, and make it more readable. Comments can be
single-line or multi-line and are ignored by the Java
compiler.
Java Source File Structure and
Compilation
package com.example;

import java.util.Scanner;

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Defining Classes in Java
Define a class in Java, you can follow the below steps:

Open a text editor or an integrated development


environment (IDE) such as Eclipse, IntelliJ IDEA, or
NetBeans.

Create a new Java file and name it after your class,


making sure to use the .java extension. For example, if
your class is named "Car", name your file "Car.java".
Defining Classes in Java
Begin your class definition by typing "public class"
followed by the name of your class, using CamelCase
naming convention. For example, "public class Car".

Inside the curly braces that follow your class name,


define the properties of your class using instance
variables. For example, "private String make;" and
"private int year;".
Defining Classes in Java
Define the behavior of your class using methods, which
are also declared inside the curly braces that follow
your class name. For example, "public void start() {}"
and "public void accelerate() {}".

Optionally, you can define constructors to instantiate


your class and set its initial values. For example, "public
Car(String make, int year) {}".

Save your Java file.


Defining Classes in Java
public class Car {
private String make;
private int year;

public Car(String make, int year) {


this.make = make;
this.year = year;
}

public void start() {


System.out.println("The car is starting.");
}

public void accelerate() {


System.out.println("The car is accelerating.");
}
}
This code defines a Car class with two instance variables (make and year), a constructor, and
two methods (start and accelerate).
Constructors and their use in Java classes

In Java, a constructor is a special method that is called when an


object of a class is created. The purpose of a constructor is to
initialize the object's state, which typically involves setting values
for the object's fields or variables.

Constructors have the same name as the class they belong to


and do not have a return type (not even void). They can take
parameters or have no parameters at all, depending on what
needs to be initialized. If a constructor does not explicitly declare
any parameters, it is called the default constructor
Constructors and their use in Java classes

public class Person {


String name;
int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}
}
Constructors and their use in Java classes

In the above example, we have a class called


Person with two instance variables name and
age.

We also have a constructor that takes two


parameters, name and age, and initializes the
name and age instance variables with the values
passed in.
Constructors and their use in Java classes

To create an object of the Person class using the


constructor, we can use the new keyword and
pass in the necessary parameters:

Person person1 = new Person("John", 30);

This will create a new Person object with the name "John" and
age 30, and assign it to the person1.
Methods in Java classes

To create a method in a Java class, you need to


specify the method name, return type (if any),
and the list of parameters it accepts (if any). The
method body contains the code that executes
when the method is called.
Methods in Java classes

Here's an example of a simple method in Java:

public class ExampleClass {


public void printMessage(String message) {
System.out.println(message);
}
}
Methods in Java classes
In the above example, we've defined a method
called printMessage that accepts a single
parameter of type String and returns nothing
(void). The method body simply prints the
message to the console.
Methods in Java classes
To call this method, you need to create an
instance of the class and then call the method
on that instance:
ExampleClass example = new ExampleClass();
example.printMessage("Hello, world!");

In the above example, we've created an instance of


ExampleClass and assigned it to the variable example. We then
called the printMessage method on that instance and passed it
the string "Hello, world!" as an argument.
Methods in Java classes
You can also pass multiple arguments to a
method by separating them with commas:
public class ExampleClass {
public int addNumbers(int a, int b) {
return a + b;
}
}

ExampleClass example = new ExampleClass();


int sum = example.addNumbers(2, 3); // sum = 5
Methods in Java classes
In this example, we've defined a method called
addNumbers that accepts two integer parameters and
returns their sum.

We then created an instance of ExampleClass and


called the addNumbers method on it, passing it the
values 2 and 3.

The method returns the sum of these two values,


which we've assigned to the variable sum.
Access Specifiers and Static Members
Java has four access specifiers: public, protected,
default (also known as package-private), and private.
Each access specifier has a different level of visibility.

Public: The public access specifier is the most


permissive access level. A public class, method, or
variable can be accessed from anywhere in the code,
including outside of the class hierarchy. For example, a
public method in a class can be called from any other
class, regardless of its package.
Access Specifiers and Static Members
Protected: The protected access specifier allows access
to the class, method, or variable from within the same
package or subclasses of the class, even if they are in a
different package. A protected method or variable
cannot be accessed by code outside the class hierarchy.

Private: The private access specifier is the most


restrictive access level. A private class, method, or
variable can be accessed only from within the same
class. It cannot be accessed from outside the class, not
even by subclasses.
Access Specifiers and Static Members
Default: The default access specifier, also known
as package-private, allows access only within the
same package.
If a class, method, or variable is declared with
the default access specifier, it is accessible only
within the same package.
It cannot be accessed from outside the package,
even by subclasses of the class.
Access Specifiers and Static Members
The choice of access specifier depends on the
requirements of the program design.

Public access specifiers are typically used for interfaces


and methods that need to be accessed from multiple
packages, while private access specifiers are used for
methods that are only used within the class.

Protected and default access specifiers are used for


classes or methods that need to be accessed only by
subclasses or within the same package.
Access Specifiers and Static Members
In Java, static members are associated with a class
rather than with an instance of the class. This means
that static members can be accessed without creating
an object of the class.

To declare a static member variable in a Java class, you


can use the "static" keyword in the variable declaration.
Access Specifiers and Static Members
For example:
public class MyClass {
static int myStaticVariable = 0;
}
To access the static variable from outside the
class, you can use the class name followed by
the variable name, like this:

int x = MyClass.myStaticVariable;
Access Specifiers and Static Members
To declare a static method in a Java class, you
can use the "static" keyword in the method
declaration. For example:

public class MyClass {


static void myStaticMethod() {
// Code here
}
}
Access Specifiers and Static Members
To call a static method from outside the class,
you can use the class name followed by the
method name, like this:

MyClass.myStaticMethod();

It's important to note that static members are shared


across all instances of a class, and their values are
stored in memory for the entire lifetime of the
program.
Non-Access Modifiers
• static: Can be accessed without creating an
instance of the class.
• final: The value of the variable cannot be
changed once it is assigned. It can be applied
to method and class also.
• abstract: Used to declare abstract classes and
methods that have no implementation and
must be implemented by a subclass.
Non-Access Modifiers
• synchronized: Ensures that only one thread
can access the method at a time.
• transient: The value of the variable will not be
saved during serialization.
• volatile: Used for variables that may be
accessed by multiple threads to ensure that
the value is always up-to-date.
Strictfp Modifier
• strictfp: Used for floating-point calculations to
ensure that they are performed identically on
all platforms.
Comments, Data Types and Variables in Java
Comments in Java code are important for several
reasons:
Code Readability: Comments help make the code more
readable and understandable for other developers
who might be working on the project. It makes it easier
for them to understand what each section of code is
doing and how it fits into the larger picture.

Code Debugging: Comments can be helpful when


debugging the code. They can help the developer
identify the source of a problem more quickly and
easily.
Comments, Data Types and Variables in Java

Code Maintenance: Comments make it easier to


maintain and update the code in the future. If someone
needs to make changes to the code, they can easily
understand what each section of code is doing and why
it is there.
Code Collaboration: Comments make it easier for
multiple developers to collaborate on a project. They
can communicate with each other about what each
section of code is doing, and this can help prevent
misunderstandings or mistakes.
Comments, Data Types and Variables in Java

Different types of comments in Java and their use:


In Java, there are two main types of comments ,single-
line comments and multi-line comments.

Single-line comments: Single-line comments start with


// and are used to make a comment on a single line.
They are often used to explain what is happening in the
code and provide context to the reader. Single-line
comments are ignored by the compiler and are not
included in the compiled code.
Comments, Data Types and Variables in Java

// This is a single-line comment


int x = 5; // This line declares a variable and assigns it
the value 5

Multi-line comments: Multi-line comments start with


/* and end with */. They can span multiple lines and
are used to comment on a larger block of code. Multi-
line comments are also ignored by the compiler and are
not included in the compiled code.
Comments, Data Types and Variables in Java

/*
This is a multi-line comment
It can span multiple lines
and is often used to provide detailed explanations of
code
*/
int x = 5; // This line declares a variable and assigns it the value 5
It is important to use comments in your code to make it
easier to understand and maintain.
Comments, Data Types and Variables in Java
Understanding data types in Java:
Primitive data types:
byte: 8-bit integer.
short: 16-bit integer.
int: 32-bit integer.
long: 64-bit integer.
float: 32-bit floating-point number.
double: 64-bit floating-point number.
char: 16-bit Unicode character.
boolean: true/false value
Comments, Data Types and Variables in Java

Reference data types:


Class: Used to create objects that can contain multiple data types.

String: Used to store a sequence of characters.

Array: Used to store multiple values of the same data type.

Interface: Used to define a set of methods that a class must


implement.

Enumeration: Used to define a set of named constants.


Comments, Data Types and Variables in Java

enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY,


FRIDAY, SATURDAY, SUNDAY }

DayOfWeek today = DayOfWeek.MONDAY;


System.out.println("Today is " + today);

In the above example, we define an enumeration DayOfWeek that


lists the days of the week. We then assign the value
DayOfWeek.MONDAY to a variable called today, and print out a
message that includes the value of today. The output of this
program would be:
Today is MONDAY
Comments, Data Types and Variables in Java
When declaring a variable, you must specify its data
type. For example:
int myAge = 25;
String myName = "John";
double mySalary = 50000.00;
You can also convert data types using casting. For
example:
int myAge = 25;
double myDoubleAge = (double) myAge;
In the above example, the myAge variable is cast as a double to create the
myDoubleAge variable, which stores the same value as myAge but as a
double.
Comments, Data Types and Variables in Java

Declaring and initializing variables in Java


In Java, you can declare and initialize variables using
the following syntax:
data_type variable_name = value;

Here, data_type refers to the type of data the variable


will hold, such as int, double, float, String, etc. The
variable_name is the name you want to give to your
variable, and value is the initial value that you want to
assign to the variable.
Comments, Data Types and Variables in Java

For example,
if you want to declare and initialize an integer variable
named age with an initial value of ’25’, you would use
the following code:
int age = 25;
If you want to declare and initialize a string variable
named name with an initial value of "John", you would
use the following code:
String name = "John";
Comments, Data Types and Variables in Java

You can also declare multiple variables of the same


data type in a single line by separating them with a
comma, like this:

int num1 = 10, num2 = 20, num3 = 30;

Keep in mind that once you declare a variable, you can


assign a new value to it later in your code.
Comments, Data Types and Variables in Java
Working with primitive and reference data types in Java:
Java is a strongly typed programming language, which
means that all variables must be declared with a specific
data type before they can be used.
There are two main categories of data types in Java:
primitive types and reference types.
Primitive data types are the basic building blocks of data
in Java. They are predefined by the language and have a
fixed size and range of values. There are eight primitive
data types in Java:
Comments, Data Types and Variables in Java

• byte: 8-bit signed integer (-128 to 127)


• short: 16-bit signed integer (-32,768 to 32,767)
• int: 32-bit signed integer (-2^31 to 2^31-1)
• long: 64-bit signed integer (-2^63 to 2^63-1)
• float: 32-bit floating-point number
• double: 64-bit floating-point number
• char: 16-bit Unicode character
• boolean: true/false value
Comments, Data Types and Variables in Java

int x = 10;
double y = 3.14;
char c = 'a';
boolean b = true;

System.out.println(x); // output: 10
System.out.println(y); // output: 3.14
System.out.println(c); // output: a
System.out.println(b); // output: true
Comments, Data Types and Variables in Java

Reference data types, on the other hand, are variables


that store references to objects in memory.

Unlike primitive types, reference types can vary in size


and can be used to represent more complex data
structures.

Some examples of reference types in Java include


arrays, strings, and objects.
Comments, Data Types and Variables in Java

// declare a string variable and initialize it with a string value


String message = "Hello, world!";

// declare an array of integers and initialize it with some values


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

System.out.println(message); // output: Hello, world!


System.out.println(numbers[0]); // output: 1
System.out.println(numbers[1]); // output: 2
Comments, Data Types and Variables in Java

It's important to note that when passing primitive data


types to a method, a copy of the value is passed,
whereas when passing reference data types, a copy of
the reference to the object is passed.

This means that changes made to a primitive data type


within a method will not affect the original value
outside the method, whereas changes made to a
reference data type within a method will affect the
original object outside the method.
Operators in Java

Overview of operators in Java:


Operators in Java are special symbols or characters that are
used to perform specific operations on variables or values.
They can be classified into several categories based on their
functionality.
Arithmetic Operators: Arithmetic operators are used to
perform basic mathematical operations such as addition,
subtraction, multiplication, division, and modulus. The
following operators are available in Java for arithmetic
operations:
+(Addition), -(Subtraction), (Multiplication), / (Division) and % (Modulus)
Operators in Java

Assignment Operators: Assignment operators are used to


assign values to variables. The following operators are
available in Java for assignment operations:
= (Simple assignment)
+= (Add and assign)
-= (Subtract and assign)
*= (Multiply and assign)
/= (Divide and assign)
%= (Modulus and assign)
Operators in Java
Comparison Operators: Comparison operators are used
to compare two values and return a boolean value
(true or false) based on the comparison result. The
following are the comparison operators available in
Java:
Operator Description
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Operators in Java

int a = 10;
int b = 20;
boolean result = (a == b); // false
result = (a != b); // true
result = (a < b); // true
result = (a > b); // false
result = (a <= b); // true
result = (a >= b); // false
Operators in Java

Logical Operators: Logical operators are used to


combine two or more boolean expressions and return a
boolean value based on the logical result. The following
are the logical operators available in Java:
Operator Description
&& Logical AND
|| Logical OR
! Logical NOT
Operators in Java

boolean a = true;
boolean b = false;
boolean result = (a && b); // false
result = (a || b); // true
result = !a; // false
Operators in Java
Bitwise Operators: Bitwise operators are used to
perform operations on individual bits of a number. They
are used in low-level programming and are not
commonly used in everyday programming. The
following are the bitwise operators available in Java:
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
<< Left Shift (Use 0)
>> Right Shift (Signed use 1)
>>> Unsigned Right Shift (Signed use 0)
Operators in Java

int a = 3; // 0011
int b = 6; // 0110
int result = (a & b); // 0010 (AND)
result = (a | b); // 0111 (OR)
result = (a ^ b); // 0101 (XOR)
result = ~a; // 1100 (Complement)
result = (a << 1); // 0110 (Left Shift)
result = (a >> 1); // 0001 (Right Shift)
result = (a >>> 1); // 0001 (Unsigned Right Shift)
Operators in Java

• In Java, operator priority determines the order in


which operators are evaluated in an expression,
while associativity determines the order in which
operators of the same priority are evaluated.
• The following table shows the operator priority and
associativity in Java, from highest to lowest priority:
Operators in Java
Operators in Java
Operators in Java

– Operators with higher priority are evaluated first, and


operators with the same priority are evaluated according
to their associativity. For example, in the expression a + b *
c, the multiplication operator (*) has higher priority than
the addition operator (+), so b * c is evaluated first, and
the result is added to a. If we want to change the order of
evaluation, we can use parentheses to group the
operations, like this: (a + b) * c.
– It's important to keep in mind the operator priority and
associativity when writing complex expressions, to ensure
that they are evaluated correctly.
Control Flow
Control flow statements are used in Java to determine
the order in which statements are executed in a
program.

There are three types of control flow statements in


Java:

•selection statements
•iteration statements
•jump statements
Control Flow
Selection statements:
Selection statements in Java allow you to make decisions
based on certain conditions. There are two types of
selection statements in Java: the if-else statement and the
switch statement.
The if-else statement allows you to execute a block of
code if a certain condition is true, and another block of
code if it is false. For example
int x = 5;
if(x > 0) {
System.out.println("x is positive");
} else {
System.out.println("x is not positive");
}
Control Flow
The switch statement allows you to execute different
blocks of code based on the value of a variable. For
example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
Control Flow
Iteration statements:
Iteration statements in Java allow you to execute a
block of code repeatedly. There are three types of
iteration statements in Java: the while loop, the do-
while loop, and the for loop.
The while loop executes a block of code repeatedly as
long as a certain condition is true. For example:
int i = 0;
while(i < 10) {
System.out.println(i);
i++;
}
Control Flow
The do-while loop is similar to the while loop, but it
always executes the block of code at least once, even if
the condition is false. For example:

int i = 0;
do {
System.out.println(i);
i++;
} while(i < 10);
Control Flow
The for loop is used to execute a block of code
repeatedly a fixed number of times. For example:

for(int i = 0; i < 10; i++)


{
System.out.println(i);
}
Control Flow
Jump statements:
Jump statements in Java allow you to transfer control to
another part of the program.

There are three types of jump statements in Java:

•break statement
•continue statement
•return statement
Control Flow
The break statement is used to terminate a loop or
switch statement. For example:

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


if(i == 5) {
break;
}
System.out.println(i);
}
Control Flow
The continue statement is used to skip over certain
iterations of a loop. For example:

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


if(i == 5) {
continue;
}
System.out.println(i);
}
Control Flow
The return statement is used to return a value from a
method. For example:

public int add(int x, int y)


{
return x + y;
}
Control Flow
public class ControlFlowExample {
public static void main(String[] args) {
int x = 5;

// if statement
if (x < 10) {
System.out.println("x is less than 10");
}
Control Flow
// if-else statement
if (x > 10)
{
System.out.println("x is greater than 10");
}
else
{
System.out.println("x is not greater than 10");
}
Control Flow
// switch statement
switch (x) {
case 1:
System.out.println("x is 1");
break;
case 2:
System.out.println("x is 2");
break;
case 3:
System.out.println("x is 3");
break;
default:
System.out.println("x is not 1, 2, or 3");
break;
}
Control Flow
// while loop
int y = 0;
while (y < x) {
System.out.println("y is " + y);
y++;
}

// for loop
for (int i = 0; i < x; i++) {
System.out.println("i is " + i);
}
Control Flow
// do-while loop
int z = 0;
do {
System.out.println("z is " + z);
z++;
} while (z < x);
}
}
Control Flow
• This program initializes a variable x to 5, and then demonstrates several
control flow statements:
• if statement: checks if x is less than 10, and prints a message if it is.
• if-else statement: checks if x is greater than 10, and prints a message if it is,
or a different message if it is not.
• switch statement: checks the value of x, and prints a message based on the
case it matches (or the default case if it doesn't match any).
• while loop: initializes a variable y to 0, and repeatedly prints its value while
it is less than x.
• for loop: initializes a variable i to 0, and repeatedly prints its value while it is
less than x.
• do-while loop: initializes a variable z to 0, and repeatedly prints its value
while it is less than x. Note that the loop body is executed at least once,
even if the condition is false initially.
Java Array
In Java, an array is a data structure that allows you to
store a collection of elements of the same type in a
contiguous block of memory. It is a fundamental
concept in programming and is used extensively in Java
programs.
Declaring an array in Java
To declare an array in Java, you need to specify the type
of the elements and the number of elements in the
array. The syntax for declaring an array is as follows:

type[] arrayName = new type[arraySize];


Java Array

Here, type is the data type of the elements in the array,


arrayName is the name of the array, and arraySize is the
number of elements in the array.

For example, to declare an array of integers with 5


elements, you would use the following code:
int[] numbers = new int[5];
Java Array
Initializing an array in Java

You can initialize an array in Java when you declare it, or


you can initialize it later using a loop or individual
assignments.

To initialize an array when you declare it, you can use the
following syntax:
type[] arrayName = { element1, element2, ..., elementN };
Java Array
Here, type is the data type of the elements in the array,
arrayName is the name of the array, and element1,
element2, ..., elementN are the initial values of the
elements in the array.

For example, to declare and initialize an array of


integers with the values 1, 2, 3, 4, and 5, you would use
the following code:

int[] numbers = { 1, 2, 3, 4, 5 };
Java Array
Accessing elements in an array
To access an element in an array in Java, you use the
index of the element. The index of the first element in
the array is 0, and the index of the last element is
arraySize-1.

For example, to access the third element in the


numbers array we declared earlier, we would use the
following code:

int thirdNumber = numbers[2];


Java Array
Modifying elements in an array
To modify an element in an array, you simply assign a
new value to the element using its index.

For example, to change the value of the third element


in the numbers array to 10, you would use the
following code:

numbers[2] = 10;
Java Array
Iterating over an array
To iterate over an array in Java, you can use a loop such
as a for loop.

For example, to iterate over the numbers array we


declared earlier and print each element, you would use
the following code:
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i]);
}
Java Array
One-Dimensional Arrays
One-dimensional arrays are a collection of elements of
the same data type, all stored in a contiguous memory
location. To declare and initialize a one-dimensional
array, you can use the following syntax:

dataType[] arrayName = new dataType[arraySize];

For example, to declare an array of integers with 5


elements, you can use:
int[] numbers = new int[5];
Java Array
You can also initialize the array elements at the same
time:
int[] numbers = { 1, 2, 3, 4, 5 };

To access an element in the array, you can use the


index of the element, which starts at 0:

// Accesses the third element, which is 3


int thirdElement = numbers[2];
Java Array
One-Dimensional Array:
public class OneDimensionalArray {
public static void main(String[] args) {
//declaring an array of integers
int[] arr = new int[5];

//inserting elements into the array


arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;

//displaying the elements of the array


for (int i = 0; i < arr.length; i++) {
System.out.println("Element at index " + i + ": " + arr[i]);
}
}
}
Java Array
Multi-Dimensional Arrays
Multi-dimensional arrays are arrays that contain other
arrays as elements. You can create a two-dimensional
array, which is an array of arrays, by using the following
syntax:
dataType[][] arrayName = new dataType[rowSize][columnSize];

For example, to declare a two-dimensional array of


integers with 3 rows and 4 columns, you can use:

int[][] matrix = new int[3][4];


Java Array
You can initialize the elements of the array in the same
way as a one-dimensional array:

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

To access an element in a two-dimensional array, you


need to specify both the row and column index:
// Accesses the element in the second row and third
column, which is 7

int element = matrix[1][2];


Java Array
Multi-Dimensional Array:
public class MultiDimensionalArray {
public static void main(String[] args) {
//declaring a 2D array
int[][] arr = new int[3][3];

//inserting elements into the array


arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 4;
arr[1][1] = 5;
arr[1][2] = 6;
arr[2][0] = 7;
arr[2][1] = 8;
arr[2][2] = 9;

//displaying the elements of the array


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Java Array
Note that in the multi-dimensional array example, we
used a nested loop to iterate over the elements of the
array. The outer loop iterates over the rows, while the
inner loop iterates over the columns.

You might also like