0% found this document useful (0 votes)
6 views248 pages

Day 2 - Introduction To Java, Tokens, Control Flow

The document outlines a program aimed at bridging the digital skills gap for over 10 million young professionals by providing training in Java programming. It includes detailed instructions on setting up the Java environment, using command prompt, and employing the Eclipse IDE for Java development. Additionally, it emphasizes coding standards, practices, and the importance of documentation in programming.

Uploaded by

2k23aids46
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views248 pages

Day 2 - Introduction To Java, Tokens, Control Flow

The document outlines a program aimed at bridging the digital skills gap for over 10 million young professionals by providing training in Java programming. It includes detailed instructions on setting up the Java environment, using command prompt, and employing the Eclipse IDE for Java development. Additionally, it emphasizes coding standards, practices, and the importance of documentation in programming.

Uploaded by

2k23aids46
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

We are on a mission to address the digital

skills gap for 10 Million+ young professionals,


train and empower them to forge a career
path into future tech
Industry Driven MCA Degree Program
OBJECT-ORIENTED PROGRAMMING USING JAVA

UNIT I: INTRODUCTION TO JAVA PROGRAMMING

DATE-20-11-25
Contents

01
Introduction to
Java 02

Java Tokens 03

Read User
Input

4 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Contents

04
Control Flow
Statements

5 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

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))

• The Java Developer Kit (JDK) ( Includes the Java Compiler)

• A text editor

• If JDK is installed, you automatically get the JRE.

6 UNIT I - Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java Application using Command Prompt

• To execute Java applications, the environment must be properly configured.

• Step 1: Verify or Install Java 21

o Open Command Prompt and type:

– java -version

– javac -version

• If you get version numbers, Java is already installed.

• If you see something like “java is not recognized”, install the JDK from:
[Link]

7 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java Application using Command Prompt

Click here to download


the JDK21 version

8 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java Application using Command Prompt

• After downloading, run the msi installer :Keep the default installation path as shown in the
picture(recommended)

9 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java Application using Command Prompt

• Once the setup completes, click Close on the success screen.

10 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java Application using Command Prompt

• After installation ,You should see something like:

11 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java Application using Command Prompt

Step 2: Set the PATH Variable

• You can set the PATH in two ways — temporarily or permanently.

• Option 1: Temporary PATH (for current cmd session only)

– In Command Prompt, type: set path = C:\Program Files\Java\jdk-21\bin;%path%

– Now check:

o java -version

o javac -version

12 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java Application using Command Prompt

• Option 2: Permanent PATH (recommended)

– Right-click on “This PC” → choose Properties.

– Click Advanced system settings → Environment

Variables.

– Under System variables, scroll to find Path → click Edit.

– Click New → Paste your JDK path, for example:

C:\Program Files\Java\jdk-21\bin

– Click OK to save all windows.

13 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java Application using Command Prompt

• Add JAVA_HOME Variable (Optional)

– In the same window:

o Click New

o Variable name: JAVA_HOME

o Variable value: C:\Program Files\Java\jdk-21

14 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java Application using Command Prompt

• Then edit Path → click New → add: %JAVA_HOME%\bin

15 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java Application using Command Prompt

• Step 3: Create a Project Folder as shown in the below image and create your Java file.

16 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java Application using Command Prompt

• Step 4 : Compile and run the program:

– Compile the code : javac [Link]

– Run the code : java HelloWorldApp

17 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Eclipse IDE

• Using a text editor is the basic way of creating a Java program, but there are tools available to make it

easier to create Java programs called IDEs like Eclipse.

• Eclipse is a third-party open-source IDE that is very powerful and popular.

• It can be downloaded here: [Link]

18 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Eclipse IDE

Eclipse download page

Click Download packages

19 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Eclipse IDE

Choose an option from the list

Download this
package

20 UNIT I - Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Eclipse IDE

After download, right click and extract the eclipse file

21 UNIT I - Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Eclipse IDE

Configuring Eclipse: Select a directory to create a workspace for projects

22 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Eclipse IDE

Once the workspace is chosen, you will get the welcome page

23 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Eclipse IDE

After closing the welcome screen ,the project explorer and other options will be shown up.
Now you are ready to start working.

24 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Eclipse IDE

Start working by creating the Java Project as FirstJavaProject

25 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Eclipse IDE

Create First Java Program with file extension .java Example: [Link]

26 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Eclipse IDE

After creating the application, run the application with a run command

27 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Eclipse IDE

After execution, in the console, the output is displayed as Hello World!

28 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

First Java Program

/**

* The HelloWorldApp class implements an application that

* simply prints "Hello World!" to standard output.

*/

