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

Java Unit 1

Object-oriented programming (OOP) is a programming paradigm centered around 'objects' that encapsulate data and methods. Key principles of OOP include encapsulation, inheritance, polymorphism, and abstraction, which enhance code reusability and maintainability. Java exemplifies these principles and is widely used in various applications, including software development, mobile apps, and web applications, while also having limitations such as larger program sizes and memory consumption.

Uploaded by

Shashi Prakash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views60 pages

Java Unit 1

Object-oriented programming (OOP) is a programming paradigm centered around 'objects' that encapsulate data and methods. Key principles of OOP include encapsulation, inheritance, polymorphism, and abstraction, which enhance code reusability and maintainability. Java exemplifies these principles and is widely used in various applications, including software development, mobile apps, and web applications, while also having limitations such as larger program sizes and memory consumption.

Uploaded by

Shashi Prakash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Principals of object oriented paradigm:

 Object-oriented programming (OOP) is a programming paradigm based on the concept of


"objects", which can contain data and code: data in the form of fields (often known as
attributes or properties), and code, in the form of procedures (often known as methods).

1. 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.
 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.

2. Class
 Collection of objects is called class. It is a logical entity.
 Class is a predefined or user-defined template from which objects are created.

3. Inheritance
 When one object acquires all the properties and behaviors of a parent object, it is known
as inheritance. It provides code reusability.

4. Polymorphism
 If one task is performed in different ways, it is known as polymorphism.
 5. Abstraction
 Hiding internal details and showing functionality is known as abstraction.
 For example phone call, we don't know the internal processing.

5. 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.
 Encapsulation is a means of binding data variables and methods together in a class. Only
objects of the class can then be allowed to access these entities. This is known as data
hiding and helps in the insulation of data.

Advantages of OOPS:

 Modularity: OOP divides complex systems into smaller components, making the
codebase easier to comprehend, create, and maintain.
 Encapsulation: Protects data integrity and privacy by restricting direct access and
allowing controlled access through methods.
 Flexibility and Scalability: OOP enables easy addition and modification of features
without impacting the entire codebase.
 Code Organization: OOP promotes a structured approach, enhancing collaboration and
code readability.
 Code Maintenance: Changes and bug fixes can be made to specific objects or classes
without affecting other parts of the system, reducing errors and improving debugging.
 Code Reusability: OOP encourages the development of reusable code elements, saving
time and improving system reliability.
 Better Problem Solving: OOP models real-world systems, allowing developers to create
intuitive solutions that closely mimic real-world circumstances.

Applications of OOPs

1. Software Development:

OOPs, are widely used in software development because it allows developers to design
modular and reusable code.

It improves code organization by encapsulating data and methods within objects, making
complex software systems easier to manage and maintain.

2. Development of Graphical User Interfaces (GUIs):

OOPs lends itself well to GUI development, giving a natural approach to model and
representing graphical elements. Developers may construct engaging and intuitive user
interfaces using classes and objects.

3. Game Development:

OOPs are commonly used in game development due to their ability to express game
things as objects. Complex interactions between people, objects, and settings are common
in games. Developers can use OOPs to describe these entities as objects and define their
behaviors and characteristics.
4. Database Management Systems:

Encapsulation and abstraction are OOPs ideas used in database management systems
(DBMS). OOPs languages like Python and Java have libraries like JDBC and SQL.

Database activities can be encapsulated within objects, enhancing code organization and
maintainability. OOPs also enables the building of data models, which makes mapping
database tables easier.

5. Mobile App Development:

OOPs are widely utilized in mobile app development, powering popular platforms such
as Android and iOS. Languages that adhere to OOPs concepts, like Java and Swift,
enable developers to create robust and scalable mobile applications.

6. Web-based Applications

Java is also used to develop web applications. It provides vast support for web
applications through Servlets, Struts, or JSPs. With the help of these technologies, you can
develop any kind of web application that you require.

7. Enterprise Applications

Java is the first choice of many software developers for writing applications and Java
Enterprise Edition (Java EE) is a very popular platform that provides API and runtime
environment for scripting. It also includes network applications and web-services.

8. Distributed Applications:

Distributed applications have several common requirements that arise specifically because
of their distributed nature and of the dynamic nature of the system and platforms they
operate on.

9. Cloud-Based Applications:

Cloud computing means on-demand delivery of IT resources via the internet with pay-as-
you-go pricing.

