Day 2 - Introduction To Java, Tokens, Control Flow
Day 2 - Introduction To Java, Tokens, Control Flow
DATE-20-11-25
Contents
01
Introduction to
Java 02
Java Tokens 03
Read User
Input
04
Control Flow
Statements
Environmental Setup
• To run Java applications, we need to prepare the environmental setup. For installing Java, we need
the following:
• The Java Runtime Environment (JRE) (Includes Java Virtual Machine (JVM))
• A text editor
– java -version
– javac -version
• If you see something like “java is not recognized”, install the JDK from:
[Link]
• After downloading, run the msi installer :Keep the default installation path as shown in the
picture(recommended)
– Now check:
o java -version
o javac -version
Variables.
C:\Program Files\Java\jdk-21\bin
o Click New
• Step 3: Create a Project Folder as shown in the below image and create your Java file.
Eclipse IDE
• Using a text editor is the basic way of creating a Java program, but there are tools available to make it
Eclipse IDE
Eclipse IDE
Download this
package
Eclipse IDE
Eclipse IDE
Eclipse IDE
Once the workspace is chosen, you will get the welcome page
Eclipse IDE
After closing the welcome screen ,the project explorer and other options will be shown up.
Now you are ready to start working.
Eclipse IDE
Eclipse IDE
Create First Java Program with file extension .java Example: [Link]
Eclipse IDE
After creating the application, run the application with a run command
Eclipse IDE
/**
*/
class HelloWorldApp {
}
29 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Introduction to Java
• Code conventions are important to the programmer for the following reasons
• Readability: Describe the code with comments and name the Identifiers relative to the objective of
the code and ensure other people can understand the code.
• Modularity: When there is a need to redo the small fraction of code then practice using the existing
or reusing the code.
• Efficiency: The code should be fast and economical. When using data files, read a value once and
store it in a variable – don’t go back and forward for the same value. Close connections if they are
not required. Do not hold onto references to variables if not required, so as not to impose a memory
leak.
• Source file of java can be saved with the extension or suffixes “[Link]”.
• Comments
Indentation
• When the statement is not fit in a single line, then wrap the lines based on the following principles.
Example:
public void Cart(string product_name, double cost,
int quantity, string description)
Indentation
Example: //Breaking an arithmetic expression before an operator and outside the parenthesized
expression at a high level.
Calculation = a*(b + c - d)
+4*b
• Align the new line with the beginning of the expression at the same level on the previous line.
• If the above rules lead to confusing code or to code that's squished up against the right margin, just
Indentation
Indentation
Blank Lines:
- Between methods
Indentation
Blank Spaces:
• Black Spaces are used to improve the reliability of the code and can be used in the following
circumstances
Example:
while (false){
}
• It should not be used between a method name and its opening parenthesis. This helps to
distinguish keywords from method calls.
Indentation
• Except ‘.’ and unary operators all the binary operators should be separated their operands by spaces.
Comments
• Block comments:
• Block comments (/***/) are used to provide descriptions of files, methods, data structures,
and algorithms.
• Block comments may be used at the beginning of each file and before each method and also
within methods.
• Block comments inside a function or method should be indented to the same level as the
code they describe.
Example:
/*
*Here is a block comment
*/
Comments
• Single-Line comments:
• A short description of a block of code can be given using single-line comments (/*..*/).
• If a comment can't be written in a single line, it should follow the block comment format.
Example:
if(condition) {
/* Description about bock of code in a single line */
}
Comments
• Trailing comments:
• Trailing comments (/*..*/) are very short comments that describe the statements.
• These comments can be included in the same line of the statement but should be separated
• If more than one short comment appears in a code, they should all be indented to the same tab.
Example:
class HelloWorldApp {
public static void main(String[] args) {
[Link]("Hello World!"); /* Display the Hello World! */
}
}
Comments
• This comment line (//) can be used as a single-line comment or a short comment for a statement.
• These comments can be included in the same line of the statement but should be separated from the
• This can be used in consecutive multiple lines for commenting out sections of code.
Example:
class HelloWorldApp {
public static void main(String[] args) {
[Link]("Hello World!"); // Display the Hello World!
}
}
Documentation Comments
• Documentation comments are generally used when writing code for a project/software package.
• It helps to generate a documentation page for reference, which can be used for getting information
• The JavaDoc tool is used to process the doc comments that come with JDK and it is used for generating
Java code documentation in HTML(HyperText Markup Language) format from Java source code, which
Documentation Comments
Javadoc Tag:
• These doc tags enable you to autogenerate a complete, well-formatted API from your source code.
• The tags start with an "at" sign (@) and are case-sensitive (i.e).,they must be in upper and lowercase
• A tag must start at the beginning of a line (after any leading spaces and an optional asterisk) or it is
Documentation Comments
• Block tags - Can be placed only in the tag section that follows the main description.
- Example: @tag
• Inline tags - Can be placed anywhere in the main description or in the comments for block tags and
- Example: {@tag}
Documentation Comments
Javadoc Tags:
• Below table describe the Javadoc tag that is used in documentation comments.
Documentation Comments
@return Adds a "Returns" section with the description text. @return description
Documentation Comments
@throws The @throws and @exception tags are synonyms. @throws class-name description
Documentation Comments
Documentation Comments
• Each line above is indented to align with the code below the comment.
• Write the first sentence as a short summary of the method, as Javadoc automatically
• The inline tag can be used anywhere that a comment can be written, such as in the text
Documentation Comments
• If we have more than one paragraph in the doc comment, separate the paragraphs with a <p>
paragraph tag.
• Insert a blank comment line between the description and the list of tags.
• The first line that begins with an "@" character ends the description.
• There is only one description block per doc comment; we cannot continue the description following
block tags.
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
* Doc comment
* @author SmartCliff
*/
class HelloWorldApp {
public static void main(String[] args) {
[Link]("Hello World!"); // Display the Hello World!
}
}
• public keyword is an access modifier which represents visibility, it means it is visible to all.
• 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
• void is the return type of the method, it means it doesn't return any value.
53 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Introduction to Java
[Link]();
Package: Introduction
Java Package
Sub-Packages (lang, io, util, etc.,) interfaces
Package: Introduction
1. Built-in Packages: The already defined package in Java API like [Link].*, [Link].* etc. are known
2. User-defined Packages: The package created by user and use based on application needs is called
user-defined package.
Note:
• Programmers typically use packages to organize classes belonging to the same category or providing
similar functionality.
56 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Introduction to Java
Package: Introduction
[Link]();
Note:
• As per Java 1.8 standard version, Java have 14 predefined packages, 150 sub packages, 7000
classes and 7 lakh methods.
• The source code of Java will be created with file extension .java, Example: [Link]
• The java Compiler compiles a java file and convert into bytecode / classfile.
• The .class file is interpreted by the JVM and morphed into machine specific code.
• The Just-In-Time (JIT) compiler is one of the integral parts of the Java Runtime Environment.
• It improves the performance of Java applications by compiling byte codes to native machine code at
run time.
• The JIT compiler is enabled by default. When a method has been compiled, the JVM calls the compiled
• Theoretically, if compilation did not require processor time and memory usage, compiling every method
could allow the speed of the Java program to approach that of a native application.
Introduction
• The tokens are the small building blocks of a Java program that are meaningful to the Java compiler.
• The Java compiler breaks the line of code into text (words) is called Java tokens.
• These tokens are separated by the delimiters and delimiters are not part of the Java tokens.
Example: In program, we will be using many statements and expressions to perform the operation. These
Introduction
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Special symbols
Keywords
• Keywords are predefined or reserved words that have special meaning to the Java compiler.
• Each keyword is assigned a special task or function and cannot be changed by the user.
• We cannot use keywords as variables or identifiers as they are a part of Java syntax itself.
Keywords
Keywords
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
65 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens
Identifiers
• An identifier is the name given by the user for the various programming elements like variables,
classes, methods, interface, etc.
• Allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign)
and ‘_‘ (underscore).
Identifiers
• There is no limit on the length of the identifier, but it is advisable to use an optimum length of 4 – 15
letters only.
• All the identifiers such as classes, interfaces, packages, methods, and fields of Java programming
• By using this naming convention, we can achieve readability and can also easily understand the code.
• In programming, we often remove the spaces between words because programs of different sorts
• Because the space character is reserved, we cannot use it to represent a concept that we express in
Example
• That is in programming we cannot refer, user login count=5.
• We can represent as userLoginCount=5.
• Java follows the CamelCase for identifiers naming conventions.
CamelCase
- Combines the compound words and removes the space between the words.
- Two types: UpperCamelCase and lowerCamelCase.
- UpperCamelCase: The first letter of each word is capitalized.
Example: Product, ProductDescription, CountValue.
- LowerCamelCase: The first letter of the compound words is lowercase.
Example: product, iPad, countValue, productDescription
• A variable's name can be any legal identifier i.e., begins with a letter, the dollar sign "$", or the
underscore character “_“.
• The variable name should be short and meaningful.
• The choice of a variable name should be mnemonic- that is, designed to indicate to the casual
observer the intent of its use.
• One-character variable names should be avoided except for temporary variables.
• The temporary variables can be i,j,k,m, and n for integer and c,d,e for characters.
• Apart from its name and its type, the scope of a variable is its most important feature.
• Indicating class scope by using underscore makes it easy to distinguish class variables from local
scratch variables.
• This is important because class variables are considered to have higher significance than method
variables, and should be treated with special care by the programmer
Example:
class Login{
private String _userName;
…
}
Constants:
• If we specify the constant with two words, then separated by underscores ("_").
Example:
static final int MAX_HEIGHT = 70;
static final int MAX_WIDTH = 100;
static final int LENGTH = 20;
Methods
Example:
void calculateTax()
String getSurname()
void draw()
• The first non-comment line of the java source file is a package followed by import statements.
• The prefix of a unique package name is always written in all-lowercase ASCII letters.
Example:
package [Link].*;
import [Link];
Example:
class Customer
class CustomerAccount
class Login
• Interface tends to have a name that describes an operation that a class can do.
Example:
interface Enumerable
interface CompEnumerable
interface Login
Data Types
• Data types defines the type data a variable can hold. It specify the different sizes and values that can be
stored in the variable.
Data Types
• byte: (1 byte):
–It has a minimum value of -128 and a maximum value of 127 (inclusive).
–Default value : 0
• short: (2byte)
–It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).As byte ,can use
a short to save memory in large arrays
–Default value : 0
Data Types
• int: (4 byte)
– By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of
-231 and a maximum value of 231 -1.
– Default value : 0
• long: (8 byte)
– The long data type is a 64-bit two's complement integer.
– The signed long has a minimum value of -263 and a maximum value of 263-1
– Default value : 0L
• float: (4 byte)
– The float data type is a single-precision 32-bit IEEE 754 floating point.
– Default value : 0.0f
Data Types
• double: (8 byte)
– The double data type is a double-precision 64-bit IEEE 754 floating point
– Default value : 0.0d
• boolean: (1 bit)
– The boolean data type has only two possible values: true and false
– Default value : false
• char: (2 byte)
– single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value
of '\uffff‘
– Default value : '\u0000'
Variables
• A symbolic name associated with a value and whose associated value may be changed.
• All variables have a scope, which defines their visibility, and a lifetime.
[Link] Variables
Variables
Local Variables
• Other methods in the class aren't even aware that the variable exists.
Variables
• A variable declared inside the class but outside the body of the method, is called instance
variable.
• Instance variables are created when the objects are instantiated and therefore they are associated
Variables
• A variable which is declared as static is called static variable. It is also called as a class 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.
Variables
/**
* The VariableApp class implements an application that
* illustrate different Java variable
* @author Smartcliff
*/
class VariableApp {
int mark = 95 ;//instance variable
static char grade = ‘S’; // static variable
public static void main(String[] args) {
float average=95.0 // local variable
}
}
Literals
Literals
• In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits
in a numerical literal.
• Enables to separate groups of digits in numeric literals, which can improve the readability of your
code.
Example:
Literals
• You can place underscores only between digits; you cannot place underscores in the following
places:
–Prior to an F or L suffix
Unicode
• It is Computing industry standard designed to encode characters of the world's written languages.
• Unicode System?
–ASCII (American Standard Code for Information Interchange) for the United States.
Unicode
• Problems:
–A particular code value corresponds to different letters in the various language standards.
–The encodings for languages with large character sets have variable length.
– Some common characters are encoded as single bytes, other require two or more byte.
• Solution:
–To solve these problems, a new language standard was developed i.e. Unicode System.
–In Unicode, character holds 2 byte, so java also uses 2 byte for characters.
Operators
• An operator in Java is a special symbol that signifies the compiler to perform some specific
Expression
• An expression in Java is any valid combination of tokens like variables, constants and operators.
• An expression may consist of one or more operands, and zero or more operators to produce a value.
Examples:
-a+b*c
- (a * b) / (c + d)
- 10 – 4 * 5
- Etc.,
• Below table we have listed down all the operators, along with their expressions:
Type Operators Expressions
Unary Operator ++,--,+(unary),-(unary), ~,! a++,--a, -a, ~a, !a
Precedence
• Operator precedence determines the order in which the operators in an expression are evaluated.
To evaluate the above expression Java, consider the precedence of the operator. Here, Multiplication (*) has the
highest precedence over subtraction (-). So multiplication will be performed before the subtraction.
Associativity
• If an expression has two operators with similar precedence, the expression is evaluated according
to its associativity.
= += -= *= /= %=
assignment right to left
&= ^= |= <<= >>= >>>=
Expression Evaluation
Example 1 : 10 – 3 % 8 + 6 / 4 Example 2: 6 - ( 5 – 3 ) + 10 Example 3 : 3+4*4>5*(4+3) -1
• Bitwise operators are used to perform operations at the bit level and help to manipulate data at the
• These can be done by first converting a decimal value to its binary form. This binary form is nothing
Operator Meaning
& Bitwise AND operator
| Bitwise OR operator
^ Bitwise exclusive OR operator
• Example: Let's take a look at the bitwise AND operation of two integers 12 and 25.
• Now move from left to right, and perform logical AND operations on the bits, and store the result
in the corresponding position.
00001100
& 00011001
____________
// Bitwise AND
class Main { Output: 8
public static void main(String[] args) {
AND, i.e. if at least any one of the operands has 1, then Result=Num1 |
Num1 Num2
Num2
the result will also have 1 in the corresponding position,
0 0 0
• Example: Let's take a look at the bitwise OR operation of two integers 12 and 25.
• Now move from left to right, and perform logical OR operations on the bits, and store the result in
the corresponding position.
00001100
| 00011001
____________
// Bitwise OR
Output: 29
class Main {
public static void main(String[] args) {
that they perform logical XOR on the bit level, i.e., if Result=Num1 ^
Num1 Num2
Num2
exactly one of the operands has 1 and the other has 0
0 0 0
• Example: Let's take a look at the bitwise OR operation of two integers 12 and 25.
• Now move from left to right, and perform logical AND operations on the bits, and store the result
in the corresponding position.
00001100
^ 00011001
____________
// Bitwise XOR
Output: 21
class Main {
public static void main(String[] args) {
• The bitwise complement operator takes a single value Truth table for Bitwise Complement
operator
and returns the one’s complement of the value.
• It is important to note that the bitwise complement of any integer N is equal to - (N + 1).
• For example :Consider an integer 35. As per the rule, the bitwise complement of 35 should be -(35 +
1) = -36. Now let's see if we get the correct answer or not.
~ 00100011
__________
11011100
• In the above example, we get that the bitwise complement of 00100011 (35) is 11011100. Here, if we
convert the result into decimal we get 220.
• However, it is important to note that we cannot directly convert the result into decimal and get the
desired output. This is because the binary result 11011100 is also equivalent to -36.
2's Complement
• In binary arithmetic, we can calculate the binary negative of an integer using 2's complement.
• 1's complement changes 0 to 1 and 1 to 0. And, if we add 1 to the result of the 1's complement, we get
the 2's complement of the original number. Example as Follows
2's complement:
11011011
+ 1
_________
11011100
• Here, we can see the 2's complement of 36 (i.e. -36) is 11011100. This value is equivalent to the bitwise
complement of [Link], we can say that the bitwise complement of 35 is -(35 + 1) = -36.
// Bitwise Complement
class Main { Output: -36
• The left shift operator (<<) is a bitwise operator that shifts the bits of a binary number to the left by
• In other words, it multiplies the number by 2 raised to the power of the shift count.
– Each bit in the binary representation of the number is shifted to the left by the specified number of
positions.
– The leftmost bits that are shifted out (if any) are discarded.
Decimal
14<<1 0 0 0 1 1 1 0 0 = 28 Representation -
00011100
• The right shift operator (>>) is a bitwise operator that shifts the bits of a binary number to the right
by a specified number of positions.
• In other words, it divides the number by 2 raised to the power of the shift count, discarding the
remainder.
– Each bit in the binary representation of the number is shifted to the right by the specified number
of positions.
– The vacant positions on the left are filled with the sign bit (for signed integers) or with zeros (for
unsigned integers).
– The rightmost bits that are shifted out (if any) are discarded.
0 0 0 1 1 1 0 to the Right
14>>1 00
Step 4: Add a 0 to the Leftmost
position to fill the empty space
After the right shift the binary representation is: Step 5: Calculate and display the
decimal equivalent of the shifted
binary number.
14>>1 0 0 0 0 1 1 1 0 = 7 Decimal
Representation
- 00000111
118 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens
• In the example, the value of num is 12, and the result of num >> 2 is 3.
• The binary representation of 12 is 0000 1100, and after right-shifting by 2 positions, it becomes
0000 0011, which is 3 in decimal.
119 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens
Type Conversions
• Widening or Automatic Type Conversion – lower data types are automatically convert into higher data
• Automatic type conversion will take place if the following two conditions are met:
Type Conversions
float → double
• Generally safe because they tend to go from a small data type to a larger one
Type Conversions
/**
* The ConversionAutomatic class implements an application that
* Illustrate the automatic type conversion
*/
class ConversionAutomatic {
public static void main(String[] args) {
int i = 100;
long l = i; // automatic type conversion
float f = l; // automatic type conversion
[Link]("Int value "+i);
[Link]("Long value "+l);
[Link]("Float value "+f);
}
}
122 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens
Type Conversions
• Narrowing or Explicit Conversion - If we want to assign a value of larger data type to a smaller data
type we perform explicit type casting or narrowing.
• Useful for incompatible data types where automatic conversion cannot be done.
• Here, target-type specifies the desired type to convert the specified value to.
Type Conversions
/**
* The ConversionExplicit class implements an application that
* Illustrate the explicit type conversion
*/
class ConversionExplicit {
public static void main(String[] args) {
double d = 100.04;
long l = (long)d; //convert double into long
int i = (int)l; // long convert into int
[Link]("Double value "+d);
[Link]("Long value "+l);
[Link]("Int value "+i);
}
}
124 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens
Type Conversions
• Type promotion in Expressions - While evaluating expressions, the intermediate value may exceed
the range of operands and hence the expression value will be promoted.
[Link] automatically promotes each byte, short, or char operand to int when evaluating an
expression.
[Link] one operand is a long, float or double the whole expression is promoted to long, float or double
respectively.
Type Conversions
/**
* The TypePromotion class implements an application that
* Illustrate the type promotion
* @author Smartcliff
*/
class TypePromotion{
public static void main(String[] args){
byte b = 50;
b = (byte)(b * 2); //promote into int
[Link](b);
}
}
126 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens
Type Conversions
/**
* The TypePromotion1 class implements an application that
* Illustrate the type promotion
*/
class TypePromotion1{
public static void main(String[] args){
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s); //promote into double
[Link]("result = " + result);
}
}
Special Symbols
• Special symbols in Java are a few characters which have special meaning known to Java compiler
• In the below table we have listed down the special symbols supported in Java along with their
description.
Special Symbols
Symbols Description
These are used as an array element reference and also indicates single and
brackets []
multidimensional subscripts
These indicate a function call along
Parentheses()
with function parameters
The opening and ending curly braces indicate the beginning and end of a block
Braces{}
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
Introduction
• There are three different ways to read input from the user:
2. Scanner Class
• Scanner Class: It is a class in [Link] package used for obtaining the user input of the primitive
types like int and double. It is the easiest way to read input in a Java program.
• Scanner object is constructed from Scanner Class and [Link] (input stream) object is passed
as a parameter while creating a scanner object.
Methods
• After creating the scanner object, we can use below Scanner class methods for reading the
respective primitive data types from the console.
Method Description
boolean nextBoolean() This method reads the boolean value from the user.
double nextDouble() It accepts the input in double datatype from the user.
Methods
Method Description
String nextLine() This method reads the String value from the user.
long nextLong() This method reads the long type of value from the user.
short nextShort() It reads the short type of value from the user.
Note:
• 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) function returns the first character in
that string.
133 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Read User Input
Example: #1
/** Output:
Enter your Name : Arun
* The ReadSomeInput class implements an application that
Hi, Arun . Welcome to the Training Program
* Illustrate reading a console input */
}}
134 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Read User Input
Example: #2
/**
* The ReadInput class implements an application that
* Illustrate reading a console input */
import [Link]; //import Scanner class from util package
public class ReadInput {
public static void main(String[] args) {
Scanner console = new Scanner([Link]);
[Link]("Enter your User Name : ");
String name = [Link]();
[Link]("Enter your Password : ");
String password = [Link]();
Example: #2
Example: #3
/**
* The ReadMovie class implements an application that
* Illustrate reading a different types of input
*/
import [Link];
public class ReadMovie {
public static void main(String[] args) throws ParseException {
Scanner console = new Scanner([Link]);
[Link]("Enter Movie ID : ");
int movieid = [Link]();
Example: #3
Example: #3
Example: #3
Input/ Output:
Enter Movie ID : 1231 ENTERED MOVIE DETAILS ARE
Enter Movie Name : AAA Movie ID : 1231
Enter Movie Description : Dramaof1956 Movie Name : AAA
Enter Movie Language : English Movie Description : Dramaof1956
Enter Movie Genre : ACTION Movie Language : English
Enter Movie release date (dd/mm/yyyy) : 23/03/2022 Movie Genre : ACTION
Enter Movie Seat Cost : 120.0 Movie Date : 23/03/2022
Movie Seat Cost : 120.0
Quiz
a) int b) float
c) double d) boolean
Quiz
a) Class b) Method
c) Block d) Object
b) & c)
Quiz
a) Variable b) int
c)Identifiers d) Constant
d) Constant
Quiz
a) Identifier b) Keyword
b) Keyword
Quiz
a) Widening b) Narrowing
a) Widening
Quiz
a) L b) l
c) D d) 0x
a) & b)
Quiz
b) Instance variables
Quiz
a) double b) switch
c) instanceof d) then
d) then
Quiz
a) & b) |
c) ^ d) <=
d) <=
Quiz
a) ~ b) <<
c) ^ d) >>>
a) ~
Quiz
Quiz
a) true b) false
b)false
Quiz
a) num1>>2 b) num1<<<2
c) num1%=2; d) num1<<2;
b) num1<<<2
Quiz
14) In Java, after executing the following code what are the
values of x, y, and z?
x = y++ + z++;
Quiz
a)next() b) nextInt()
c) nextInteger() d) readInt()
b) nextInt()
Introduction
• Control flow is the order in which individual statements or instructions of a program are executed or
evaluated and Control flow statements is categorized as follows:
Control Statements
for
Conditional Unconditional while
Statements Statements
Simple If do..while
break
If..else If..elseif..else
continue
Switch
case Nested if
157 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Introduction
• Sequential statements describe a sequence of actions that a program carries out one after another,
unconditionally.
Example:
import [Link];
public class CircleArea {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the radius of the circle: ");
double radius = [Link]();
double area = [Link] * radius * radius;
[Link]("The area of the circle with radius " + radius + " is: " + area);
[Link]();
}
}
Introduction
• if
• if…else
• if-else-if
• nested if
• switch
Decision-Making : simple if
• Simple if: If the condition is true, the body of the if statement is executed. If it is false, the body
if ( condition ){
statement(s);
}
Decision-Making : simple if
/** Output:
* The IfControlStructure class implements an application that
10
* Illustrate the if decision Making control statement
*/
class IfControlStructure{
public static void main(String[] args){
boolean isMoving=true;
int currentSpeed=10;
if(isMoving){
[Link](currentSpeed);
}
}
}
Decision-Making : simple if
/**
*The SimpleIf class implements an application that checks the seat availability status for movie ticket booking using
*simple if decision Making control statement
*/
import [Link];
public class SimpleIf {
public static void main(String[] args){
boolean seatAvailable = true; //Seat Available Status
Scanner input = new Scanner([Link]); //Scanner class object creation
[Link]("Enter the Seat Number : ");
String SeatNumber = [Link](); //get Seat Number from User
Decision-Making : simple if
Output:
Enter the Seat Number : A32
Your have booked the seat number : A32
• if –else: If the condition is true, the body of the if statement is executed. If it is false, the body of
• Syntax
if ( condition ){
if Body;
}
else{
else Body;
}
/** * The SimpleIfElse class implements an application that that checks the seat availability status for movie ticket
booking using the if ..else decision-Making control statement */
Output:
Enter the Seat Number : A22
Seat Numer A22 is already booked
• if-else-if: It is also called else-if ladder. Here execute any one block of statements among many blocks.
• Syntax
if ( condition 1){
statement 1;
}else if ( condition 2 ){
statement 2;
}else if (condition 3){
statement 3;
} else {
else Body
}
/** Output:
* The IfEsleIFControlStructure class implements an application that
Color Red!
* Illustrate the if ..elseif decision Making control statement */
class IfElseIFControlStructure{
public static void main(String[] args){
int colorValue=2;
if(colorValue==1)
[Link](“Color Blue!”);
else if(colorValue==2)
[Link](“Color Red!”);
else
[Link](“Color Green!”);
}
}
Output:
Type of seats Available
REGULAR
PREMIUM
EXECUTIVE
VIP
choose any one of the option : PREMIUM
You have selected Premium Seat and cost Rs.100
Decision-Making : Nested if
• Nested if: Use more than if statement inside another if statement. The outer if statement condition true
means inside if statements execute.
• Syntax
if ( condition 1){
if ( condition 2 ){
Nested if Body
}else{
Nested else Body
}
}else
else Body
}
173 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Decision-Making : Nested if
Decision-Making : Nested if
/* * The Booking class implements an application that validates the login and check for the seat availability
* using nestedif decision Making control statement */
import [Link].*;
public class NestedIf {
public static void main(String[] args){
String username = "Sarvesh",password = "sarvesh@123",usernameentered,passwordentered;
boolean seatAvailable = true;
String seatNumber;
Scanner input = new Scanner([Link]); //Scanner class object creation
[Link]("Enter the Username : ");
usernameentered = [Link](); //getting the username
[Link]("Enter the Password : ");
passwordentered = [Link](); //getting the password
175 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Decision-Making : Nested if
Decision-Making : Nested if
Output:
Enter the Username : Sarvesh
Enter the Password : sarvesh@123
You have logged in and you can book a ticket now
Enter the Seat Number : A10
Seat Number A10 you have chosen is available
• switch-case: Select one of many possible statements to execute. It gives alternate for
long if..else..if ladders which improves code readable.
• Syntax
switch ( expression ) {
case value1 :
statement-list1;
break;
case value2 :
statement-list 2;
break;
default:
statement-list 3;
break;
}
178 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Note:
• In switch, Case value must be in expression type only and case values must be unique.
• Each case break statement is optional. It helps terminate from switch expression. If a break
default:
[Link]("Invalid Letter");
break;
}
}
Output:
Uppercase Letter
/** The SwitchCase class implements an application that demonstrate the movie searching by different types of languages
* using switch decision Making control statement Searching the Movie detail by Title, Language, ReleaseDate, Genre*/
import [Link];
public class SwitchCase {
public static void main(String[] args){
[Link]("Enter the type to be search \n1. Search by Title \n2. Search by Language \n3. Search by Release
Date \n4. Search by Genre \nEnter the Choice (1/2/3/4)");
Scanner input = new Scanner([Link]); //Scanner class object creation
int choice = [Link](); //getting the choice from user
switch(choice){
case 1:
[Link]("Your searching choice is Movies by Title");
break;
case 2:
182 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Output:
Enter the type to be search
1. Search by Title
2. Search by Language
3. Search by Release Date
4. Search by Genre
2
Your searching choice is Movies by Language
Looping - Introduction
• Loop/ iterative statements are used for executing a block of statements repeatedly until a particular
condition is satisfied.
• while
• do…while
• for
• for…each
Looping - Introduction
• Initialization: To set initial value to the iteration variable at the very start of the loop.
• Loop-body: If the test condition is true, the body of the loop runs once.
• Updation: Increment/decrement statement executes just after executing the body, and then the
Looping - while
• while: It is used to rrepeat a specific block of code. It is preferable while we do not know the exact
• Syntax
while (condition){
statement(s)
}
Looping - while
/**
* The WhileStructure class implements an application that
* Illustrate While Looping control statement
*/
class WhileStructure{
public static void main(String[] args){
int counter = 1;
while (counter < 11)
{
[Link]("Count is: " + counter);
counter++;
}
}
}
Looping - while
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Looping - while
/**
* The ShowSeat class implements an application that display the current seat availability
* using While Looping control statement
*/
public class ShowSeat {
public static void main (String[] args){
int MaxSeatCount = 10, seatCount = 0;
while(seatCount < MaxSeatCount){
[Link](“Current Seat Availability : "+(MaxSeatCount-seatCount));
seatCount++;
}
[Link]("Seats are Filled");
}
}
190 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Looping - while
Output:
Current Seat Availability : 10
Current Seat Availability : 9
Current Seat Availability : 8
Current Seat Availability : 7
Current Seat Availability : 6
Current Seat Availability : 5
Current Seat Availability : 4
Current Seat Availability : 3
Current Seat Availability : 2
Current Seat Availability : 1
Seats are Filled
Looping - do - while
• do-while: Executes the statement first and then checks for the condition. It is also called an
exit-controlled loop.
• Syntax
do {
statement(s)
} while (condition);
Looping - do - while
/**
* The DoWhileStructure class implements an application that that checks the seat availability
* status for movie ticket booking and Illustrate do..while Looping control statement
*/
class DoWhileStructure{
public static void main(String[] args){
int counter = 1;
do {
[Link]("Count is: " + counter);
counter++;
} while (counter < 11)
}
}
Looping - do - while
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Looping - do - while
/**
* The ShowSeat class implements an application that that checks the seat
* availability status for movie ticket booking using do.. while Looping control statement */
public class ShowSeat {
public static void main (String[] args){
int MaxSeatCount = 5, seatCount = 0;
do{
[Link]("Current Seat Availability : "+(MaxSeatCount-seatCount));
seatCount++;
} while(seatCount < MaxSeatCount);
[Link]("Seats are Filled");
}
}
Looping - do - while
Output:
Current Seat Availability : 5
Current Seat Availability : 4
Current Seat Availability : 3
Current Seat Availability : 2
Current Seat Availability : 1
Seats are Filled
Looping - for
• for: When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop
• Syntax
for (initialization; condition ; updation) {
statement(s)
}
Looping - for
/**
*/
class ForStructure{
Looping - for
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Looping - for
/**
* The ShowSeat class implements an application that that checks the seat availability status for
*/
class ShowSeat{
public static void main (String[] args){
int MaxSeatCount = 5, seatCount = 0;
for(seatCount=0;seatCount < MaxSeatCount;seatCount++){
[Link]("Current Seat Availability : "+(MaxSeatCount-seatCount));
}
[Link]("Seats are Filled");
}
}
200 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Looping - for
Output:
Current Seat Availability : 5
Current Seat Availability : 4
Current Seat Availability : 3
Current Seat Availability : 2
Current Seat Availability : 1
Seats are Filled
• for-each: It’s commonly used to iterate over an array or a Collections class. It is also called
• Syntax:
for (type var : arrayName) {
statements;
}
• It is used to iterate over the elements of a collection without knowing the index of each element.
• It is immutable which means the values which are retrieved during the execution of the loop are read
only
/**
* The ForEachApp class implements an application that
* illustrate foreach looping Structure
*/
class ForEachApp{
public static void main (String[] args){
int[] marks = { 125, 132, 95, 116, 110 };
int maxSoFar = marks[0];
//for each loop
Output:
The highest score is 132
/**
* The ForEach class implements an application that list the movie based on their Genre
* using foreach looping Structure
*/
import [Link];
public class ForEach {
public static void main(String[] args) {
String MovieName[] = {"AAA","BBB","CCC","DDD"};
String MovieGenre[] = {"ACTION","COMEDY","THRILLER","ACTION"};
Scanner input = new Scanner([Link]); //Scanner class object creation
[Link]("Enter the Genre to be searched : ");
String Genre = [Link]();
int counter = 0;
205 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Nested Loop
• Nested Loop: A loop inside another loop is called a nested loop. The number of loops depend on the
requirement of a problem. It contains outer loop and inner loop. For each iteration of outer loop the inner
• Syntax
while(condition) {
for (initialization; condition; updation) { do { ……….
statements(s)
…….. statement(s)
while(condition) {
for (initialization; condition; updation) { do {
statement(s) statement(s)
statement(s)
……. ………
……..
} } while(condition);
}
………. ……….
………..
} } while(condition);
}
Nested Loop
/**
* The NestedWhileApp class implements an application that
* illustrate nested while loop */
class NestedWhileAPP{
public static void main (String[] args){
int outerLoop=1,innerLoop=1;
whlie(outerLoop<=5){
while(innerLoop<=5){
[Link](“*”);
innerLoop++;
}
Nested Loop
[Link](“ “);
outerLoop++;
innerLoop=1;
}
}
}
Output:
*****
*****
*****
*****
*****
Nested Loop
/**
* The NestedWhile class implements an application that demonstrate the seat availability while the seats are getting
booked in multiple screens using nested while loop */
class NestedWhile{
public static void main (String[] args){
int MaxSeatCount = 5, TotalScreenCount = 2, seatCount = 0, screenCount = 0;
while(screenCount < TotalScreenCount){
seatCount = 0;
[Link]("Screen "+(screenCount+1)+" Availability details");
while(seatCount < MaxSeatCount){
[Link]("Current Seat Availability : "+(MaxSeatCount-seatCount));
seatCount++;
}
210 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Nested Loop
Nested Loop
/** Output:
* The Nested DoWhileApp class implements an application that illustrate nested do…while loop */
class NestedDoWhileApp {
111222333
public static void main (String[] args){
int outerLabel= 1;
do {
int innerLabel = 1;
do{
[Link](outerLabel);
innerLabel++;
Nested Loop
/**
* The NestedDoWhile class implements an application that demonstrate the seat availability while the seats are
getting booked in multiple screens using nested do…while loop */
class NestedDoWhile{
public static void main (String[] args){
int MaxSeatCount = 10, TotalScreenCount = 2, seatCount = 0, screenCount = 0;
do{
[Link]("Screen "+(screenCount+1)+" Availability details");
seatCount = 0;
do{
[Link](“Current Seats Availability : "+(MaxSeatCount-seatCount));
seatCount++;
} while(seatCount < MaxSeatCount);
213 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Nested Loop
Nested Loop
/**
* The Nested ForApp class implements an application that
* illustrate nested for looping structure
*/
class NestedForApp
{
public static void main (String[] args)
{
int rows = 5;
// outer loop
Nested Loop
Nested Loop
/**
* The NestedFor class implements an application that demonstrate the seat availability while the seats are getting
booked in multiple screens and illustrate nested for looping structure
*/
class NestedFor{
Nested Loop
} Output:
Screen 1 Availability details
[Link]("Seats Filled in Screen "+(screenCount+1));
Current Seat Availability : 5
}
Current Seat Availability : 4
}
Current Seat Availability : 3
} Current Seat Availability : 2
Current Seat Availability : 1
Seats Filled in Screen 1
Screen 2 Availability details
Current Seat Availability : 5
Current Seat Availability : 4
Current Seat Availability : 3
Current Seat Availability : 2
Current Seat Availability : 1
Seats Filled in Screen 2
218 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Branching - Unconditional
• Branching (Unconditional) - To transfers the control from one part of the program to another part
• break
• labelled break
• continue
• labelled continue
Branching - Unconditional
• break: When a break statement is encountered inside a loop, the loop is immediately terminated and
the program control resumes at the next statement following the loop.
• The Java break is used to break loop or switch statement. It breaks the current flow of the program
• Break statement use all types of loops such as for loop, while loop and do-while loop.
• Syntax
break;
Branching - Unconditional
/** Output:
Branching - Unconditional
/**
* The UnconditionalBreak class implements an application that demonstrate the seat availability while the seats are
getting booked assuming that the VIP seats are already reserved using Break branching statement
*/
class UnconditionalBreak {
public static void main (String[] args){
int premiumSeat = 5, vipSeat = 5, seatBooked = 0;
int totalSeat = premiumSeat + vipSeat;
for(seatBooked = 0;seatBooked < totalSeat;seatBooked++) {
if(seatBooked > premiumSeat) {
Branching - Unconditional
else {
[Link](“PREMIUM Seat Availability : "+(premiumSeat - seatBooked));
}
}
}
}
Branching - Unconditional
Output:
PREMIUM Seat Availability : 5
PREMIUM Seat Availability : 4
PREMIUM Seat Availability : 3
PREMIUM Seat Availability : 2
PREMIUM Seat Availability : 1
All PREMIUM Seats Booked
All VIP Seats 6 to 10 are Reserved
Branching - Unconditional
• continue: When you need to jump to the next iteration of the loop immediately.
• It continues the current flow of the program and skips the remaining code at the specified condition.
• Continue statement use all types of loops such as for loop, while loop and do-while loop.
• Syntax:
continue;
Branching - Unconditional
/** Output:
* The ContinueApp class implements an application that Count is: 1
* illustrate Continue branching statement Count is: 2
*/ Count is: 3
class ContinueApp { Count is: 4
Count is: 6
public static void main (String[] args) {
Count is: 7
for(int count = 1;count<10;count++) {
Count is: 8
if(count ==5) Count is: 9
continue;
[Link]("Count is: " + count);
}
}
Branching - Unconditional
/**
* The UnconditionalContinue class implements an application that demonstrate the seat availability while the seats are
getting booked assuming that the VIP seats are already reserved using Continue branching statement
*/
class UnconditionalContinue {
Public static void main (String[] args){
int executiveSeat = 5, premiumSeat = 5, vipSeat = 5, seatBooked = 0;
int totalSeat = regularSeat + executiveSeat + premiumSeat + vipSeat;
for(seatBooked = 0;seatBooked < totalSeat;seatBooked++) {
if(seatBooked < (vipSeat)){
[Link]("All VIP Seats 1 to 5 are Reserved ");
continue;
}
Branching - Unconditional
Branching - Unconditional
• Labeled Loop: In java, use labels with break and continue. A Label is used to identify a block of code.
In case of multiple loop involved use labeled loop to transfer any specific loop with help of labels.
Branching - Unconditional
/** * The LabeledBreakApp class implements an application that * illustrate Labeled Break */
Output:
class LabeledBreakApp{
00
public static void main(String[] args){
01
first: // First label 02
for (int i = 0; i < 3; i++) { 10
second: // Second label
for (int j = 0; j < 3; j++) {
if (1== i && 1 == j) {
// Using break statement with label
break first;
}
[Link](i + " " + j);
}
}
}
}
230 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Branching - Unconditional
/** * The LabeledBreakApp class implements an application that illustrate Labeled Break */
public class LabelledBreak {
public static void main (String[] args){
int MaxSeatCount = 10, TotalScreenCount = 2, seatCount = 0, screenCount = -1;
Start:
//[Link](screenCount);
while(screenCount < TotalScreenCount){
screenCount++;
[Link]("Screen "+(screenCount+1)+" Seat Booked detail");
seatCount=0;
while(seatCount < MaxSeatCount){
if(seatCount >3 && screenCount == 1) {
[Link]("Seat No 4 & 5 are Reserved");
Branching - Unconditional
break Start;
}
else
[Link]("Seats No Booked : "+(seatCount+1));
seatCount++;
}
[Link]("All Seats Filled in Screen "+(screenCount+1));
}
}
}
Branching - Unconditional
Output:
Screen 1 Seat Booked detail
Seats No Booked : 1
Seats No Booked : 2
Seats No Booked : 3
Seats No Booked : 4
Seats No Booked : 5
All Seats Filled in Screen 1
Screen 2 Seat Booked detail
Seats No Booked : 1
Seats No Booked : 2
Seats No Booked : 3
Seat No 4 & 5 are Reserved
233 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Branching - Unconditional
/*** The LabeledContinueApp class implements an application that illustrate LabeledContinue loop */
Output:
class LabeledContinueApp {
00
public static void main(String[] args){ 01
first: // First label 02
for (int i = 0 ; i < 3; i++) { 10
second: // Second label 20
for (int j = 0; j < 3; j++) { 21
if (1 == i && 1 == j) { 22
// Using continue statement with label
continue second;
}
[Link](i + " " + j);
}
}
}
}
234 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Branching - Unconditional
/*** The LabeledContinueApp class implements an application that illustrate LabelledContinue loop */
public class LabelledContinue {
public static void main (String[] args){
int MaxSeatCount = 5, TotalScreenCount = 2, seatCount = 0, screenCount = 0;
SkipScreen:
//[Link](screenCount);
while(screenCount < TotalScreenCount){
Branching - Unconditional
}
[Link]("All Seats Filled in Screen "+(screenCount+1));
screenCount++;
}
}
}
Branching - Unconditional
Output:
Screen 1 Ticket Booking detail
Seats No Booked : 1
Seats No Booked : 2
Seats No Booked : 3
Seats No Booked : 4
Seats No Booked : 5
All Seats Filled in Screen 1
Screen 2 Ticket Booking detail
Seats No Booked : 1
Seat No 2 is Reserved
Seat No 3 is Reserved
Seats No Booked : 4
Seats No Booked : 5
All Seats Filled in Screen 2
Quiz
b) if else statement
Quiz
if (num>0)
[Link](“Positive Number\n”);
else
[Link](“Negative Number\n”);
[Link](“The number is %d”,num);
c) Positive Number
d) The number is 6
The number is 6
c) Positive Number
The number is 6
239 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Quiz
a) case b) break
c) default
Quiz
Quiz
a) while b) do…while
b) do…while
Quiz
a) 1 b) 9
c) 10 d) 11
b) 11
Quiz
7. Which of the following are true about the enhanced for loop?
A. It can iterate over an array or a Collection but not a Map.
B. Using an enhanced for loop prevents the code from going into
an infinite loop
C. Using an enhanced for loop on an array may cause infinite
loop.
D. An enhanced for loop can iterate over a Map.
E. You cannot find out the number of the current iteration while
iterating.
a) A,B,E b) A,B,C
c) B,C,E d) A,D,E
a) A,B,E
Quiz
8. What is printed as a result of the following code segment?
for (int k = 0; k < 20; k+=2)
{
if (k % 3 == 1)
[Link](k + " ");
}
a) 0 2 4 6 8 10 12 14 16 18 b) 4,6
c) 4,10,16 d) 0,6,12,18
c) 4,10,16
Quiz
9. What is the output after the following code has been executed?
class FlowControl1 {
[Link](“Hello Friend");
else
}
246 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements
Quiz
10. What is stored in the variable result after the following code has been
executed?
class FlowControl2{
public static void main(String[] args){
int index = 0;
int result = 1;
while ( true ){
++index;
if ( index % 2 == 0 )
continue;
else if ( index % 5 == 0 )
break;
result *= 3;
}
}
}