class HelloWorldApp {

public static void main(String[] args){

[Link]("Hello World!"); // Display the Hello World!

}
29 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Introduction to Java

Need of Coding standards

• Code conventions are important to the programmer for the following reasons

• To facilitate the copying, changing, and maintenance of the code.

• To maintain the readability of the code.

• Helps to understand the code quickly and thoroughly.

• Helps to well package the code when deploying as the product.

30 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

General coding practice

• All code should have the following attribute:

• Simplicity: Code should be easily understood and be concise.

• 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.

31 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Java source files

• Source file of java can be saved with the extension or suffixes “[Link]”.

• Java source file has the following order:

• Comments

• Package and import statements

• Class and interface declaration

32 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Indentation

• In Java, the exact construction of the indentation is unspecified.

• so, set the tabs exactly for every 8 spaces.

• The line length should not exceed 80 characters.

• When the statement is not fit in a single line, then wrap the lines based on the following principles.

• Break the lines after a comma.

Example:
public void Cart(string product_name, double cost,
int quantity, string description)

33 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Indentation

• Break the line before an operator.

• Prefer higher-level breaks to lower-level breaks.

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

indent 8 spaces instead.


34 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Introduction to Java

Indentation

Example: //8 space indentation is used to breaking the if statements


if ((condition1 && condition2)
|| (condition3 && condition4)
||!(condition5 && condition6)) {
Method();
}

• The ternary expression can be formatted as below:

Variable = Expression1 ? Expression 2 : Expression 3;


Variable = Expression1 ? Expression 2
: Expression 3;
Variable = Expression1
? Expression 2
: Expression 3;

35 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Indentation

Blank Lines:

• Blank lines improve readability.

• Two blank lines should always be used in the following circumstances:

- Between sections of a source file.

- Between class and interface definitions

• One blank line should always be used in the following circumstances:

- Between methods

- Between the local variables in a method and its first statement

- Before a block or single-line comment.

- Between logical sections inside a method.


36 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Introduction to Java

Indentation

Blank Spaces:

• Black Spaces are used to improve the reliability of the code and can be used in the following
circumstances

• A keyword followed by a parenthesis should be separated by a space.

Example:
while (false){
}

• It should not be used between a method name and its opening parenthesis. This helps to
distinguish keywords from method calls.

• This can be included after commas in an argument list.

37 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Indentation

• Except ‘.’ and unary operators all the binary operators should be separated their operands by spaces.

• Expression in the for statement should be separated using space.

38 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Comments

• Comments are the overview or description of the code.

• In Java, the comments can be implemented in four styles as follows

• 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
*/

39 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

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 */
}

40 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

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

from the statement using spaces.

• 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! */
}
}

41 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Comments

• End - Of - Line 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

statement using spaces.

• 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!
}
}

42 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

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

about the present method, its parameters, class, variables, etc..,

• 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

requires documentation in a predefined format.

• It is made up of two parts: a description and Javadoc tags.

43 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Documentation Comments

Javadoc Tag:

• Special tag embedded within a Java doc comment.

• 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

letters as shown in the below table.

• A tag must start at the beginning of a line (after any leading spaces and an optional asterisk) or it is

treated as normal text.

• By convention, tags with the same name are grouped together.


44 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Introduction to Java

Documentation Comments

Two Types of Javadoc tag :

• 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

Inline tags are denoted by curly braces

- Example: {@tag}

45 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Documentation Comments

Javadoc Tags:

• Below table describe the Javadoc tag that is used in documentation comments.

Tag Description Syntax


@author Adds the author of a class. @author name-text
Displays text in code font without interpreting the text as
{@code} {@code text}
HTML markup or nested javadoc tags.

Represents the relative path to the generated document's


{@docRoot} {@docRoot}
root directory from any generated page.
Adds a comment indicating that this API should no longer
@deprecated @deprecated deprecatedtext
be used.

Adds a Throws subheading to the generated


@exception @exception class-name description
documentation, with the classname and description text.

46 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Documentation Comments

Tag Description Syntax


Inherits a comment from the nearest inheritable class or Inherits a comment from the
{@inheritDoc}
implementable interface. immediate surperclass.
Inserts an in-line link with the visible text label that
{@link} points to the documentation for the specified package, {@link [Link]#member label}
class, or member name of a referenced class.

Identical to {@link}, except the link's label is displayed in {@linkplain [Link]#member


{@linkplain}
plain text than code font. label}

Adds a parameter with the specified parameter-name


@param followed by the specified description to the "Parameters" @param parameter-name description
section.

@return Adds a "Returns" section with the description text. @return description

47 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Documentation Comments

Tag Description Syntax


Adds a "See Also" heading with a link or text entry that
@see @see reference
points to reference.
@serial field-description | include |
@serial Used in the doc comment for a default serializable field.
exclude

Documents the data written by the writeObject( ) or


@serialData @serialData data-description
writeExternal( ) methods.

@serialField field-name field-type


@serialField Documents an ObjectStreamField component.
field-description

Adds a "Since" heading with the specified since-text to


@since @since release
the generated documentation.

@throws The @throws and @exception tags are synonyms. @throws class-name description

48 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Documentation Comments

Tag Description Syntax


