0% found this document useful (0 votes)
9 views39 pages

MCA_Java_Programming_01_PdfToWord_(Recovered)

This document provides an introduction to Java programming, covering its fundamentals, features, and key components such as JDK, JVM, and JRE. It explains the basics of Java, including its object-oriented programming attributes, data types, operators, and control statements. The document also outlines the process of creating, compiling, and running Java programs, along with the differences between JDK, JVM, and JRE.

Uploaded by

shitalshalini88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
9 views39 pages

MCA_Java_Programming_01_PdfToWord_(Recovered)

This document provides an introduction to Java programming, covering its fundamentals, features, and key components such as JDK, JVM, and JRE. It explains the basics of Java, including its object-oriented programming attributes, data types, operators, and control statements. The document also outlines the process of creating, compiling, and running Java programs, along with the differences between JDK, JVM, and JRE.

Uploaded by

shitalshalini88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 39

UNIT

01 Introduction to Java Programming

Names of Sub-Units

Java Programming Fundamentals: Basics of Java, The Key Attributes of Object-Oriented Programming,
The Java Development Kit, A First Simple Program, Java Magic: Byte Code, Difference between JDK,
JVM, and JRE
Data Types and Operators: Java’s Primitive Types, Literals, Variables, Type Conversion and Casting,
Operators, Shorthand Assignments
Program Control Statements: Input characters from the Keyword, if statement, Nested ifs, if-else-if
Ladder, Switch Statement, Nested switch statements, For Loop, Enhanced For Loop, While Loop, do-
while Loop, Use break, Use continue, Nested Loops

Overview
In this unit, you learn about the features of Java programming language. The unit introduces you to
Java platform and explains JVM, Java Development Kit (JDK), Java Runtime Environment (JRE), and
Java Application Programming Interfaces (APIs). It also discusses how to create, compile, and run a
simple Java program. Next, you learn about the data types and operators in Java. Finally, you learn
about the control structure, which is divided into three categories: conditional statements, iteration
statements, and jump statements.
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

Learning Objectives

In this unit, you will learn to:


 Define basics of Java
 Explain the difference between JDK, JVM, and JRE
 Discuss data types in Java
 Use variables and operators in Java
 Explain different types of program control statements

Learning Outcomes

At the end of this unit, you would:


 Explain the basics of Java
 Describe the role of byte codes in Java, JVM, and JRE
 Create and execute simple Java programs
 Explain the role of data types, variables and operators in Java
 Create Java programs using different control statements

Pre-Unit Preparatory Material

 https://www.youtube.com/watch?v=avT5E9ZMCpw

1.1 INTRODUCTION
Java is a programming language, which inherits its object-oriented features from C++. It was created
by James Gosling, a software developer at Sun Microsystems, in 1991. It was first called Oak, which
was later renamed as Java in 1995, when it was first released for public use. The driving inspiration
behind Java was to create something that could be used on all computers. Java has been popularized
through the Internet where a huge and increasing number of corporations are adopting it internally
because it can be used on all computers irrespective of the operating system. Another advantage of a
Java program is that it consumes less memory, as compared to other programming languages, such as
Microsoft Visual C++ . Let’s learn more about Java programming language.

1.2 BASICS OF JAVA


Java is a simple, robust, platform-independent, and portable programming language. It is designed to
meet the real-world requirements with its following features:
 Simple: Java is simple to learn and use. In Java, it is easy to write and debug programs because Java
does not use pointers. Moreover, it provides bug free system because to strong memory management
and also has automatic memory allocation and de-allocation system.

2
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

 Portable: Allows Java programs to execute on machines with different hardware configurations. In
today’s distributed world of the Internet, an application developed with the help of a programming
language might be accessed on various computers having different kinds of operating systems.
However, it is not guaranteed that the developed application is portable, i.e., the application runs
successfully on all operating systems. Therefore, to overcome this portability issue, Java introduces
a concept known as bytecode.
Bytecode is a set of instructions generated by Java compiler on compiling a Java program. In other
modern programming languages, a program is compiled in an executable code; however, in Java,
a program is compiled in an intermediate code called bytecode. This bytecode then gets executed
through Java runtime system, which is known as JVM. Now, only the JVM, which is considered as
the interpreter of bytecode, needs to be implemented on the system where the Java program is to be
executed. In this way, Java has solved the problem of portability.
 Multithreading: Allows you to write interactive programs wherein multiple tasks can be performed
simultaneously, thus making it a robust programming language. Java is a programming language
designed for the distributed environment of the Internet, wherein the concept of multithreading is
important to be implemented.
 Memory management: Relieves a Java programmer from explicitly providing code to deallocate and
allocate memory for the objects used in the program. In Java, all memory management processes
are handled automatically. Whenever a program is created in any language, you allocate some
memory to the objects used in the program and deallocate (free) that allocated memory when the
objects are no longer in use. However, in Java, you do not need to worry about freeing the memory
because it provides automatic garbage collection, which means memory allocated to objects is freed
implicitly by Java runtime system when it is not in use. For example, you have created an array that
can store 100 elements, which means you have reserved space for 100 elements. When the array
completes its functioning and is no longer in use, Java frees the memory allocated to the array so
that this space can be used by other Java objects. In other programming languages such as C++,
you have to write the code to deallocate (free) the memory. It seems a very tedious process as a
programmer needs to remember objects for which the memory is to be deallocated. Sometimes,
programmers deallocate the memory of the objects that are currently in use and this can harm the
process. Therefore, memory management is a tedious task in other languages, such as C++, but not
in Java because the memory management is automatic in it.
 Security: Represents the reliability of the Java programs. Java is a secure language as programs
created in it are confined to the JRE, i.e. they can only access that part of your computer’s hard disk,
which are required for their execution. Java programs are not allowed to access the data outside
JRE; therefore, downloading Java application through the Internet would not harm your computer
as compared to the applications created in other programming languages.
 Platform-Independent: It is one of the most important features of Java as it is the first programming
language that is not bound to any specific operating system. In other words, Java programs can be
executed anywhere on any system. Before the evolution of Java, no other programming language
was platform-independent, and it can therefore be said that Java is a revolutionary technology.
Apart from cross-platform in source form, Java is also platform-independent in complied binary
form.
A Java program does not execute natively on the host machine; instead, a Java interpreter reads
the bytecode and executes the corresponding native machine instructions. The Java interpreter is a
special naive program that reads the bytecode, an intermediate form after compilation. Therefore,
in order to port a Java program to a new platform, you need the interpreter and some of the library

3
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

routines. Moreover, the Java compiler is also written in Java, and the bytecodes are precisely defined,
which remain the same on all platforms.
 Distributed: Java is a distributed language as it can be used to create applications for communicating
over the network. Java can communicate over the network because it supports TCP/IP (Transmission
Control Protocol/Internet Protocol). The TCP/IP protocol is a set of network communication protocols.
 Dynamic: During the runtime of a Java program, the relevant information that is used to verify and
resolve access to objects is required. This concept of providing runtime information is referred to as
dynamically linking the code. This feature of Java adds strength to the applet environment, in which
small fragments of bytecode are dynamically updated on a running system.

1.3 THE KEY ATTRIBUTES OF OBJECT-ORIENTED PROGRAMMING


Object-Oriented Programming (OOP) is a programming technique where you specify various objects
and define the interaction among them to implement program logic. Classes and objects are the two
main elements of OOP. Objects in OOP are based on real-life objects, such as a car. Similar to the real-
life objects that have specific properties and behaviour, objects in OOP encompass specific properties
and behaviours, which make them unique. For example, the colour of a car represents a property
and the speed of the car represents its behavior. The properties and behaviours of objects in OOP are
represented through variables and methods, which are defined in a class. In Java, OOP is implemented
through following attributes:
 Encapsulation: A protective mechanism by which members of a class (methods and variables) are
