JAVA Unit-1
JAVA Unit-1
Contents
1.1 Program Structure in Java:
1.1.1 Introduction,
1.1.2 Writing Simple Java Programs,
1.1.3 Tokens in Java Programs,
1.1.4 Command Line Arguments,
1.1.5 Comments.
1.2 Data Types, Variables, and Operators:
1.2.1 Introduction,
1.2.2 Data Types in Java,
1.2.3 Static Variables and Methods,(It will be covered
in unit-2)
1.2.4 Attribute Final, (It will be covered in unit-3)
1.2.5 Operators.
1.3 Control Statements:
1.3.1 If Expression,
1.3.2 Switch Statement,
1.3.3 Loops
1.1 Program Structure in Java
1.1.1 Introduction
History of Java:
James Gosling invented a platform independent programming language called as JAVA in the year
1994. At first Java was called as OAK. Java was originally designed for interactive TV, but the digital
cable industry wasn’t ready for the technology.
Java started out as a research project. Research began in 1991 as the Green Project at Sun
Microsystems, Inc. Research efforts birthed a new language, OAK. (A tree outside of the window of
James Gosling’s office at Sun). It was developed as an embedded programming language, which
would enable embedded system application. It was not really created as web programming language.
Java is available as jdk and it is an open-source s/w.
Language was created with 5 main goals:
It should be object oriented.
A single representation of a program could be executed on multiple operating systems. (i.e.
write once, run anywhere)
It should fully support network programming.
It should execute code from remote sources securely.
It should be easy to use.
Oak was renamed Java in 1994. Now Sun Microsystems is a subsidiary of Oracle Corporation.
Java Platforms:
There are three main platforms for Java:
Java SE (Java Platform, Standard Edition) – runs on desktops and laptops.
Java ME (Java Platform, Micro Edition) – runs on mobile devices such as cell phones.
Java EE (Java Platform, Enterprise Edition) – runs on servers.
Java Terminology:
Java Development Kit: It contains one (or more) JRE's along with the various development tools
like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.
Java Runtime Environment: A runtime environment which implements Java Virtual Machine, and
provides all class libraries and other facilities necessary to execute Java programs. This is the software
on your computer that actually runs Java programs. JRE = JVM + Java Packages Classes (like util,
math, lang, awt, swing etc) +runtime libraries.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
What is JVM
1. A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Oracle and other
companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java class,
an instance of JVM is created.
What it does
The JVM performs following operation:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution
engine etc.
1) Class loader
Class loader is a subsystem of JVM which is used to load class files. Whenever we run the java
program, it is loaded first by the class loader. There are three built-in class loaders in Java.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method
data, the code for methods.
3) Heap
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return. Each thread has a private JVM stack, created at the same time as thread. A new
frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.
PC (program counter) register contains the address of the Java virtual machine instruction currently
being executed.
7) Execution Engine
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte
code that have similar functionality at the same time, and hence reduces the amount of time needed for
compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.
8) Java Native Interface
Java Native Interface (JNI) is a framework which provides an interface to communicate with another
application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to
the Console or interact with OS libraries.
C++ Java
C++ is designed to work with compiler only Java can support both compiler and interpreter
C++ uses “cin” and “cout” Complex in/out methods (System.in and System.out)
C++ can provide multiple inheritances Java cannot support multiple inheritances
C++ supports both method overloading
Java supports only method overloading
and operator overloading
Source code is not portable between
Source code is portable to any operating system
different operating systems
Libraries offer low-level of functionality Libraries offer high-level functionality
The programmer is responsible for run-time JVM is responsible for run-time errors and
errors and exceptions exceptions
C++ supports structures (custom data type) Java does not provide structures
C++ needs manual class and object Java is completely automatic regarding class and
management using new and delete keywords object management
C++ needs manual garbage memory clearance Java has an automatic garbage collector
Differences between procedural and object-oriented programming
Below are some of the differences between procedural and object-oriented
programming:
Adding new data and functions is not easy. Adding new data and function is easy.
Java achieving
platform independence:
What is Platform?
Computer is a combination of hardware and software this is called as "PLATFORM". Hardware mostly refers
to microprocessor. Software mostly refers to Operating System. The combination of microprocessor and OS is
called as platform.
platform dependency means the operating system of compilation and operating system of execution should be
same.
JAVA designed its own compiler called as Java Compiler which converts HLL into byte codes. This
byte code is given to Java Virtual Machine (JVM) which converts it to MLL.
Java Execution Procedure:
WORKING:
Let us assume you are writing code using java in your computer which has windows OS. User should
save the file with the extension ".java" so that it is consider to be a java file. For example, consider
Test.java is a file which consist of HLL code. Since Machine understands Machine Level code [MLL]
not your high-level code [HLL], conversion must happen.
Let us see how exactly conversion happens in java. Initially your HLL code is given as input to
compiler but java compiler will not give MLL code as output like C and C++ compiler rather it takes
HLL as input and gives a special type of code as output called as "BYTE CODE" which is platform
independent. Byte code is neither HLL code nor MLL code, hence it is also referred to as intermediate
code. If you can recollect machine understands only MLL code but java compiler gave you byte code.
To resolve this, James Gosling provided a software called as "Java virtual Machine"(JVM) which was
platform dependent that is different OS have different JVM. Since you are writing code on windows
OS, you will have to download windows compatible JVM. JVM will now convert byte code to
machine level code which machine can easily understand. In this way, java achieved platform in
dependency using a special type of code which is byte code
Disadvantage of Java
● In java, extra step is involved in conversion from HLL to java code to MLL code java program are
relatively slower in execution when compared to C/C++ programs.
● Time consumption is more in java.
● Speed of execution is slower.
Flowchart 1 is execution steps in C and Flowchart 2 is execution steps in Java.
The Java compiler breaks the line of code into text (words) is called Java tokens. These are the
smallest element of the Java program. The Java compiler identified these words as tokens. These
tokens are separated by the delimiters. It is useful for compilers to detect errors. Remember that the
delimiters are not part of the Java tokens.
In the above code snippet, public, class, Demo, {, static, void, main, (, String, args, [ ], ), System,
., out, println, javatpoint, etc. are the Java tokens.
Types of Tokens
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
6. Comments
1)Java Keywords
Java keywords are also known as reserved words. Keywords are particular words that act as a key to
a code. These are predefined words by Java so they cannot be used as a variable or object name or
class name.
1. abstract: Java abstract keyword is used to declare an abstract class. An abstract class can
provide the implementation of the interface. It can have abstract and non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold
True and False values only.
3. break: Java break keyword is used to break the loop or switch statement. It breaks the current
flow of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
5. case: Java case keyword is used with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must
be used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode
characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current flow of
the program and skips the remaining code at the specified condition.
10. default: Java default keyword is used to specify the default block of code in a switch
statement.
11. do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of
the program several times.
12. double: Java double keyword is used to declare a variable that can hold 64-bit floating-point
number.
13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are
always private or default.
15. extends: Java extends keyword is used to indicate that a class is derived from another class or
interface.
16. final: Java final keyword is used to indicate that a variable holds a constant value. It is used
with a variable. It is used to restrict the user from updating the value of the variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is
always executed whether an exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point
number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the number of iteration
is fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and accessible to the
current source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance of the
specified class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
25. interface: Java interface keyword is used to declare an interface. It can have only abstract
methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native code
using JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything. It
removes the garbage value.
30. package: Java package keyword is used to declare a Java package that includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a method or
variable may be accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible within the
package and outside the package but through inheritance only. It can't be applied with the
class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is
accessible anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class method. The
static keyword in Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
38. super: Java super keyword is a reference variable that is used to refer to parent class objects.
It can be used to invoke the immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code based on test
value. The switch statement tests the equality of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or methods
in multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword
is mainly used to throw custom exceptions. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exceptions can be
propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try
block must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the program
several times. If the number of iteration is not fixed, it is recommended to use the while loop.
2)Identifier: Identifiers are used to name a variable, constant, function, class, and array. It usually
defined by the user. It uses letters, underscores, or a dollar sign as the first character. The label is also
known as a special kind of identifier that is used in the goto statement. Remember that the identifier
name must be different from the reserved keywords.
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start with
digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
Examples:
PhoneNumber
PRICE
radius
a
a1
_phonenumber
$circumference
jagged_array
12radius //invalid
3)Literals: In programming literal is a notation that represents a fixed value (constant) in the source
code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the
programmer. Once it has been defined cannot be changed.
23 int
9.86 double
"javatpoint" String
4)Operators: In programming, operators are the special symbol that tells the compiler to perform a
special operation. Java provides different types of operators that can be classified according to the
functionality they provide.
separator <= ; | , | . | ( | ) | { | } | [ | ]
o Square Brackets []: It is used to define array elements. A pair of square brackets represents
the single-dimensional array, two pairs of square brackets represent the two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates the two
statements.
o Period (.): It separates the package name form the sub-packages and class. It also separates a
variable or method from a reference variable.
6)Java Comments: The Java comments are the statements in a program that are not executed by the
compiler and interpreter.
o Comments are used to make the program more readable by adding the details of the code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
o It can also be used to prevent the execution of program code while testing the alternative code.
What is args?
Arguments means data passed on the command line. Args is technically called as "Dynamic Array"
using which the command line arguments are collected. In java, along with the control of execution
we can also give inputs/ data to the main method. To collect the input / data there is args. Initially args
is an empty basket.
Different way to declare Syntax / Signatures in main method
● public static void main (String [] args)
● static public void main (String [] args)
● public static void main (String args [])
● public static void main (String...args)
The single-line comment is used to comment only one line of the code. It is the widely used and easiest
way of commenting the statements. Single line comments starts with two forward slashes (//). Any
text in front of // is not executed by Java.
Syntax:
//This is single line comment
2) Java Multi Line Comment
The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex
code snippet or to comment multiple lines of code at a time (as it will be difficult to use single-line
comments there). Multi-line comments are placed between /* and */. Any text between /* and */ is
not executed by Java.
Syntax:
/*
This
is
multi line
comment
*/
3) Java Documentation Comment
Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e., which
classes, methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation comments are
placed between /** and */.
Syntax:
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/
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, Strings
and Arrays.
In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.
Syntax:
byte byteVar;
Ex: byte b, c=100;
2) short is a signed 16-bit byte. Assume, if we create a short type variable as short a; It means in the
memory two bytes is allocated and it is referred as a
Syntax:
short shortVar;
Ex: short b, c=234;
3) int is a signed 32-bit byte. It is the most commonly used integer type. In addition to other uses,
variables of type int are commonly employed to control loops and to index arrays. Assume, if we
create an int type variable as int a; It means in the memory four bytes is allocated and it is referred as
a.
Syntax:
int intVar;
Ex: int b, c=234443;
4) long is a signed 64-bit byte and is useful for those occasions where an int type is not large enough
to hold the desired value. The range of long is quite large. This is useful, when big whole numbers are
needed. Assume, if we create an long type variable as long a; It means in the memory eight bytes is
allocated and it is referred as a.
Syntax:
long longVar;
Ex: long b, c=233444L;
Syntax:
float floatVar;
Ex: float b, c=2.4f;
2)double: The double data type is a double-precision 64-bit IEEE 754 floating-point. The double data
type is normally the default choice for decimal values. The data type should never be used for precise
values, such as currency. Double data type stores decimal values with 15-16 digits of precision. The
default value is 0.0d, this means that if you do not append f or d to the end of the decimal, the value
will be stored as a double in Java. Assume, if we create an double type variable as double a; It means
in the memory eight bytes is allocated and it is referred as a.
Syntax:
double doubleVar;
Ex: double b, c=2.4;
Syntax:
boolean booleanVar;
Ex: boolean b, c=true;
1)Local variables:
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered and the variable will be
destroyed once it exits the method, constructor or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor or block.
• There is no default value for local variables so local variables should be declared and an initial value
should be assigned before the first use.
The control of execution will start from the main method and the memory for variables a,b,c,d is
allocated in the stack segment and values will be assigned. Default values for local variables will not
be assigned by jvm.
2)Instance variables:
• Instance variables are declared in a class, but outside a method, constructor or any block.
• Instance variables are created when an object is created with the use of the key word 'new' and
destroyed when the object is destroyed.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the class.
• Instance variables have default values.
• Instance variables can be accessed directly by calling the variable name inside the class.
• However, within static methods and different class (when instance variables are given accessibility)
that should be called using the fully qualified name ObjectReference.VariableName
Here control of execution will start from the main method. In the main method when a new keyword
is called an object is created in the heap segment and memory for instance variables name, breed and
cost is allocated the default values for the variables is allocated then the values that is assigned will
get allocated i.e name=” scooby”, breed = “pug”, cost = 12000.
3) Class/Static variables:
• Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of how many objects are
created from it.
• Static variables are stored in static memory.
• Static variables are created when the program starts and destroyed when the program stops.
• Visibility is similar to instance variables.
• Default values are same as instance variables.
• Static variables can be accessed by calling with the class name
Syntax:
ClassName.VariableName
Program:
public class DefaultVariables
{
This conversion is implicitly done without user interaction and hence it is referred to as implicit type
casting.
Explicit type casting(type casting or narrowing conversion):
When a larger data type is converted to a smaller data type, the conversion not automatically
performed by the java complier and must be done by programmer explicitly and hence it is referred
to as explicit type casting.
Let us consider a simple code snippet to understand this, the way we understood explicit type casting.
double a = 45.5;
byte b;
b = a; → error
a is a variable of type double whose size is 8 bytes. b is a variable of type byte whose size is 1 byte.
b = a;
will give you error as you are trying to store a larger type of data into smaller type.
The above conversion will result in error as loss of precision occurs. To get the error free output, we
have to explicitly convert the data as shown below
double a = 45.5;
byte b;
b = byte(a);
b is of type byte and it will only store 45 and 0.5 is lost during the conversion which is the disadvantage
of explicit type casting.
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only. We will
have detailed learning of these. Let's first learn the basics of final keyword.
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.
Program:
class FinalKeyword
{
public static void main(String args[]){
final int speedlimit=90;
speedlimit=40; /* error: cannot assign a value to final //variable speedlimit=40; */
System.out.print(speedlimit);
}
}
1.2.5 Operators
In programming, operators are the special symbol that tells the compiler to perform a special
operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators
Arithmetic Operators:
Operator Result
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
Assignment Operators:
Operator Result
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
Relational Operators:
The relational operators determine the relationship that one operand has to the other. They determine
equality and ordering.
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Unary Operator:
++. --,!
Logical Operator:
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
! Logical unary NOT
|| Short-circuit OR
&& Short-circuit AND
Ternary Operator:
Operator Result
?: Ternary if-then-else
Bitwise Operators:
bitwise operators can be applied to the integer types, long, int, short, byte and char. These operators
act upon the individual bits of their operands.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
Shift Operator:
Operator Result
>> Shift right
>>> Shift right zero fill
<< Shift left
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
Increement and Decreement Operators:
Increment and Decrement in Java programming let you easily add 1 or subtract 1 from variable. To achieve
this, we have two different types of operators.
INCREMENT In Java, the increment unary operator increases the value of the variable by one.
" ++ " is the operator used to increment.
There are two types of Increment
● Pre-Increment.
● Post-Increment.
Pre-Increment-
● "++” is written before Variable name.
● Value will be Incremented First and then incremented value is used in expression.
Post-Increment
● "++” is written after Variable name.
● Value is used in expression first and then gets incremented.
Decrement
In Java, the decrement unary operator decreases the value of the variable by one. " -- " is the operator used to
decrement.
There are two types of Increment
● Post-Decrement.
● Pre-Decrement.
Pre-Decrement-
● “--” is written before Variable name.
● Value is decremented First and then decremented value is used in expression
Post-Decrement-
● “--” is written after Variable name.
● Value is used in expression first and then gets decremented.
Expressions:
An expression is a combination of constants (like 10), operators ( like +), variables(section of memory)
and parentheses ( like “(” and “)” ) used to calculate a value.
Ex1: x = 1;
Ex2: y = 100 + x;
Ex3: x = (32 - y) / (x + 5)
1.3 Control Statements
Java Control Statements or Control Flow in Java
Java compiler executes the code from top to bottom. The statements in the code are executed according
to the order in which they appear. However, Java provides statements that can be used to control the
flow of Java code. Such statements are called control flow statements. It is one of the fundamental
features of Java, which provides a smooth flow of program.
1. Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow depending
upon the result of the condition provided. There are two types of decision-making statements in Java,
i.e., If statement and switch statement.
If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value, either
true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
Program:
Output:
x + y is greater than 20
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.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Program:
Output:
x + y is greater than 20
if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the program
may enter in the block of code where the condition is true. We can also define an else statement at the
end of the chain.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Program:
Output:
Delhi
Nested if-statement:
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-
if statement.
Program:
Output:
Delhi
1.3.2 Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being switched.
The switch statement is easier to use instead of if-else-if statements. It also enhances the readability
of the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It
is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
Output:
While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value. The switch permits only int, string, and Enum type
variables to be used.
In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when we exactly
know the number of times, we want to execute the block of code.
Consider the following example to understand the proper functioning of the for loop in java.
Program:
Output:
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-
each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is
given below.
Consider the following example to understand the functioning of the for-each loop in Java.
Program:
Output:
Java
C
C++
Python
JavaScript
while loop:
The while loop is also used to iterate over the number of statements multiple times. However, if we
don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for
loop, the initialization and increment/decrement doesn't take place inside the loop statement in while
loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If
the condition is true, then the loop body will be executed; otherwise, the statements after the loop will
be executed.
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
Program:
Output:
0
2
4
6
8
10
do-while loop:
The do-while loop checks the condition at the end of the loop after executing the loop statements.
When the number of iteration is not known and we have to execute the loop at least once, we can use
do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax
of the do-while loop is given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
Example for do-while:
Program:
Output:
3. Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java, i.e., break and continue.
As the name suggests, the break statement is used to break the current flow of the program and transfer
the control to the next statement outside a loop or switch statement. However, it breaks only the inner
loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
Program:
Output:
0
1
2
3
4
5
6
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
Program:
Output:
0
1
2
3
5
1
2
3
5
2
3
5