When {@value} is used in the doc comment of a static
{@value} {@value [Link]#field}
field, it displays the value of that constant.
Adds a "Version" subheading with the specified version-
@version text to the generated docs when the -version option is @version version-text
used.

49 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Documentation Comments

• Format of Documentation comments.

• Each line above is indented to align with the code below the comment.

• The first line contains the begin-comment delimiter (/**).

• Write the first sentence as a short summary of the method, as Javadoc automatically

places it in the method summary table (and index).

• The inline tag can be used anywhere that a comment can be written, such as in the text

following block tags.

50 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

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 last line contains the end-comment delimiter (*/).

51 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

First Java Program using Documentation Comments

/**
* 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!
}
}

52 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

First Java Program in Detail

• Class: keyword is used to declare a class in java.

• public keyword is an access modifier which represents visibility, it means it is visible to all.

• static is a keyword, if we declare any method as static, it is known as 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.

• 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

First Java Program in Detail

• main represents startup of the program.

• String[] args is used for command line argument.

• [Link]() is used print statement.

- System is a final class defined in the [Link] package.

[Link]();

Is a Class name Is a Static variable present Is a method present in


in System Class of type PrintStream Class
PrintStream

54 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Package: Introduction

• Package: It is a mechanism to organize related classes, interfaces, and sub-packages according to


their functionality. It is like a folders in a file directory.

Java Package
Sub-Packages (lang, io, util, etc.,) interfaces

Each sub-packages have lot of related classes

Each class have lot of methods

55 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Package: Introduction

There are two types of Packages:

1. Built-in Packages: The already defined package in Java API like [Link].*, [Link].* etc. are known

as built-in packages. It is simply import based on your application needs.

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

• Example: [Link] (System class is a one of the class of lang package)

[Link]();

Is a Class Is a Static variable Is a method


name present in System present in
Class of type PrintStream Class
PrintStream

Note:

• As per Java 1.8 standard version, Java have 14 predefined packages, 150 sub packages, 7000
classes and 7 lakh methods.

57 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Compiling and Executing

• To run java application both compiler and interpreter involves.

• 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 byte code will be in a file with extension .class

• The .class file is interpreted by the JVM and morphed into machine specific code.

58 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Compiling and Executing

59 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Introduction to Java

Just-In-Time (JIT) Compiler

• 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

code of that method directly instead of interpreting it.

• 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.

60 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

61 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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.

• The Java compiler identified these words as tokens.

• These tokens are separated by the delimiters and delimiters are not part of the Java tokens.

• It is useful for compilers to detect errors.

Example: In program, we will be using many statements and expressions to perform the operation. These

statements and expressions are made up of tokens.

62 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Introduction

• Java supports 5 types of tokens as follows:

1. Keywords

2. Identifiers

3. Literals

4. Operators

5. Special symbols

63 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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.

• A keyword should always be written in lowercase as Java is a case-sensitive language.

64 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Keywords

• They are some available keywords in Java

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.

• Rules for defining Identifiers

• Allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign)
and ‘_‘ (underscore).

–Example: “blue@” is not a valid as it contain ‘@’ special character.

• Identifiers should not start with digits([0-9]).

– Example: “123blue” is a not a valid

• Java identifiers are case-sensitive.

–Example: test and Test both are different

66 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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.

• Reserved Words can’t be used as an identifier.

– Example: int while = 20; is an invalid statement as while is a reserved word.

• Some Valid Identifiers Some Invalid Identifiers

test, Test, _name, name100 int, 100name, test@123

ABC, File_100, _abc_ [Link],

67 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Naming Convention of Identifiers

• All the identifiers such as classes, interfaces, packages, methods, and fields of Java programming

language are given according to the Java naming convention.

• 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

reserve the space (‘ ’) character for special purposes.

• Because the space character is reserved, we cannot use it to represent a concept that we express in

our human language with multiple word

68 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Naming Convention: Identifiers

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

69 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Naming Convention : Variables

• 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.

• The variable name should be in lowerCamelCase.


Example:
String firstName;
int orderNumber ;
int count;
float price;
70 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens

Naming Convention : Variables

• Private class variables should have an underscore prefix.

• 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;

}

71 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Naming Convention : Constants and Methods

Constants:

• The names of variables declared class constants and should be in uppercase.

• 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;

72 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Naming Convention : Constants and Methods

Methods

• Method should be in the verb.

• Method name should be lowerCamelCase.

Example:
void calculateTax()
String getSurname()
void draw()

73 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Naming Convention : Package and Import statements

• 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];

74 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Naming Convention: Class and interface

• Class names should be nouns and must be simple and descriptive.

• Use whole words-avoid acronyms and abbreviations.

• Class name should be in UpperCamelCase.

Example:
class Customer
class CustomerAccount
class Login

75 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Naming Convention: Class and interface

• Interface tends to have a name that describes an operation that a class can do.

• Name of the interface should be UpperCamelCase.

Example:
interface Enumerable
interface CompEnumerable
interface Login

76 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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.

• Java is a strongly typed language

–All variables must be declared before its use.

• Two Types of Data types

1. Primitive data type

–byte, short, in, long, float, double, char, boolean

2. Non Primitive data type

- Classes, interfaces, arrays, strings

77 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Data Types

• byte: (1 byte):

–The byte data type is an 8-bit signed two's complement integer.

–It has a minimum value of -128 and a maximum value of 127 (inclusive).

–Useful for saving memory in large arrays.

–Default value : 0

• short: (2byte)

–The short data type is a 16-bit signed two's complement integer.

–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

78 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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

79 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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'

80 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Variables

• A symbolic name associated with a value and whose associated value may be changed.

• A variable is defined by the combination of an identifier, a type and an optional initializer.

• All variables have a scope, which defines their visibility, and a lifetime.

• There are three types of variables:

[Link] Variables

[Link] Variables (Non-Static Fields)

[Link] Variables (Static Fields)

81 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Variables

Local Variables

• Variable that's declared within the body of a method.

• Will be used only within that method.

• Other methods in the class aren't even aware that the variable exists.

• A method will often store its state in local variables.

• A local variable cannot be defined with "static" keyword.

82 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Variables

Instance Variables (Non-Static Variables)

• A variable declared inside the class but outside the body of the method, is called instance

variable.

• It is not declared as static.

• Instance variables are created when the objects are instantiated and therefore they are associated

with the objects.

83 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Variables

Class Variables (Static 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.

84 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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
}
}

85 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Literals

• A fixed value assigned to a variable

• Different types of literals are as follows:


Types Examples
Integer Literals
1. Decimal int decValue=56;
2. Hexa Decimal int hexaValue=0x10;
3. Binary int binVal=0b11010 ;
double d1 = 123.4;
Floating-Point Literals double d2 = 1.234e2;
float f1 = 123.4f;
Character Literals char chrlit=‘0108’;

String Literals String check=“Test” ;


Boolean Literals boolean result=true;
86 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens

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.

• Enables 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;

long bytes = 0b11010010_01101001_10010100_10010010;

87 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Literals

• 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

88 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Unicode

• It is Computing industry standard designed to encode characters of the world's written languages.

• Unicode System?

–Before Unicode, there were many language standards:

–ASCII (American Standard Code for Information Interchange) for the United States.

–ISO 8859-1 for Western European Language.

–KOI-8 for Russian.

–GB18030 and BIG-5 for Chinese, and so on.

89 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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.

– The range of a char is 0 to 65,536

90 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Operators

• An operator in Java is a special symbol that signifies the compiler to perform some specific

mathematical or non-mathematical operations on one or more operands.

• Value that the operator operates on is called operand.

• Java supports 8 types of operators.

91 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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.,

92 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Operators & Expressions

• 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

Arithmetic Operator +,-,%,*,/ a=b+c, a=b%d


Shift Operator <<,>>,>>> a=a>>2
Relational Operator >,>=,<,<=,==, !=,instance of a=10>5,5!=10,8==8

Bitwise Operator &,^,| a =2&3


Logical Operator &&,|| (2>5)&&(10>8)
Ternary Operator ?: a=(b>c)?1:0
Assignment Operator = ,+=, -=, *= ,/= ,%= .&= ,^= a=b a+=b a^=b
,|= <<= ,>>=,>>>

93 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Precedence and Associativity

Precedence

• Operator precedence determines the order in which the operators in an expression are evaluated.

Example: int num = 6 -3 *8;

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.

• That is either left to right or right to left.


Example: X=Y=Z; Operator has same precedence. Here, the value of Z is assigned to variable Y. Then the value
of Y is assigned of variable X because the associativity of = operator is from right to left
94 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens

Precedence and Associativity

Operators Precedence Associativity

postfix increment and


++ -- left to right
decrement

prefix increment and


++ -- + - ~ ! right to left
decrement, and unary

multiplicative */% left to right

additive +- left to right

shift << >> >>> left to right

relational < > <= >= instanceof left to right

equality == != left to right

95 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Precedence and Associativity

Operators Precedence Associativity

bitwise AND & left to right

bitwise exclusive OR ^ left to right

bitwise inclusive OR | left to right

logical AND && left to right

logical OR || left to right

ternary ?: right to left

= += -= *= /= %=
assignment right to left
&= ^= |= <<= >>= >>>=

96 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Expression Evaluation
Example 1 : 10 – 3 % 8 + 6 / 4 Example 2: 6 - ( 5 – 3 ) + 10 Example 3 : 3+4*4>5*(4+3) -1

97 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

What are Bitwise operators?

• Bitwise operators are used to perform operations at the bit level and help to manipulate data at the

bit level which we can call bit-level programming.

• Bit-level programming contains 0 and 1.

• These can be done by first converting a decimal value to its binary form. This binary form is nothing

but a sequence of bits. Bitwise operators perform operations on these bits.

98 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types

• There are 6 bitwise operators in Java language. They are

Operator Meaning
& Bitwise AND operator
| Bitwise OR operator
^ Bitwise exclusive OR operator

~ Binary One’s Complement Operator

<< Left shift operator


>> Right shift operator

99 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise Operator -Types : AND(&)

• The bitwise AND operator is denoted using a single

ampersand symbol,(&) and it needs two operands to Result=Num1 &


Num1 Num2
Num2
work on.
0 0 0
1 0 0
• It takes the binary values of both the left and right
0 1 0
operands and performs the logical AND operation over 1 1 1
Truth table for Bitwise AND operator
them on the bit level, i.e. if both the operands have 1 on

the specified position then the result will also have 1 in

the corresponding position or else there will be 0.

100 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : AND(&)

• 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.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

// Bitwise AND Operation of 12 and 25

00001100

& 00011001

____________

00001000 = 8 (In Decimal)

101 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : AND(&)

// Bitwise AND
class Main { Output: 8
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise AND between 12 and 25


result = number1 & number2;
[Link](result); // prints 8
}
}