prevented from being accessed by members of other classes. You can think of a class as an example
of encapsulation because a class binds its variables and methods and hides their complexity from
other classes.
 Abstraction: Abstraction is the mechanism by which you hide data that is not required by a user.
The advantage of abstraction is that the user can work only with the needed data and is not required
to view the unwanted data.
 Inheritance: The feature by which one class acquires the characteristics of an existing class is
known as inheritance. In Java, a class that is inherited is called a superclass and the class that
inherits the superclass is called a subclass. For example, the BallPointPen class is a subclass of the
Pen class. In terms of OOP, this means that BallPointPen is a subclass derived from its superclass
Pen. The principle behind inheritance is that each derived class acquires all the characteristics of its
superclass, thereby ensuring reusability of the code.

1.4 THE JAVA DEVELOPMENT KIT


A software development environment comprises numerous development tools, classes, and methods.
The development tools for Java are provided as a part of the system known as Java Development Kit
(JDK).
Java developers can use JDK on Windows, macOS, Solaris, and Linux. JDK helps them to code and run
Java programs. It is possible to install more than one JDK version on the same computer.
JDK provides a collection of the Java tools, which are used while developing and running Java programs.
The kit comprises the following development tools:
 java: Serves as a Java interpreter used to run Java applets and applications by reading and
interpreting bytecode files
 javac: Serves as a Java compiler used to translate Java source code into bytecode files

4
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

 javacdoc: Creates HyperText Markup Language (HTML) documentation for Java source code files
 javap: Serves as a Java disassemble used to convert bytecode files into a Java program description
 jdb: Serves as a Java debugger used to find errors in Java programs
 appletviewer: Facilitates to run Java applets
 jar: Serves as an archive used to package related class libraries into a single executable JAR file and
also helps to manage the JAR files
 javah: Serves as the C header and stub generator used to write native methods

Note: Sun introduced JDK originally, which is now an Oracle product.

1.4.1 Java Magic: Bytecode


In all programming languages, a compiler translates the source code into machine code for a specific
computer. In Java, a compiler translates the Java source code into an intermediate code known as
bytecode for a virtual machine, known as JVM. Bytecode is the machine language for JVM and is not
machine-specific. Instead, the machine-specific code is generated by the Java interpreter, which serves
as a mediator between virtual machine and real machine. Figure 1 shows the process of compilation
and conversion of bytecode into machine code:

Java Compiler Java Interpreter Real Machine


Java Program Bytecode
(javac) (java) (Machine Code)

Figure 1: Displaying the Process of Compilation and Execution in Java


In order to run a Java program on a different computer, you need a Java interpreter for Java bytecode.
Although Java bytecode interpreter is required depending upon the type of operating system in use,
once a computer has an interpreter, it can run a Java bytecode. In other words, the most important
feature of Java is that the same compiled program can run on any operating system, as shown in
Figure 2:

Java Program

Compiler

Java bytecode

Java Interpreter for Java Interpreter for Java Interpreter for


MacOS Wi ndows Linux

Figure 2: Displaying the Process of Running a Program on Any Operating System

5
JGI JAINDEEMED-TO-BE UNIVERSIT Y Java Programming

1.4.2 Java API


It is a collection of classes, interfaces, and methods provided in the form of Java packages. In other words,
it is a large collection of already created classes and interfaces, which provide many useful capabilities,
such as Graphical User Interface (GUI), date, time, and calendar capabilities. The categorization of Java
API in the form of Java packages is as follows:
 Application Programming Packages
 java.lang: Provides classes that are fundamental to the design of the Java programming
language
 java.util: Provides legacy collection classes, event model, collection framework, date and time
capabilities, internationalization, and other utility classes, such as string tokenizer
 java.io: Provides classes for system input and output through data streams, serialization, and
the file system
 Applet and Network Programming Packages
 java.awt: Provides classes for creating user interface and painting graphics and images
 java.applet: Provides classes that are necessary for creating an applet and those that are used
to communicate with its applet context
 java.net: Provides classes that are used for implementing networking in Java programs

1.4.3 Java Programs


A Java programmer can create either a Java application or a Java applet depending upon the
requirement. In Java, you create the following types of program:
 Applications
 Applets

We’ll use the term program in this book to refer to both applets and applications. Now, let’s discuss each
of them in detail.

Applications
A Java application is a program that is created by using Java programming language. Java applications
are console-based, Character User Interface (CUI)-based, and GUI-based standalone applications. Once
you become used to creating applications, you will find that creating an application by using Java is
also as simple as creating an application with any other programming language. In order to execute a
Java application, you need to perform the following steps:
 Compile the Java source code by using javac compiler to translate the source code into bytecode
 Execute the bytecode by using the Java interpreter

Apart from applications, you can also create applets in Java.

Applets
An applet is a program written in the Java programming language that can be included in an HTML
page in the same way as an image is included. An applet can be used in both static and dynamic web

6
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

pages to either display content or share information through the pages. You need to import the java.
applet package that provides classes to either create an applet or allow an applet to communicate with
its applet context.
The applet context is an application that is responsible for loading and running applets. For example,
the applet context could be a web browser or an applet development environment. In other words, an
applet is a Java application designed to be transmitted over the Internet and is executed by a Java-
compatible web browser. After understanding the types of Java program, let’s create a simple Java
program. But to do this, you need to create a source code file by using a text editor first. After creating
the Java program, you need to compile it by using the Java compiler javac and execute by using the
Java interpreter java. The compiler generates a .class file by translating the source code into bytecode,
which is then executed by the Java interpreter.

1.5 DIFFERENCE BETWEEN JDK, JVM, AND JRE


JDK is a software development kit whereas Java Runtime Environment (JRE) is a software bundle that
allows Java program to run, whereas Java Virtual Machine (JVM) is an environment for executing
bytecode. JDK is platform dependent, JRE is also platform dependent, but JVM is platform independent.
JDK contains tools for developing, debugging, etc. JRE contains class libraries and other supporting
files, whereas software development tools are not included in JVM. JDK comes with the installer, on the
other hand, JRE only contains the environment to execute source code whereas JVM bundled in both
software JDK and JRE. Figure 3 depicts the role of JDK, JRE and JVM:

Set of libraries
e.g. rt.jar etc.
Development
JVM tools e.g .
javac, java etc
Other files

JRE

JDK

Figure 3: Role of JDK, JRE, and JVM


 JDK: The Java Development Kit (JDK) is a software development environment which is used to develop
Java applications and applets. It physically exists. It contains JRE and development tools. JDK is an
implementation of any one of the below given Java Platforms released by Oracle Corporation:
 Standard Edition Java Platform
 Enterprise Edition Java Platform
 Micro Edition Java Platform

7
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc),
etc. to complete the development of a Java Application.
 JRE: A set of software tools which are used for developing Java applications. It is used to provide
the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of
libraries + other files that JVM uses at runtime. The implementation of JVM is also actively released
by other companies besides Sun Micro Systems.
 JVM: An abstract machine or called a virtual machine because it doesn’t physically exist. It is a
specification that provides a runtime environment in which Java bytecode can be executed. It can
also run those programs which are written in other languages and compiled to Java bytecode. JVMs
are available for many hardware and software platforms.

1.6 A FIRST SIMPLE PROGRAM