It provides a solution for IT infrastructure at a low cost. Java provides you with features
that can help you build applications meaning that it can be used in the SaaS, IaaS and
PaaS development. It can serve the companies to build their applications remotely or help
companies share data with others, whatever the requirement.

Limitations of OOP:

1. The length of the programmes developed using OOP language is much larger
than the procedural approach. Since the programme becomes larger in size, it
requires more time to be executed that leads to slower execution of the
programme.
2. Everything is treated as object in OOP so before applying it we need to have
excellent thinking in terms of objects.
3. Software developed using this approach requires a substantial amount of pre-work
and planning.
4. In certain scenarios, these programs can consume a large amount of memory.

Features of Java

1. Simple

Java is a simplified version of the C++ language, and therefore, it is familiar also.
There is no support of pointers, preprocessor header files, operator overloading, and
multiple inheritances in Java. This makes Java easier as compared to C++.

2. Object-oriented

Java is an object-oriented language and mainly focuses on objects

 Objects
 Classes
 Inheritance
 Encapsulation / Data hiding
 Abstraction
 Polymorphism

3. Platform-independent

Java is a platform-independent language as the source code of Java can run on multiple
operating systems. Java programs can run on any machine or the operating system that
does not need any special software installed.

4. Portable

Java is portable because Java code is executable on all the major platforms. Once we
compile Java source code to bytecode, we can use it in any Java-supported platform
without modification

Java is portable because we can carry bytecode over to any other platform it runs on.

5. Robust & Secure

 Java provides a strong memory management


 It supports Automatic garbage collection, so there is no need to delete the
unreferenced objects manually.
 Java also provides exception handling and type-checking mechanisms.
 Java does not support pointers that make Java robust and secure.

6. Multithreaded and Interactive

Java is a multithreaded language that means it can handle different tasks simultaneously.
Java supports multithreaded programs, in which there is no need to wait for one task to
finish for another to start.
7. 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.

What is JDK?
 JDK stands for java development kit.
 It internally contains JRE & JVM
 JDK provides all the tools to work with java languages.

What is JRE?
 JRE stands for java runtime environment.
 It provides environment to execute the java program.
 It provides the class libraries and other resources that a specific Java program requires
to run.
 It internally contains JVM which is responsible to execute java program.
 The JRE is one of three interrelated components for developing and running Java
programs. The other two components are as follows:
1. Java Development Kit, or JDK
2. Java Virtual Machine, or JVM

The JRE combines Java code created by using the JDK with the necessary
libraries required to run it on a JVM and then creates an instance of the JVM that
runs the resulting program.
How does JRE work?
The Java Runtime Environment (JRE) runs on top of the operating system,
providing additional Java-specific resources. The Java Development Kit (JDK)
and JRE interact to create a sustainable runtime environment that runs Java
program files on any machine. The JRE uses three core components to work.
ClassLoader

The Java ClassLoader dynamically loads all classes necessary to run a Java program.
Bytecode verifier

The bytecode verifier ensures the format and accuracy of Java code before it passes to the
interpreter.

Interpreter
After the bytecode successfully loads, the Java interpreter creates an instance of the JVM
that allows the Java program to be run

Java Virtual Machine (JVM)


JVM is the center of Java programming language and Java platform. The JVM converts
the byte code into machine-specific code.

This platform-independence of JVM allows us to create Java programs on one machine


and execute them on another machine (WORA – Write – Once – Run – Anywhere).

The Java Runtime Environment (JRE)


JRE, as the name suggests, is the runtime environment that is required to execute Java
programs and applications.

The Java Development Kit (JDK)


This is the core component of any Java environment. JDK contains JRE (Java Runtime
Environment) along with Java compiler, Java debugger, and other core classes.
JDK is used for Java development as it provides the entire executable and tools required
to compile, debug a Java program.

JVM (Java Virtual Machine):

 Class Loader: Class loader is a subsystem of JVM. It is used to load class files.
Whenever we run the java program, class loader loads it first.

 Class method area: It is one of the Data Area in JVM, in which Class data will be
stored. Static Variables, Static Blocks, Static Methods, Instance Methods are stored in
this area.

 Heap: It is the runtime data area in which objects are allocated.


 Stack: to store various elements i.e.; local variables, partial results.
 Native stack: It subsumes all the native methods used in your application.
 Execution Engine:
1. JIT compiler
2. Garbage collector

 JIT compiler: The Just-In-Time (JIT) compiler is a part of the runtime environment.

 The JIT compiler compiles the bytecode of that method into machine code.

 Garbage collector: As the name explains that Garbage Collector means to collect the
unused material.

 It tracks each and every object available in the JVM heap space and removes unwanted
ones.

How is Java platform independent?

 Java is platform-independent just because of the bytecode.

 Bytecode is a code of the JVM which is machine-understandable.

 Below is the explanation of the steps involved:


 [Link] → javac (sample. class) → JVM([Link]) → final output
 First source code is used by java compiler and is converted in .class file. The class file
code is in byte code form and that class file is used by JVM to convert into an object file.
After that, you can see the final output on your screen.
Java platform
Java platform is a software or collection of programs that help us to execute applications
written in Java programming language.
Java platform consists of the following components.
 Java language
 The Java Development Kit (JDK)
 The Java Runtime Environment (JRE)
 The Java Compiler
 The Java Virtual Machine (JVM)

Following diagram that depicts the relationship between all these components.

So from the above diagram, we can conclude that,

JRE = JVM + library classes.


JDK = JRE + Developer tools.
Java Language
Java is a programming language that the Java platform uses. Java is an object-oriented
programming language whose syntax is derived from C and OOPS features are derived
from C++. It has its syntax, rules, format, and programming paradigm.

The Java Compiler


This is a compiler for Java programming language and its function is to generate Java
class files from the Java source code.

Java class file contains a platform-independent Java byte code.

Java Tokens:
Tokens known as the fundamental building blocks of the program. Tokens can be
classified as follows:

1. Keywords
2. Identifiers
3. Constants
4. Special Symbols
5. Operators
6. Comments

Keyword:
Keywords are pre-defined or reserved words in a programming language. Each keyword
is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names because by doing so, we are
trying to assign a new meaning to the keyword which is not allowed. Java language
supports the following keywords:
2. Identifiers:
Identifiers are used as the general terminology for naming of variables, functions and
arrays. These are user-defined names consisting of an arbitrarily long sequence of
letters and digits with either a letter or the underscore (_) as a first character. Identifier
names must differ in spelling and case from any keywords. You cannot use keywords as
identifiers

Examples of valid identifiers:

MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123

Examples of invalid identifiers:

My Variable // contains a space


123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character

3. Constants/Literals:
Constants are also like normal variables. But the only difference is, their values cannot
be modified by the program once they are defined. Constants refer to fixed values. They
are also called as literals. Constants may belong to any of the data type.
Syntax:
final data_type variable_name;

4. Special Symbols:
The following special symbols are used in Java having some special meaning and thus,
cannot be used for some other purpose.
[] () {}, ; * =

 Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and function
parameters.
 Braces{}: These opening and ending curly braces marks the start and end of a block
of code containing more than one executable statement.
 comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
 semi colon : It is an operator that essentially invokes something called an
initialization list.
 asterick (*): It is used to create pointer variable.
 assignment operator: It is used to assign values.

5. Operators:

Java provides many types of operators which can be used according to the need. They
are classified based on the functionality they provide. Some of the types are-
 Arithmetic Operators
 Unary Operators
 Assignment Operator
 Relational Operators
 Logical Operators
 Ternary Operator
 Bitwise Operators
 Shift Operators
 Precedence and Associativity

6. Comments:
In Java, Comments are the part of the program which are ignored by the compiler while
compiling the Program. They are useful as they can be used to describe the operation or
methods in the program. The Comments are classified as follows:
 Single Line Comments
 Multiline Comments
// This is a Single Line Comment
/*
This is a Multiline Comment
*/

Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Boolean:
The boolean data type has two possible values, either true or false.
Default value: false.
Ex: boolean flag = true;
Byte:
The byte data type can have values from -128 to 127 (8-bit signed two's complement
integer).
It’s used instead of int or other integer data types to save memory if it's certain that the
value of a variable will be within [-128, 127].
Default value: 0
Ex: byte range=124;
Short:
The short data type can have values from -32768 to 32767 (16-bit signed two's complement
integer).
It’s used instead of other integer data types to save memory if it’s certain that the value of the
variable will be within [-32768, 32767].
Default value: 0
short temperature = -200;

Int:
The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
int a = 100000, int b = -200000;

Long:
The long data type is a 64-bit two's complement integer.
Its value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0.
The long data type is used when you need a range of values more than those provided by
int.
long a = 100000L, long b = -200000L

