Advance OOP - 021814
Advance OOP - 021814
1
Java Data Types .................................................................................................................................... 20
Types of Data Types in Java ............................................................................................................... 20
1. Java Primitive Data Types.............................................................................................................. 21
2. Java Reference/Object Data Type ................................................................................................ 21
Example ......................................................................................................................................... 21
Java Class Attributes ........................................................................................................................... 22
Creating (Declaring) Java Class Attributes ..................................................................................... 22
Syntax ............................................................................................................................................. 22
Example: Declaring Java Class Attributes ................................................................. 22
Java Class Methods .............................................................................................................................. 23
Creating (Declaring) Java Class Methods ........................................................................................ 23
Syntax ............................................................................................................................................. 23
Example ......................................................................................................................................... 24
this Keyword in Java Class Methods ................................................................................................ 24
Public Vs. Static Class Methods ......................................................................................................... 25
Example ......................................................................................................................................... 25
The finalize( ) Method ........................................................................................................................ 26
Java Methods ........................................................................................................................................ 27
Creating a Java Method....................................................................................................................... 27
Syntax to Create a Java Method ...................................................................................... 27
Example to Create a Java Method .................................................................................. 28
Calling a Java Method.......................................................................................................................... 28
Java Methods Overloading ................................................................................................................. 29
Example: Methods Overloading in Java ...................................................................... 29
Important Points About Variables Scope ........................................................................................ 31
Java Constructors ................................................................................................................................ 31
Rules for Creating Java Constructors ............................................................................................... 31
Creating a Java Constructor ............................................................................................................... 32
Syntax ............................................................................................................................................. 32
Example to create a Java Constructor ......................................................................... 32
Types of Java Constructors ................................................................................................................ 33
1. Default Constructor ........................................................................................................... 33
2. No-Args (No Argument) Constructor...................................................................... 34
2
3. Parameterized Constructor .......................................................................................... 35
Constructor Overloading in Java ...................................................................................................... 36
Example: Constructor Overloading................................................................................ 37
Java Interfaces...................................................................................................................................... 38
Java Interfaces and Classes: Similarities and Differences ........................................................... 39
Similarities ................................................................................................................................... 39
Differences ................................................................................................................................... 39
Declaring an Interface in Java ........................................................................................................... 40
Example to Declare a Java Interface ........................................................................... 40
Propeties of Java Interface................................................................................................................. 40
Example ......................................................................................................................................... 40
Implementing Interfaces in Java ...................................................................................................... 40
Example: Implement an Interface in Java ................................................................ 41
Difference between abstract class and interface................................................................................. 41
Java Packages ....................................................................................................................................... 43
Types of Java Packages ....................................................................................................................... 43
User-defined Java Packages............................................................................................................... 43
Creating a Java Package...................................................................................................................... 43
Compiling with Java Package ............................................................................................................ 44
Java Package Example ........................................................................................................................ 44
Java Abstraction................................................................................................................................... 46
Java Abstract Classes .......................................................................................................................... 46
What Is an Exception in Java? ........................................................................................................... 46
Why Exception Occurs? ...................................................................................................................... 46
The Throws/Throw Keywords.......................................................................................................... 47
Example ......................................................................................................................................... 47
Example ......................................................................................................................................... 47
The Finally Block ................................................................................................................................. 48
Syntax ............................................................................................................................................. 48
Example ......................................................................................................................................... 48
Java try and catch .............................................................................................................................. 49
The try Block ............................................................................................................................... 49
The catch Block .......................................................................................................................... 49
3
Syntax of Java try and catch Block ............................................................................... 50
Example of Java try and catch Block ............................................................................ 50
Java - Multithreading .............................................................................................................................. 50
Java Multithreading ............................................................................................................................ 51
Life Cycle of a Thread in Java Multithreading ................................................................................ 51
Java - Applet Basics.................................................................................................................................... 52
Life Cycle of an Applet in Java ....................................................................................................... 52
AWT ............................................................................................................................................................ 53
AWT Hierarchy .................................................................................................................................... 53
Introduction to Java Servlets .................................................................................................................. 54
What is CGI? .................................................................................................................................... 54
Difference between Servlet and CGI ......................................................................................... 55
if: ............................................................................................................................................................. 55
if-else: ................................................................................................................................................. 57
nested-if: .......................................................................................................................................... 58
if-else-if ladder: .................................................................................................................................. 59
switch-case: ........................................................................................................................................ 61
jump: ..................................................................................................................................................... 62
Break: .................................................................................................................................................... 62
Continue:.............................................................................................................................................. 63
Return: .................................................................................................................................................. 64
Introduction To Java
Java is an object-oriented, class-based programming language. The language is
designed to have as few dependencies implementations as possible. The intention of
using this language is to give relief to the developers from writing codes for every
platform. The term WORA, write once and run everywhere is often associated with this
language. It means whenever we compile a Java code, we get the byte code (.class
file), and that can be executed (without compiling it again) on different platforms
provided they support Java. In the year 1995, Java language was developed. It is
mainly used to develop web, desktop, and mobile devices. The Java language is known
for its robustness, security, and simplicity features. That is designed to have as few
implementation dependencies as possible.
4
History
The Java language has a very interesting history. Patrick Naughton, Mike Sheridan, and
Jame Gosling, known as the Green team, started the development of Java in the year
1991. These people were the engineers at Sun Microsystems. In 1996, the first public
implementation was released as Java 1.0. The compiler of Java 1.0 was rewritten by
Arthur Van Hoff to comply strictly with its specification. With the introduction of Java 2,
the new versions have multiple different configurations that have been built for the
various platforms. It is worth noting that James Gosling is also known as the father of
Java.
The ISO standard body was approached by Sun Microsystems in the year 1997 to
formalize Java, but the process was withdrawn soon. At one point in time, Sun
Microsystems provided most of its implementation of Java available without any cost,
despite having the status of proprietary software.
Applications of Java
Java has become the most robust programming language because of its amazing
features. Some of its features are platform independence, high performance,
Object orientation, support for automatic garbage management, and many more.
In this blog, we will discuss the Top 10 Applications of Java in the real world
in a detailed manner.
• Desktop GUI Applications
• Mobile Applications
• Artificial intelligence
• Web applications
• Big Data technology
• Gaming applications
• Business applications
• Embedded systems
• Cloud applications
• Scientific applications
Features of Java
Platform Independent: Instead of directly generating the .exe file, Java compiler converts
the Java code to byte code, and this byte code can be executed on different platforms
without any issue, which makes Java a platform-independent language. Note that in order
to execute the byte code, JVM has to be installed on the system, which is platform
dependent.
5
Object-Oriented Programming Language: The concept of object-oriented programing
is based on the concept of objects and classes. Also, there are several qualities that are
present in object-oriented programming. A few of them are mentioned below.
o Abstraction
o Inheritance
o Polymorphism
o Encapsulation
The Java language also extensively uses the concepts of classes and objects. Also, all these
features mentioned above are there in Java, which makes Java an object-oriented
programming language. Note that Java is an object-oriented programming language but
not 100% object-oriented.
Simple: Java is considered a simple language because it does not have the concept of
pointers, multiple inheritances, explicit memory allocation, or operator overloading.
Robust:
Java language is very much robust. The meaning of robust is reliable. The Java language
is developed in such a fashion that a lot of error checking is done as early as possible. It
is because of this reason that this language can identify those errors that are difficult to
identify in other programming languages. Exception Handling, garbage collections, and
memory allocation are the features that make Java robust.
Secure: There are several errors like buffer overflow or stack corruption that are not
possible to exploit in the Java language. We know that the Java language does not have
pointers. Therefore, it is not possible to have access to out-of-bound arrays. If someone
tries to do so, ArrayIndexOutofBound Exception is raised. Also, the execution of the Java
programs happens in an environment that is completely independent of the Operating
System, which makes this language even more secure.
Distributed: Distributed applications can be created with the help of the Java language.
Enterprise Java beans and Remote Method Invocation are used for creating distributed
applications. The distribution of Java programs can happen easily between one or more
systems that are connected to each other using the internet.
6
Portability: We know that Java is a platform-independent language. Thus, the byte code
generated on one system can be taken on any other platform for execution, which makes
Java portable.
SandBox Execution: It is a known fact that Java programs are executed in different
environment, which gives liberty to users to execute their own applications without
impacting the underlying system using the bytecode verifier. The Bytecode verifier also
gives extra security as it checks the code for the violation of access.
Write Once Run Anywhere: The Java code is compiled by the compiler to get the .class
file or the byte code, which is completely independent of any machine architecture.
Byte Code: It has already been discussed in the introductory part that the Java compiler
compiles the Java code to generate the .class file or the byte code. One has to use
the javac command to invoke the Java compiler.
Java Development Kit (JDK): It is the complete Java Development Kit that encompasses
everything, including JRE(Java Runtime Environment), compiler, java docs, debuggers, etc.
7
JDK must be installed on the computer for the creation, compilation, and execution of a
Java program.
Java Runtime Environment (JRE): JRE is part of the JDK. If a system has only JRE
installed, then the user can only run the program. In other words, only the java command
works. The compilation of a Java program will not be possible (the javac command will
not work).
Garbage Collector: Programmers are not able to delete objects in Java. In order to do so,
JVM has a program known as Garbage Collector. Garbage Collectors recollect or delete
unreferenced objects. Garbage Collector makes the life of a developer/ programmer easy
as they do not have to worry about memory management.
Classpath: As the name suggests, classpath is the path where the Java compiler and the Java
runtime search the .class file to load. Many inbuilt libraries are provided by the JDK. However, if
someone wants to use the external libraries, it should be added to the classpath.
What is JVM?
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a
Java program.
When you run the Java program, Java compiler first compiles your Java code to
bytecode. Then, the JVM translates bytecode into native machine code (set of
instructions that a computer's CPU executes directly).
Java is a platform-independent language. It's because when you write Java code, it's
ultimately written for JVM but not your physical machine (computer). Since JVM
executes the Java bytecode which is platform-independent, Java is platform-
independent.
What is JRE?
JRE (Java Runtime Environment) is a software package that provides Java class
libraries, Java Virtual Machine (JVM), and other components that are required to run
Java applications.
8
JRE is the superset of JVM.
What is JDK?
JDK (Java Development Kit) is a software development kit required to develop
applications in Java. When you download JDK, JRE is also downloaded with it.
Java vs C++
Comparison C++ Java
Index
9
Platform- C++ is platform-dependent. Java is platform-independent.
independent
Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
Windows-based, web-based, enterprise,
and mobile applications.
Design Goal C++ was designed for systems Java was designed and created as an
and applications interpreter for printing systems but later
programming. It was an extended as a support network
extension of the C computing. It was designed to be easy to
programming language. use and accessible to a broader
audience.
Pointers C++ supports pointers. You can Java supports pointer internally.
write a pointer program in C++. However, you can't write the pointer
program in java. It means java has
restricted pointer support in java.
Compiler and C++ uses compiler only. C++ is Java uses both compiler and interpreter.
Interpreter compiled and run using the Java source code is converted into
compiler which converts bytecode at compilation time. The
source code into machine interpreter executes this bytecode at
code so, C++ is platform runtime and produces output. Java is
dependent. interpreted that is why it is platform-
independent.
10
Call by Value C++ supports both call by value Java supports call by value only. There is
and Call by and call by reference. no call by reference in java.
reference
Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.
Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies on
third-party libraries for thread
support.
Virtual C++ supports virtual keyword Java has no virtual keyword. We can
Keyword so that we can decide whether override all non-static methods by
or not to override a function. default. In other words, non-static
methods are virtual by default.
Inheritance C++ always creates a new Java always uses a single inheritance
Tree inheritance tree. tree because all classes are the child of
the Object class in Java. The Object class
is the root of the inheritance tree in java.
11
OOPs (Object-Oriented Programming System)
12
1. Object
2. Class
3. Inheritance
4. Polymorphism
13
the inheritance where we can have multiple methods with the same
name in parent and child classes.
5. Abstraction
6. Encapsulation
• Classes
• Objects
• Inheritance
• Polymorphism
• Encapsulation
• Abstraction
• Instance
14
• Method
• Message Passing
In this tutorial, we will learn about Java Classes and Objects, the
creation of the classes and objects, accessing class methods, etc.
Java Classes
For example, if you want to create a class for students. In that case,
"Student" will be a class, and student records
(like student1, student2, etc) will be objects.
16
public void setAge(int age) {
this.age = age;
}
public void setColor(String color) {
this.color = color;
}
If we consider the real world, we can find many objects around us,
cars, dogs, humans, etc. All these objects have a state and a
behavior.
If we consider a dog, then its state is - name, breed, and color, and
the behavior is - barking, wagging the tail, and running.
17
Creating (Declaring) a Java Object
18
public void setAge(int age) {
this.age = age;
}
public void setColor(String color) {
this.color = color;
}
// Printing values
obj.printDetails();
}
}
Output
Dog detials:
Golden Retriever
2
Golden
19
Accessing Instance Variables and Methods
Java data types are used to define the type of data for the
different types of variables, constants, method parameters, returns
type, etc. The variables are nothing but reserved memory locations
to store some values. This means that when you create a variable
you reserve some space in the memory to store some data. The
data type tells the compiler about the type of data to be stored and
the required memory.
20
1. Java Primitive Data Types
• byte
• short
• int
• long
• float
• double
• boolean
2. Java Reference/Object Data Type
Example
21
Java Class Attributes
Java class attributes are the variables that are bound in a class i.e.,
the variables which are used to define a class are class attributes.
Syntax
void barking() {
}
void hungry() {
}
void sleeping() {
}
22
}
In above class, we've fields like breed, age, and color which are also
known as class attributes.
The class methods are methods that are declared within a class. They
perform specific operations and can access, modify the class
attributes.
Syntax
23
• Parameter List − The list of parameters, it is the type, order,
and number of parameters of a method. These are optional,
method may contain zero parameters.
• method body − The method body defines what the method does
with the statements.
Example
class Util {
/** the snippet returns the minimum between two numbers */
public int minimum(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
24
class Student {
int age;
Student(int age) {
this.age = age;
}
}
• Call one type of constructor (parametrized constructor or
default) from other in a class. It is known as explicit
constructor invocation.
class Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
There are two types of class methods public and static class method.
The public class methods are accessed through the objects whereas,
the static class methods are accessed are accesses without an object.
You can directly access the static methods.
Example
25
// Creating a public method
public void fun2() {
System.out.println("fun2: This is a public method.");
}
For example, you might use finalize( ) to make sure that an open
file owned by that object is closed.
Inside the finalize( ) method, you will specify those actions that
must be performed before an object is destroyed.
26
The finalize( ) method has this general form −
This means that you cannot know when or even if finalize( ) will be
executed. For example, if your program ends before garbage
collection occurs, finalize( ) will not execute.
Java Methods
In this tutorial, we will learn how to create your own methods with
or without return values, invoke a method with or without
parameters, and apply method abstraction in the program design.
27
The syntax shown above includes −
return min;
}
Calling a Java Method
28
This called method then returns control to the caller in two
conditions, when −
System.out.println("This is tutorialspoint.com!");
When a class has two or more methods by the same name but
different parameters, it is known as method overloading. It is
different from overriding. In overriding, a method has the same
method name, type, number of parameters, etc.
29
int result1 = minFunction(a, b);
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Output
Minimum Value = 6
Minimum Value = 7.3
30
Overloading methods makes program readable. Here, two methods
are given by the same name but with different parameters. The
minimum number from integer and double types is the result.
31
•The name of the constructors must be the same as the class
name.
• Java constructors do not have a return type. Even do not use
void as a return type.
• There can be multiple constructors in the same class, this
concept is known as constructor overloading.
• The access modifiers can be used with the constructors, use if
you want to change the visibility/accessibility of constructors.
• Java provides a default constructor that is invoked during the
time of object creation. If you create any type of constructor,
the default constructor (provided by Java) is not invoked.
Creating a Java Constructor
Syntax
class ClassName {
ClassName() {
}
}
Example to create a Java Constructor
32
// Creating a class's object
// that will invoke the constructor
Main obj_x = new Main();
}
}
• Default Constructor
• No-Args Constructor
• Parameterized Constructor
1. Default Constructor
33
public class Main {
int num1;
int num2;
Output
num1 : 0
num2 : 0
2. No-Args (No Argument) Constructor
34
num2 = -1;
}
Output
num1 : -1
num2 : -1
3. Parameterized Constructor
Most often, you will need a constructor that accepts one or more
parameters. Parameters are added to a constructor in the same way
that they are added to a method, just declare them inside the
parentheses after the constructor's name.
35
num1 = a;
num2 = b;
}
System.out.println("obj_y");
System.out.println("num1 : " + obj_y.num1);
System.out.println("num2 : " + obj_y.num2);
}
}
Output
obj_x
num1 : 10
num2 : 20
obj_y
num1 : 100
num2 : 200
36
Example: Constructor Overloading
// no-args constructor
Student() {
this.name = "Unknown";
this.age = 0;
}
37
Student std1 = new Student(); // invokes no-args constructor
Student std2 = new Student("Jordan"); // invokes parameterized constructor
Student std3 = new Student("Paxton", 25); // invokes parameterized
constructor
// Printing details
System.out.println("std1...");
std1.printDetails();
System.out.println("std2...");
std2.printDetails();
System.out.println("std3...");
std3.printDetails();
}
}
Output
td1...
Name : Unknown
Age : 0
std2...
Name : Jordan
Age : 0
std3...
Name : Paxton
Age : 25
Java Interfaces
38
Along with abstract methods, an interface may also contain
constants, default methods, static methods, and nested types.
Method bodies exist only for default methods and static methods.
39
Declaring an Interface in Java
40
A class uses the implements keyword to implement an interface. The
implements keyword appears in the class declaration following the
extends portion of the declaration.
41
Abstract class and interface both are used to achieve abstraction where we can declare
the abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract class can extend another An interface can extend another Java interface
Java class and implement multiple Java only.
interfaces.
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
42
Java Packages
43
enumerations, and annotation types that you want to include in the
package.
The package statement should be the first line in the source file.
There can be only one package statement in each source file, and it
applies to all types in the file.
interface Animal {
public void eat();
public void travel();
}
interface Animal {
public void eat();
public void travel();
}
Output
$ javac -d . Animal.java
$ javac -d . MammalInt.java
45
Java Abstraction
46
Some of these exceptions are caused by user error, others by
programmer error, and others by physical resources that have failed
in some manner.
Example
import java.io.*;
public class className {
Example
import java.io.*;
public class className {
47
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}
The Finally Block
The finally block follows a try block or a catch block. A finally block
of code always executes, irrespective of occurrence of an Exception.
A finally block appears at the end of the catch blocks and has the
following syntax −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Example
public class ExcepTest {
Output
49
Syntax of Java try and catch Block
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
Example of Java try and catch Block
package com.tutorialspoint;
Java - Multithreading
50
Java is a multi-threaded programming language which means we
can develop multi-threaded program using Java. A multi-threaded
program contains two or more parts that can run concurrently and
each part can handle a different task at the same time making
optimal use of the available resources specially when your computer
has multiple CPUs.
Java Multithreading
A thread goes through various stages in its life cycle. For example,
a thread is born, started, runs, and then dies. The following diagram
shows the complete life cycle of a thread.
51
Java - Applet Basics
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java
application, including the following −
Four methods in the Applet class gives you the framework on which you build any
serious applet −
• init − This method is intended for whatever initialization is needed for your
applet. It is called after the param tags inside the applet tag have been
processed.
• start − This method is automatically called after the browser calls the init method.
It is also called whenever the user returns to the page containing the applet after
having gone off to other pages.
• stop − This method is automatically called when the user moves off the page on
which the applet sits. It can, therefore, be called repeatedly in the same applet.
• destroy − This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not normally
leave resources behind after a user leaves the page that contains the applet.
• paint − Invoked immediately after the start() method, and also any time the
applet needs to repaint itself in the browser. The paint() method is actually
inherited from the java.awt
52
AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in simple and
easy steps.
AWT Hierarchy
The hierarchy of Java AWT classes are given below.
53
Introduction to Java Servlets
Servlets are the Java programs that run on the Java-enabled web server or
application server. They are used to handle the request obtained from the web
server, process the request, produce the response, and then send a response
back to the web server.
The properties of Servlets are as follows:
• Servlets work on the server side.
• Servlets are capable of handling complex requests obtained from the
web server.
Execution of Servlets basically involves six basic steps:
1. The clients send the request to the webserver.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the
form of output.
5. The servlet sends the response back to the webserver.
6. The web server sends the response back to the client and the client
browser displays it on the screen.
What is CGI?
CGI is actually an external application that is written by using any of the
programming languages like C or C++ and this is responsible for processing
client requests and generating dynamic content.
In CGI application, when a client makes a request to access dynamic Web
pages, the Web server performs the following operations:
• It first locates the requested web page i.e the required CGI application
using URL.
• It then creates a new process to service the client’s request.
• Invokes the CGI application within the process and passes the request
information to the application.
• Collects the response from the CGI application.
• Destroys the process, prepares the HTTP response, and sends it to
the client.
54
Difference between Servlet and CGI
CGI (Common Gateway
Servlet Interface)
Servlets are less expensive than CGI. CGI is more expensive than Servlets.
Servlets can handle the cookies. CGI cannot handle the cookies.
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 statements 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) //Assume condition is true
55
statement1; //part of if block
statement2; // separate from if block
Example:
• Java
class IfDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("Inside If block"); // part of if block(immediate one statement after if
condition)
System.out.println("10 is less than 15"); //always executes as it is outside of if block
// This statement will be executed
// as if considers one statement by default again below statement is outside of if block
System.out.println("I am Not in if");
}
}
Output
56
Inside If block
10 is less than 15
I am Not in if
if-else:
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something
else if the condition is false? Here comes the else statement. We can use the else
statement with the if statement to execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example:
• Java
class IfElseDemo {
public static void main(String args[])
{
int i = 10;
57
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
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
58
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
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. There can be as
59
many as ‘else if’ blocks associated with one ‘if’ block but only one ‘else’ block is
allowed with one ‘if’ block.
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Example:
• Java
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
60
System.out.println("i is not present");
}
}
Output
i is 20
switch-case:
The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
• Java
61
import java.io.*;
class GFG {
public static void main (String[] args) {
int num=20;
switch(num){
case 5 : System.out.println("It is 5");
break;
case 10 : System.out.println("It is 10");
break;
case 15 : System.out.println("It is 15");
break;
case 20 : System.out.println("It is 20");
break;
default: System.out.println("Not present");
}
}
}
Output
It is 20
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:
62
• 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
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;
Output
63
13579
Return:
The return statement is used to explicitly return from a method. That is, it causes
program control to transfer back to the caller of the method.
Example:
• Java
if (t)
return;
Output
Before the return.
64