Object-Oriented
Programming Using Java
Java Basics
Programming Languages
Machine Language Assembly Language High-Level Language
Machine language is a set of primitive instructions
built into every computer. The instructions are in
the form of binary code, so you have to enter binary
codes for various instructions. Program with native
machine language is a tedious process. Moreover
the programs are highly difficult to read and modify.
For example, to add two numbers, you might write
an instruction in binary like this:
1101101010011010
Programming Languages
Machine Language Assembly Language High-Level Language
Assembly languages were developed to make
programming easy. Since the computer cannot understand
assembly language, however, a program called assembler is
used to convert assembly language programs into machine
code. For example, to add two numbers, you might write
an instruction in assembly code like this:
ADDF3 R1, R2, R3
Programming Languages
Machine Language Assembly Language High-Level Language
The high-level languages are English-like and easy to learn
and program. For example, the following is a high-level
language statement that computes the area of a circle with
radius 5:
area = 5 * 5 * 3.1415;
Compilation of High-Level Language Programs
A program written in a high-level language is called a source
program. Since a computer cannot understand a source program.
Program called a compiler is used to translate the source program
into a machine language program called an object program. The
object program is often then linked with other supporting library
code before the object can be executed on the machine.
How Java Works
• Java's platform independence is achieved by the use of the Java Virtual
Machine
• A Java program consists of one or more files with a .java extension
• these are plain old text files
• When a Java program is compiled the .java files are fed to a compiler
which produces a .class file for each .java file
• The .class file contains Java bytecode
• Bytecode is like machine language, but it is intended for the Java Virtual
Machine, not for a specific chip such as a Pentium or PowerPC chip
More on How Java Works
• To run a Java program the bytecode in a .class file is fed to an
interpreter which converts the byte code to machine code for a
specific chip (IA-32, PowerPC)
• Some people refer to the interpreter as "The Java Virtual Machine"
(JVM)
• The interpreter is platform specific because it takes the platform
independent bytecode and produces machine language instructions
for a particular chip
• So a Java program could be run an any type of computer that has a
JVM written for it
• PC, Mac, Unix, Linux, BeaOS, Sparc
A Picture is Worth…
The output of the
compiler is .class
file
The Interpreter's are sometimes referred to as the Java Virtual Machines
Java Programs: Compilation and Interpretation
Why Java?
The answer is:
Java enables users to develop and deploy applications on
the Internet for servers, desktop computers, and small hand-held
devices. The future of computing is being profoundly influenced
by the Internet, and Java promises to remain a big part of that
future. Java is the Internet programming language.
FJava is a general purpose programming language.
FJava is the Internet programming language.
Brief History and Overview
of the Language
[Link]/features/1998/05/[Link]
History of Java
• It was started in December '90 by Patrick Naughton, Mike Sheridan, Chris
Warth, Ed Frank and James Gosling when they were chartered to spend time
trying to figure out what would be the "next wave" of computing and how
they might catch it
• They came to the conclusion that at least one of the waves was going to be
the convergence of digitally controlled consumer devices and computers
• In January '91, a formal team of persons like Bill Joy, James Gosling, Mike
Sheridan, Patrick Naughton and several other individuals met in Aspen,
Colorado for the first time to plan for the Stealth Project
• The Stealth Project was a project to develop software for consumer electronic
devices that could be controlled by a remote. The project was originally part
of Sun Micro Systems Inc. in 1990, but was later renamed the Green Project
• The original impetus for Java was not the Internet!!
• Primary motivation was the need for a platform-independent (that is,
architecture-neutral) language
History of Java
• Initially JAVA was named as Oak - coined by Gosling while staring at an
oak tree just outside his office window
• Oak is an image of solidarity and picked as a national tree of numerous
nations like the U.S.A., France, Germany, Romania, etc.
• Unfortunately, the name Oak was already a trademark by Oak
Technologies and had already been patented by some other programming
language. Owing to the fear of copyright violation, the name ‘Oak’ was
dropped and renamed to JAVA in 1995
• Java is the name of a sort of espresso bean produced on the islands of
Java in Indonesia. Gosling came up with this name while having a coffee
near his office
Object-Oriented Programming using Java
• Process abstraction is a very old idea (subroutines!)
• Data abstraction is somewhat newer and is the pillar of Object-Oriented
Programming
• An Abstract Data Type is one that is defined in terms of the operations that it
supports (i.e., that can be performed upon it) rather than in terms of its structure or
implementation
• Why abstractions?
• easier to think about - hide what doesn't matter to programmer
• protection - prevent access to things you shouldn't see
• plug compatibility
• replacement of pieces, often without recompilation, definitely without rewriting libraries
• division of labor in software projects
Object-Oriented Programming using Java
• Pillars of Object-Oriented Programming
vAbstraction: The property by virtue of which only the essential details are displayed
to the user
vEncapsulation: The wrapping up of data under a single unit
vAlso termed as Data hiding
vInheritance: The mechanism by which one class is allowed to inherit the features
(fields and methods) of another class
vSuper Class: The class whose features are inherited)
vSub Class: The class that inherits the other class
vReusability: Inheritance supports the concept of “reusability”
vPolymorphism: The ability of OOPs programming languages to differentiate between
entities with the same name efficiently
vCompile-time polymorphism
vRun-time polymorphism
Setting Up Java: Things You Will Need
• Mandatory:
• The Java Runtime Environment (JRE)
• Includes Java Virtual Machine (JVM)
• The Java Developer Kit (JDK)
• Includes the Java Compiler, Java Debugger
• A text editor
• Optional:
• An Integrated Development Environment (IDE) – a software application that
provides comprehensive facilities to computer programmers for software
development
• Netbeans
• Eclipse
• IntelliJ IDEA, or something similar
• Note: When you install the JDK, you automatically get the JRE
Popular IDEs (integrated development environments)
• NetBeans Open Source by Sun, now owned by Oracle
• Platform – Linux/macOS/Solaris/Windows
• First Released – 1997
• Eclipse Open Source by IBM
• Platform – Linux/macOS/Solaris/Windows
• First Released – November 2001
• IntelliJ IDEA by JetBrains for Java, Kotlin and other JVM-based languages
• Platform – Linux/macOS/Windows
• First Released – January 2001
JDK, JRE, JVM
• JDK and JRE are the core concepts in Java programming
• JRE stands for Java Runtime Environment
• It is the implementation of JVM (Java Virtual Machine)
• Specially designed to provide an environment to execute Java programs
• Consists of JVM, Java binaries, and other class libraries
• JDK stands for Java Development Kit
• A software development environment used to develop Java applications and applets
• This is a platform-specific software
• It contains Java Runtime Environment (JRE) and other development tools like an
interpreter, compiler, archiver, and a document generator.
• One can install more than one JDK version on the same computer
• Only to execute a Java program, we just need to install JRE and not JDK
JDK, JRE and JVM: A Simple Visualization
Java Compiler
Java Binaries
JVM JRE JDK
Class Libraries
Java Debugger
Just In Time (JIT) Compiler
• The JIT or Just-In-Time compiler is an essential part of the JRE (Java Runtime
Environment), that is responsible for performance optimization of java based
applications during run time
• The JIT compiler compiles Java bytecode into native machine code at run time
-- the process is transparent to the user
• The JIT compiler is enabled by default, but you can disable it temporarily to
help isolate a problem
• JIT compiler is able to perform certain simple optimizations while compiling a
series of bytecode to native machine language
• Some of these optimizations are data analysis, reduction of memory accesses
by register allocation, translation from stack operations to register operations,
elimination of common sub-expressions, etc.
• However, it cannot afford to do all the optimizations that a static compiler is
capable of, because of the extra overhead added to the execution time and
moreover, its view of the program is very restricted
Setting Up Java Development Environment
• Check whether a JDK version is installed in your system
• If no JDK version is
available, download
and install JDK from
the Internet
• Installing JDK will
automatically install
corresponding JRE
version in your
computer
• Install Java IDE of your
choice, if you wish
Java Version Development History
• JDK Beta – 1995
• JDK 1.0 – January 1996
• Java SE 7 – July 2011
• Java SE 8 (LTS: Long-term Support Release) – March 2014
• Java SE 9 -- September 2017
• Java SE 11 (LTS) -- September 2018
• Java SE 16 – March 2021
• Java SE 17 (LTS) – September 2021
• Java SE 18 - March 2022
• Java SE 19 - September 2022
• Java SE 20 - March 2023
19th
• Java SE 23 - 17th September 2024
• Java SE 25 (LTS) - September 2025 - September 2033 (Latest Release)
Characteristics of Java
• Java Is Simple Java is partially modeled on C++, but
• Java Is Object-Oriented greatly simplified and improved. Some
• Java Is Distributed people refer to Java as "C++--" because it is
like C++ but with more functionality and
• Java Is Interpreted fewer negative aspects.
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
Characteristics of Java
• Java Is Simple Java is inherently object-oriented. Although
• Java Is Object-Oriented many object-oriented languages began strictly
• Java Is Distributed as procedural languages, Java was designed
from the start to be object-oriented. Object-
• Java Is Interpreted oriented programming (OOP) is a popular
• Java Is Robust programming approach that is replacing
• Java Is Secure traditional procedural programming
• Java Is Architecture-Neutral techniques.
• Java Is Portable One of the central issues in software
• Java's Performance development is how to reuse code. Object-
• Java Is Multithreaded oriented programming provides great
• Java Is Dynamic flexibility, modularity, clarity, and reusability
through encapsulation, inheritance, and
polymorphism.
Characteristics of Java
• Java Is Simple Distributed computing involves several
• Java Is Object-Oriented computers working together on a network.
• Java Is Distributed Java is designed to make distributed
computing easy. Since networking capability
• Java Is Interpreted is inherently integrated into Java, writing
• Java Is Robust network programs is like sending and
• Java Is Secure receiving data to and from a file.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
Characteristics of Java
• Java Is Simple Yo u n e e d a n i n t e r p r e t e r t o r u n J a v a
• Java Is Object-Oriented programs. The programs are compiled into
• Java Is Distributed the Java Virtual Machine code called
bytecode. The bytecode is machine-
• Java Is Interpreted independent and can run on any machine
• Java Is Robust that has a Java interpreter, which is part of
• Java Is Secure the Java Virtual Machine (JVM).
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
Characteristics of Java
• Java Is Simple Java compilers can detect many problems that
• Java Is Object-Oriented would first show up at execution time in other
• Java Is Distributed languages.
• Java Is Interpreted Java has eliminated certain types of error-
• Java Is Robust prone programming constructs found in other
• Java Is Secure languages.
• Java Is Architecture-Neutral
Java has a runtime exception-handling feature
• Java Is Portable to provide programming support for
• Java's Performance robustness.
• Java Is Multithreaded
• Java Is Dynamic
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
Java implements several security
• Java Is Robust
mechanisms to protect your system against
• Java Is Secure harm caused by stray programs.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral Write once, run anywhere
• Java Is Portable
With a Java Virtual Machine (JVM), you
• Java's Performance can write one program that will run on
• Java Is Multithreaded any platform.
• Java Is Dynamic
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable Because Java is architecture neutral, Java
• Java's Performance programs are portable. They can be run on
any platform without being recompiled.
• Java Is Multithreaded
• Java Is Dynamic
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable Interpreted and High Performance. Unlike
• Java's Performance earlier cross-platform solutions that
compromised in performances, Java bytecode
• Java Is Multithreaded was carefully designed so that it would be
• Java Is Dynamic easy to translate directly into native machine
code for very high performance
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance Multithread programming is smoothly
• Java Is Multithreaded integrated in Java, whereas in other
• Java Is Dynamic languages you have to call procedures
specific to the operating system to enable
multithreading.
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable Java was designed to adapt to an evolving
• Java's Performance environment. New code can be loaded on the fly
• Java Is Multithreaded without recompilation. There is no need for
developers to create, and for users to install,
• Java Is Dynamic
major new software versions. New features can
be incorporated transparently as needed.
Compiling and Running a Java Program
• Using a text editor and compiling from the command line is the most
basic way of creating a Java program
• You can create a Java programs using any text editor of your choice
• Remember to save you java source file as a .java file
• You can compile a java source file from either a Windows or Unix
command prompt
• The command to Compile a java program: javac [Link]
• The command to run the java program: java YourProgramName
• IDEs make creating Java programs easier
Demonstration: A Simple Java Program
public class HelloWorld {
[Link]("Hello World!");
} // End of Main class
class Alpha {
/* main class */
Compiling Java Source Code
public static void main(String[] args) { Main Class
/* Method Body */
} [Link]
/* uses class Bravo somewhere in the code */
}
[Link]
javac
[Link]
class Charlie {
/* Class Body */
}
[Link]
class Delta {
/* Class Body */
}
[Link]
Compiling a Simple Java Program
• Unlike other programming languages, name of the file containing the
source code of a Java program (i.e., the Java source file) is significant:
• In Java, all parts of the source code must reside in a class
• A Java program may have one or more classes
• Only one of these classes containing the main() method. That class is called the Main
class
• The name of main class should be same as the name of the corresponding Java
source file
• Upon compilation, a .class file is generated for each class in the source Java program
• In fact, when a call to java command with the name of the source file is
made, it simply searches for the .class file corresponding to the Main class
and launches it
Demonstration: Edit, Compile and Run
Search for the language features:
A Closer Look at the First Sample Program
• Comments: Single-line vs multiline
• Use of the keyword class to declare that a new class is being defined
• The main() method where program starts executing
• Moral???
• The public keyword:
• An access modifier
• Access modifiers allow the programmer to control the visibility of class and its
members
• Since the access modifier is public, it can be accessed from outside the class
• The static keyword:
• Allows a method to be called without having to instantiate a particular instance (i.e.,
an object) of the class
• This is necessary as main() is to be called by the JVM before any objects are made
Search for the language features:
A Closer Look at the First Sample Program
• The void keyword:
• For every method in Java, we need to specify the type of return value by the method
• Ironically, the same need to be done even when it does not return a value at all
• The “void” keyword tells the compiler that main() method will not return a value
• Java is case-sensitive:
• Main() is different from main()
• Java compiler can compile classes that do not contain main() method, but java has no
way to run these classes
• Moral???
• The [Link]() method:
• Predefined method for console I/O
Example: A Second Simple Java Program
public class SecondExample {
public static void main(String[] args) {
int num;
num = 100;
[Link](“This is num: “ + num);
num = num * 2;
[Link](“The value of num*2 is ");
[Link](num);
} // End of main() method
} // End of Main class
Search for the language features:
A Closer Look at the Second Sample Program
• Variable Declaration
• Value assignment
• A simple arithmetic expression
• The use of “+” operator inside the argument of the println() method
• Difference between print() and println() methods
The if Statement
• Syntax: Similar to if statement in C/C++
if(condition) statement;
• You may have blocks of code in place of statement
• The is an expression that evaluates to a Boolean quantity
Example: A Third Simple Java Program
public static void main(String[] args) {
int x, y ;
x = 10;
y = 20;
if (x < y) [Link](“x is less than y”);
x = x * 2;
if (x == y) [Link](“x is equal to y”);
x = x * 2;
if (x > y) [Link](“x is greater than y”);
if (x == y) [Link](“This won’t be displayed”);
} // End of main() method
} // End of Main class
The for Statement
• Syntax: Similar to if statement in C/C++
for(initialization; condition; iteration) statement;
• You may have blocks of code in place of statement
Example: A Fourth Simple Java Program
public class FourthExample {
public static void main(String[] args) {
int x, y ;
y = 20;
[Link](“This is x: ” + x);
[Link](“This is y: ” + y);
y = y – 2;
}
}
Console Input in Java
• Console input can be a bit awkward to work with Java.
• Most real-world Java programs will be graphical and window-based
• Not much use of console input in real-life Java applications
• Console input is handled using specialized built-in Java Classes
• Three different ways to read the input from Java Console
• Using Bufferedreader Class
• the traditional technique for console input
• Using Scanner Class
• the most favored technique to take input
• Using Console Class
• has been turning into a favored route
• Each approach has its pros and cons
Console Input in Java: Scanner Class
import [Link];
public static void main(String args[]) {
Scanner input = new Scanner([Link]);
[Link]("Enter Your Name:");
String s = [Link]();
[Link]("You Name is " + s);
[Link]("Enter Your Roll Number: ");
int a = [Link]();
[Link]("Your Roll Number is " + a);
[Link]("Enter the value of Pi in decimal: ");
float b = [Link]();
[Link]("The value of Pi in decimal is " + b);
[Link]();
} // End of main() method
Java Data Types
• Java is a strongly-typed language
• Every variable has a type
• Every expression has a type
• Every type is strictly defined
• Java compiler checks all the assignments for type compatibility
• No automatic conversion of conflicting types
• Type mismatches are treated as syntax errors by Java Compiler
• Differs here from C/C++
Primitive Data Types
• Integers: four types
• byte (8-bit, Signed)
• short (16-bit, Signed)
• int (32-bit, Signed)
• long (64-bit, Signed)
• Floating Point Numbers: two types
• float (32-bit, Signed)
• double (64-bit, Signed)
• Characters: Unicode characters
• char (16-bit, Unsigned) // arithmetic operations allowed on char variables
• Boolean: have two possible named values – true or false
• boolean // Boolean variables can control Java control statements
Java Literals
• Various categories of literals
• Integer Literals
• Decimal Default
• Octal Denoted by a leading ‘0’
• Hexadecimal Denoted by a leading ‘0x’ or ‘0X’
• Binary Denoted by a leading ‘0b’ or ‘0B’
• Floating Point Literals
• Double-precision Default, append ‘d’ or ‘D’ at the end for explicit specification
• Single-precision append ‘f’ or ‘F’ at the end for explicit specification
• Note: One or more ‘_’ characters can be embedded to enhance ease
of reading
Java Literals
• More Java Literal types
• Boolean Literals
• Only two possible values: true and false
• Character Literals
• Single quote representation
• Integral representation
• Unicode representation format: ‘\uxxxx’ (hexadecimal)
• Escape Sequence representation
• String Literals
• Any sequence of characters with a double quote
Java Variables
• The basic unit of storage in a program
• Defined by the combination of an identifier, a type, and an optional
initializer
• All variables must be declared before they can be used
• Each variable has a scope, that defines its visibility
• It also has a lifetime
Variable Naming Conventions in Java
• Naming conventions are used to enhance program readability:
• Its convention to start the names of a variable with an alphabet
rather than an underscore or a dollar sign
• Variable names can have any alphabets or numbers after the first
letter. However, spaces are not allowed
• The reserved words such as int, static, void and so on CANNOT be
used as variable names
• Constant values can be stored in variables which are named in
• Variables which need two distinct words can be written together
using
Java Variables: Scope & Lifetime
• Java allows variables to be declared within any block
• A block of codes defines a
• Each time you start a new block, you are creating a new scope
• Typical Blocks:
• A scope determines
• What objects are visible to other parts of your program
• The of the objects defined in that scope
• Scopes can be nested
• The outer scope encloses the inner scope
• Cannot declare a variable having SAME name as one in outer scope
Types of Java Variables
• Three types of variables in Java based on Scope and Lifetime:
• A variable which has value within a particular method
• The scope is withing the body of the method
• Lifetime is a particular call of that method
• A variable which is declared inside the body of a class, but not within any methods of it
• These differ with each instance of the class created
• Any method inside the class have access
• A variable that is shared across all the instances of a class
• Same for all the instances generated
• As soon a class loads, the static variables get their initialization
Type Conversion & Casting
• Not all data types are compatible in Java
• If two data types are compatible
• Example: byte int, int long, float double, etc
• If two data types are not compatible
• double byte
• Automatic Type Conversion:
• Types are compatible
• Destination type is larger than source type
• Casting Incompatible types:
• Example: int byte, long int, etc.
• Truncation
• Example: float int
Type Conversion & Casting: Examples
Example 1:
byte b = 10;
int a;
a = b; // Perfectly OK in Java, as b converted automatically to an int (Widening conversion)
Example 2:
byte b;
int a = 10;
b = a; // Not allowed in Java, as b has size less than a
b = (byte) a; // Perfectly OK, users responsibility to know the consequences (Narrowing)
Example 3:
float f = 3.14;
int a;
a = f; //Not allowed in Java, as a and f has incompatible types
a = (int) f; // Perfectly OK, users responsibility to know the consequences (Truncation)
Automatic Type Promotion
• Automatic type conversion may occurs in expressions
• Result of an intermediate term with byte, short or char may exceed the range
of these operand types
• Java automatically promotes each byte, short, or char operand to int when
evaluating an expression
• This can cause confusing compile-time errors!!
• Should use an explicit cast, if absolutely necessary!!
• Type Promotion Rules:
• All byte, short, and char values are promoted to int
• If one operand is a long, the whole expression is promoted to long
• If one operand is a float, the entire expression is promoted to float
• If any of the operands are double, the result is double
Automatic Type Promotion: Example
public class TypePromotionExample {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 10000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
[Link]("c: " + c);
[Link]("(int) c: " + (int) c);
[Link]("(i / c): " + (i / c));
[Link]("(char) (i / c): " + (char) (i / c));
[Link]((f * b) + " + " + (i / c) + " + " + (d * s));
[Link]("Result: " + result); }
Type Inference with Local Variables
• Java compiler can infer the type of a local variable based on the type of its
initializer
• It avoids the need to explicitly specify the type of the local variables
• Introduced with JDK10
• Example: You can write in your code the following:
var avg = 10.0; Instead of double avg = 10.0;
• Older versions of JDK won’t support this feature!!
• Advantages:
• simplify declarations in cases in which the type name is quite lengthy
• Eliminates typing redundancy when it can be inferred from its initializer
• Helpful when variable type is difficult to discern or cannot be denoted (Ex: variables
of an Anonymous class)
Java Operators
• Most operators in Java can be classified into four groups:
• Arithmetic
• Bitwise
• Relational
• Logical
• Some additional operators that handle certain special situations!!
• Arithmetic Operators: Similar set of operators as in C/C++
• Operands of Arithmetic operators are integers, or floating point numbers, or
characters
• Cannot apply on Boolean data types
• Exception: Modulus operator (%) can be applied on floating point numbers, too!!
Java Arithmetic Operators
Left operand can be floating point number!!
Java Bitwise Operators
• Bitwise operators that can be applied to the integer types
• These act upon the individual bits of their operands
• Caution:
• All the integers except char are signed values
• Java uses two’s complement scheme to represent negative integers
• Applying the bitwise operators can easily produce unexpected results!!
• Categories of Bitwise Operators:
• Bitwise Logical Operators
• Bitwise shift Operators
• Bitwise Compound Assignment Operators
Java Bitwise Operators
Logical
Termed as Sign Extension.
May be undesirable at times
A faster alternative to division by 2; preserves sign bit.
Shift Right Shift without Sign Extension.
A faster alternative to multiplication by 2
Compound
Assignment
Java Relational Operators
Boolean Logical Operators
Logical AND/OR vs Short-Circuit AND/OR
• The code snippet works fine for all values of denom!
• If the above line is written using & instead of &&, the code
would throw runtime exception when denom is zero!!
Why???
Boolean Logical Operators
Logical AND/OR (&,|) vs Short-Circuit AND/OR (&&,||)
x y AND
true true true
• The code snippet works fine for all values of denom!
false true false
true false false
• If the above line is written using & instead of &&, the code false false false
would throw runtime exception when denom is zero!!
x y OR
true true true
Why??? false true true
true false true
false false false
Java Control Statement Categories
• Categories of Java Control Statements:
• Selection Statements
• if statement
• switch-case statement
• Iteration Statements
• for loop
• while loop
• do-while loop
• for-each Version of for loop
• Jump Statements
• break statement
• continue statement
• Labelled break statement
• Labelled continue statement
• return statement
Java Control Structures
• linear flow of control
• statements executed in consecutive order
• Decision making with if - else statements
if(boolean-expression)
statement;
if(boolean-expression)
{ statement1;
statement2;
statement3;
}
• Boolean expressions are expressions that involve Boolean Relational
Operators and evaluate to true or false
• A single statement could be replaced by a statement block, braces with 0 or
more statements inside
Java Control Structures
• if-else Statement:
if(boolean-expression)
statement1;
else
statement2;
• Multiway selection or if-else ladder:
if(boolean-expression1)
statement1;
else if(boolean-expression2)
statement2;
else
statement3;
• individual statements could be replaced by a statement block, a set of braces with
0 or more statements
• Java also has the switch-case statement
Switch-case Statement
• The switch statement provides another means to decide which statement
to execute next
• The switch statement evaluates an expression, then attempts to match
the result to one of several possible cases
• Each case contains a value and a list of statements
• The flow of control transfers to statement list associated with the first
value that matches
Switch-case Statement: Use of default
• A switch statement can have an optional default case which has no
associated value
• If the default case is present, control will transfer to it if no other case
value matches
• The default case can be positioned anywhere in the switch, it is usually
placed at the end
• If there is no default case, and no other value matches, control falls
through to the next statement after the switch
Switch-case Statement: Use of break
• Often a break statement is used as the last statement in each case’s
statement list
• A break statement causes control to transfer to the end of the switch
statement
• If a break statement is not used, the flow of control will continue into the
next case
• The expression of a switch statement must result in an integral data type,
like an integer or character
• You cannot perform relational checks with a switch statement
Switch-case Statement: Example
switch(mark) {
case 0:
case 1:
case 2:
case 3:
case 4: [Link]("F");
break;
case 5: [Link]("D");
break;
case 6:
case 7: [Link]("C");
break;
case 8: [Link]("B");
break;
case 9:
case10: [Link]("A");
break;
default: [Link]("Incorrect score");
}
for Loops
• for loops
for(init-expr;boolean-expr;incr-expr)
statement; //or statement-block
• init-expr and incr-expr can be zero or more expressions or statements
separated by commas
false
execute evaluate skip to 1st statement after
init-expr boolean-expr body of loop
true
execute execute
body of loop incr-expr
while loops
• while loops
while(boolean-expression)
statement; //or statement block
• do-while loop part of language
do
statement;
while(boolean-expression);
• Again, could use a statement block
• In case of do-while loop, the statement is executed at least once!
for-each version of for Loop
• The general form of the for-each version of the for loop is:
for(type itr-var : collection) statement-block
• It’s commonly used to iterate over an array or a Collections class
• With each iteration of the loop, the next element in the collection is
retrieved and stored in itr-var
• The loop repeats until all elements in the collection have been obtained
• Data type of the iteration variable must be the same as (or compatible
with) the elements stored in the collection
• Remarks:
• The iteration variable is “read-only” as it relates to the underlying collection
• For-each loops do not keep track of index of the collection
• For-each only iterates forward over the array in single steps
for-each version of for Loop: Example
/* Find sum of first ten integers */
class ForEachExample {
public static void main (String args []) {
int nums[] = {2, 3, 1, 5, 6, 9, 7, 8, 6, 5};
int sum = 0;
for (int x : nums) {
[Link](“Value is “ + x);
sum += x;
}
[Link](“Summation is “ + sum);
}
}
break statement
• Used in switch-case statements (already discussed) and in loops
• break statement inside a loop
• When encountered inside a loop, the loop is immediately terminated
• The program control resumes at the next statement following the loop
• Can use with all types of loops
• Example: break in simple for loop
for(int i=1;i<=10;i++){
if(i==5) break; //breaking the loop when i is equal to 5
[Link](i);
}
C:\Users\mtc01\Desktop\MyProgs>
break statement: Nested Loop java BreakInnerLoopExample
11
12
13
• Example: break in nested for loop: 21
for(int i=1; i<=3; i++){ //outer loop 31
32
for(int j=1; j<=3; j++){ //inner loop 33
if(i==2 && j==2){ C:\Users\mtc01\Desktop\MyProgs>
break; //breaks inner loop
}
[Link](i + " “ + j);
} // end of inner loop
} // end of outer loop
break statement: Labelled Loop C:\Users\mtc01\Desktop\MyProgs>
java
BreakOuterLabelledLoopExample
• One can use break statement with a label 11
• One can break any loop in Java whether it is outer or inner loop 12
• Example: break in labelled for loop: 13
21
outerLabel:
for(int i=1; i<=3; i++){ //outer loop C:\Users\mtc01\Desktop\MyProgs>
for(int j=1; j<=3; j++){ //inner loop
if(i==2 && j==2){
break outerLabel; // breaks outer loop
}
[Link](i + " “ + j);
} // end of inner loop
} // end of outer loop
continue Statement
• Used when you need to jump to the next iteration of the loop immediately
• Skips the remaining code at the specified condition
• Can use Java continue statement in all types of loops
• Can be used in nested loops as well as in labelled loops
• Example:
for(int i=1;i<=10;i++){
if(i==5){
continue; //it will skip the rest of the block
}
[Link](i);
}