Let’s create a simple Java program using the text editor called Notepad. First, put the Java code into the
Notepad to create the first Java program:
Program 1: Hello World Program
public class HelloWorld
{
public static void main (String args[])
{
System.out.println("Hello World This is our first java program");
}
}

In Program 1, the class keyword is used to declare a class called HelloWorld. This name HelloWorld is
used as an identifier, which is used to give an appropriate name to a class. Let’s look at the following line:
public static void main (String args[])
This is the line from where the program begins executing. It is by calling this main() method that all
Java programs begin their execution. The line begins with the public keyword that is an access specifier,
making the main() method accessible outside the class in which it is declared.
The static keyword allows the main() method of a class to be loaded into the memory before the instance
members of the class. The void keyword specifies that the main() method does not return any value.
Now, save the file as HelloWorld.java to a desired location on your system. In our case, we have saved
the file at the location D:\Java Folder. Note that Java programs are saved with the file extension
‘.java’.
The most important point to be noted in Java is that the name of the file should match with the name of
the class. Java is a case-sensitive language, i.e. the words ‘hello’ and ‘Hello’ have two different meanings
in Java. Once a Java program is written, it is time to compile and then run it to show the desired
output.
To run a Java program, it is necessary to compile it first using the Java compiler. This Java compiler is
an application named javac.exe located in the Java directory bin folder.

8
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

To compile a program, type javac followed by a space and then the name of the file to be compiled, as
shown in Figure 4:

Figure 4: Compiling a Java Program


Errors may occur during compilation because of the following reasons:
 Incorrect syntax
 Inability of compiler to find the source file
 Incorrect file name
Once the source file is compiled, a new file with the same name (as that of the source file) followed by an
extension ‘.class’ gets created. Now, it is time to run this .class file. To do so, SDK provides a tool called
java.exe, which is an application used to run Java programs. To run the program, type java followed by
the name of the .class file and press the Enter key to view the output, as shown in Figure 5:

Figure 5: Output of the HelloWorld.java Program

1.7 DATA TYPES


Data types are very important in Java as you cannot declare a variable without specifying its data type.
There are two types of data types in Java:
 Primitive data types
 Reference data types

9
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

Figure 6 shows the classification of data types in Java:

Data Types

Primitive Data Types Reference Data Types

Boolean Numeric Class Types Interface Types Array Types

Charcater Integral

Integer Floating-poin t

Boolean Char Byte Short Long int Float Double

Figure 6: Data Types in Java


As shown in Figure 6, both Primitive and Reference data types can be further classified into various
categories. Some of the most commonly used data types in Java programming are:
 Integer: Represents byte, short, int, and long data types that store numeric values
 Character: Represents char, which is used to store characters, such as letters and numbers
 Floating point: Represents float and double data types
 Boolean: Represents the boolean data type that is used to store logical values

Let’s learn about each of these data types in detail in the next subsections.

1.7.1 Integer Types


Java provides four integer types — byte, short, int, and long. Java supports only signed integers, so
these integer types have –ve and +ve values. Among all the integer types, byte is the smallest and long is
the largest. Table 1 explains the width and range of the integer types:

Table 1: Width and Range of the Integer Types

Data type Representation Width (bytes) Range


byte 1 -128 to 127
short 2 -32, 768 to 32, 767
int 4 -2, 147, 483, 648 to 2, 147, 483, 647
long 8 -9, 223, 372, 036, 854, 775, 808 to 9, 223, 372, 036, 854, 775, 807

10
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Some examples of the integer types are shown in the following code snippet:
int x;
int sum;
int age;
In the preceding code snippet, x, sum, and age are variables having the int data type.

1.7.2 Character
Character data type follows the Unicode character set to represent characters that can be uniquely
identified by the processor. Unicode is a standard character set that supports all the international
characters of various languages, such as American and Latin. Table 2 lists the range of character data
type:

Table 2: Range of Character Data type

Data type Representation Width (bytes) Range

Char 2 0 to 65536

The following code statement uses char with variables:


char ch = 'a';
In the preceding code, a variable ch is declared and initialized with ‘a’. You should remember to enclose
any character within single quotes while initializing it.

1.7.3 Floating Point Types


Floating point numbers are represented by float and double data types. They are used to represent
numbers along with decimal values. The difference between float and double data types is that float can
represent a maximum of 7 digits after decimal, while double can represent 15 digits after the decimal
point. Table 3 shows the width and range of the float and double data types:

Table 3: Showing the Width and Range of the Floating Point Types

Data type Width (bytes) Range


float 4 1.40129846432481707e-45 to 3.40282346638528860e+38
Double 8 4.94065645841246544e-324d to 1.79769313486231570e+308d

The following code statement shows how to declare and initialize a floating point variable:
float x = 3.458;
In the preceding code, a variable ‘x’ that has float data type is declared and initialized. Similarly, you can
use double data types with variables.

1.7.4 Boolean Type


The boolean data type represents two logical values denoted by true or false. The following code shows
the use of the boolean data type to declare a variable:
boolean x = true;

11
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

In the preceding code, a variable x of type boolean is declared and initialized as true. You can also
initialize it with false value.

1.8 LITERALS
In a Java program, you can assign a literal value to a variable. Literal refers to the constant values that
can be changed depending on the program requirement. The source code representations of the values
of primitive data types in a Java program are known as primitive literals. These primitive literals can be
an integer number, floating-point number, a boolean value, a character, or a string that you use in your
program. Some examples of the primitive literals are as follows:
24 //an int literal
124.543 // a double literal
true // a boolean literal
'v' // a char literal
"Java" // a String literal
In the preceding example, 24 is an integer value, 124.543 is a floating point number, true is the boolean
literal, v is a character value, and “Java” is a string literal.

1.9 VARIABLES
Java provides containers or placeholders to store data within a program. These containers are called
variables since the value stored in them can be changed during the course of execution of the program.
To define a variable in a Java program, you need to use the combination of a data type and an identifier.
An identifier should be a logical name representing a variable, constant, or method. The following
syntax shows how to declare a variable:
data type identifier;// declaring variable
The description of the elements in the preceding syntax is as follows:
 data type: Specifies a valid Java’s data type, such as int, char, and so on.
 identifier: Represents any name that follows some specified naming conventions.

After declaring the variable, use the following code to initialize it:
identifier = val; // declaring variable
In the preceding code, val represents the value that is used to initialize the variable and it should be
according to the data type used with the variable. It is also possible to initialize the variable at the time
of declaration. The following code shows how to initialize the variable at the time of declaration:
data type variableName = val; // declaring variable
While declaring a variable, appropriate data type must also be associated with it.

1.10 TYPE CONVERSION AND CASTING


Java is a strongly typed language; and as a result, you are often faced with the situation of assigning a
variable of one type to a variable of another type. The assigning of a variable of one type to a variable
of another type can be done by either relying on automatic type conversion or making an explicit type
cast. We’ll take a look at both here.

12
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

1.10.1 Automatic Conversions


When you are assigning one type of data to a variable of another type, Java will convert the data to the
new variable type automatically if both the following conditions are true:
 The data type and the variable types are compatible.
 The target type has a larger range than the source type.

For example, you can assign a byte value to an int variable because byte and int are compatible types,
and int variables have a larger range than byte values. Therefore, no data will be lost in the type
conversion. Here’s an example in Program 2:
Program 2: Type Conversion
public class App {
public static void main(String[] args) {
byte byte1 = 1;
int int1;
int1 = byte1;
System.out.println("int1 = " + int1); }
}
The Java compiler has no problem with this code, and it makes the type conversion automatically. Here’s
the result of Program 2:
D:\Java folder\java App
int1 = 1
Converting a data type to another with a larger range is called widening conversion. In widening
conversions, the numeric types, such as the integer and floating-point types, are compatible with
each other. On the other hand, char and boolean types are not compatible with each other or with the
numeric types.