float:
Useful for representing real numbers with a fractional part.
Ex: float f1 = 234.5f
double: Used for more precise floating-point calculations.
Ex: double d1 = 12.3
char: The char data type is used to store characters.
Ex: char letterA = 'A'
Structure of java program:

1. Documentation section :

It is used to improve the readability of the program. It consists of comments in


Java which include basic information.

These are optional, but we suggest you use them because they are useful to understand
the operation of the program

The compiler ignores these comments during the time of execution

There are two types of comments that Java supports

1. Single line Comment


2. Multi-line Comment

Ex: 1. //Single-line comment

/* Multiline comment
in Java */

Package Declaration

You can create a package with any name. A package is a group of classes that are
defined by a name. That is, if you want to declare many classes within one element, then
you can declare it within a package. It is an optional part of the program.

Syntax: package package_name;

Import statements:

This line indicates that if you want to use a class of another package, then you can do
this by importing it directly into your program.

import [Link]; //imports the date class

import [Link].*; //imports all the classes from the java applet package

Interface Section

This section is used to specify an interface in Java. It is an optional section which is


mainly used to implement multiple inheritance in Java.

Class Definition

A class is a collection of variables and methods that operate on the fields. Every program
in Java will have at least one class with the main method.

Main Method Class

This is a compulsory part of the structure of Java program. This is the entry point of the
compiler where the execution starts.

The main() method should be defined inside a class. We can call other functions and
create objects using this method.
Operators In java:
Operators in Java are the symbols used for performing specific operations in Java.
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators

1. Arithmetic Operators

Operators Operations
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

class Main
{
public static void main(String[] args)
{
// declare variables
int a = 15, b = 5;
// addition operator
[Link]("a + b = " + (a + b));
// subtraction operator
[Link]("a - b = " + (a - b));
// multiplication operator
[Link]("a * b = " + (a * b));
// division operator
[Link]("a / b = " + (a / b));

// modulo operator
[Link]("a % b = " + (a % b));
}}

Assignment Operator in Java

Assignment Operators are mainly used to assign the values to the variable that is situated
in Java programming. There are various assignment operators in Java, such as
Operators Examples Equivalent to

= X = Y; X = Y;

+= X += Y; X = X + Y;

-= X -= Y; X = X - Y;

*= X *= Y; X = X * Y;

/= X /= Y; X = X / Y;

%= X %= Y; X = X % Y;
class Main
{
public static void main(String[] args)
{

// create variables
int a = 5;
int var;
// assign value using =
var = a;

[Link]("var using =: " + var);

// assign value using =+


var += a;

[Link]("var using +=: " + var);

// assign value using =*


var *= a;

[Link]("var using *=: " + var);

}
}

Relational Operators in Java

Java relational operators are assigned to check the relationships between two particular
operators. There are various relational operators in Java, such as

Operators Description Example

== Is equal to 3 == 5 returns false


Operators Description Example

!= Not equal to 3 != 5 returns true

> Greater than 3 > 5 returns false

< Less than 3 < 5 returns true

>= Greater than or equal to 3 >= 5 returns false

<= Less than or equal to 3 <= 5 returns true


class Main
{
public static void main(String[] args)
{

// create variables
int a = 7, b = 11;

// value of a and b
[Link]("a is " + a + " and b is " + b);

// == operator
[Link](a == b); // false

// != operator
[Link](a != b); // true

// > operator
[Link](a > b); // false

// < operator
[Link](a < b); // true

// >= operator
[Link](a >= b); // false

// <= operator
[Link](a <= b); // true

}
}
Logical Operators in Java

Logical Operators in Java are used for checking whether the expression is true or false. It
is generally used for making any decisions in Java programming.
Operators Example Meaning
(true) only if both of the expressions
&& [ logical AND ] expression1 && expression2
are true
|| [ logical OR ] expression1 || expression2 (true) if one of the expressions in true
(true) if the expression is false and
! [ logical NOT ] !expression
vice-versa

class Main
{
public static void main(String[] args)
{

// && operator
[Link]((6 > 3) && (8 > 6)); // true
[Link]((6 > 3) && (8 < 6)); // false
// || operator
[Link]((6 < 3) || (8 > 6)); // true
[Link]((6 > 3) || (8 < 6)); // true
[Link]((6 < 3) || (8 < 6)); // false

// ! operator
[Link](!(6 == 3)); // true
[Link](!(6 > 3)); // false

}
}

