KEMBAR78
Java Unit - 1 First Part | PDF | Inheritance (Object Oriented Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
8 views63 pages

Java Unit - 1 First Part

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995. It features a platform-independent runtime environment (JRE), a development kit (JDK), and key object-oriented programming concepts such as classes, objects, inheritance, encapsulation, and polymorphism. Java is widely used in various applications, including simulations, real-time systems, and artificial intelligence, due to its simplicity, security, and dynamic capabilities.

Uploaded by

kowsalyakavya08
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)
8 views63 pages

Java Unit - 1 First Part

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995. It features a platform-independent runtime environment (JRE), a development kit (JDK), and key object-oriented programming concepts such as classes, objects, inheritance, encapsulation, and polymorphism. Java is widely used in various applications, including simulations, real-time systems, and artificial intelligence, due to its simplicity, security, and dynamic capabilities.

Uploaded by

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

Object Oriented Programming

Using Java
Basic Concept of Java
• Java is a programming language and a platform. Java is a high level,
robust, object-oriented and secure programming language.

• Java was developed by Sun Microsystems (which is now the


subsidiary of Oracle) in the year 1995. James Gosling is known as the
father of Java. Before Java, its name was Oak. Since Oak was already
a registered company, so James Gosling and his team changed the
name from Oak to Java.

• Platform: Any hardware or software environment in which a program


runs, is known as a platform. Since Java has a runtime environment
(JRE) and API, it is called a platform.
The terms JVM, JDK, and JRE are all related to Java, a popular
programming language. Here's a breakdown of each:
1. JVM (Java Virtual Machine):

• JVM (Java Virtual Machine) is an abstract machine. It is a specification


that provides runtime environment in which java bytecode can be
executed.
• JVMs are available for many hardware and software platforms (i.e.
JVM is platform dependent).
• The JVM is a virtual machine that runs Java bytecode. It is the runtime
environment in which Java programs are executed.
• It provides a platform-independent way of executing code by
converting Java bytecode into machine code that can run on the
underlying hardware.
• JVM manages system memory and provides a secure environment for
executing Java programs.
2. Java Development Kit (JDK)
• Role: The JDK is a complete software development kit for developing
Java applications.
Components:
• Compiler (javac): Converts Java source code into bytecode.
• Java Runtime Environment (JRE): Includes the JVM, core libraries, and
other components to run Java applications.
• Libraries: A set of libraries for developing Java applications, including
Java Standard Edition libraries.
• Tools: Various tools like javadoc (for generating documentation), jar
(for packaging applications into JAR files), and debugging tools.
• Usage: Developers use the JDK to write, compile, and debug Java
applications.
3. Java Runtime Environment (JRE)
• Role: The JRE provides the environment required to run Java
applications.
Components:
• JVM: The core part of the JRE, which executes the bytecode.
• Core Libraries: Pre-written code that Java applications can use (like
classes for handling data structures, network operations, etc.).
• Other Components: Necessary components and files required to run
Java programs.
• Usage: The JRE is used by end-users to run Java applications.
Developers need the JRE to test their applications, but they typically
need the full JDK for development work.
Object Oriented Programming (OOPs) Concept in Java

• As the name suggests, Object-Oriented Programming or Java OOPs


concept refers to languages that use objects in programming

• Object-oriented programming aims to implement real-world entities


like inheritance, hiding, polymorphism, etc. in programming. The
main aim of OOPs is to bind together the data and the functions that
operate on them so that no other part of the code can access this
data except that function.
• OOPS concepts are as follows:

1. Class
2. Object
3. Pillars of OOPs
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Objects and Classes in Java
object in Java
• An entity that has state and behavior is known as an object or An object
is an instance of a class.
• e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical
(tangible and intangible). The example of an intangible object is the
banking system.
An object has three characteristics:
• State: represents the data (value) of an object.
• Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
• Identity: An object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. However, it is used
internally by the JVM to identify each object uniquely.
Class in Java
• A class in Java is a blueprint for creating objects. It defines a datatype by
bundling data and methods that work on the data into one single unit.
Definition: A class is a template or blueprint from which objects are
created. It encapsulates data for the object and methods to manipulate
that data.
Components:
• Fields (Attributes): Variables that hold the state of an object.
• Methods: Functions that define the behavior of an object.
• Constructors: Special methods that are called when an object is
instantiated.
• Pillar 1: Abstraction
• Data Abstraction is the property by virtue of which only the essential details are
displayed to the user. The trivial or non-essential units are not displayed to the
user. Ex: A car is viewed as a car rather than its individual components.
• Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object, ignoring the irrelevant details.
Ex: Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the car speed or applying brakes will stop the car, but he does not know how
on pressing the accelerator, the speed is actually increasing. He does not know about the inner
mechanism of the car or the implementation of the accelerators, brakes etc. in the car. This is what
abstraction is.
• In Java, abstraction is achieved by interfaces and abstract classes. We can
achieve 100% abstraction using interfaces.
• Pillar 2: Encapsulation
• It is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together the code and the data it manipulates. Another way to think about encapsulation is
that it is a protective shield that prevents the data from being accessed by the code outside
this shield.
• Technically, in encapsulation, the variables or the data in a class is hidden from any other
class and can be accessed only through any member function of the class in which they are
declared.
• In encapsulation, the data in a class is hidden from other classes, which is similar to what
data-hiding does. So, the terms “encapsulation” and “data-hiding” are used interchangeably.
• Encapsulation can be achieved by declaring all the variables in a class as private and writing
public methods in the class to set and get the values of the variables.
• Pillar 3: Inheritance
• Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism
in Java by which one class is allowed to inherit the features of another class. We are achieving
inheritance by using extends keyword.
• Terminologies:
• Superclass: The class whose features are inherited is known as superclass (also known as base
or parent class).
• Subclass: The class that inherits the other class is known as subclass (also known as derived or
extended or child class).
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Pillar 4: Polymorphism(Many Forms)
Polymorphism is one of the core concepts of Object-Oriented Programming (OOP) in Java. It refers to
the ability of a single interface to represent different underlying forms (data types). In simpler terms,
polymorphism allows one interface to be used for a general class of actions. The specific action is
determined by the exact nature of the situation.
Polymorphism can be classified into two types:
1. Compile-time Polymorphism (Method Overloading)
2. Runtime Polymorphism (Method Overriding)

1. Compile-time Polymorphism (Method Overloading)


Method Overloading: Allows a class to have multiple methods with the same name but different
parameters.
If subclass (child class) has the same method as declared in the superclass( parent

2. Runtime Polymorphism (Method Overriding) If subclass (child class)class),


hasthe it is
the known
same asmethod
method overriding . superclass( parent class), it is known
If subclass
IIf (child(child
subclass class)class)
has has same
the method
same asasdeclared
method
declared
as ininthe
declared
the
insuperclass( parent
the superclass( class),
parent it is known
class), it is known
asmethodoverriding
asmethod overriding. .
asmethod overriding .

Method Overriding: Involves creating a method in a subclass with the same signature as a method in its
superclass, thereby replacing or extending the behavior of the superclass method.
Applications Of Java
1. Simulations and Modeling
Java is an excellent choice for developing simulations and modeling applications due to its robustness,
portability, and extensive libraries.

2. Real-Time Systems
Real-time systems require timely and predictable responses to events. Java, with its Real-Time Specification
for Java (RTSJ), is used to develop such systems.

3.Artificial Intelligence and Machine Learning


Java is used in AI and machine learning for modeling and simulations.

4.Object-Oriented Databases
Object-oriented databases (OODBs) store data as objects, making them more aligned with object-oriented
programming principles compared to traditional relational databases.
Applications: Used where complex data structures need to be stored and retrieved efficiently, such as in
engineering simulations, CAD systems, and multimedia applications.
5.Neural Networks and Parallel Programming
Neural Networks
In Java, neural networks can be implemented and utilized through various libraries and frameworks that
provide the necessary tools for training, testing, and deploying models. Here are some key aspects of
neural networks in the context of Java
Parallel Programming
Parallel programming involves executing multiple tasks simultaneously, leveraging multiple processors
or cores to improve performance.

6.Hypertext and Hypermedia