102 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : OR(|)

• The bitwise OR operator is much similar to the bitwise

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

and 0 if they both have 0 in the corresponding position. 1 0 1


0 1 1
• This is denoted using the vertical bar or pipe symbol, 1 1 1
Truth table for Bitwise OR operator
i.e. |.

103 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : OR(|)

• 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.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25

00001100

| 00011001

____________

00011101 = 29 (In Decimal)

104 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : OR(|)

// Bitwise OR
Output: 29
class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise OR between 12 and 25


result = number1 | number2;
[Link](result); // prints 29
}
}
105 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens

Bitwise operator - Types : XOR(^)

• This is similar to the other two, but the only difference is

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

then the result will have 1 in the corresponding position, 1 0 1


0 1 1
and 0 if they have the same bits such as both 0s or both 1 1 0
Truth table for Bitwise XOR operator
1s.

106 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : XOR(^)

• 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.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

// Bitwise XOR Operation of 12 and 25

00001100

^ 00011001

____________

00010101 = 21 (In Decimal)

107 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : XOR(^)

// Bitwise XOR
Output: 21
class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise XOR between 12 and 25


result = number1 ^ number2;
[Link](result); // prints 21
}
}
108 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens

Bitwise operator - Types : Complement (~)

• We have seen three bitwise so far, if you have noticed, all