Unary Operators
unary operators are the types that need only one operand to perform any operation like
increment, decrement, negation etc.
Operators Operator Name Description
It is used to denote
+ Unary Plus
a positive value.
It is used to denote
- Unary Minus
a negative value.
++ Increment operator Increments value by 1
-- Decrement Operator Decrements value by 1
Reverse the value of boolean
! Logical complement operator
variable

Unary Operators in Java Example

// Increment operator
int count = 5;

count++; // increments count to 6

// Decrement operator

count–-; // decrements count to 5

// Unary minus operator

int x = -10; // negates 10 to -10

// NOT operator

boolean isTrue = true;

boolean isFalse = !isTrue; // inverts true to false

// Bitwise complement operator

int y = ~5; // bitwise complement of 5 is 10


Bitwise Operator in Java

Bitwise operations directly manipulate bits. In all computers, numbers are represented
with bits, a series of zeros and ones.

public class JavaOperators {


public static void main(String[] args) {
int a = 58; //111010
int b=13; //1101
[Link](a&b); //returns 8 = 1000
[Link](a|b); //63=111111
[Link](a^b); //55=11011
[Link](~a); //-59
}
}
Ternary Operators in Java
This method is an alternative for using if-else and nested if-else statements.
Syntax:
(Condition) ? (Statement1) : (Statement2);

 Condition: It is the expression to be evaluated which returns a boolean value.


 Statement 1:It is the statement to be executed if the condition results in a true state.
 Statement 2:It is the statement to be executed if the condition results in a false state.

public class Main {


public static void main(String[] args) {
int time = 20;
String result;
result = (time < 18) ? "Good day." : "Good evening.";
[Link](result);
}
}
Shift Operator:
By shifting the bits of its first operand right or left, a shift operator performs bit
manipulation on data.

Name Operator Syntax Description

Signed Left << Operand << It moves all the bits of the operand towards the
Shift number left by a given number.

Signed Right >> Operand >> It moves all the bits of the operand towards the
Shift number right by a given number.

Left Shift Operator


The left shift operator shifts the bits of the binary representation of a number to the left.

Syntax:

left_operand << number

public class Main


{
public static void main (String[] args)
{
int x = 5;
int n = 2;
int answer = x << n;
[Link]("Left shift " + x + " by " + n + " positions : " + answer);
}
}
Right Shift Operator
The right shift operator shifts the bits of the binary representation of a number to the
right.
public class Main
{
public static void main (String[] args)
{
int x = 5, y = -5;
int n = 2;
int answer1 = x >> n;
[Link]("Right shift " + x + " by " + n + " positions : " + answer1);
}
}

Precedence & Associativity of operators:

Precedence is the priority order of an operator, if there are two or more operators in an
expression then the operator of highest priority will be executed first then higher, and
then high.

For example, in expression 1 + 2 * 5, multiplication (*) operator will be processed first


and then addition. It's because multiplication has higher priority or precedence than
addition.

Associativity tells the direction of execution of operators that can be either left to
right or right to left.

For example, in expression a = b = c = 8 the assignment operator is executed from right


to left that means c will be assigned by 8, then b will be assigned by c, and finally a will
be assigned by b.
Type conversion in java(Type casting):

Typecasting is the process of converting the value of a single data type (such as an
integer [int], float, or double) into another data type.

This conversion is done either automatically or manually.

The compiler performs the automatic conversion, and a programmer does the manual
conversion.
Types of Type Casting in Java

o Implicit / Widening Type Casting


o Narrowing Type Casting

1. Widening Type Casting

Converting a lower data type into a higher one is called widening type casting. It is also
known as implicit conversion

It is done automatically.

It takes place when:

o Both data types must be compatible with each other.


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

byte -> short -> char -> int -> long -> float -> double

For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other.
Let's see an example.

public class WideningTypeCastingExample


{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
[Link]("Before conversion, int value "+x);
[Link]("After conversion, long value "+y);
[Link]("After conversion, float value "+z);
}
}
2. Narrowing Type Casting

Converting a higher data type into a lower one is called narrowing type casting. It is also
known as explicit conversion.

It is done manually by the programmer. If we do not perform casting then the compiler
reports a compile-time error.

1. double -> float -> long -> int -> char -> short -> byte