Hypertext and hypermedia refer to systems that enable the sharing and navigation of interconnected
content.
Features Of Java
1. Simple
Java is one of the simplest programming languages to learn and master in order to grasp the concept of Object-oriented
learning.
For experienced developers, there was once a problem of unreferenced objects clogging up the memory. With Java, that
problem is now solved as Java was one of the first programming languages to bring in the concept of Automatic Garbage
Collection.

When Java came into being, a lot of developers were already working in the then programming language C++. In order to
tackle the migration problem, the Java syntax is actually very similar to the C++ syntax which made it easier for developers
to migrate from C++ to Java.

2. Object-Oriented Programming Language


This is one of the primary reasons why Java is so popular amongst developers. Java strictly conforms to the rules of Object
Oriented Programming or OOP. Object-oriented development includes concepts of Objects and Classes and many more.
This enables developers to have a wide variety of options for designing their software.
Java also supports
• Polymorphism
• Inheritance
• Abstraction
• Encapsulation
3.Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform
specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment
in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based platform

4.Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
Java language provides these securities by default. Some security can also be provided by an application developer
explicitly through SSL, JAAS, Cryptography, etc.

5.Robust
The English mining of Robust is strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not
being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these points make Java robust.
6.Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive
types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit
architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

7.Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.

8.Interpreted programming
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is
still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.

9.Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating
distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the
internet.
10.Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares
a common memory area. Threads are important for multi-media, Web applications, etc.

11.Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also
supports functions from its native languages, i.e., C and C++.
Structure Of Java Program
Java is an object-oriented programming,
platform-independent, and secure
programming language that makes it popular.
Using the Java programming language, we
can develop a wide variety of applications.

• A typical structure of a Java program


