Skip to main content
CS8392 - Object Oriented
Programming
Unit I
Introduction to OOP and Java Fundamentals
• Java is an Object-oriented, class-based, concurrent,
secured and general-purpose programming language.
• It is a widely used robust technology.
• Java is a platform.
– Platform: Any hardware or software environment in which
a program runs, is known as a platform.
– Since Java has a runtime environment (JRE) and API, it
is called a platform.
2
JAVA: Introduction
• Java initial work started in 1990 by Sun Microsystems engineer Patrick
Naughton as a part of the Stealth Project.
• The Stealth Project soon changed to the Green Project, with Mike Sheridan
and James Gosling joining the ranks, and the group began developing new
technology for programming next-generation smart appliances.
• James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991.
• Gosling attempted to modify and extend C++ (a development he refers to as
"C++ ++ --"), but quickly abandoned this approach in favour of creating an
entirely new language.
• Firstly, it was called "Greentalk" by James Gosling, and file extension
was .gt. After that, it was called Oak, named after the tree that stood outside
his office. 3
JAVA: History
• Originally designed for small, embedded systems in electronic
appliances like set-top boxes. Then incorporate some changes based on
emergence of World Wide Web, which demanded portable programs.
• In 1995, Oak was renamed as "Java" because it was already a trademark
by Oak Technologies.
• The first publicly available version of Java (Java 1.0) was released in
1995.
• In 2006 Sun started to make Java available under the GNU General
Public License (GPL). Sun Microsystems was acquired by the Oracle
Corporation in 2010. Oracle continues this project called OpenJDK.
4
JAVA: History
Programming Popularity Java by Industry
5
JAVA: Why Java?
• 850 million PCs as Java Runtime Environment
• More then 3 billion devices run java
– Desktop Applications such as acrobat reader, media player,
antivirus etc.
– Web Applications
– Enterprise Applications such as banking applications.
– Mobile
– Web services
– Cloud
– Embedded System
– Smart Card
– Robotics
– Games etc.
6
JAVA: Where it is used?
7
JAVA: Version
8
C Vs C++ Vs JAVA
9
Java Editions
10
Java Editions
11
Characteristics of JAVA
12
Characteristics of JAVA
Simple
• Java is very easy to learn, and its syntax is simple, clean and
easy to understand.
– Java syntax is based on C++ (so easier for programmers to
learn it after C++).
– Java has removed many complicated and rarely-used
features, for example, explicit pointers, operator overloading,
etc.
– There is no need to remove unreferenced objects because
there is an Automatic Garbage Collection in Java.
13
Characteristics of JAVA
Object Oriented
• Java is an fully object-oriented programming language.
Everything in Java is an object.
• Object-oriented means we organize our software as a combination
of different types of objects that incorporates both data and
behaviour.
• It supports all the OOPs concepts.
Platform independent
• Java code can be run on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled
by the compiler and converted into bytecode or class file.
• This bytecode is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run
Anywhere(WORA).
14
Characteristics of JAVA
Secure:
• Java is secured because:
– No explicit pointer
– Java Programs run inside a virtual machine sandbox
Classloader:
• Classloader in Java is a part of the Java Runtime
Environment(JRE) which is used to load Java classes into the
Java Virtual Machine dynamically.
• It adds security by separating the package for the classes of
the local file system from those that are imported from network
sources.
15
Characteristics of JAVA
Secure
• Bytecode Verifier: It checks the code fragments for illegal
code that can violate access right to objects.
• Security Manager: It determines what resources a class can
access such as reading and writing to the local disk.
• Java language provides these securities by default. Some
security can also be provided by an application developer
explicitly through SSL, JAAS, Cryptography, etc.
16
Characteristics of JAVA
Robust
• Robust simply means strong.
Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java which runs on
the Java Virtual Machine to get rid of objects which are not
being used by a Java application anymore.
• There are exception handling and the type checking
mechanism in Java. All these points make Java robust.
17
Characteristics of JAVA
Architecture Neutral
• Java is architecture neutral because there are no
implementation dependent features, for example, the size of
primitive types is fixed.
• In C programming, int data type occupies 2 bytes of memory
for 32-bit architecture and 4 bytes of memory for 64-bit
architecture.
• However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
18
Characteristics of JAVA
Portable
• Java is portable because it facilitates you to carry the Java
bytecode to any platform. It doesn't require any implementation.
High-Performance
• Java is a little bit slower than a compiled language (e.g., C++).
Java is an compiled and interpreted language that is why it is
slower than compiled languages, e.g., C, C++, etc.
• But with the use of Just-In-Time compilers, Java enables high
performance than C, C++, etc.
19
Characteristics of JAVA
Distributed
• Java is distributed because it facilitates users to create distributed
applications in Java.
• RMI and EJB are used for creating distributed applications.
• This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
Dynamic
• Java is a dynamic language. It supports dynamic loading of classes.
• It means classes are loaded on demand. It also supports functions from
its native languages, i.e., C and C++.
• Java supports dynamic compilation and automatic memory
management (garbage collection).
20
Characteristics of JAVA
Multi-threaded
• A thread is like a separate program, executing concurrently.
• We can write Java programs that deal with many tasks at once
by defining multiple threads.
• The main advantage of multi-threading is that it doesn't occupy
memory for each thread.
• It shares a common memory area. Threads are important for
multi-media, Web applications, etc.
• For executing any java program, you need to Install the JDK if
you don't have installed it, download the JDK and install it.
– https://www.oracle.com/technetwork/java/javase/downloads/index.html
• Create the java program using any editor like notepad, notepad++
and save with file extension .java.
‑ Ex: Simple.java
21
First Java Program
/** First Java Program **/
import java.io.*;
public class Simple
{
public static void main (String args[])
{
System.out.println(“Hello Worldn”);
} //end main
}//end class
22
First Java Program
• The path is required to be set for using tools such as javac, java, etc.
• If you are saving the Java source file inside the JDK/bin directory, the
path is not required to be set because all the tools will be available in the
current directory.
• However, if you have your Java file outside the JDK/bin folder, it is
necessary to set the path of JDK.
• There are two ways to set the path in java:
• Temporary
• In Comment Prompt
• set path= C:Program FilesJavajdk1.8.0_191bin
• Permanent
• Set Path using Environmental Variables option
First Java Program
• To compile
– javac Simple.java
• To run
– java Simple
23
To compile and run a java program
24
First Java Program: Compilation & Execution
• JDK = Java Runtime Environment (JRE) + Development
Tools
• JRE = Java Virtual Machine (JVM) + Library Classes
• JVM=Java Interpreter + Just-In-Time Compiler
25
JDK vs JRE vs JVM
• JDK stands for “Java Development Kit”.
• It is a software development environment used for
developing Java applications and applets.
• It includes the Java Runtime Environment (JRE), an
interpreter/loader (Java), a compiler (javac), an archiver (jar),
a documentation generator (Javadoc) and other tools needed in
Java development.
26
JDK: Java Development Kit
• JRE stands for “Java Runtime Environment” and may also
be written as “Java RTE.”
• The Java Runtime Environment provides the minimum
requirements for executing a Java application;
• it consists of the Java Virtual Machine (JVM), core classes,
and supporting files.
27
JRE: Java Runtime Environment
• JVM
– Java Interpreter + Just-In-Time Compiler
– JVM (Java Virtual Machine) is an abstract machine. It is a
specification that provides runtime environment in which
java byte code can be executed.
– JVMs are available for many hardware and software
platforms. It is the code execution component of the Java
platform.
– It is a Runtime Instance Whenever you write java
command on the command prompt to run the java class, an
instance of JVM is created.
• Note:
– JVM, JRE and JDK are platform dependent because
configuration of each OS differs. But, Java is platform
independent.
28
JVM: Java Virtual Machine
29
Need for JVM
• The Java Virtual Machine is a program whose purpose is to execute
other programs.
• The JVM has two primary functions:
₋ to allow Java programs to run on any device or operating system
(known as the "Write once, run anywhere" principle)
₋ to manage and optimize program memory.
• Each operating system has different JVM, however the output they
produce after execution of byte code is same across all operating
systems.
• Bytecode: Byte code is the set of optimized instructions generated
during compilation phase and it is more powerful than ordinary pointer
code.
30
JDK vs JRE vs JVM
JVM JDK JRE
It stands for Java Virtual
machine.
It stands for Java
Development Kit
It stands for Java
Runtime Environment
It is an abstract machine.
It is a specification that
provides a run-time
environment in which
java byte code can be
executed.
It is the tool necessary to
compile, document and
package java programs.
JRE refers to a runtime
environment in which
java byte code can be
executed.
JVM follows three
notation: Specification,
Implementation and
Runtime instance
It contains JRE +
development tools.
It is an implementation
of the JVM which
physically exists.
31
JVM Architecture
32
JVM Architecture
• Class Loader: The class loader reads the .class file and save
the byte code in the method area.
• Method Area: There is only one method area in a JVM
which is shared among all the classes. This holds the class
level information of each .class file.
• Heap: Heap is a part of JVM memory where objects are
allocated. JVM creates a Class object for each .class file.
• Stack: Stack is a also a part of JVM memory but unlike
Heap, it is used for storing temporary variables.
33
JVM Architecture
• PC Registers: This keeps the track of which instruction has been
executed and which one is going to be executed. Since instructions
are executed by threads, each thread has a separate PC register.
• Native Method stack: A native method can access the runtime data
areas of the virtual machine.
• Native Method interface: It enables java code to call or be called
by native applications. Native applications are programs that are
specific to the hardware and OS of a system.
• Garbage collection: A class instance is explicitly created by the
java code and after use it is automatically destroyed by garbage
collection for memory management.
34
JIT: Just In Time Compiler
• The Just-In-Time compiler is one of the integral parts of the Java
Runtime Environment.
• It is mainly responsible for performance optimization of Java-based
applications at run time or execution time.
35
JIT: Just In Time Compiler
Step:1
• When you code the Java Program, JRE uses javac compiler to
compile the high-level Source code to byte code.
• After this, JVM loads the byte code at run time and converts
into machine level binary code for further execution using
Interpreter.
Step:2
• Interpretation of Java byte code reduces the performance
when compared to a native application i.e JIT Compiler aids to
boost up the performance by compiling the byte code into
native machine code “just-in-time” to run.
36
JIT: Just In Time Compiler
Step:3
• The JIT Compiler is activated and enabled by default when
a method is invoked in Java.
• When a method is compiled, Java Virtual Machine invokes the
compiled code of the method directly without interpreting it.
• Hence, it does not require much memory usage and
processor time. That basically speeds up the performance of
the Java Native Application.
37
First Java Program
/** First Java Program **/
import java.io.*;
public class Simple
{
public static void main (String args[])
{
System.out.println(“Hello Worldn”);
} //end main
}//end class
Question and Answer
38
Java: Data Types
Is necessary main class is public in java?
• To compile a program, you doesn’t really need a main method in your program.
But, while execution JVM searches for the main method. In the Java the main
method is the entry point Whenever you execute a program in Java JVM
searches for the main method and starts executing from it.
• The main method must be public, static, with return type void, and a String
array as argument.
public static void main(String[] args)
• You can write a program without defining a main it gets compiled without
compilation errors. But when you execute it a run time error is generated saying
“Main method not found”.
Question and Answer
39
Java: Data Types
Is necessary main class name should be same as filename?
• The filename must have the same name as the public class name in that file,
which is the way to tell the JVM that this is an entry point.
• Suppose when we create a program in which more than one class resides
and after compiling a java source file, it will generate the same number of
the .class file as classes reside in our program. In this condition, we will not
able to easily identify which class need to interpret by java interpreter and
which class containing Entry point for the program.
Question and Answer
40
Java: Data Types
Why java main method is static and public?
• Java program's main method has to be declared static because keyword
static allows main to be called without creating an object of the class in
which the main method is defined. If we omit static keyword before main
Java program will successfully compile but it won't execute.
41
First Java Program
• Access modifiers (or access specifiers) are keywords in
object oriented languages that
‑ set the accessibility of classes,
methods, and other members.
• Access modifiers are a specific part of programming language
syntax used to facilitate the encapsulation of components.
42
Java: Access Modifiers
43
Java: Access Modifiers
44
First Java Program
• public keyword is an access modifier which represents visibility. It means it is
visible to all.
• class keyword is used to declare a class in java. (Here, Simple is a class name)
• static is a keyword. If we declare any method as static, it is known as the static
method.
– The core advantage of static method is that there is no need to create object
to invoke the static method.
– The main method is executed by the JVM, so it doesn't require to create
object to invoke the main method. So it saves memory.
/** First Java Program **/
import java.io.*;
public class Simple
{
public static void main (String args[])
{
System.out.println(“Hello World
n”);
} //end main
45
First Java Program
• void is the return type of the method. It means it doesn't return any value.
• main represents the starting point of the program.
• String[] args is used for command line argument.
• System.out.println() is used to print statement.
/** First Java Program **/
import java.io.*;
public class Simple
{
public static void main (String args[])
{
System.out.println(“Hello World
n”);
} //end main
}//end class
• A token is the smallest element of a program that is
meaningful to the compiler.
• Tokens can be classified as follows:
‑ Keywords
‑ Identifiers
‑ Constants / Literals
‑ Special Symbols
‑ Operators
46
Java: Tokens
47
Java: Keywords
• Keywords are terms or phrases appropriated for special use that
may not be utilized in the creation of variable names.
₋ For example, “while" is a reserved word because it is a function in
many languages to show text on the screen.
• Keywords are also known as Reserved words
48
Java: Identifiers
• Identifiers are used for identification purposes.
• An identifier is the name given by the user for the various
programming elements like variables, functions, arrays,
structure, class and file.
Rules for defining an identifier
• The only allowed characters for identifiers are all alphanumeric
characters([A-Z],[a-z],[0-9]), ‘$‘(dollar) and ‘_‘ (underscore).
• Identifiers should not start with digits([0-9]).
– For example “123geeks” is a not a valid identifier.
• Java identifiers are case-sensitive.
• There is no limit on the length of the identifier but it is advisable
to use an optimum length of 4 – 15 letters only.
• Reserved Words can’t be used as an identifier.
– For example “int while = 20;” is an invalid statement as while is a
reserved word. There are 53 reserved words in Java.
49
Java: Data Types
• Data types define the type of data a variable can hold
• For example an integer variable can hold integer data, a
character type variable can hold character data etc.
50
Java: Data Types
Question and Answer
51
Java: Data Types
Why is the size of char is 2 byte in java..?
• In other languages like C/C++ uses only ASCII characters and to represent all
ASCII characters 8-bits is enough,
• But java uses Unicode system not ASCII code system and to represent
Unicode system 8 bit is not enough to represent all characters so java uses 2
byte for characters.
Why Java is a statically typed language?
• 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.
52
Java: Variables
Variable:
• A variable is a container which holds the value while the Java
program is executed.
• The variable's name represents what information
the variable contains.
• A variable is defined by the combination of an identifier, a type,
and an optional initializer.
Example:
int age=20;
string name=“hello”;
Java: Variables
Types of variables
– Local Variable
– Instance Variable or Non-static Variable
– Static Variable
Local Variable
• Local variables are declared within a method or within a block
of code in a method.
• In general, a local variable is accessible from its declaration to
the end of the code block in which it was declared.
• A local variable cannot be defined with "static" keyword.
53
Instance Variable or Non-static variable
• A variable declared inside the class but outside the body of the
method, is called instance variable. Instance variables are defined
without the STATIC keyword .
• Instance variables are created when the objects are instantiated and
therefore they are associated with the objects.
Static Variable
• A variable which is declared as static is called static variable. It
cannot be local.
• You can create a single copy of static variable and share among all
the instances of the class. Memory allocation for static variable
happens only once when the class is loaded in the memory. 54
Java: Variables
Example:
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class 55
Java: Variables
Literal :
• Any constant value which can be assigned to the variable is
called as literal/constant.
Example
• boolean result = true;
• char capitalC = 'C';
• byte b = 100;
• short s = 10000;
• int i = 100000; 56
Java: Literals
Using Underscore Characters in Numeric Literals
• In Java SE 7 and later, any number of underscore characters (_)
can appear anywhere between digits in a numerical literal.
• This feature enables you, for example. to separate groups of digits
in numeric literals, which can improve the readability of your
code.
• Example
• long creditCardNumber = 1234_5678_9012_3456L;
• long socialSecurityNumber = 999_99_9999L;
• float pi = 3.14_15F;
• long bytes = 0b11010010_01101001_10010100_10010010;
• You can place underscores only between digits; you cannot place
underscores in the following places:
• At the beginning or end of a number
• Adjacent to a decimal point in a floating point literal
• Prior to an F or L suffix
• In positions where a string of digits is expected 57
Java: Literals
What is the difference between character literals and string
literals in Java?
• Character literals represents alphabets (both cases), numbers (0
to 9), special characters (@, ?, & etc.) and escape sequences
like n, b etc.
• The String literal represents objects of String class.
58
Java: Literals
Question and Answer
• Special symbols in Java are a few characters which have
special meaning known to Java compiler and cannot be used
for any other purpose.
59
Java: Special Symbols
Symbol Description
Brackets []
These are used as an array element reference and also
indicates single and multidimensional subscripts
Parentheses()
These indicate a function call along with function
parameters
Braces{}
The opening and ending curly braces indicate the
beginning and end of a block of code having more than
one statement
Comma ( , )
This helps in separating more than one statement in an
expression
Semi-Colon (;) This is used to invoke an initialization list
Asterisk (*) This is used to create a pointer variable in Java
Write a Java program
5.1 To print an int, a double and a char variable on screen.
5.2 To print the area of a rectangle of sides 2 and 3 units
respectively.
5.3 To print the product of the numbers 8.2 and 6.
5.4 Print the ASCII value of the character 'h'.
60
Java: Datatypes
Exercise:5
• Operator in Java is a symbol which is used to perform
operations. For example: +, -, *, / etc. There are many types of
operators in Java which are given below:
₋ Unary Operator,
₋ Arithmetic Operator,
₋ Shift Operator,
₋ Relational Operator,
₋ Bitwise Operator,
₋ Logical Operator,
₋ Ternary Operator and
₋ Assignment Operator. 61
Java: Operators
62
Java: Operators
6.1 Length and breadth of a rectangle are 5 and 7 respectively. Write a
program to calculate the area and perimeter of the rectangle.
6.2 Write a program to calculate the perimeter of a triangle having sides of
length 2,3 and 5 units.
6.3 Write a program to add 8 to the number 2345 and then divide it by 3.
Now, the modulus of the quotient is taken with 5 and then multiply the
resultant value by 5. Display the final result.
1. Now, solve the above question using assignment operators (eg.
+=, -=, *=).
6.4 Write a program to print the power of 7 raised to 5. 63
Java: Operators
Exercise:6
• The Java comments are the statements that are not executed by
the compiler and interpreter.
• The comments can be used to provide information or
explanation about the variable, method, class or any
statement.
64
Java: Comments
Single line comment
• This type of comment is mainly used for describing the code
functionality. It is the easiest typed comments.
• Single-line comments start with two forward slashes (//). Any
text between // and the end of the line is ignored by Java implies
it will not be executed.
• The single line comment is used to comment only one line.
Syntax:
//Comments here(Text in this line will be considered as comment)
Example:
//my first comment 65
Basic Java: Comments
Java: Comments
Syntax:
/*Comment starts
Continues
…….
Comment ends*/
Example:
/* This is the beginning of a
multi-line comment
this is the end */
66
Multi line comment
• To describe a full method in a code or a complex snippet
single line comments can be tedious to write since we have to
give ‘//’ at every line.
• So to overcome this multi-line comments can be used. Multi-
line comments start with /* and end with */.
• Any text between /* and */ will be ignored by Java. It is used
to comment multiple lines of code.
Java: Comments
Syntax:
/**Comment start
*
*tags are used in order to specify
a parameter
*or method or heading
*HTML tags can also be used
*such as <h1>
*comment ends*/
Example:
67
Java Documentation Comment
• This type of comments is used generally when you are writing code for
a project/ software package.
• It helps you to generate a documentation page for reference, which
can be used for getting information about methods present, its
parameters, etc.
• The documentation comment is used to create documentation API. To
create documentation API, you need to use Javadoc tool.
Tag Author Descritpion
@author Adds the author of a class. @author name-text
@exception
Adds a Throws subheading
to the generated
documentation, with the
classname and description
text.
@exception class-
name description
@return
Adds a “Returns” section
with the description text.
@return
description
• Casting is a process of changing one type of value to another
type. In Java, we can cast one type of value to another type. It is
known as type casting.
• When you assign the value of one data type to another, you
should be aware of the compatibility of the data type.
• If they are compatible, then Java will perform the conversion
automatically known as Automatic Type Conversion and if not,
then they need to be casted or converted explicitly.
• Types of casting
– Automatic or Implicit or widening
– Explicit or Narrowing 68
Java: Type Casting
Automatic or Implicit or Widening:
Automatic Type casting take place when,
– the two types are compatible
– the target type is larger than the source type
Note:
• In java the numeric data types are compatible with each other
but no automatic conversion is supported from numeric type
to char or boolean. Also, char and boolean are not compatible
with each other.
Example: Auto_Conversion.java 69
Java: Type Casting
Explicit or Narrowing:
• When you are assigning a larger type value to a variable of
smaller type, then you need to perform explicit type casting.
• This is useful for incompatible data types where automatic
conversion cannot be done.
• Here, target-type specifies the desired type to convert the
specified value to.
Example: Demo_Narrow.java,Narrowing.java 70
Java: Type Casting
Write a Java program
7.1 To assign a value of 100.235 to a double variable and then convert
it to int.
7.2 To add 3 to the ASCII value of the character 'd' and print the
equivalent character.
7.3 To add an integer variable having value 5 and a double variable
having value 6.2.
71
Java: Type Casting
Exercise:7
72
Java: Read input from console
• Java Scanner class allows the user to take input from the
console. It belongs to java.util package.
• It is used to read the input of primitive types like int, double,
long, short, float, and byte.
• It is the easiest way to read input in Java program.
• To create an object of Scanner class, we usually pass the
predefined object System.in, which represents the standard input
stream. We may pass an object of class File if we want to read
input from a file.
73
Java: Read input from console
• To read numerical values of a certain data type XYZ, the function
to use is nextXYZ().
– For example, to read a value of type short, we can use nextShort()
• To read strings, we use nextLine() or next().
• To read a single character, we use next().charAt(0). next()
function returns the next token/word in the input as a string and
charAt(0) funtion returns the first character in that string.
Example: Getinputfromuser.java, Demochar.java 74
Java: Read input from console
75
Java: Read input from console
Example:
Write a Java program
8.1 That accepts two integer inputs from user and print sum and
product of them.
8.2 That takes name, roll number and field of interest from user and
print in the format below :
Output: Hey, my name is xyz and my roll number is xyz. My field of
interest are xyz.
8.3 To find square of a number.
Test Cases: Input : 2 Output : 4
Input : 5 Output : 25
76
Java: Read input from console
Exercise:8
• A programming language uses control statements to control the
flow of execution of program based on certain conditions.
77
Java: Control Statements
• In Java, if statement is used for testing the conditions.
• The condition matches the statement it returns true else it returns
false.
• There are four types of if statement they are:
₋ if statement
₋ if-else statement
₋ if-else-if ladder
₋ nested if statement
₋ Switch statement
78
Java: Selection Statements
• if statement tests the condition. It executes the if block if
condition is true.
• Syntax: Example: IfDemo1.java
if(condition)
{
//code to be executed
}
79
Selection Statements :Simple if
Practice:
Write Java program for the following
problem:
1. To check the entered mark is pass (if
it is greater than 40).
2. To check whether given number is
divisor of 7.
Flowchart
• if-else statement also tests the condition. It executes the if block
if condition is true else if it is false the else block is executed.
• Syntax: Example: IfElseDemo1.java
if(condition){
//code for true
}
else{
//code for false
}
80
Selection Statements :if-else
Practice:
Write Java program for the following problem:
1. To find the greatest of two numbers.
2. To check whether the given number is odd
or even.
3. To check whether the given year is leap year
or not.
4. To check whether the given age is valid for
vote or not.
Flowchart
• The if-else-if ladder statement is used for testing conditions. It is
used for testing one condition from multiple statements.
• Syntax: Example: IfElseIFDemo1.java
if(condition1)
{
//code for if condition1 is true
}
else if(condition2)
{
//code for if condition2 is true
}
...
else
{
//code for all the false conditions
}
81
Selection Statements :if-else-if
Flowchart
82
Selection Statements :if-else-if
Practice:
Write Java program for the following problem:
1. To find the largest of three numbers
2. To Check whether the given Character is a
Vowel /Consonant /Digit /Special Symbol.
3. To input basic salary of an employee and calculate
gross salary according to given conditions.
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary is between 10001 to 20000 : HRA =
25%, DA = 90%
Basic Salary >= 20001 : HRA = 30%, DA = 95%
Gross Salary=Basic Salary + HRA + DA
• Nested if-else statements, is that using one if or else if statement
inside another if or else if statement(s).
• Syntax: Example: NestedIfDemo1.java
if(condition)
{
if(condition)
{
//statement
}
else
{
//statement
}
…
}
else
{
//statement 83
Selection Statements : Nested if
Flowchart
84
Selection Statements : Nested if
Practice:
Write Java program for the following problem:
1. To Read a Coordinate Point in a XY Coordinate
System and Determine its Quadrant.
2. To find the greatest of three numbers.
• In Java, the if..else..if ladder executes a block of code among
many blocks.
• The switch statement can be a substitute for
long if..else..if ladders which generally makes your code more
readable.
• It's also important to note that switch statement in Java only works
with:
– Primitive data types: byte, short, char and int
– Enumerated types (Java enums)
– String class
– a few classes that wrap primitive types: Character, Byte, Short &
Integer
85
Selection Statements: Switch
Syntax: Flowchart
switch(expression)
{
case value1:
//code for execution;
break; //optional
case value2:
// code for execution
break; //optional
......
Case value n:
// code for execution
break; //optional
default:
//code for execution
when none of the case is true;
}
Example:SwitchDemo1.java
86
Selection Statements: Switch
Practice:
Write Java program for the following
problem:
1. To Check the given Character is a
Vowel.
2. Simple Calculator (Try both integer
(1,2,3) and character(+, -, *, /, %) as a
case in separate program)
Write a Java program
9.1Write a program to calculate the monthly telephone bills as per the
following rule:
Minimum Rs. 200 for up to 100 calls.
Plus Rs. 0.60 per call for next 50 calls.
Plus Rs. 0.50 per call for next 50 calls.
Plus Rs. 0.40 per call for any call beyond 200 calls.
9.2 Write a program that asks the user to enter a number and displays
the absolute value of that number. 87
Selection Statements
Exercise:9
9.3 A triangle is valid if the sum of all the three angles is equal to 180
degrees. Write a program that asks the user to enter three integers as
angles and check whether a triangle is valid or not.
9.4 Write a program that prompts the user to enter grade. Your program
should display the corresponding meaning of grade as per the
following table
88
Selection Statements
Exercise:9
Grade Meaning
A Excellent
B Good
C Average
D Deficient
F Failing
• In programming languages, loops are used to execute a set of
instructions/functions repeatedly when some conditions become
true.
• There are three types of loops in java.
89
Java: Iterative Statements
• In java, while loop is used for iterating a part of the program
several times. When the number of iteration is not fixed then
while loop is used.
• Syntax: Example:
WhileDemo1.java
while(condition)
{
//code for execution
}
90
Iterative Statements: while
Practice:
Write Java program for the following
problem:
1. Rectangle number pattern.
2. To check the number is palindrome.
Flowchart
• In java, do-while loop is used to execute a part of the program
again and again. If the number of iteration is not fixed then the
do-while loop is used. This loop executes at least once because
the loop is executed before the condition is checked.
• Syntax: Example:
WhileDemo1.java
do
{
//code for execution
}while(condition);
91
Iterative Statements: do-while
Practice:
Write Java program for the following
problem:
1. To print the numbers from 10 to 1.
2. Sum of ‘n’ natural numbers.
Flowchart
• In java, for loop is used for executing a part of the program
again and again. When the number of execution is fixed
then it is suggested to use for loop.
• In java there are 2 types of for loops, they are as follows:
₋ Simple for loop
₋ For-each loop
92
Iterative Statements: for
Syntax:
for(initialization;condition;increment/decrement)
{
//statement
}
Example: ForDemo1.java
93
Iterative Statements: for
Flowchart
Practice:
Write Java program for the following
problems:
1. To print numbers from 1 to 10.
2. To find the factorial
3. To calculate the sum of following
series where n is input by user.
1 + 1/2 + 1/3 + 1/4 + 1/5 +…………1/n
• Nested Loop: A loop inside another loop is called a nested loop.
The number of loops depend on the complexity of a problem.
• Suppose, a loop, outer loop, running n number of times consists
of another loop inside it, inner loop, running m number of times.
Then, for each execution of the outer loop from 1...n, the inner
loop runs maximum of m times.
• Syntax:
Example: PyramidExample.java, Pattern.java
94
Iterative Statements: Nested Loop
• In Java, a break statement is used inside a loop. The loop is
terminated immediately when a break statement is encountered
and resumes from the next statement.
Syntax: Flowchart:
break;
Example: BreakDemo1.java
95
Jump Statements: Break
Practice:
Write Java program for the
following problem:
The sum of numbers entered by
the user until user enters a
negative number.
• In Java, the Continue statement is used in loops. Continue
statement is used to jump to the next iteration of the loop
immediately. It is used with for loop, while loop and do-while
loop.
Syntax: Example:ContinueDemo1.java
continue; Flowchart:
96
Jump Statements: Continue
Practice:
Write Java program for the
following problem:
The sum of numbers entered by the
user until user enters a negative
number.
• In Labelled Break Statement, we give a label/name to a loop.
• When this break statement is encountered with the label/name of
the loop, it skips the execution any statement after it and takes the
control right out of this labelled loop.
• The control goes to the first statement right after the loop.
Example:LabelledBreak.java,LabelledBreak1.java
97
Jump Statements: labelled break
• In Labelled Continue Statement, we give a label/name to a
loop.
• When this continue statement is encountered with the label/name
of the loop, it skips the execution any statement within the loop
for the current iteration and continues with the next iteration and
condition checking in the labelled loop.
Example: LabelledContinue.java
98
Jump Statements: labelled Continue
Write a Java program
10.1 To check the number is prime or not.
10.2 Guess the integer.
10.3 To enter the numbers till the user wants and at the end it should
display the count of positive, negative and zeros entered.
99
Java: Control Statements
Exercise:10
Write a Java program
10.4 To print the right angular triangle pattern.
10.5 To write the even numbers from 10 to 20, both
included, except 16, in 3 different ways:
- Incrementing 2 in each step (use "continue" to skip 16)
- Incrementing 1 in each step (use "continue")
- With and endless loop (using "break" & "continue")
100
Java: Control Statements
Exercise:10