of them were [binary i.e. they all require two operands to
perform their functions. Result=Num1 ^
Num1
Num2
• But complement operator (~), is the only bitwise operator 0 1
that requires only one operand. 1 0

• The bitwise complement operator takes a single value Truth table for Bitwise Complement
operator
and returns the one’s complement of the value.

• The one’s complement of a number is obtained by


changing all the 0’s in its binary value to 1’s and by
changing the 1’s to 0’s.

109 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : Complement (~)

• 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.

35 = 00100011 (In Binary)

// using bitwise complement operator

~ 00100011

__________

11011100

110 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : Complement (~)

• 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.

• To understand this we first need to calculate the binary output of -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

111 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : Complement (~)

// compute the 2's complement of 36

36 = 00100100 (In Binary)

1's complement = 11011011

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.

112 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : Complement (~)

// Bitwise Complement
class Main { Output: -36

public static void main(String[] args) {


int number = 35, result;
// bitwise complement of 35
result = ~number;
[Link](result); // prints -36
}
}

113 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : Shift Left (<<)

• The left shift operator (<<) is a bitwise operator that shifts the bits of a binary number to the left by

a specified number of positions.

• In other words, it multiplies the number by 2 raised to the power of the shift count.

• Here's how the left shift operation works:

– Each bit in the binary representation of the number is shifted to the left by the specified number of

positions.

– The vacant positions on the right are filled with zeros.

– The leftmost bits that are shifted out (if any) are discarded.

114 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator : Shift Left (<<)


Steps for Left Shift Operator
8 Bits - Binary Representation
Step 1: Represent the Binary
Number for the given decimal.

14 0 0 0 0 1 1 1 0 Step 2: Decide the number of


positions to shift the binary
number to the left.
Shift
Vacated bit leftShift
(1 position)
left Shift
(1 position)Shift
left (1 left (1Shift
position) position)
Shift
left (1left
Shift (1 position)
position)
left (1 position)
Step 3: moves each bit in the
14 Left shift by 1 bit
filled bit binary representation one position
to the left.

Step 4: Add a 0 to the rightmost


14<<1 0 0 0 0 1 1 1 00 position to fill the empty space.

Step 5: Calculate and display the


decimal equivalent of the shifted
After the left shift the binary representation is: binary number.

Decimal
14<<1 0 0 0 1 1 1 0 0 = 28 Representation -
00011100

115 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : Shift Left (<<)

// Left shift Operators


Output: 8
class Main {
public static void main(String[] args) {
int number = 2;
// 2 bit left shift operation
int result = number << 2;
[Link](result); // prints 8
}
}

116 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Bitwise operator - Types : Shift Right (>>)

• 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.

• Here's how the right shift operation works:

– 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.

117 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens
Steps for Right Shift Operator
Bitwise operator : Shift Right (>>)
Step 1: Represent the Binary
8 Bits - Binary Representation
Number (8 Bit) for the given
decimal.
14 0 0 0 0 1 1 1 0 Step 2: Decide the number of
positions to shift the binary
Filled Shift Right (1
14 Right shift by Shiftbit Shift
Right Right (1 Position)
(1 Position) Shift Right Shift
(1 Position)
RightShift
(1 Position)
Right (1 Position)
Shift Right (1 Position) number to the Right
Vacated bit Position)
1 bit
Step 3: moves each bit in the
binary representation one position

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

Bitwise operator - Types : Shift Right (>>)

// Right shift Operators Output:


Right shift of 12 by 2 is 3
public class Main {
public static void main(String[] args) {
int num = 12;
int result = num >> 2;
[Link]("Right shift of %d by 2 is %d\n", num, result);
}
}

• 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

types. It is also known as implicit conversion.

• Automatic type conversion will take place if the following two conditions are met:

–The two types are compatible.

–The destination type is larger than the source type

120 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Type Conversions

• Widening primitive conversions:

byte → short, int, long, float, double

short → int, long, float, double

char → int, long, float, double

int → long, float, double

long → float, double

float → double

• Generally safe because they tend to go from a small data type to a larger one

• No automatic conversion is supported from numeric type to char or boolean

121 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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.

• Narrowing primitive conversions:


byte → char
short → byte, char
char → byte, short
int → byte, short, char
long → byte, short, char, int
float → byte, short, char, int, long
double→ byte, short, char, int, long, float
123 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Java Tokens

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.

• Some conditions for type promotion are:

[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.

125 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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);
}
}

127 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

Special Symbols

• Special symbols in Java are a few characters which have special meaning known to Java compiler

and cannot be used for any other purpose.

• In the below table we have listed down the special symbols supported in Java along with their

description.

128 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens

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

129 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Read User Input

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

130 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Read User Input

Introduction

• There are three different ways to read input from the user:

1. Buffered Reader Class

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.

• Constructing a Scanner object to read console input:


Scanner read = new Scanner([Link]);

131 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Read User Input

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.

byte nextByte() It reads the byte value from the user.

double nextDouble() It accepts the input in double datatype from the user.

float nextFloat() It takes the float value from the user.

int nextInt() It reads the integer value from the user.

132 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Read User Input

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.

String next() It reads the character input from the user.

Note:

• Scanner class no specific method to read character type.

• 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 */

import java. [Link]; //import Scanner class from util package

public class ReadSomeInput {

public static void main(String[] args) {

Scanner console = new Scanner([Link]);


[Link]("Enter your Name : ");
String name = [Link]();
[Link](“Hi, ” +name+“ . Welcome to the Training Program ”);
[Link]();

}}
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]();

135 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Read User Input

Example: #2

if(name == "Admin" && password == "admin@123") {


[Link]("You are Successfully Logged in");
}
else {
Input/Output 1:
[Link]("User Name or Password is Wrong");
Enter User Name : Admin
}
Enter Password : admin@123
[Link](); You are Successfully Logged in
} Input/Output2:
} Enter User Name : Admin
Enter Password : admin
User Name or Password is Wrong

136 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Read User Input

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]();

137 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Read User Input

Example: #3

[Link]("Enter Movie Name : ");


String moviename = [Link]();
[Link]("Enter Movie Description : ");
String moviedescription = [Link]();
[Link]("Enter Movie Language : ");
String movielanguage = console.n
String moviegenre = [Link]();
[Link]("Enter Movie release date (dd/mm/yyyy) : ");
String date = [Link]();
[Link]("Enter Movie Seat Cost : ");