public class NarrowingTypeCastingExample


{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
[Link]("Before conversion: "+d);
//fractional part lost
[Link]("After conversion into long type: "+l);
//fractional part lost
[Link]("After conversion into int type: "+i);
}
}

Selection statements / Control statemnets in java:

Selection statements are a program control structure in Java. As the name suggests, they are
used to select an execution path if a certain condition is met.

1. The if Statement

This is a single selection statement.


When you want a certain statement to execute if a given condition is true, then use
the if statement.

Ex:
public class Student {
public static void main(String[] args) {
int x = 20;
if(x > 18) {
[Link]("Eligible for vote");
}
}
}
2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block. The else block is executed if the condition of the if-block is
evaluated as false.
[Link] If-else:

A nested if-else statement is an if statement inside another if statement.

if (condition1) {
/* code to be executed if condition1 is true */
if (condition2) {
/* code to be executed if condition2 is true */
} else {
/* code to be executed if condition2 is false */
}
} else {
/* code to be executed if condition1 is false */
}
Example:
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;

if (i == 10)
{
// First if statement
if (i < 15)
[Link]("i is smaller than 15");

// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
[Link]("i is smaller than 12 too");
else
[Link]("i is greater than 15");
}
}
}

1. Else –if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements.
Syntax:
if(condition_expression_One) {
statement1;
} else if (condition_expression_Two) {
statement2;
} else if (condition_expression_Three) {
statement3;
} else {
statement4;
}

Example:

class GFG {
public static void main(String[] args)
{
// initializing expression
int i = 20;

// condition 1
if (i == 10)
[Link]("i is 10\n");

// condition 2
else if (i == 15)
[Link]("i is 15\n");

// condition 3
else if (i == 20)
[Link]("i is 20\n");

else
[Link]("i is not present\n");

[Link]("Outside if-else-if");
}
}

[Link] Statements
The switch statement in Java is a multi-way branch statement.
The Java switch statement executes one statement from multiple conditions.

Syntax:
switch(expression)
{
case value1 :
// Statements
break; // break is optional

case value2 :
// Statements
break; // break is optional
....
....
....
default :
// default Statement
}

Example:
public class GFG {

// Main driver method


public static void main(String[] args)
{
int day = 5;
String dayString;

// Switch statement with int data type


switch (day) {

// Case
case 1:
dayString = "Monday";
break;

// Case
case 2:
dayString = "Tuesday";
break;

// Case
case 3:
dayString = "Wednesday";
break;

// Case
case 4:
dayString = "Thursday";
break;

// Case
case 5:
dayString = "Friday";
break;

// Case
case 6:
dayString = "Saturday";
break;

// Case
case 7:
dayString = "Sunday";
break;

// Default case
default:
dayString = "Invalid day";
}
[Link](dayString);
}
}

Looping structures:
1. For Loop
2. While loop
3. Do-while loop

1. For Loop:
for loop is used to iterate a part of the program several times. If the
number of iteration is fixed, it is recommended to use for loop.

Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}

Example:

public class ForExample {


public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
[Link](i);
}
}
}

2. For each loop:


 For-each is another array traversing technique like for loop, while loop, do-while
loop introduced in Java5.
 It starts with the keyword for like a normal for-loop.
 Instead of declaring and initializing a loop counter variable, you declare a variable
that is the same type as the base type of the array, followed by a colon, which is then
followed by the array name.
 In the loop body, you can use the loop variable you created rather than using an
indexed array element.

Syntax:
for (type var : array)
{
statements using var;
}

Example:

class Easy

public static void main(String[] args)

// array declaration

int ar[] = { 10, 50, 60, 80, 90 };

for (int element : ar)


[Link](element + " ");
}
}

3. While loop:

while loop is used to iterate a part of the program repeatedly until the specified
condition is true.
As soon as the condition becomes false, the loop automatically stops.

Syntax:
while (condition){
//code to be executed
Increament / decrement statement
}

public class WhileExample {


public static void main(String[] args) {
int i=1;
while(i<=10){
[Link](i);
i++;
}
}
}

4. Do while loop:
 Java do-while loop is used to iterate a part of the program repeatedly, until the specified
condition is true.
 If the number of iteration is not fixed and you must have to execute the loop at least once,
it is recommended to use a do-while loop.

SYNTAX:
do{
//code to be executed / loop body
//update statement
}while (condition);