contains the following elements:
1. Documentation Section
2. Package Declaration
3. Import Statements
4. Interface Section
5. Class Definition
6. Class Variables and Variables
7. Main Method Class
1.Documentation Section
The documentation section is an important section but optional for a Java program. It includes basic information about a
Java program. The information includes the author's name, date of creation, version, program name, company name, and
description of the program. It improves the readability of the program. Whatever we write in the documentation section,
the Java compiler ignores the statements during the execution of the program. To write the statements in the
documentation section, we use comments.
• The comments may be single-line, multi-line, and documentation comments.
1.Single-line Comment: It starts with a pair of forwarding slash (//). For example:
//First Java Program
2.Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols. For example:
/*It is an example of
multiline comment*/
3.Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:
/**It is an example of documentation comment*/

2.The package declaration is optional. It is placed just after the documentation section. In this section, we declare the
package name in which the class is placed. Note that there can be only one package statement in a Java program. It must be
defined before any class and interface declaration. It is necessary because a Java class can be placed in different packages
and directories based on the module they are used. For all these classes package belongs to a single parent directory. We
use the keyword package to declare the package name.
For example:
3.Import Statements
The package contains the many predefined classes and interfaces. If we want to use any class of a particular package, we
need to import that class. The import statement represents the class stored in the other package. We use the import
keyword to import the class. It is written before the class declaration and after the package statement. We use the import
statement in two ways, either import a specific class or import all classes of a particular package. In a Java program, we
can use multiple import statements. For example:

4.Interface Section
It is an optional section. We can create an interface in this section if required. We use the interface keyword to create an
interface. An interface is a slightly different from the class. It contains only constants and method declarations. Another
difference is that it cannot be instantiated. We can use interface in classes by using the implements keyword. An interface
can also be used with other interfaces by using the extends keyword. For example:
5.Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class, we cannot create any Java program. A
Java program may conation more than one class definition. We use the class keyword to define the class. The class is a
blueprint of a Java program. It contains information about user-defined methods, variables, and constants. Every Java
program has at least one class that contains the main() method. For example:

6.Main Method Class


In this section, we define the main() method. It is essential for all Java programs. Because the execution of all Java programs
starts from the main() method. In other words, it is an entry point of the class. It must be inside the class. Inside the main
method, we create objects and call the methods. We use the following statement to define the main() method:
public static void main(String args[])
{
}
Data Types In Java
Data types in Java are of different sizes and values that can be stored in the variable that is made as per
convenience and circumstances to cover up all test cases. Java has two categories in which data types are
segregated

Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
Non-Primitive Data Type or Object Data type: such as String, Array, etc.
Primitive Data Types
1.byte 1 byte

• A byte is an 8-bit signed integer.


• It can store values from -128 to 127.
• Often used for saving memory in large arrays.

2.short 2 bytes

• A short is a 16-bit signed integer.


• It has a range from -32,768 to 32,767.
• Used to save memory in large arrays when the memory savings are critical.

3.int 4 bytes

• An int is a 32-bit signed integer.


• It is the default integer type and has a range from -2^31 to 2^31-1.
• Used in arithmetic operations and control statements.
4.long 8 bytes

• 64-bit signed integer.


• Range: -2^63 to 2^63-1.
• Ends with an 'L' or 'l' suffix in literals, e.g., 1000L.

5.float 4 bytes

• Single-precision 32-bit IEEE 754 floating point.


• Used for decimal values with 6-7 significant decimal digits.
• Ends with an 'f' or 'F' suffix in literals, e.g., 3.14f.

6.double 8 bytes
• Double-precision 64-bit IEEE 754 floating point.
• Provides greater precision for decimal values, with 15 significant decimal digits.
• Default type for decimal values, e.g., 3.14.
7.boolean
• Has only two possible values: true and false.
• Used for simple flags that track true/false conditions.
• Commonly used in control flow statements like if-else and loops.

8.char 1 or 2 bytes

• 16-bit Unicode character.


• Represents any character in the Unicode standard, from '\u0000' to '\uffff'.
• Used to store any single character, e.g., 'A'.
Non-primitive data types/Reference types
In Java, reference data types refer to objects and arrays. These types are created using constructors of the classes. They store
references (addresses) to the memory locations where the actual data is stored, rather than the data itself. The main types of
reference data types in Java are:
1. Classes
• Blueprints for creating objects, encapsulating data and methods.
• Can contain fields, methods, constructors, and other class members.
• Classes can be instantiated into objects using the new keyword.

2.Interfaces

• Define a contract that classes can implement.


• Can contain abstract methods, default methods, static methods, and constants.
• A class implements an interface using the implements keyword.

3.Arrays
• Container objects that hold a fixed number of values of a single type.
• The length of an array is established when it is created and cannot be changed.
• Access elements using an index, starting at 0.
Strings

• Immutable sequences of characters.


• Widely used in Java for representing text.
• String objects are immutable, meaning they cannot be changed after they are created.
Variables In Java
• In Java, Variables are the data containers that save the data values during Java program execution. Every
Variable in Java is assigned a data type that designates the type and quantity of value it can hold. A variable
is a memory location name for the data.
• Java variable is a name given to a memory location. It is the basic unit of storage in a program.
• In Java, all variables must be declared before use.
How to Declare Variables in Java?
The declaration involves specifying the type of the variable and giving it a name.

Ex:
int a=10;
float b=10.8;
boolean c=true;
Types of Variables
1. Local Variables
2. Instance Variables
3. Static Variables

1. Local Variables
Definition: Local variables are declared inside a method, constructor, or block and are only
accessible within that method, constructor, or block.
2.Instance Variables (Non-Static Fields)
Instance variables are declared in a class but outside any method, constructor, or block. They are created when an object is
instantiated and are destroyed when the object is destroyed. They are associated with instances of the class.

3.Static variables
Definition: Class variables are declared with the static keyword inside a class but outside any method, constructor, or block.
They are associated with the class itself rather than instances of the class.
Operators in Java
In Java, operators are special symbols that perform operations on variables and values. Java operators can be
classified into several categories:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators

1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive data types.
* ,/ ,% ,+ ,-
2.Unary Operators
Unary operators need only one operand. They are used to increment, decrement, or negate a value.

1. – : Unary minus, used for negating the values.


2. + : Unary plus indicates the positive value. It performs an automatic conversion to int when the type of its operand is the
byte, char, or short. This is called unary numeric promotion.

3. ++ : Increment operator, used for incrementing the value by 1. There are two varieties of increment operators.
• Post-Increment: Value is first used for computing the result and then incremented.
• Pre-Increment: Value is incremented first, and then the result is computed. ++ , Increments by 1.
Post-Increment: Uses value first, then increments.
Pre-Increment: Increments first, then uses value.

4. – – : Decrement operator, used for decrementing the value by 1. There are two varieties of decrement operators.
• Post-decrement: Value is first used for computing the result and then decremented. -- , Decrements by 1.
• Pre-Decrement: The value is decremented first, and then the result is computed. Post-Decrement: Uses value first, then
decrements.
Pre-Decrement: Decrements first, then uses value.

5. ! : Logical not operator, used for inverting a boolean value.


pre increment
int x = 5;
int y = ++x; // x becomes 6, and y is assigned the value 6
// Now, x is 6 and y is 6
o/p post increment
Postincrement : 10 int a= 5;
Preincrement : 12 int b = a++; // b is assigned the value 5, and then a becomes 6
Postdecrement : 10 // Now, a is 6 and b is 5
Predecrement : 8
3. Assignment Operator//+=, -=, and *=
• ‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left associativity, i.e. value given on the
right-hand side of the operator is assigned to the variable on the left, and therefore right-hand side value must be
declared before using it or should be a constant.

• The general format of the assignment operator is:


variable = value;
• In many cases, the assignment operator can be combined with other operators to build a shorter version of the statement
called a Compound Statement. For example, instead of a = a+5, we can write a += 5.
4. Relational Operators(<, >, =, <=, >=, !=)
• These operators are used to check for relations like equality, greater than, and less than. They return boolean results after
the comparison and are extensively used in looping statements as well as conditional if-else statements. The general
format is,
variable relation_operator value;
5. Logical Operators
• These operators are used to perform “logical AND” and “logical OR” operations, i.e., a function similar to AND gate
and OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is
false, i.e., it has a short-circuiting effect. Used extensively to test for several conditions for making a decision. Java also
has “Logical NOT”, which returns true when the condition is false and vice-versa

• Conditional operators are:

• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-versa
6.Ternary operator/Conditional Operator
• It has three operands and hence the name Ternary.

• The general format is: condition ? if true : if false

• The above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else execute
the statements after the ‘:’.
7. Bitwise Operators(&,|,^,~)
• These operators are used to perform the manipulation of individual bits of a number. They can be used with any of the
integer types. They are used when performing update and query operations of the Binary indexed trees.

• &, Bitwise AND operator: returns bit by bit AND of input values.
• |, Bitwise OR operator: returns bit by bit OR of input values.
• ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
• ~, Bitwise Complement Operator: This is a unary operator which returns the one’s complement representation of the
input value, i.e., with all bits inverted.
Control Statement

Control statements decide the flow (order or sequence of execution of statements) of a Java program. In Java, statements are
parsed from top to bottom. Therefore, using the control flow statements can interrupt a particular section of a program based
on a certain condition.
1.Selection statements
In Java, selection statements are used to execute different blocks of code based on specified conditions. There are primarily
two types of selection statements:

1.if-else Statement:
• The if-else statement executes a block of code if a specified condition is true. If the condition evaluates to false, an
optional else block of code can be executed.

• Syntax of if statement is given below.


if(condition) {
statement 1; //executes when condition is true
}

Ex
2. if-else:
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it
won’t. But what if we want to do something else if the condition is false? Here comes the else statement. We can use the
else statement with the if statement to execute a block of code when the condition is false.
Syntax:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Ex
3.else-if ladder
An "else-if ladder" in Java is a sequence of else if statements that follow an initial if statement, providing multiple conditions
to be evaluated in sequence until a matching condition is found or the default else block is executed.
Syntax
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
4. nested-if:
A nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside an if
statement. Yes, java allows us to nest if statements within if statements. i.e, we can place an if statement inside another if
statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
5. switch-case:
The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of
code based on the value of the expression.
Syntax
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Looping Statement

1.For loop
2.While loop
3.do while loop
4.Nested loop
1.For Loop
In Java, a for loop is used to iterate a block of code a certain number of times or over elements of an array or collection.
There are two main types of for loops in Java: the traditional for loop and the enhanced for-each loop.

Syntax:

for (initialization; condition; update) {


// Code block to be executed
}

Ex:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
2.while loop
In Java, a while loop repeatedly executes a block of code as long as a specified condition is true. The while loop evaluates
the condition before executing the code block, so if the condition is false initially, the code block may not execute at all.

Syntax:
while (condition) {
// Code block to be executed
}

Ex:
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
3.do while loop
A do-while loop in Java is similar to a while loop, but the key difference is that the do-while loop guarantees
that the code block will be executed at least once. This is because the condition is evaluated after the code
block is executed.

Syntax:
do {
// Code block to be executed
} while (condition);

Ex:
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
}
}
4.Nested Loop