138 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Read User Input

Example: #3

float movieseatcost = [Link]();


[Link]("ENTERED MOVIE DETAILS
[Link]("ENTERED MOVIE DETAILS ARE");
[Link]("Movie ID : "+movieid);
[Link]("Movie Name : "+moviename);
[Link]("Movie Description : "+moviedescription);
[Link]("Movie Language : "+movielanguage);
[Link]("Movie Genre : "+moviegenre);
[Link]("Movie Date : "+moviedate);
[Link]("Movie Seat Cost : "+movieseatcost);
}
}
139 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Read User Input

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

140 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

1) Which of the following are primitive data types?

a) int b) float

c) double d) boolean

e) All the above

e)All the Above

141 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

2) A local variable stores temporary state; it is declared inside a

a) Class b) Method

c) Block d) Object

b) & c)

142 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

3) A _____ is a value that should not be altered by the


program during normal execution.

a) Variable b) int

c)Identifiers d) Constant

d) Constant

143 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

4) Which of these can not be used for a variable name in Java?

a) Identifier b) Keyword

c) Both a and b d) None of the above

b) Keyword

144 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

5) Which conversion also called Automatic Type Conversion?

a) Widening b) Narrowing

c) Both A and B d) All the above

a) Widening

145 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

6) Long Literals in java must be appended by which of these?

a) L b) l

c) D d) 0x

a) & b)

146 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

7) Which variables are created when an object is created and


destroyed when the object is destroyed?

a) Local variables b) Instance variables

c) Class Variables d) Static variables

b) Instance variables

147 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

8) Which of the following are not Java keyword ?

a) double b) switch

c) instanceof d) then

d) then

148 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

9) Which of these is not a bitwise operator?

a) & b) |

c) ^ d) <=

d) <=

149 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

10) Which operator is used to invert all the digits in binary


representation of a number?

a) ~ b) <<

c) ^ d) >>>

a) ~

150 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

11) It is time to buy a new phone when at least one of the


following situations occurs:

• the phone breaks

• the phone is at least 3 years old

int phoneAge; // in years


boolean isBroken;
…….. //code initializes variables
boolean needPhone =______________

(isBroken == true) || (phoneAge >= 3);

151 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

12) Evaluate the following expression:

(17 < 4*3+5) || (8*2 == 4*4) && !(3+3 == 6)

a) true b) false

b)false

152 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

13) Assume num1=10. Which of the following is not a valid


statement?

a) num1>>2 b) num1<<<2

c) num1%=2; d) num1<<2;

b) num1<<<2

153 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

14) In Java, after executing the following code what are the
values of x, y, and z?

int x,y=10; z=12;

x = y++ + z++;

a) x=22, y=10, z=12 b) x=24, y=10, z=12

c) x=24, y=11, z=13 d) x=22, y=11, z=13

d) x=22, y=11, z=13

154 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Java Tokens and Read User Input

Quiz

15) Which Scanner class method is used to read integer value


from the user?

a)next() b) nextInt()

c) nextInteger() d) readInt()

b) nextInt()

155 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control flow statements

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

156 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

Sequential statement Branching Statement Looping Statement

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.

• Execute a list of statements in order.

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]();
}
}

158 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Introduction

• Branching (Conditional) /Decision Making – To make decisions based on a given condition. If


the condition evaluates to True, a set of statements is executed, otherwise another set
of statements is executed. In Java, we have five types of decision making statements:

• if

• if…else

• if-else-if

• nested if

• switch

159 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

of the if statement is skipped.

if is a Java The condition must be a boolean [Link]


must evaluate to either true or false.
reserved word
• Syntax

if ( condition ){
statement(s);
}

If the condition is true, the statement(s) is/are executed.

If it is false, the statement(s) is/are skipped.


160 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

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);
}
}
}

161 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

162 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Decision-Making : simple if

if(seatAvailable){ //Check the availability of seat


[Link]("Your have booked the seat number : "+SeatNumber);
}
[Link]();
}
}

Output:
Enter the Seat Number : A32
Your have booked the seat number : A32

163 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Decision-Making : simple if - else

• if –else: If the condition is true, the body of the if statement is executed. If it is false, the body of

the false statement is executed.

• Syntax

if ( condition ){
if Body;
}
else{
else Body;
}

164 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Decision-Making : simple if - else

/** * The IfEsleControlStructure class implements an application that Illustrate Output:


the if ..else decision Making control statement */
class IfElseControlStructure{ The bicycle speed got reduced!
public static void main(String[] args){
boolean isMoving=true;
int currentSpeed=10;
if(isMoving){
currentSpeed--;
[Link]("The bicycle speed got reduced!");
}
else{
[Link](“The bicycle has already stopped!”);
}
}
}
165 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

Decision-Making : simple if - else

/** * 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 */

public class SimpleIfElse {


public static void main(String[] args){
boolean seatAvailable = false; //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
if(seatAvailable){ //Check the availability of seat
[Link]("Your have booked the seat number : "+SeatNumber);
}

166 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Decision-Making : simple if - else

else { //if seat not available then display


[Link]("Seat Numer "+SeatNumber+" is already booked");
}
[Link]();
}
}

Output:
Enter the Seat Number : A22
Seat Numer A22 is already booked

167 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Decision-Making : simple if – else – if

• 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
}

168 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Decision-Making : simple if – else – if