1.10.2 Casting to New Data Types


Performing a conversion from a data type of larger range to one that has a smaller range is called
narrowing conversion. The Java compiler does not perform automatic narrowing conversions because
there are chances of losing accuracy. To perform a narrowing conversion, it must be done with an
explicit cast, which looks like this:
(target-data-type) value
For example, in Program 3, we are converting an integer type into a byte type:
Program 3: Converting an Integer type into a Byte type
public class App {
public static void main(String[] args) {
byte byte1; int int1 = 1;
byte1 = (byte) int1;
System.out.println("byte1 = " + byte1); }
}
Trying to perform a narrowing conversion would throw an exception, but performing the same with
the explicit type cast would not. This is due to the fact that Java assumes that you are aware of the
possibility of losing data by converting a potentially larger data with a larger data type into a smaller

13
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

type. Simply put, the programmer is responsible for any loss of data while performing any narrowing
conversions. For example, when you put a floating-point number into a long, the fractional part of the
number will be truncated, and you may lose more data if the floating-point value is outside the range
that a long can hold.
Here’s the output of Program 3:
D:\Java folder\java App
byte1 = 1
One thing to note is that the Java compiler also automatically promotes types as needed when it
evaluates expressions. For example, consider Program 4:
Program 4: Using Bytes, in which everything looks like it involves only bytes
public class App {
public static void main(String[] args) {
byte byte1 = 100; byte byte2 = 100; byte byte3;
byte3 = byte1 * byte2 / 100;
System.out.println("byte3 = " + byte3); }
}
Here Java gives the following error:
D:\Java folder\javac App.java
App.java:4: error: incompatible types: possible lossy conversion from int
to byte
byte3 = byte1 * byte2 / 100;
^
1 error
However, because Java knows that multiplying bytes can result in integer-sized values, it automatically
promotes the result of the byte1 * byte2 operation to an integer, which means you actually have to use
an explicit cast here to get back to the byte type, as shown in Program 5:
Program 5: Explicit Cast
public class App {
public static void main(String[] args) {
byte byte1 = 100;
byte byte2 = 100;
byte byte3;
byte3 = (byte) (byte1 * byte2 / 100);
System.out.println("byte3 = " + byte3); }
}
This code compiles and runs as you’d expect—but it wouldn’t without the (byte) cast:
D:\Java folder\java App
byte3 = 100

Note: In general, the Java compiler promotes byte and short types to int types in expressions. If one operand is
a long, the entire expression is made a long. Similarly, if one operand is a float, the whole expression is made a
float; if one operand is a double, the whole expression is made a double.

14
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

1.11 OPERATORS
While creating a program, a programmer may need to do some operations, such as addition and
multiplication, on the declared variables to perform certain functions. These operations can be done
with the help of operators. An operator is just a symbol, such as ‘+’, that acts on some variable (operands).
The operators available in Java are as follows:
 Arithmetic operators
 Increment and decrement operators
 Bitwise operators
 Relational operators
 Boolean operators
 Boolean Logical operators
 ?: operator
 Double Colon (::) operator
Let’s now discuss each of these operators in detail.

1.11.1 Arithmetic Operators


Arithmetic operators are used to perform mathematical calcualtions on the operands of numeric types.
These operators are also called binary operators as they work on two operands. Table 4 lists the various
arithmetic operators available in Java:

Table 4: Arithmetic Operators in Java

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

Let’s understand these operators more clearly with the help of a simple class named Arithmetic.
Program 6 shows the code of the Arithmetic class:
Program 6: Showing the Arithmetic.java File
public class Arithmetic
{

15
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

public static void main(String args[])


{
int addNum=30+10;
String addStr="Arithmetic"+"Operators";
int subNum=50-20;
int mulNum=5*8;
int modNum=20%3;
int divNum=20/5;
System.out.println("Sum of two numbers is:"+addNum);
System.out.println("concatenated string is:"+addStr);
System.out.println("Difference of two numbers is:"+subNum);
System.out.println("Product of two numbers is:"+mulNum);
System.out.println("Modulus result is:"+modNum);
System.out.println("Division of two numbers is:"+divNum);
}
}
Here’s the output of Program 6:
D:\Java folder\java Arithmetic
Sum of two numbers is:40
concatenated string is:ArithmeticOperators
Difference of two numbers is:30
Product of two numbers is:40
Modulus result is:2
Division of two numbers is:4
Program 6 demonstrates the implementation of some of the commonly used arithmetic operators.
The operator ‘+’ serves two purposes. One is the addition of two numeric operands and giving back a
numeric output. Another purpose is that it joins together two string values and returns a concatenated
string as the output. The ‘-’ operator shown in the example is used to perform the subtraction of two
given numbers and return their difference.
The operator ‘*’ is used to return the product of two numbers as an output. The modulus operator ‘%’
is used to divide the first number by the second number and returns the remainder as an output. The
operator ‘/’ divides the first number by the second number and returns the quotient as output.

Increment and Decrement Operators


The increment (++) and decrement (--) operators perform manipulation on a single operand and hence
they are known as unary operators. You can increase or decrease the value of an operand by one using
the increment and decrement operators. The increment and decrement operators operate on operands
in two forms, namely postfix and prefix. Note that these forms of operators increase or decrease the
appropriate variable, but they do so at different times.
The statement ++i (prefix form) increments i before its value is used, while i++ (postfix form) increments
it after its value has been used. Similarly, --i decreases ‘i’ before its value is used, while i-- decreases it
once its value has been used.
The difference between the prefix form of increment and decrement operators can be made clear with
the help of an example. Program 7 shows the code of the PreExample class that helps to understand the
prefix form of increment and decrement operators:

16
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Program 7: Using the Increment and Decrement Operators


public class PreExample
{
public static void main(String args[])
{
int x=1;
int y=++x;
int a=2;
int b=--a;
System.out.println("The value of x:"+x);
System.out.println("The value of y:"+y);
System.out.println("The value of a:"+a);
System.out.println("The value of b:"+b);
}
}
Here’s the output of Program 7:
D:\Java folder\java PreExample
The value of x:2
The value of y:2
The value of a:1
The value of b:1
In Program 7, variable y is set to an incremented value of variable x, since in the prefix form of increment,
the value of x is incremented before being assigned to y. In the same way, b is set to the decremented
value of a.
It can be seen in output that the value of x is set to 2 as it is incremented. The value of y, however, is set to
2 since the increment occured before x is assigned to y. In the same way, the value of a is set to 1 because
of the decrement done on it. The value of b is also set to 1 because the decrement occured before a is
assigned to b.

Bitwise Operators
Bitwise operators operate on the individual bits (0 and 1) of their operands. They can be applied only on
the integer types, that is, long, int, short, and byte. The bitwise operators should be used where memory
savings are needed, such as for system programming. Some of the useful bitwise operators are discussed
in Table 5:

Table 5: Bitwise Operators

Operator Meaning
& AND
| OR
^ Exclusive OR or ZOR
>> Right Shift
<< Left Shift

17
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

Let’s now discuss the operators provided in Table 5.

The AND Operator


The AND operator is a binary operator that operates on the binary representation of two operators
provided in the form of 1 and 0. It produces ‘1’ bit in case the corresponding bits in both the operands are
‘1’; otherwise, it produces 0, as explained in Table 6:

Table 6: Outcomes of the AND Operator

A B A&B
0 0 0
1 0 0
0 1 0
1 1 1

