MCA_Java_Programming_01_PdfToWord_(Recovered)
MCA_Java_Programming_01_PdfToWord_(Recovered)
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
Learning Outcomes
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.
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.
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
Java Program
Compiler
Java bytecode
5
JGI JAINDEEMED-TO-BE UNIVERSIT Y Java Programming
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
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.
Set of libraries
e.g. rt.jar etc.
Development
JVM tools e.g .
javac, java etc
Other files
JRE
JDK
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.
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:
9
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming
Data Types
Charcater Integral
Integer Floating-poin t
Let’s learn about each of these data types in detail in the next subsections.
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:
Char 2 0 to 65536
Table 3: Showing the Width and Range of the Floating Point Types
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.
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.
12
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
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.
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.
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
16
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
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:
Operator Meaning
& AND
| OR
^ Exclusive OR or ZOR
>> Right Shift
<< Left Shift
17
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming
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:
A B A|B
0 0 0
1 0 1
0 1 1
1 1 1
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
Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
19
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming
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.
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
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);
}
}
21
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming
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:
23
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming
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
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
26
UNIT 01: Introduction to Java Programming JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
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
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++) {
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
{
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
33
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y Java Programming
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)
{
}
}
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.
35
JGI JAIN DEEMED-TO-BE UNIVERSIT Y Java Programming
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.
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.
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
https://www.oracle.com/webfolder/technetwork/tutorials/oraclecode/windows-hol-setup.pdf
Explore and discuss why the Java programming language is called “Java”.
39