[go: up one dir, main page]

0% found this document useful (0 votes)
17 views32 pages

Java Theory

Java, developed by James Gosling in 1995, is a simple, class-based, object-oriented programming language that allows developers to write code once and run it anywhere. It uses a combination of compilation to bytecode and interpretation to machine code, enabling cross-platform compatibility. Key concepts include classes, objects, methods, variables, and various data types, with Java being a statically and strongly typed language.

Uploaded by

Lakhimi doley
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)
17 views32 pages

Java Theory

Java, developed by James Gosling in 1995, is a simple, class-based, object-oriented programming language that allows developers to write code once and run it anywhere. It uses a combination of compilation to bytecode and interpretation to machine code, enabling cross-platform compatibility. Key concepts include classes, objects, methods, variables, and various data types, with Java being a statically and strongly typed language.

Uploaded by

Lakhimi doley
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/ 32

JAVA

JAVA was developed by James Gosling at Sun Microsystems Inc in the


year 1995, later acquired by Oracle Corporation. It is a simple programming
language. Java makes writing, compiling, and debugging programming easy. It
helps to create reusable code and modular programs. Java is a class-based,
object-oriented programming language and is designed to have as few
implementation dependencies as possible. A general-purpose programming
language made for developers to write once run anywhere that is compiled
Java code can run on all platforms that support Java. Java applications are
compiled to byte code that can run on any Java Virtual Machine. The syntax of
Java is similar to c/c++.

JAVA PROGRAMMING LANGUAGE IS NAMED JAVA. WHY?


After the name OAK, the team decided to give a new name to it and the
suggested words were Silk, Jolt, revolutionary, DNA, dynamic, etc. These all
names were easy to spell and fun to say, but they all wanted the name to
reflect the essence of technology. In accordance with James Gosling, Java the
among the top names along with Silk, and since java was a unique name so
most of them preferred it.
Java is the name of an island in Indonesia where the first coffee(named java
coffee) was produced. And this name was chosen by James Gosling while
having coffee near his office. Note that Java is just a name, not an acronym.

JAVA WORKING:

➢ JAVA is compiled into bytecode and then it is interpreted to machine code.

COMPILED INTERPRETED
SOURCE CODE BYTE CODE MACHINE CODE

JDK: collection of tools used for developing and running Java programs.
JRE: JAVA RUNNING ENVIRONMENT.
➢ It helps in executing programs developed in JAVA.

A Simple JAVA Program

Class SampleOne

Public static void main(String args[])

System.out.println(“JAVA is better than C++”);

➢ SampleOne: It is a JAVA identifier that specifies the name of the class to be defined.

OPENING BRACES:

➢ Every class definition in JAVA begins with an opening brace “{“ and ends with a matching a
closing brace “}” .
➢ A class definition in C++ ends with a semicolon.

THE MAIN LINE:

➢ PUBLIC: It is an access specifier that declares the main method as unprotected and therefore
making it accessible to all other classes.
➢ STATIC: It declares this method as one that belongs to the entire class and not a part of any
objects of the class.
➢ The main must always be declared as static since the interpreter uses this method
before any objects are created.
➢ VOID: The type modifier void states that main method does not return any value.

THE OUTPUT LINE:


System.out.println
➢ It is similar to the printf( statement of c.
➢ The println method is a member of the out object, which is a static data member of
system class.
➢ The method println always appends a newline character to the end of the string.
➢ Every Java statement must end with a semicolon.
READING DATA FROM THE KEYBOARD

➢ In order to read data from the keyboard, Java has a scanner class.
➢ Scanner class has a lot of members to read the data from the keyboard.

Scanner S = new.Scanner(System.in)

Read data from the keyboard

Int a = S.nextInt();

Method to read from keyboard

For using scanner we have to include a header file i.e


Import java.util.scanner;

For inputting String:

String = s.nextline();

For inputting character:

Char c = s.next().charAt(0);

Java program is a collection of objects, and these objects communicate


through method calls to each other to work together. Here is a brief discussion
on the Classes and Objects, Method, Instance variables, syntax, and
semantics of Java.
Basic terminologies in Java
1. Class: The class is a blueprint (plan) of the instance of a class (object). It
can be defined as a template that describes the data and behavior
associated with its instance.
• Example: Blueprint of the house is class.
2. Object: The object is an instance of a class. It is an entity that has
behavior and state.
• Example: A car is an object whose states are: brand, color, and
number plate.
• Behavior: Running on the road.
3. Method: The behavior of an object is the method.
• Example: The fuel indicator indicates the amount of fuel left in the
car.
4. Instance variables: Every object has its own unique set of instance
variables. The state of an object is generally created by the values that are
assigned to these instance variables.
5. public static void main(String [] args)
The method main() is the main entry point into a Java program; this is where
the processing starts. Also allowed is the signature public static void
main(String… args).
6. Method Names
i. All the method names should start with a lowercase letter.
ii. If several words are used to form the name of the method, then each first
letter of the inner word should be in Uppercase. Underscores are allowed,
but not recommended. Also allowed are digits and currency symbols.
public void employeeRecords() // valid syntax
public void EmployeeRecords() // valid syntax, but discouraged
7. Identifiers in java
Identifiers are the names of local variables, instance and class variables, and
labels, but also the names for classes, packages, modules and methods. All
Unicode characters are valid, not just the ASCII subset.
I . All identifiers can begin with a letter, a currency symbol or an underscore
(_). According to the convention, a letter should be lower case for variables.

ii. The first character of identifiers can be followed by any combination of


letters, digits, currency symbols and the underscore. The underscore is not
recommended for the names of variables. Constants (static final attributes and
enums) should be in all Uppercase letters.

IiI . Most importantly identifiers are case-sensitive.

iv. A keyword cannot be used as an identifier since it is a reserved word and


has some special meaning.
Legal identifiers: MinNumber, total, ak74, hello_world, $amount,
_under_value
Illegal identifiers: 74ak, -amount
8. White spaces in Java
A line containing only white spaces, possibly with the comment, is known as a
blank line, and the Java compiler totally ignores it.
9. Access Modifiers: These modifiers control the scope of class and
methods.
• Access Modifiers: default, public, protected, private
• Non-access Modifiers: final, abstract, strictfp.

10. Understanding Access Modifiers:


Access Within Within Outside Package by Outside
Modifier Class Package subclass only Package
Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

11. Java Keywords


Keywords or Reserved words are the words in a language that are used
for some internal process or represent some predefined actions. These
words are therefore not allowed to use as variable names or objects.
abstract assert boolean break

byte case catch char

class const continue default

do double else enum

extends final finally float

for goto if implements

import instanceof int interface

long native new package

private protected public return

short static strictfp super

switch synchronized this throw

throws transient try void

volatile While
Variables in Java
Variable in Java is a data container that saves the data values during Java
program execution. Every variable 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.
A variable is a name given to a memory location. It is the basic unit of
storage in a program.
• The value stored in a variable can be changed during program
execution.
• A variable is only a name given to a memory location. All the
operations done on the variable affect that memory location.
• In Java, all variables must be declared before use.

1. datatype: Type of data that can be stored in this variable.


2. data_name: Name given to the variable.
In this way, a name can only be given to a memory location. It can be
assigned values in two ways:
• Variable Initialization
• Assigning value by taking input

How to initialize variables?

It can be perceived with the help of 3 components that are as follows:


• datatype: Type of data that can be stored in this variable.
• variable_name: Name given to the variable.
• value: It is the initial value stored in the variable.

Types of Variables in Java

1. Local Variables
2. Instance Variables
3. Static Variables

1. Local Variables
A variable defined within a block or method or constructor is called a local
variable.
• These variables are created when the block is entered, or the
function is called and destroyed after exiting from the block or when
the call returns from the function.
• The scope of these variables exists only within the block in which
the variables are declared, i.e., we can access these variables only
within that block.

2. Instance Variables
Instance variables are non-static variables and are declared in a class
outside of any method, constructor, or block.
• As instance variables are declared in a class, these variables are
created when an object of the class is created and destroyed when
the object is destroyed.
• Unlike local variables, we may use access specifiers for instance
variables. If we do not specify any access specifier, then the default
access specifier will be used.

3.Static variables are also known as class variables.


• These variables are declared similarly as instance variables. The
difference is that static variables are declared using the static
keyword within a class outside of any method, constructor or block.
• Unlike instance variables, we can only have one copy of a static
variable per class, irrespective of how many objects we create.

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:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
1. Arithmetic Operators: They are used to perform simple arithmetic
operations on primitive data types.
• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• – : Subtraction
2. Unary Operators: Unary operators need only one operand. They are
used to increment, decrement or negate a value.
• – : Unary minus, used for negating the values.
• + : Unary plus indicates the positive value (numbers are positive
without this, however). 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.
• ++ : 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.
• — : 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.
• Pre-Decrement: Value is decremented first, and then the
result is computed.
• ! : Logical not operator, used for inverting a boolean value.
3. Assignment Operator: ‘=’ Assignment operator is used to assigning a
value to any variable. It has a 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.
• +=, for adding left operand with right operand and then assigning it
to the variable on the left.
• -=, for subtracting right operand from left operand and then
assigning it to the variable on the left.
• *=, for multiplying left operand with right operand and then
assigning it to the variable on the left.
• /=, for dividing left operand by right operand and then assigning it to
the variable on the left.
• %=, for assigning modulo of left operand by right operand and then
assigning it to the variable on the left.
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
• Some of the relational operators are-
• ==, Equal to returns true if the left-hand side is equal to
the right-hand side.
• !=, Not Equal to returns true if the left-hand side is not
equal to the right-hand side.
• <, less than: returns true if the left-hand side is less than
the right-hand side.
• <=, less than or equal to returns true if the left-hand side
is less than or equal to the right-hand side.
• >, Greater than: returns true if the left-hand side is
greater than the right-hand side.
• >=, Greater than or equal to returns true if the left-hand
side is greater than or equal to the right-hand side.
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

ata types are 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.
Also, let us cover up other important ailments that there are majorly two types
of languages that are as follows:
1. First, one is a Statically typed language where each variable and
expression type is already known at compile time. Once a variable is
declared to be of a certain data type, it cannot hold values of other
data types. For example C, C++, Java.
2. The other is Dynamically typed languages. These languages can
receive different data types over time. For example Ruby, Python
Java is statically typed and also a strongly typed language because, in
Java, each type of data (such as integer, character, hexadecimal, packed
decimal, and so forth) is predefined as part of the programming language and
all constants or variables defined for a given program must be described with
one of the data types.

Java has two categories in which data types are segregated


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

Types Of Primitive Data Types

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

Let us discuss and implement each one of the following data types that are
as follows:
Type 1: boolean
Boolean data type represents only one bit of information either true or
false which is intended to represent the two truth values of logic and
Boolean algebra, but the size of the boolean data type is virtual machine-
dependent. Values of type boolean are not converted implicitly or explicitly
(with casts) to any other type. But the programmer can easily write
conversion code.
Syntax:
boolean booleanVar;
Size: Virtual machine dependent
Values: Boolean such as true, false
Default Value: false
Example:
• Java
// Java Program to Demonstrate Boolean Primitive DataType

// Class

class GFG {

// Main driver method

public static void main(String args[])

//Boolean data type is a data type that has one of two


possible values (usually denoted true and false).

// Setting boolean to false and true initially

boolean a = false;

boolean b = true;

// If condition holds

if (b == true){

// Print statement

System.out.println("Hi Geek");

// If condition holds

if(a == false){

// Print statement
System.out.println("Hello Geek");

Output
Hi Geek
Hello Geek

Type 2: byte
The byte data type is an 8-bit signed two’s complement integer. The byte
data type is useful for saving memory in large arrays.
Syntax:
byte byteVar;
Size: 1 byte (8 bits)
Values: -128 to 127
Default Value: 0
Example:
• Java
// Java Program to demonstrate Byte Data Type

// Class

class GFG {

// Main driver method

public static void main(String args[]) {

byte a = 126;

// byte is 8 bit value

System.out.println(a);
a++;

System.out.println(a);

// It overflows here because

// byte can hold values from -128 to 127

a++;

System.out.println(a);

// Looping back within the range

a++;

System.out.println(a);

Output
126
127
-128
-127
Type 3: short
The short data type is a 16-bit signed two’s complement integer. Similar to
byte, use a short to save memory in large arrays, in situations where the
memory savings actually matters.
Syntax:
short shortVar;
Size: 2 byte (16 bits)
Values: -32, 768 to 32, 767 (inclusive)
Default Value: 0
Type 4: int
It is a 32-bit signed two’s complement integer.
Syntax:
int intVar;
Size: 4 byte ( 32 bits )
Values: -2, 147, 483, 648 to 2, 147, 483, 647 (inclusive)
Note: The default value is ‘0’
Remember: In Java SE 8 and later, we can use the int data type to
represent an unsigned 32-bit integer, which has a value in the range [0, 232-
1]. Use the Integer class to use the int data type as an unsigned integer.
Type 5: long
The range of a long is quite large. The long data type is a 64-bit two’s
complement integer and is useful for those occasions where an int type is
not large enough to hold the desired value.
Syntax:
long longVar;
Size: 8 byte (64 bits)
Values: {-9, 223, 372, 036, 854, 775, 808} to {9, 223, 372, 036, 854, 775,
807} (inclusive)
Note: The default value is ‘0’.
Remember: In Java SE 8 and later, you can use the long data type to
represent an unsigned 64-bit long, which has a minimum value of 0 and a
maximum value of 264-1. The Long class also contains methods like
comparing Unsigned, divide Unsigned, etc to support arithmetic operations
for unsigned long.
Type 6: float

The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a
float (instead of double) if you need to save memory in large arrays of
floating-point numbers.
Syntax:
float floatVar;
Size: 4 byte (32 bits)
Values: upto 7 decimal digits
Note: The default value is ‘0.0’.
Example:

• Java
// Java Program to Illustrate Float Primitive Data Type

// Importing required classes

import java.io.*;
// Class

class GFG {

// Main driver method

public static void main(String[] args)

// Declaring and initializing float value

// float value1 = 9.87;

// Print statement

// System.out.println(value1);

float value2 = 9.87f;

System.out.println(value2);

Output
9.87
If we uncomment lines no 14,15,16 then the output would have been totally
different as we would have faced an error.

Type 7: double
The double data type is a double-precision 64-bit IEEE 754 floating-point.
For decimal values, this data type is generally the default choice.
Syntax:
double doubleVar;
Size: 8 bytes or 64 bits
Values: Upto 16 decimal digits
Note:
• The default value is taken as ‘0.0’.
• Both float and double data types were designed especially for
scientific calculations, where approximation errors are acceptable. If
accuracy is the most prior concern then, it is recommended not to
use these data types and use BigDecimal class instead.
It is recommended to go through rounding off errors in java.
Type 8: char
The char data type is a single 16-bit Unicode character.
Syntax:
char charVar;
Size: 2 byte (16 bits)
Values: ‘\u0000’ (0) to ‘\uffff’ (65535)
Note: The default value is ‘\u0000’
You must be wondering why is the size of char 2 bytes in Java?
So, in other languages like C/C++ uses only ASCII characters, and to
represent all ASCII characters 8-bits is enough. But java uses the Unicode
system not the ASCII code system and to represent the Unicode system 8
bits is not enough to represent all characters so java uses 2 bytes for
characters. Unicode defines a fully international character set that can
represent most of the world’s written languages. It is a unification of dozens
of character sets, such as Latin, Greeks, Cyrillic, Katakana, Arabic, and
many more.
Example:
• Java
// Java Program to Demonstrate Char Primitive Data Type

// Class

class GFG {

// Main driver method

public static void main(String args[])

// Creating and initializing custom character

char a = 'G';
// Integer data type is generally

// used for numeric values

int i = 89;

// use byte and short

// if memory is a constraint

byte b = 4;

// this will give error as number is

// larger than byte range

// byte b1 = 7888888955;

short s = 56;

// this will give error as number is

// larger than short range

// short s1 = 87878787878;

// by default fraction value

// is double in java

double d = 4.355453532;

// for float use 'f' as suffix as standard

float f = 4.7333434f;

//need to hold big range of numbers then we need this data


type

long l = 12121;
System.out.println("char: " + a);

System.out.println("integer: " + i);

System.out.println("byte: " + b);

System.out.println("short: " + s);

System.out.println("float: " + f);

System.out.println("double: " + d);

System.out.println("long: " + l);

Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121

Non-Primitive Data Type or Reference Data Types

The Reference Data Types will contain a memory address of variable


values because the reference types won’t store the variable value directly in
memory. They are strings, objects, arrays, etc.
A: Strings
Strings are defined as an array of characters. The difference between a
character array and a string in Java is, that the string is designed to hold a
sequence of characters in a single variable whereas, a character array is a
collection of separate char type entities. Unlike C/C++, Java strings are not
terminated with a null character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
// Declare String without using new operator
String s = "GeeksforGeeks";
// Declare String using new operator
String s1 = new String("GeeksforGeeks");
B: Class
A class is a user-defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to
all objects of one type. In general, class declarations can include these
components, in order:
1. Modifiers: A class can be public or has default access. Refer
to access specifiers for classes or interfaces in Java
2. Class name: The name should begin with an initial letter
(capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if
any, preceded by the keyword extends. A class can only extend
(subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces
implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
5. Body: The class body is surrounded by braces, { }.
C: Object
It is a basic unit of Object-Oriented Programming and represents real-life
entities. A typical Java program creates many objects, which as you know,
interact by invoking methods. An object consists of :
1. State: It is represented by the attributes of an object. It also reflects
the properties of an object.
2. Behavior: It is represented by the methods of an object. It also
reflects the response of an object to other objects.
3. Identity: It gives a unique name to an object and enables one
object to interact with other objects.
D: Interface
Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no
body).
• Interfaces specify what a class must do and not how. It is the
blueprint of the class.
• An Interface is about capabilities like a Player may be an interface
and any class implementing Player must be able to (or must
implement) move(). So it specifies a set of methods that the class
has to implement.
• If a class implements an interface and does not provide method
bodies for all functions specified in the interface, then the class
must be declared abstract.
• A Java library example is Comparator Interface. If a class
implements this interface, then it can be used to sort a collection.
E: Array
An array is a group of like-typed variables that are referred to by a common
name. Arrays in Java work differently than they do in C/C++. The following
are some important points about Java arrays.
• In Java, all arrays are dynamically allocated. (discussed below)
• Since arrays are objects in Java, we can find their length using
member length. This is different from C/C++ where we find length
using size.
• A Java array variable can also be declared like other variables with
[] after the data type.
• The variables in the array are ordered and each has an index
beginning from 0.
• Java array can also be used as a static field, a local variable, or a
method parameter.
• The size of an array must be specified by an int value and not long
or short.
• The direct superclass of an array type is Object.
• Every array type implements the
interfaces Cloneable and java.io.Serializable.

Loops in Java
• Difficulty Level : Easy
• Last Updated : 11 May, 2022
Looping in programming languages is a feature which facilitates the execution of
a set of instructions/functions repeatedly while some condition evaluates to true.
Java provides three ways for executing the loops. While all the ways provide
similar basic functionality, they differ in their syntax and condition checking
time.
• while loop: A while loop is a control flow statement that allows code to
be executed repeatedly based on a given Boolean condition. The while
loop can be thought of as a repeating if statement.
Syntax :

while (boolean condition)


{
loop statements...
}
• Flowchart:

• While loop starts with the checking of condition. If it


evaluated to true, then the loop body statements are executed
otherwise first statement following the loop is executed. For
this reason it is also called Entry control loop
• Once the condition is evaluated to true, the statements in the
loop body are executed. Normally the statements contain an
update value for the variable being processed for the next
iteration.
• When the condition becomes false, the loop terminates which
marks the end of its life cycle.
• for loop: for loop provides a concise way of writing the loop structure.
Unlike a while loop, a for statement consumes the initialization,
condition and increment/decrement in one line thereby providing a
shorter, easy to debug structure of looping.
Syntax:
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}
• Flowchart:

• Initialization condition: Here, we initialize the variable in


use. It marks the start of a for loop. An already declared
variable can be used or a variable can be declared, local to
loop only.
• Testing Condition: It is used for testing the exit condition for
a loop. It must return a boolean value. It is also an Entry
Control Loop as the condition is checked prior to the
execution of the loop statements.
• Statement execution: Once the condition is evaluated to
true, the statements in the loop body are executed.
• Increment/ Decrement: It is used for updating the variable
for next iteration.
• Loop termination:When the condition becomes false, the
loop terminates marking the end of its life cycle.
• do while: do while loop is similar to while loop with only difference
that it checks for condition after executing the statements, and
therefore is an example of Exit Control Loop.
Syntax:
do
{
statements..
}
while (condition);
• Flowchart:

• do while loop starts with the execution of the statement(s).


There is no checking of any condition for the first time.
• After the execution of the statements, and update of the
variable value, the condition is checked for true or false value.
If it is evaluated to true, next iteration of loop starts.
• When the condition becomes false, the loop terminates which
marks the end of its life cycle.
• It is important to note that the do-while loop will execute its
statements atleast once before any condition is checked, and
therefore is an example of exit control loop.

DECISION MAKING IN JAVA (IF, IF-ELSE, SWITCH, BREAK,


CONTINUE, JUMP):

Decision Making in programming is similar to decision-making in real life. In


programming also face some situations where we want a certain block of
code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of
execution of a program based on certain conditions. These are used to
cause the flow of execution to advance and branch based on changes to the
state of a program.
Java’s Selection statements:
• if
• if-else
• nested-if
• if-else-if
• switch-case
• jump – break, continue, return
1. if: if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed
or not i.e if a certain condition is true then a block of statement is executed
otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if statement
accepts boolean values – if the value is true then it will execute the block of
statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by
default if statement will consider the immediate one statement to be inside its
block. For example,
if(condition)
statement1;
statement2;

// Here if the condition is true, if block


// will consider only statement1 to be inside
// its block.

Example:
• Java
// Java program to illustrate If statement

class IfDemo {

public static void main(String args[])

int i = 10;

if (i > 15)

System.out.println("10 is less than 15");

// This statement will be executed

// as if considers one statement by default

System.out.println("I am Not in if");

Output
I am Not in if
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 if statement to execute a
block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

Example:
• Java
// Java program to illustrate if-else statement

class IfElseDemo {

public static void main(String args[])

int i = 10;

if (i < 15)

System.out.println("i is smaller than 15");

else

System.out.println("i is greater than 15");

Output
i is smaller than 15
3. 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
}
}

Example:
• Java
// Java program to illustrate nested-if statement

class NestedIfDemo {

public static void main(String args[])


{

int i = 10;

if (i == 10 || i<15) {

// First if statement

if (i < 15)

System.out.println("i is smaller than 15");

// Nested - if statement

// Will only be executed if statement above

// it is true

if (i < 12)

System.out.println(

"i is smaller than 12 too");

} else{

System.out.println("i is greater than 15");

Output
i is smaller than 15
i is smaller than 12 too

4. if-else-if ladder: Here, a user can decide among multiple options.The if


statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions is
true, then the final else statement will be executed.
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

Example:
• Java
// Java program to illustrate if-else-if ladder

class ifelseifDemo {

public static void main(String args[])

int i = 20;

if (i == 10)

System.out.println("i is 10");

else if (i == 15)

System.out.println("i is 15");
else if (i == 20)

System.out.println("i is 20");

else

System.out.println("i is not present");

Output
i is 20

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)
{
cswitch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

•The expression can be of type byte, short, int char, or an
enumeration. Beginning with JDK7, expression can also be of type
String.
• Duplicate case values are not allowed.
• The default statement is optional.
• The break statement is used inside the switch to terminate a
statement sequence.
• The break statement is optional. If omitted, execution will continue
on into the next case.
6. jump: Java supports three jump statements: break, continue and return.
These three statements transfer control to another part of the program.
• Break: In Java, a break is majorly used for:
• Terminate a sequence in a switch statement (discussed
above).
• To exit a loop.
• Used as a “civilized” form of goto.
• Continue: Sometimes it is useful to force an early iteration of a
loop. That is, you might want to continue running the loop but stop
processing the remainder of the code in its body for this particular
iteration. This is, in effect, a goto just past the body of the loop, to
the loop’s end. The continue statement performs such an action.

Example:
• Java
// Java program to illustrate using

// continue in an if statement

class ContinueDemo {

public static void main(String args[])


{

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

// If the number is even

// skip and continue

if (i % 2 == 0)

continue;

// If number is odd, print it

System.out.print(i + " ");

Output
1 3 5 7 9

You might also like