The OR Operator
The OR operator produces 1 if one or both the corresponding bits in its operands are 1, and it produces
0 if both the corresponding bits are 0. In other words, the OR operator, which is represented by the |
symbol, returns 1 in all cases, except in a situation where the corresponding bits of both operands are
zero, as presented in Table 7:

Table 7: Outcomes of the OR Operator

A B A|B
0 0 0
1 0 1
0 1 1
1 1 1

The Exclusive OR Operator


The Exclusive OR operator produces 1 when the corresponding bits in its operands are different and
produces 0 if they are same. Table 8 presents the outcomes of the Exclusive OR operator:

Table 8: Outcomes of the Exclusive OR Operator

A B A^B
0 0 0
1 0 1
0 1 1
1 1 0

Before discussing about shift operators, you must understand what exactly does shifting means.
Shifting means moving bits left or right depending upon the kind of shift operator used. In shifting, one
bit moves forward, making space for the next bit to take its place.

18
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

The Right Shift Operator


The Right Shift operator >> shifts the bits to the right by a specified number of positions. The number
of positions up to which the shifting should occur depends on the value given after the operator. When
shifting right >>, the lost bits are filled in with the previous leftmost bits and the leftmost bits are filled
with 0s.
To understand the right shift operator more clearly, let’s see an example. Consider the number 78 whose
binary equivalent is as follows:
00000000 00000000 00000000 01001110
By shifting it right >> 2 times, you get the following output:
00000000 00000000 00000000 00010011 ( = 19 )

The Left Shift Operator


The Left Shift operator shifts the bits to the left by a specified number of positions. When you shift
left <<, the void left behind by the shift is filled by zeros and the lost bits are filled in with the previous
rightmost bits.
To understand the left shift operator more clearly, let’s consider the example of number 78 whose binary
equivalent is as follows:
00000000 00000000 00000000 01001110
By shifting it left << 3 times , the output obtained is as follows:
00000000 00000000 00000010 01110000 ( = 624 )
Let’s learn about the relational operators in the next section.

The Relational Operators


Relational operators compare two operands and draw relationship between them, such as whether the
two operands are equal to each other or not. The outcome of these operators is a boolean value that is
true or false.
Table 9 explains the relational operators:

Table 9: Various Relational Operators

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

The Boolean Operator


The operators that act on the boolean variables are called boolean operators. They produce the result in
the form of ‘true’ or ‘false’. Table 10 explains the various boolean operators:

19
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

Table 10: Various Boolean Operators

Operator Meaning
| OR
& AND
! NOT

The | operator returns true if any of the operand is true. The ‘&’ operator returns true if both the operands
are true; else, it returns false. On the other hand, the ‘!’ operator is used to convert the true value to false
and false to true.
Let’s suppose you have declared two variables x and y. The variable x is initialized as true, while the
varable y as false. To convert x to false, the ! operator can be used, as shown in the following code
statement:
!x
On execution of the preceding code statement, the ! operator will return a false value.

The Boolean Logical Operator


Boolean logical operators also operate only on the boolean operands and are used in compound conditions.
For example, suppose you initialize two variables with value ‘2’ and then want to check whether these
variables are initialized with the same values. To verify whether the variables are initialized to 2 or not,
you can use the boolean logical operators. Table 11 lists the important boolean logical operators:

Table 11: Various Boolean Logical Operators

Operator Result
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT

These operators somewhat look similar to the bitwise logical operators. The major difference between
these two operators is that the ‘boolean logical operators’ operate on integers, whereas ‘bitwise logical
operators‘ operate on the boolean operands.
Java provides two boolean logical operators called short-circuit operators, which are && (short-circuit
AND) and || (short-circuit OR). The && operator is very useful in cases where a value has to be checked
for two facts.

The ?: Operator
There is a special kind of operator that can replace certain types of if-then-else statements. The if-then-
else is a conditional statement that is used to evaluate an expression for boolean value.
The general syntax for using the ?: operator is as follows:
Expression1? Expression2: Expression3
In the preceding syntax, Expression1 can be any expression that evaluates to a boolean value. In case it
comes out to be true, then Expression2 is evaluated; otherwise, Expression3 is evaluated.

20
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

1.12 SHORTHAND ASSIGNMENTS