public class DoWhileExample {


public static void main(String[] args) {
int i=1;
do{
[Link](i);
i++;
}while(i<=10);
}
}

5. Nested Loops:
A Nested loop means a loop statement inside another loop statement.
Syntax:
Nested For loop
for ( initialization; condition; increment ) {
for ( initialization; condition; increment ) {
// statement of inside loop
}
// statement of outer loop
}

Nested While loop

Syntax:
while(condition) {
while(condition) {
// statement of inside loop
}

Break Statements:
The Java break statement is used to break loop or switch statement. It breaks the current flow of
the program at specified condition.
We can use Java break statement in all types of loops such as for loop, while loop and do-while
loop.

Syntax:
jump-statement;
break;

Example:
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
[Link](i);
}
}
}

Continue Statement
The Java continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition.
We can use Java continue statement in all types of loops such as for loop, while loop and do-
while loop.

Syntax:
Statement;
Continue;

public class ContinueExample {


public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
[Link](i);
}
}
}

Labeled Loop:
A label is a valid variable name that denotes the name of the loop to where the control of
execution should jump. To label a loop, place the label before the loop with a colon at the
end. Therefore, a loop with the label is called a labeled loop
Syntax:
labelname:
for(initialization; condition; incr/decr)
{
//functionality of the loop
}
public class LabeledForLoop
{
public static void main(String args[])
{
int i, j;
for(i=1;i<=5;i++)
{
[Link]();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
[Link](j + " ");
if(j==9)
break inner;
}
}
}
}
 Array in Java:
 An array is a data structure that stores elements of the same type.
 You can put some data in each cell (one data element per cell). A specific cell is accessed
using its number. An element's number in the array is also called an index.
 An array is homogeneous, i.e. all its cells contain elements of the same type.

1. Declaring an array:
i. dataType[] arrayName;
Ex: int[] myArray;
ii. dataType arrayName[];
Ex: int myArray[];
2. Initialization an Array in Java
datatype[] arrayName = new datatype[length]; OR
datatype arrayName[] = new datatype[length];

Ex: int[] myArray = new int[5];


int myArray1[] = new int[5];

We can Initialize Arrays in Java in two Different ways -


1. Initialize using index - Once an array is created successfully, we can assign the
value to any specific element using its index. Un-assigned elements automatically take
the default value of the array's data type.
int[] myArray = new int[5]; // array declared
myArray[0] = 10; // assigned 10 at index 0
myArray[2] = 37; // assigned 37 at index 0

Array will be -
10 0 37 0 0
2. Initialize while declaring - We can also initialize the whole array while declaring it
just by using curly brackets {}. The string must be in quotes, whereas int, float,
etc., do not require that.
int[] myArray = {1, 2, 3, 4, 5}; // For integer type
String[] myArray1 = {"A", "B", "C", "D"}; // For string type
Ex: class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;

// allocates memory for 10 integers


anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;

[Link]("Element at index 0: "+ anArray[0]);


[Link]("Element at index 1: "+ anArray[1]);
[Link]("Element at index 2: "+ anArray[2]);
[Link]("Element at index 3: "+ anArray[3]);
[Link]("Element at index 4: "+ anArray[4]);
[Link]("Element at index 5: "+ anArray[5]);
[Link]("Element at index 6: "+ anArray[6]);
[Link]("Element at index 7: "+ anArray[7]);
[Link]("Element at index 8: "+ anArray[8]);
[Link]("Element at index 9: "+ anArray[9]);
}
}
The output from this program is:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
Create Two Dimensional Array in Java
// Declaring 2D array
DataType[][] ArrayName;

// Creating a 2D array
ArrayName = new DataType[r][c];
Ex: /Declaring 2D array
int[][] a;

//Creating a 2D array
a = new int[3][3];
import [Link];

public class Main {


public static void main(String args[]) {
int[][] StudentMarks = new int[3][3];

// Marks Attained By Student 1


StudentMarks[0][0] = 90; // English
StudentMarks[0][1] = 70; // Maths
StudentMarks[0][2] = 84; // Science

// Marks Attained By Student 2


StudentMarks[1][0] = 75; // English
StudentMarks[1][1] = 77; // Maths
StudentMarks[1][2] = 89; // Sc
// Marks Attained By Student 3
StudentMarks[2][0] = 69; // English
StudentMarks[2][1] = 93; // Maths
StudentMarks[2][2] = 83; // Science

// Displaying Marks of Students


[Link]("Student Marks Matrix");
[Link]("student marks "+StudentMarks[1][0]);
}
}