If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely
whenever outer loop executes.

Ex:
public class NestedForExample {
public static void main(String[] args) {
for(int i=1;i<=3;i++) //loop of i
{
for(int j=1;j<=3;j++) //loop of j
{
System.out.println(i+" "+j);
}
}
}
}
Jump Statements
Java, jump statements are used to transfer control to another part of the program. Java provides three primary jump
statements: break, continue. Each serves a different purpose and is used in different contexts.
• The continue statement skips the current iteration of a loop and proceeds with the next iteration.
• The break statement is used to terminate a loop (or a switch statement) immediately and transfer control to the next
statement after the loop.

Ex:
public class Main {
public static void main(String[] args) {
// Example with break and continue in a nested loop
for (int i = 0; i < 3; i++) {
System.out.println("Outer loop i = " + i);
for (int j = 0; j < 5; j++) {
if (j == 2) {
continue; // Skip the rest of the inner loop when j is 2
}
if (j == 4) {
break; // Exit the inner loop when j is 4
}
System.out.println(" Inner loop j = " + j);
}
}
}
}
Methods in Java
• A method is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also known as functions.

Create a Method
• A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also
create your own methods to perform certain actions:

Create a method inside Main:


public class Main {
static void myMethod() {
// code to be executed
}
}
Example
Inside main, call the myMethod() method:

public class Main {


static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}
Method Overloading

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.

Ex:
import java.util.Scanner;
public class School{
void display()
{
System.out.println("hello world");
}
void display(int a)
{
System.out.println("welocome");
}

public static void main(String args[])


{
School obj=new School(); //object 1
obj.display();
}
}
Math Class in Java
Java Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos(), tan(),
round(), ceil(), floor(), abs() etc.

• Math.abs(x): Returns the absolute value of x(ex: 8 converted to -8).


• Math.sin(x): Returns the sine of the angle x (in radians).
• Math.cos(x): Returns the cosine of the angle x (in radians).
• Math.tan(x): Returns the tangent of the angle x (in radians).
• Math.min(x, y): Returns the lesser of two values, x and y.
• Math.max(x, y): Returns the greater of two values, x and y.
• Math.sqrt(x): Returns the square root of x.
• Math.random(): Returns a pseudorandom double value between 0.0 (inclusive) and 1.0 (exclusive).
public class Mathexample{
public static void main(String args[]) {

System.out.println(Math.max(5,8));
System.out.println(Math.min(5,8));
System.out.println(Math.sqrt(2));
System.out.println(Math.abs(-8.7));
System.out.println(Math.random());// from 0.0 to 1.0
int randomNum=(int)(Math.random()*101);//if wanted between 1 to 100 and the result is in float to convert to int we use type casting
System.out.println(randomNum);

}
}
Arrays in Java
• Array is a collection of Homogeneus element/store multiple values of the same type in a single variable.
Arrays are indexed, with the first element at index 0.
• Arrays may be stored in contiguous memory [consecutive memory locations].
Array Declaration:
int[] myArray;

Initialization:
myArray = new int[8]; // Creates an array of 8 integers
One Dimentional Array

public class arrays{


public static void main(String args[]) {
int[] rollno=new int[50];
rollno[0]=1;
rollno[6]=6;
System.out.println(rollno[0]);
System.out.println(rollno[5]);
}
}
A multidimensional array/ 2D array
• Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows and columns.
• To create/declare a two-dimensional array:
dataType[][] arrayName;
• For example, to declare a two-dimensional array of integers:
int[][] myArray;
Ex:
public class myArray{
public static void main(String args[]){
int[][] matrix=new int[5][2];
matrix[0][0]=1;
matrix[2][1]=4;
matrix[1][0]=7;
matrix[01][1]=6;
for(int i=0;i<5;i++)
for(int j=0;j<2;j++)
{
System.out.println(matrix[i][j]);
}
}
}

You might also like