A shorthand operator is a shorter way to express something that is already available in the Java
programming language. Shorthand operators in Java are: +=, -=, *=, /= and *=. The following code
snippet shows the use of the shorthand operators:
public class Shorthand1
{
public static void main(String[] args)
{
int x;x`

x = 8;
x += 3;
System.out.println(x);
x = 8;
x -= 3;
System.out.println(x);

x = 8;
x *= 3;
System.out.println(x);

x = 8;
x /= 3;
System.out.println(x);

x = 8;
x %= 3;
System.out.println(x);
}
}

1.13 INPUT CHARACTERS FROM THE KEYWORD


In Java, the Scanner class is used to take input characters from the keyboards. It belongs to java.util
package. It is used to read the input of primitive types like int, double, long, short, float, and byte. It is the
easiest way to read input in Java program. The syntax is as follows:
Scanner sc=new Scanner(System.in);
The preceding syntax means it is going to read from the standard input stream of the program. The
java.util package should be import while using Scanner class. It also converts the Bytes (from the input
stream) into characters using the platform’s default charset. Program 8 shows the use of the Scanner
class:
Program 8: Input from Keyboard Using Scanner Class
import java.util.Scanner;
public class CharacterInput
{
public static void main(String[] args)
{

21
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

Scanner sc = new Scanner(System.in);


System.out.print("Enter a character: ");
// reading a character
char ch = sc.next().charAt(0);
//prints the character
System.out.println("You have entered "+ch);
}
}
Here’s the output of Program 8:
D:\Java folder\java CharacterInput
Input a character: R
You have entered R

1.14 PROGRAM CONTROL STATEMENTS


Program control statements are used by a programming language to control the flow of execution
of program based on certain conditions. These statements are used to cause the flow of execution to
advance and branch based on changes to the state of a program. In Java, program control statements
are divided into conditional statements, iteration statements, and jump statements. A conditional
statement is a control statement that allows choosing between two or more execution paths in a
program, while an iteration statement repeatedly executes the code block on the basis of the condition
specified in the conditional statement. Once the conditional statement evaluates to false, the loop exits;
thereby, the control is transferred to the next statement that follows the loop. The jump statements
allow redirecting the flow of program execution.

1.14.1 Conditional Statements


As the name suggests, conditional statements cause a program to execute a block of code on evaluating
a conditional expression. In case the conditional expression evaluates to true, the block of code following
the expression is executed; otherwise, the block is not executed. The three main types of conditional
statements are as follows:
 if statement
 if-else statement
 switch statement

The if Statement
The if statement lets you execute a statement or a set of statements depending upon the result of test
condition. However, if the test condition evaluates false, no statement is executed. In general, the if
statement is used as follows:
if (condition)
statement;
Note that statement can be a compound statement also, which means it can be made up of a number
of statements enclosed in curly braces.

22
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Start by checking whether the value is greater than zero; and if so, just print out the value itself, as done
in Program 9:

Program 9: Using if Statement


public class App {
public static void main(String[] args) {
int value = 10;
if(value > 0)
System.out.println("Abs(" + value + ") = " + value); }
}
Here’s the result of Program 9:
D:\Java folder\java App
Abs(10) = 10
Another example for the Programmer where an if statement is used to execute multiple statements in
Program 10:

Program 10: Executing Multiple Statement in if Statement


public class App {
public static void main(String[] args) {
int value = 10;
if(value > 0) {
System.out.println("The number was positive.");
System.out.println("Abs(" + value + ") = " + value); }
}
}
Here’s the result of Program 10:
D:\Java folder\java App
The number was positive.
Abs(10) = 10

The else Statement


The else statement lets you specify statement(s) which gets executed when the if condition evaluates
to false. Here’s an example using the else statement, which can also display absolute value of negative
numbers, in Program 11:

Program 11: Using else Statement


public class App {
public static void main(String[] args) {
int value = -10;
if(value > 0) {
System.out.println("Abs(" + value + ") = " + value); }
else {

23
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

System.out.println("Abs(" + value + ") = " + -value); }


}
}
Here’s the result of Program 11:
D:\Java folder\java App
Abs(-10) = 10

Nested if Statement
The nested if statement allows that one if statement can be written inside another if statement. Here’s
an example to show how a nested if statement works in Program 12:
Program 12: Nested if Statements
public class App {
public static void main(String[] args) {
double value = 2;
if (value != 0) {
if (value > 0)
System.out.println("The result = " + (1 / value));
else
System.out.println("The result = " + (-1 / value)); }
}
}
Here’s the result of Program 12:
D:\Java folder\java App
The result = 0.5

The if-else Ladders


An entire sequence of the if-else statements is called an if-else ladder. Here’s an example to show how an
if-else ladder works, in Program 13:
Program 13: if-else Ladder
public class App {
public static void main(String[] args) {
String month = "March";
if(month == "January")
System.out.println("It\'s January");
else if (month == "February")
System.out.println("It\'s February");
else if (month == "March")
System.out.println("It\'s March");
else if (month == "April")
System.out.println("It\'s April");
else if (month == "May")
System.out.println("It\'s May"); }
}

24
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

In this case, we test the value in a string variable successively until we find a match to the current year
of the calendar (we are testing only for the first five months). Here’s the result of Program 13:
D:\Java folder\java App
It's March
Note that although it’s possible to create if-else ladders in this way, Java actually includes a statement
expressly for situations like this—the switch statement.

Switch Statement
The switch statement is Java’s multipath branch statement; it provides the same kind of functionality
as an if-else ladder does (see the previous topic) but in a form that’s much easier to work with. Here’s
what the switch statement looks like in general:
switch (expression) {
case value1:
statement1;
[break;]
case value2:
statement2;
[break;]
case value3:
statement3;
[break;]
. . .
default:
default_statement;
}
Here, the value of expression, which must be of type byte, char, short, or int, is compared against the
various test values in the case statements: value1, value2, and so on. If the expression matches one of the
case statements, the code associated with that case statement—statement1, statement2, and so on—is
executed. If execution reaches a break statement, the switch statement ends. Here’s an example in which
we display the day of the week based on a numeric value by using a switch statement, in Program 14:
Program 14: Using switch Statement:
public class App {
public static void main(String[] args) {
int day = 5;
switch(day) {
case 0:
System.out.println("Today is Sunday."); break;
case 1:
System.out.println("Today is Monday."); break;
case 2:
System.out.println("Today is Tuesday."); break;
case 3:
System.out.println("Today is Wednesday."); break;
case 4:

25
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

System.out.println("Today is Thursday."); break;


case 5:
System.out.println("Today is Friday."); break;
default:
System.out.println("Today is Saturday."); }
}
}
Here’s the result of Program 14:
D:\Java folder\java App
Today is Friday.
Try to execute the preceding example without writing the break statements and see what it returns as
the day today. You’ll find that it returns Today is Friday and Today is Saturday. This signifies that if you
don’t specify a break statement at the end of a case statement, the execution will continue with the code
in the next case statement. This may prove useful when you want to execute the same code for multiple
case test values, as shown in Program 15:
Program 15: Using Multiple Cases in Switch Statement
public class App {
public static void main(String[] args) {
int temperature = 78;
switch(temperature) {
case 60:
case 61:
case 62:
case 63:
case 64:
System.out.println("Very cold"); break;
case 65:
case 66:
case 67:
case 68:
case 69:
System.out.println("It\'s cool"); break;
case 70:
case 71:
case 72:
case 73:
case 74:
case 75:
System.out.println("It\'s warm"); break;
default:
System.out.println("Uff, very hot!! "); } }
}
Here’s the result of Program 15:
D:\Java folder\java App
Uff, very hot!!
Note that a default case executes if none of the above cases match or when no break statements are
specified.

26
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Nested switch statements


Java allows to use nested switch-case statements. It means a switch statement can be inside another
switch statement. The inner switch statement will be part of any case of an outer switch and executed
only if the outer switch statement condition is true.
The syntax of the nested switch statement is as follows:
switch(variable/expression)
{
case value1 :
// code inside the case value1
break; // optional

case value2 :
// code inside the case value2
break; // optional
case value3 :
switch(variable/expression)
{
case valueOne :
// code inside the case valueOne
break; // optional

case valueTwo :
// code inside the case valueTwo
break; // optional
.
.
.
default :
// code inside the default case .
}
.
.
.
default :
// code inside the default case .
}

1.14.2 Iteration
Repeating the same code fragment several times is called iterating. The basic logic behind iteration is
that a sequence of statements is repeated until a certain condition is satisfied. When this condition is
false, the iteration terminates and the loop is completed. The iteration statements are also known as
loops in Java. There are various types of iteration statements available in Java, which are as follows:
 while loop
 do-while loop
 for loop

27
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

 for-each loop
 Nested loop

Let’s learn about the iteration statements in detail.

While Loop
A while loop executes a statement(s) inside a loop body as long as the loop test condition evaluates to
true. In general, a while loop looks as follows:
while(condition)
statement;
Note that the loop is executed not even once if the test condition evaluates to false. An example that
shows how a while loop works is Program 16:
Program 16: Using While Loop
public class App {
public static void main(String[] args) { int value = 10;
while (value > 0) {
System.out.println("Current value = " + value--); } }
}
In this case, we display a value, successively subtract 1 from that value and then display the result. When
the value becomes 0, the while loop stops because the condition (value > 0) has become false. In other
words, the loop executes till value remains positive.
Here’s what this while loop returns:
D:\Java folder\java App
Current value = 10
Current value = 9
Current value = 8
Current value = 7
Current value = 6
Current value = 5
Current value = 4
Current value = 3
Current value = 2
Current value = 1

Do-While Loop
The do-while loop is similar to a while loop. It is also used to repeat a set of statements a number of times.
However, the difference lies where the test condition is evaluated. A do-while loop tests the condition
after the loop body is executed, whereas a while loop tests the condition before the loop body executes.
Both loops terminate once the test condition evaluates to false.
A do-while loop looks as follows:
do
statement;
while(condition);

28
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

It can be seen in the preceding lines that a do-while loop will always execute at least once even if the
condition evaluates to false. This is because the condition is tested after the loop body gets executed.
Here’s an example to show how a do-while loop works, in Program 17:
Program 17: Using do-while Loop:
public class App {
public static void main(String[] args) {
int values[] = {1, 2, 3, 0, 5}, test, index = 0;
do {
test = 5 * values[index++];
System.out.println(test);
} while (test < 15); }
}
The result is as follows:
D:\Java folder\java App
5
10
15
Question arises when to use a while loop and when to use a do-while loop? The answer is whenever the
situation demands that looping statements should execute only if the condition is true, you use a while
loop. The following code makes it clearer, where a do-while loop evaluates the reciprocal of a value but
can only test whether the value is a nonzero value at the end of the loop:
public class App {
public static void main(String[] args) {
double value = 0;
do {
System.out.println("The reciprocal = " + 1 / value);
} while (value > 0);
}
}
It is far better in this case to use a while loop to test for 0 first:
public class App {
public static void main(String[] args) {
double value = 0;
while (value > 0) {
System.out.println("The reciprocal = " + 1 / value); }
}
}

For Loop
The Java for loop is a good choice when you want to use a numeric index that you automatically
increment or decrement each time through the loop, such as when you are working with an array. Here’s
what the for loop looks like in general (note that statement can be a compound statement, including
several single statements inside curly braces):
for (initialization_expression; test_conditon; iteration_expression) {

29
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

statement
}
Initialization_expression lets you initialize the loop index, test_condition signifies a conditional
expression, such as loop_index<=5, and iteration_expression increments or decrements the loop index.
You can also use multiple loop indexes in a for loop.
An example to show how a for loop works is in Program 18:
Program 18: Using for Loop
public class App {
public static void main(String[] args) {
int loop_index;
for (loop_index = 1; loop_index <= 5; loop_index++) {

System.out.println("This is iteration number " + loop_index); }


}
}
The loop index is initialized with value 1 he loop terminates when the index exceeds 5, which means the
loop is executed only 5 times, and everytime the loop index is incremented by 1:
Here’s the result:
D:\Java folder\java App
This is iteration number 1
This is iteration number 2
This is iteration number 3
This is iteration number 4
This is iteration number 5
Here’s an example that finds the average student score by looping over all the scores and summing them
(note that we are actually declaring and initializing the loop index to 0 in the initialization expression):
Program 19: Using Zero Loop Index in for Loop
public class App {
public static void main(String[] args) {
double grades[] = {88, 99, 73, 56, 87, 64};
double sum, average;
sum = 0;
for (int loop_index = 0; loop_index < grades.length;
loop_index++) {
sum += grades[loop_index]; }
average = sum / grades.length;
System.out.println("Average grade = " + average); }
}
Here’s the result of Program 19:
D:\Java folder\java App
Average grade = 77.83333333333333
When you declare a loop variable (such as loop_index in this example), the scope of that variable is
limited to the for loop body.

30
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Note that you can use very general expressions in a for loop. Java lets you separate expressions in a for
loop with a comma, as shown in Program 20 in which we are using two loop indexes:
Program 20: Using Two Loops
public class App {
public static void main(String[] args) {
for (int loop_index = 0, doubled = 0; loop_index <= 10;
loop_index++, doubled = 2 * loop_index) {
System.out.println("Loop index " + loop_index +" doubled equals
" + doubled); }
}
}
Here’s the result of Program 20:
D:\Java folder\java App
Loop index 0 doubled equals 0
Loop index 1 doubled equals 2
Loop index 2 doubled equals 4
Loop index 3 doubled equals 6
Loop index 4 doubled equals 8
Loop index 5 doubled equals 10
Loop index 6 doubled equals 12
Loop index 7 doubled equals 14
Loop index 8 doubled equals 16
Loop index 9 doubled equals 18
Loop index 10 doubled equals 20
You don’t have to give a for loop to anybody at all—in fact, you can use a null statement. In
Program 21 we are summing all the elements of an array in a for loop without any code in its body:
Program 21: Using Array in for Loop
public class App {
public static void main(String[] args) {
int array[] = {1, 2, 3, 4, 5}, sum = 0;
for (int loop_index = 0; loop_index < array.length;
sum += array[loop_index++]);
System.out.println("The sum = " + sum); }
}
Here’s the result of Program 21:
D:\Java folder\java App
The sum = 15
You can even turn a for loop into a while loop, in Program 22:
Program 22: Turning for Loop into while Loop
public class App {
public static void main(String[] args) {
int value = 6, factorial = 1, temp;
temp = value;
for( ;temp > 0; ) { factorial *= temp--; }

31
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

System.out.println(value + "! = " + factorial); }


}
Here’s the result of Program 22:
D:\Java folder\java App
6! = 720

Enhanced For Loop


The for-each loop is specifically designed to handle elements of a collection. A collection is represented
by a group of elements or objects. List is an example of collection since it stores a group of objects.
Similarly, the classes of the java.util package are developed to handle a group of objects. The for-each
loop repeatedly executes a group of statements for each element of the collection. It executes as many
times as the number of elements in the collection. The general syntax for using the for-each loop is as
follows:
for(var:collection)

{
Statements:

}
In the preceding syntax, var represents the elements of the collection corresponding to the for-each loop
iteration. For example, in a collection of 5 elements, the for-each loop will execute 5 times and the var will
represent the elements of the collection one by one.

Nested Loops
The nested loop is an iteration statement contained within another iteration statement (nested loop). In
short, it is a loop within another loop. In the nested loop, the execution starts from the outer loop and
the control then passes to the inner loop. The inner loop continues to execute till the inner loop condition
evaluates to true. Once the inner loop is completed, the flow of execution is passed to the outer loop for
the next iteration and the outer loop is executed till its condition returns true.

Note: It is possible to nest conditional statements as well as iteration statements in Java. Nested conditional
statement consists of conditional statements within another conditional statements (nested if statements)

Let’s understand the nested loop of the for statement by creating a class named NestedLoopExample.
Program 23 shows the code of the NestedLoopExample class:
Program 23: Demonstrating the Code of the NestedLoopExample.java File
public class NestedLoopExample
{
public static void main(String args[])
{

int num1,num2;
for(num2 = 0; num2 <= 3; num2++)
{

32
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

for(num1 = 0; num1 <= 2; num1++)


{
System.out.println(num2 + " " + num1);
}
}
}
}
Here’s the output of Program 23:
D:\Java folder\java NestedLoopExample
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
3 0
3 1
3 2Here's the output of the preceding code:

D:\Java folder\java NestedLoopExample


0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
3 0
3 1
3 2
In Program 23, execution begins with an outer for loop in which num2 is initialized to 0. Now, the
execution enters into the inner for loop where num1 is set to 0. The inner for loop continues to execute
until the condition becomes false. In this way, the inner loop is executed three times, with num1 changing
its value from 0 to 2.
Once the inner for loop is completed, the control goes to the outer for loop and num2 is set to 1. Now,
the inner for loop is again executed three times till num1 becomes 2. Again, the control goes back to the
outer for loop and num2 is set to 2. The outer loop executes till its value exceeds 3. In this way, the outer
loop executes four times.
In the NestedLoopExample class, the outer for loop is executed four times and the inner for loop is
executed about three times for each value of num2.
The output shows the implementation of the nested for loops.

33
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming

1.14.3 Implementing the Jump Statements


Jump statements are the statements that transfer control from one part of the program to another. The
jump statements supported in Java are as follows:
 break
 continue
 return

Use the Break Statement


The break statement is mainly used to exit from the switch and loop statements. Sometimes, you need to
break out of a loop before the complete loop gets executed. The break statement allows us to get out of a
loop even before it is completely executed. It consists of a simple break keyword followed by a semicolon.
Let’s understand the use of break statement with the help of a class named BreakExample. Program 24
shows the code of the BreakExample class:
Program 24: Showing the Code of the BreakExample.java File
//To display first five even numbers using break statement
public class BreakExample {

public static void main(String[] args) {


int i = 0;
while (true) // loop will execute infinitely
{
i=i+2;
if (i >10)
{
break; // when the condition becomes true break will get execute
}
System.out.println(i);
}
}
}
Here’s the output of Program 24:
D:\Java folder\java BreakExample
2
4
6
8
10
In Program 24, an infinite loop is shown to display even numbers up to infinity. To avoid this situation,
a break statement is used within a condition stating that if the value of i variable exceeds 10, then the
control comes out of the while loop.

Use the Continue Statement


The continue statement causes the current iteration of the loop to quit and begin executing the next
iteration. When you use the continue statement without a label, it starts the new iteration of the

34
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

innermost loop. On the other hand, when used with a label, which represents the name of the containing
loop, it causes the named loop to start a new iteration.
Let’s understand the use of the continue statement with the help of a class named ContinueExample.
Program 25 shows the code of the ContinueExample class:
Program 25: Showing the Code of the ContinueExample.java File
//To display first 10 even numbers excluding 12 using continue statement
public class ContinueExample
{
public static void main(String[] args)
{

for (int i=2;i<=20;i=i+2)


{
if (i == 12) // if i becomes 12 then continue statement will get execute
{
continue;
}
System.out.println(i);
}

}
}
Here’s the output of Program 25:
D:\Java folder\java ContinueExample
2
4
6
8
10
14
16
18
20
In Program 25, the first ten even numbers are shown, excluding 12 from the result. The value 12 is not
printed because of the continue statement inside an if condition, which executes in case the value of i
variable becomes 12. In the ContinueExample class, even numbers are displayed successfully until the
value of i becomes 12. When the value of i becomes 12, the control of execution quits from the current
loop and returns back to the for loop. The succeeding iterations of the for loop then display the even
numbers up to 20 or till the value of i exceeds 20, as shown in the output.

Using the return Statement


The return statement is usually used in the method that causes the control of execution to return back to
the caller of the method. Let’s understand the use of continue statement with the help of a class named
ReturnExample. Program 26 shows the code of the ReturnExample class:

35
JGI JAIN DEEMED-TO-BE UNIVERSIT Y Java Programming

Program 26: ReturnExample Class


class ReturnExample
{
public static void main(String arg[])
{
boolean t = true;

System.out.println("Before the return statement");

if(t) return; // return to caller

System.out.println("After the return statement");


}
}

Here's the output of Program 26:


D:\Java folder\java ReturnExample
Before the return statement

In the code, there are two messages before the return statement and after
it. First message will executed successfully, as it is before the use of
the return statement, but second message will not displayed at all.

Conclusion 1.15 CONCLUSION

 Java is a programming language, which inherits its object-oriented features from C++.
 It was created by James Gosling, a software developer at Sun Microsystems, in 1991.
 Java is a simple, robust, platform-independent, and portable programming language.
 Object-Oriented Programming (OOP) is a programming technique where you specify various objects
and define the interaction among them to implement program logic. Classes and objects are the two
main elements of OOP.
 In Java, OOP is implemented through following attributes: Encapsulation, Abstraction and
Inheritance.
 A software development environment comprises numerous development tools, classes, and methods.
The development tools for Java are provided as a part of the system known as Java Development
Kit (JDK).
 Java developers can use JDK on Windows, macOS, Solaris, and Linux.
 JavaAPI is a collection of classes, interfaces, and methods provided in the form of Java packages.
 A Java application is a program that is created by using Java programming language. Java
applications are console-based, Character User Interface (CUI)-based, and GUI-based standalone
applications.
 An applet is a program written in the Java programming language that can be included in an HTML
page in the same way as an image is included.

36
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

 Java Runtime Environment (JRE) is a software bundle that allows Java program to run, whereas
Java Virtual Machine (JVM) is an environment for executing bytecode.
 Data types are very important in Java as you cannot declare a variable without specifying its data
type.
 There are two types of data types in Java: primitive data types and reference data types.
 Literal refers to the constant values that can be changed depending on the program requirement.
 Java provides containers or placeholders to store data within a program. These containers are
called variables since the value stored in them can be changed during the course of execution of the
program.
 To define a variable in a Java program, you need to use the combination of a data type and an
identifier.
 An identifier should be a logical name representing a variable, constant, or method.
 The assigning of a variable of one type to a variable of another type can be done by either relying on
automatic type conversion or making an explicit type cast.
 While creating a program, a programmer may need to do some operations, such as addition and
multiplication, on the declared variables to perform certain functions. These operations can be done
with the help of operators.
 The operators available in Java are: arithmetic operators, increment and decrement operators,
bitwise operators, relational operators, boolean operators, boolean logical operators, ?: operator,
and double colon (::) operator.
 The Scanner class is used to take input characters from the keyboards. It belongs to java.util package.
 Program control statements are used by a programming language to control the flow of execution
of program based on certain conditions. In Java, program control statements are divided into
conditional statements, iteration statements, and jump statements.
 The three main types of conditional statements are: if statement, if-else statement and switch
statement.
 There are various types of iteration statements available in Java: while loop, do-while loop, for loop
and for-each loop.
 The jump statements supported in Java are: break, continue and return.

1.16 GLOSSARY

 Java API: A collection of classes, interfaces, and methods provided in the form of Java packages.
 Java application: A program that is created by using Java programming language. Java applications
are console-based, Character User Interface (CUI)-based, and GUI-based standalone applications.
 Applet: A program written in the Java programming language that can be included in an HTML
page in the same way as an image is included. An applet can be used in both static and dynamic web
pages to either display content or share information through the pages.
 JDK: A software development kit.
 Java Runtime Environment (JRE): A software bundle that allows Java program to run.
 Java Virtual Machine (JVM): An environment for executing bytecode.

37
JGI JAINDEEMED-TO-BE UNIVERSIT Y Java Programming

 Variables: Java provides containers or placeholders to store data within a program. These
containers are called variables since the value stored in them can be changed during the course of
execution of the program.
 Data types: Data types are used along with variables or constants to signify which type of data will
be store in them.
 Program control statements: These statements are used by a programming language to control the
flow of execution of program based on certain conditions.

1.17 SELF-ASSESSMENT QUESTIONS

A. Essay Type Questions


1. The driving inspiration behind Java was to create something that could be used on all computers.
Explain the basic features of Java in detail.
2. JRE is a software bundle that allows Java program to run. How is it different from JDK and JVM?
3. A Java programmer can create either a Java application or a Java applet depending upon the
requirement. What is the difference between an application and an applet?
4. Java has a rich set of data types. What are data types? Also explain various categories of data types
used in Java.
5. A variable in Java is a data container that stores the data values during Java program execution.
How to declare and initialize variables?

1.18 ANSWERS TO SELF-ASSESSMENT QUESTIONS

A. Essay Type Questions


1. Java is a simple, robust, platform-independent, and portable programming language. It is designed
to meet the real-world requirements with its following features:
 Portable
 Multithreading
 Memory management
 Security
 Platform-Independent
 Distributed
 Dynamic
2. JDK is a software development kit whereas Java Runtime Environment (JRE) is a software bundle
that allows Java program to run, whereas Java Virtual Machine (JVM) is an environment for
executing bytecode.
3. Java applications are console-based, Character User Interface (CUI)-based, and GUI-based
standalone applications.
An applet is a program written in the Java programming language that can be included in an HTML
page in the same way as an image is included.
38
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

4. Data types are very important in Java as you cannot declare a variable without specifying its data
type. There are two types of data types in Java: primitive data types and reference data types.
5. The following code snippet shows how to declare a variable:
data type identifier;// declaring variable
After declaring the variable, use the following code snippet to initialize it:
identifier = val; // declaring variable

@ 1.19 POST-UNIT READING MATERIAL

 https://www.oracle.com/webfolder/technetwork/tutorials/oraclecode/windows-hol-setup.pdf

1.20 TOPICS FOR DISCUSSION FORUMS

 Explore and discuss why the Java programming language is called “Java”.

39

You might also like