2. class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
// Mr. Smith
[Link](names[0][0] + names[1][0]);
// Ms. Jones
[Link](names[0][2] + names[1][1]);
}
}
Array Manipulation:
Common Array Manipulation Operations:
 Declaration and Initialization: Creating an array and optionally assigning initial
values.
 Accessing Elements: Retrieving values at specific indices.
 Modifying Elements: Changing the value of an element at a given index.
 Iterating through Elements: Looping through the array to process each element.
 Finding Array Length: Determining the number of elements in the array.
 Copying Arrays: Creating a new array with the same elements as an existing one.
 Sorting Arrays: Arranging elements in ascending or descending order.
 Searching Arrays: Finding specific elements within the array.

//Program for array manipulation

//Object oriented programming concept:


In Java, the four core Object-Oriented Programming (OOP) concepts are:
Encapsulation, Inheritance, Polymorphism, and Abstraction. These principles make Java
code modular, reusable, secure, and easier to maintain.

1. Class and Object


Class: A blueprint or template that defines the structure and behavior (fields and
methods) of objects.

Example:
class Car {
String color;
void drive() {
[Link]("Car is driving");
}
}

Object: An instance of a class created using the new keyword.

Car myCar = new Car();

[Link]();

2. Encapsulation

 Bundling data (variables) and methods (functions) together inside a class.

 Provides data hiding using access modifiers (private, public, protected).

 Example:

class BankAccount

{ private double balance;


public void deposit(double amount)

balance += amount;

public double getBalance()

return balance;

}}

3. Inheritance

 Mechanism where one class acquires properties and behaviors of another.

 Promotes code reusability.

 Example:

class Animal {

void eat()

{ [Link]("Eating...");

class Dog extends Animal {

void bark() { [Link]("Barking..."); }

4. Polymorphism
 Ability of an object to take many forms.

 Two types:

o Compile-time (Method Overloading): Same method name, different


parameters.

o Runtime (Method Overriding): Subclass provides a specific


implementation of a method defined in the parent class.

 Example:

class Shape {

void draw()

{ [Link]("Drawing shape"); }

class Circle extends Shape {

void draw() { [Link]("Drawing circle"); }

5. Abstraction

 Hiding implementation details and showing only essential features.

 Achieved using abstract classes and interfaces.

 Example:

abstract class Vehicle

abstract void move();

}
class Bike extends Vehicle

void move()

[Link] ("Bike is moving");

}}

Constructors :
A constructor in Java is a special member that is called when an object is created. It
initializes the new object’s state.
Rules for Writing Constructors in Java

 The name of the constructor must be the same as the name of its class.

 A constructor must have no return type. It can not have not even void as its
return type.

 We can use the access modifiers with a constructor to control its access so
that other classes can call the constructor.

 We can not declare a constructor as final, abstract, abstract and


synchronized.

Types of Constructores

1. Default Constructor

2. Parameterised Constructor

3. Copy constructor
1. Default Constructor

A Default Constructor is a constructor with no parameter. The Java compiler


automatically creates a default constructor if we do not write any constructor in our
program.

class Myclass

int number;

String name;

Myclass ()

[Link]("Default Constructor called");

public class DefaultConstructor

public static void main(String[] args)

Myclass object = new Myclass ();

[Link]([Link]);

[Link]([Link]);

}
public class Car {
String model;
int year;

// Parameterized Constructor
public Car(String model, int year) {
[Link] = model;
[Link] = year;
}

public static void main(String[] args) {


Car car = new Car("Toyota", 2021);
[Link]("Model: " + [Link] + ", Year: " + [Link]);
}
}

Method Overloading:
Method Overloading is a feature that allows a class to have multiple methods with the
same name but with different number, sequence or type of parameters. In short multiple
methods with same name but with different signatures. For example the signature of
method add(int a, int b) having two int parameters is different from signature of
method add(int a, int b, int c) having three int parameters.
Three ways to overload a method
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
Example:
class DisplayOverloading
{
//adding two integer numbers
int add(int a, int b)
{
int sum = a+b;
return sum;
}
//adding three integer numbers
int add(int a, int b, int c)
{
int sum = a+b+c;
return sum;
}
}
class JavaExample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
}
}
Output:
30
60

You might also like