/** 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!”);
}
}

169 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Decision-Making : simple if – else – if


/**
* The IfElseIf class implements an application that display the cost of the specific seat category in movie ticket
booking using if ..elseif decision Making control statement for fixing the cost based on Movie Type */
import [Link];
public class IfElseIf {
public static void main(String[] args){
String seattype;
[Link](“Type of seats Available\nREGULAR\nPREMIUM\nEXECUTIVE\nVIP\ choose any one of the
option : ");
Scanner input = new Scanner([Link]); //Scanner class object creation
seattype = [Link](); // get Seat Number from User
if ([Link]("REGULAR")) { //Display detail for REGULAR type
[Link]("You have selected Executive Seat and cost is Rs.80");
}
170 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

Decision-Making : simple if – else – if

else if ([Link]("PREMIUM")) { //Display detail for PREMIUM type


[Link]("You have selected Premium Seat and cost is Rs.100");
}
else if ([Link]("EXECUTIVE")) { //Display detail for EXECUTIVE type
[Link]("You have selected Regular Seat and cost is Rs.120");
} else if ([Link]("VIP")) { //Display detail for VIP type
[Link]("You have selected VIP Seat and cost is Rs.150");
} else {
[Link]("You have not selected any type");
}
[Link]();
}
}
171 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

Decision-Making : simple if – else – if

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

172 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

/* * The NestedIfControlStructure class implements an application that Output:


* Illustrate the nestedif decision Making control statement */
class NestedIFControlStructure{
Not eligible because
public static void main(String[] args){ you are underage
int age=15;
int weight=50;
if(age>18) {
if(weight>50)
[Link](“You are eligible to denote blood”);
else
[Link](“Not eligible because you are under weight”);
} else
[Link](“Not eligible because you are under age”);
}
}

174 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

if ([Link](username) && [Link](password)) { //validate the user login


[Link]("You have logged in and you can book a ticket now");
[Link]("Enter the Seat Number : ");
seatNumber = [Link](); // get the seat number from the user
if (seatAvailable) { // check for seat availability status
[Link]("Seat Number "+seatNumber+" you have chosen is available");
} else{
[Link]("Your expected Seat Number "+seatNumber+" is not available");
}
} else{
[Link]("You have to login for booking the ticket");
} [Link]();
}}
176 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

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

177 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Decision-Making : switch - case

• 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

Decision-Making : switch - case

Note:

• In switch, Case value must be in expression type only and case values must be unique.

• Expression must be of byte, short, int, long, enums and string.

• Each case break statement is optional. It helps terminate from switch expression. If a break

statement is not found, it executes the next case.

• The case value can have a default label which is optional.

179 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Decision-Making : switch - case

/** The SwitchControlStructure class implements an application that


* Illustrate switch decision Making control statement */
class SwitchControlStructure{
public static void main(String[] args){
int letter='A';
switch(letter){
case 'a':
[Link]("Lowercase Letter");
break;
case 'A':
[Link]("Uppercase Letter");
break;

180 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Decision-Making : switch - case

default:
[Link]("Invalid Letter");
break;
}
}

Output:
Uppercase Letter

181 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Decision-Making : switch - case

/** 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

Decision-Making : switch - case

[Link]("Your searching choice is Movies by Language");


break;
case 3:
[Link]("Your searching choice Movies by Release Date");
break;
case 4:
[Link]("Your searching choice Movies by Genre");
break;
default:
[Link]("Your choice is wrong. Please enter the correct choice ");
}
[Link]();
}
}
183 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

Decision-Making : switch - case

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

184 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Looping - Introduction

• Loop/ iterative statements are used for executing a block of statements repeatedly until a particular

condition is satisfied.

• In Java, we have following loop statements:

• while

• do…while

• for

• for…each

• Nested loops (for, while, do…while)


185 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

Looping - Introduction

Four Looping Elements

• Initialization: To set initial value to the iteration variable at the very start of the loop.

• Condition: Test condition is evaluate and give boolean ( 0 or 1) value as a result.

• 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

program goes back to the test condition.

186 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Looping - while

• while: It is used to rrepeat a specific block of code. It is preferable while we do not know the exact

number of iterations of loop beforehand.

• Syntax

while (condition){
statement(s)
}

187 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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++;
}
}
}

188 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

189 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

191 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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);

192 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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)
}
}

193 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

194 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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");
}
}

195 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

196 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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)
}

Initialization : Initializes the loop; it's executed once.

Condition : Evaluates till the condition becomes false.

Updation : Increment / Decrement the value. Executed


(every time) after the code block is executed.
197 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

Looping - for

/**

* The ForStructure class implements an application that

* Illustrate ForLooping control statement

*/

class ForStructure{

public static void main(String[] args) {

for(int count = 1; count<10; count++) {

[Link]("Count is: " + count);

198 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

199 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Looping - for

/**

* The ShowSeat class implements an application that that checks the seat availability status for

* movie ticket booking using For Looping control statement

*/
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

201 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Looping - for - each

• for-each: It’s commonly used to iterate over an array or a Collections class. It is also called

enhanced for loop.

• 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

202 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Looping - for - each

/**
* 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

203 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Looping - for - each

for (int indexValue : marks){


if (indexValue > maxSoFar){
maxSoFar = indexValue;
}
}
[Link]("The highest score is " +maxSoFar);
}
}

Output:
The highest score is 132

204 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Looping - for - each

/**
* 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

Looping - for - each

[Link](Genre + " Movies are"); Output:


for (String M : MovieGenre ) { Enter the Genre to be searched :
ACTION
if([Link](Genre)) {
ACTION Movies are
[Link](MovieName[counter]);
} AAA
counter++; DDD
}
[Link]();
}
}

206 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

loop executes completely.

• 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);
}

207 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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++;
}

208 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Nested Loop

[Link](“ “);
outerLoop++;
innerLoop=1;
}
}
}

Output:
*****
*****
*****
*****
*****

209 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

[Link]("Seats Filled in Screen "+(screenCount+1)); Output:


screenCount++; Screen 1 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 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
211 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

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++;

} while (innerLabel <= 3);


outerLabel++;
} while (outerLabel <= 3);
}
}

212 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

[Link]("Seats Filled in Screen "+(screenCount+1)); Output:


screenCount++; Screen 1 Availability details
} while(screenCount < TotalScreenCount); 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
214 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

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

215 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Nested Loop

for (int i = 1; i <= rows; ++i){ Output:


// inner loop to print the numbers 1
for (int j = 1; j <= i; ++j) { 12
[Link](j + " "); 123
}
1234
[Link]("");
12345
}
}
}

216 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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{

public static void main (String[] args){

int MaxSeatCount = 5, TotalScreenCount = 2, seatCount = 0, screenCount = 0;

[Link]("Screen "+(screenCount+1)+" Availability details");

for(screenCount=0;screenCount < TotalScreenCount;screenCount++){

for(seatCount=0;seatCount < MaxSeatCount;seatCount++){

[Link]("Current Seat Availability "+(MaxSeatCount-seatCount));


217 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

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

without any condition.

• In Java, we have the following unconditional statements:

• break

• labelled break

• continue

• labelled continue

219 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

at specified condition. In case of inner loop, it breaks only inner loop.

• Break statement use all types of loops such as for loop, while loop and do-while loop.

• Syntax
break;

220 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Branching - Unconditional

/** Output:

* The BreakApp class implements an application that Count is: 1


* illustrate Break branching statement Count is: 2
*/ Count is: 3
class BreakApp{
Count is: 4
public static void main (String[] args){
for(int count = 1;count<10;count++) {
if(count ==5)
break; //exit from the current loop
[Link]("Count is: " + count);
}
}

221 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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) {

222 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Branching - Unconditional

[Link]("All PREMIUM Seats Booked ");


[Link]("All VIP Seats 1 to 5 are Reserved ");
break; //exit from the current loop

else {
[Link](“PREMIUM Seat Availability : "+(premiumSeat - seatBooked));
}
}
}
}

223 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

224 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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.

In case of an inner loop, it continues the inner loop only.

• Continue statement use all types of loops such as for loop, while loop and do-while loop.

• Syntax:
continue;

225 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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);
}
}

226 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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;
}

227 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Branching - Unconditional

if(seatBooked < vipSeat + premiumSeat) { Output:


All VIP Seats 1 to 5 are Reserved
[Link](“PREMIUM Seat No : "+(seatBooked+1));
All VIP Seats 1 to 5 are Reserved
} All VIP Seats 1 to 5 are Reserved
All VIP Seats 1 to 5 are Reserved
if(seatBooked < (vipSeat + premiumSeat + executiveSeat)) {
All VIP Seats 1 to 5 are Reserved
[Link]("EXECUTIVE Seat No : "+(seatBooked+1)); PREMIUM Seat No : 6
PREMIUM Seat No : 7
}
PREMIUM Seat No : 8
} PREMIUM Seat No : 9
PREMIUM Seat No : 10
}
Executive Seat No : 11
} Executive Seat No : 12
Executive Seat No : 13
Executive Seat No : 14
Executive Seat No : 15

228 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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.

Loop without Label Loop with Label

229 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 */
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");

231 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Branching - Unconditional

break Start;
}
else
[Link]("Seats No Booked : "+(seatCount+1));
seatCount++;
}
[Link]("All Seats Filled in Screen "+(screenCount+1));
}
}
}

232 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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){

[Link]("Screen "+(screenCount)+" Ticket Booking detail");


seatCount=0;
SkipSeat:
while(seatCount < MaxSeatCount){
seatCount++;
235 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0
Control Flow Statements

Branching - Unconditional

if((seatCount == 2 || seatCount == 3) && screenCount == 1) {


[Link]("Seat No "+seatCount+" is Reserved");
continue SkipSeat;
}
else
[Link]("Seats No Booked : "+(seatCount));

}
[Link]("All Seats Filled in Screen "+(screenCount+1));
screenCount++;
}
}
}

236 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

237 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Quiz

1. What do you call a statement that executes a certain


statement(s) ,if the condition is true, and executes a
different statement(s) if the condition is false?

a) if statement b) if else statement

c) if else if statement d) None of the Above

b) if else statement

238 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Quiz

2. From the given if-else statement, what will be displayed if the


value of num is 6?

if (num>0)
[Link](“Positive Number\n”);
else
[Link](“Negative Number\n”);
[Link](“The number is %d”,num);

a) Positive Number b) Negative Number

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

3. In switch case statement, what will be executed if there is no


case matched?

a) case b) break

c) default d) All the above

c) default

240 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Quiz

4. What is a java keyword used in switch statements that causes


immediate exit or that terminates the switch statement?

a) The case keyword b) The switch keyword

c) The default keyword d) The break keyword

d) The break keyword

241 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Quiz

5. Which of the following loops will execute the statements at


least once, even though the condition is false initially?

a) while b) do…while

c) for d) All the options

b) do…while

242 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Quiz

6. What value is stored in index at the end of this loop?

for(int index =1;index<=10;index++)

a) 1 b) 9

c) 10 d) 11

b) 11

243 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

244 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

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

245 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


Control Flow Statements

Quiz

9. What is the output after the following code has been executed?

class FlowControl1 {

public static void main(String[] args){

int value1= 10, value2 = 20;

if (value1 < value2 ){

if (value2 > value2 )

[Link](“Hello Friend");

else

[Link](“ Happy Day!");

}
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;
}
}
}

247 Unit I_Introduction to Java Programming | © SmartCliff | Internal | Version 1.0


THANK YOU

You might also like