Chapter1 IntroductiontoJava PDF
Chapter1 IntroductiontoJava PDF
1
Chapter 1 Introduction to Java
Main Program
Function Function
D E
Function
F
2
Chapter 1 Introduction to Java
Function Function
Object
Data
Function Function
3
Chapter 1 Introduction to Java
Objects
Object is called as the instance of the class. It is the run time entity
in an object oriented system. In short, we can call object as a variable of
type class. After creation, objects take up space in computer memory and
have associated address like ‘record’ in Pascal and ‘structure’ in C. When
the program is executed, object can establish the path of communication
among them by passing messages in between. Take an example of an
interactive game of NFS (Need For Speed). It consists of a set of racing
cars. In this, car can be called as one class and we have to create different
objects of that class. In order to create this we have to change the data
related to that class i.e. dimension, color, maximum speed etc. Common
attributes will remain constant for each object.
Each object is associated with data of type class with which they
are created. A class is thus collection of objects of similar types. For
example, Maharashtra, Gujarat, Bengal, Goa, Tamilnadu are the
members of class India.
In object oriented programming languages, objects are represented
with data and methods (functions) as shown in following figure.
Object Name
Method Name-1 ( )
Method Name-n ( )
4
Chapter 1 Introduction to Java
Batsman
Name
Innings
average( )
strike_rate( )
See the above example, the class ‘Batsman’ has been declared. It
contains data members Name and Innings as well as methods average (
) and strike_rate( ). In order to create the object of type Batsman we
have to use following notation.
Batsman opener;
opener.Name = “Sachin”;
opener.Innings = 310; etc.
opener.average ();
opener.strike_rate ();
5
Chapter 1 Introduction to Java
Inheritance
Vehicles
Attributes
Having Wheels
Manually Driven
Two-wheeler Four-wheeler
Attributes Attributes
-------------- --------------
-------------- --------------
See the example given in fig. 1.5. ‘Vehicles’ is the main class we
can call it a root class, base class or super class. It is having its own
attributes and methods. Theses properties are inherited to two different
classes i.e. Two-wheeler and Four-wheeler. So, Two-wheeler and Four-
wheeler both have wheels and can be manually driven. Furthermore,
Two-wheeler and Four-wheeler classes can have their own uncommon
6
Chapter 1 Introduction to Java
Polymorphism
Shape
Draw ( )
Dynamic Binding
7
Chapter 1 Introduction to Java
Shape
Draw ( )
Circle object
Draw ( )
Sphere object
Draw ( )
Consider the figure 1.7. The class Sphere is derived from Circle
which is again derived from Shape. All the three classes contain Draw (
) method. When we are calling, Draw ( ) method by using object of
Sphere, which method will it call? It is decided using dynamic binding.
By this, it is possible to call all three instances of Draw ( ) by creating
objects of class Sphere. It is decided at run-time.
Message Communication
8
Chapter 1 Introduction to Java
Object
1
Object
5 Object
2
Object Object
4 3
History of Java
9
Chapter 1 Introduction to Java
In 1992, the Green project delivered its first product, called “*7.” It
was an extremely intelligent remote control. Sun released the first version
of Java in early 1996. It was followed by Java 1.02 a couple of months
later. In 1998 Sun released the version of Java i.e. Java 1.2, which replaces
the early toy-like GUI and graphics toolkits with sophisticated and scalable
versions. Arthur Van Hoff rewrote the compiler of Java in Java itself which
was originally wrote in C by James Gosling.
Sun promised that their language will have feature of “Write Once,
Run Anywhere”™. In December 1998, the name was changed to Java 2.
Since then, the core Java platform has stabilized. The current release,
with the catchy name Java 2 Software Development Kit, Standard
Edition version 1.6, is an incremental improvement over the initial Java
2 release, with a small number of new features, increased performance
and, of course, quite a few bug fixes. Now that a stable foundation
exists, innovation has shifted to advanced Java libraries such as the
Java 2 Enterprise Edition and the Java 2 Micro Edition.
Note: The history of ‘Java Programming Language’ given in Patrick
Naughton’s book of ‘Java Handbook’ (see bibliography) in article ‘The
Long Strange Trip to Java’.
The Java project has seen many release versions. They are:
10
Chapter 1 Introduction to Java
Features of Java
11
Chapter 1 Introduction to Java
9. Multithreaded
10. High performance
11. Architectural Neutral
12. Dynamic
13. Extensible
Simplicity
Object Oriented
12
Chapter 1 Introduction to Java
Platform Independence
Portable
Java is the only language, which has compiler and interpreter both.
This has been designed to ensure platform independence nature for the
language. Due to this Java has been made a two-stage system. First, Java
complier translates the source code into bytecode instructions and there
after in the second stage, Java interpreter generates machine code that can
be directly executed by machine that is running Java program.
This provides portability to any machine for which a Java virtual
machine has been written. It also allows for extensive code checking
and improved security.
13
Chapter 1 Introduction to Java
Robust
Security
Distributed
14
Chapter 1 Introduction to Java
Multithreaded Programming
High Performance
Architectural Neutral
Dynamic
15
Chapter 1 Introduction to Java
Extensible
16
Chapter 1 Introduction to Java
17
Chapter 1 Introduction to Java
4. With the support of Java, web has become more interactive and
dynamic. On the other hand, with the support of the web we can
run Java programs someone else’s computer across the internet.
5. Java is strongly associated with the internet because of the fact
that the first application program written in Java was HotJava,
a web browser to run applets on the internet.
6. Internet users can use Java to create applet programs and run
them locally using a Java enabled browser such as HotJava or
Java enabled browser to download an applet located on a
computer anywhere on the internet and run it on his local
computer. In fact Java applets have made the internet a true
extension of storage of storage system of the local computer.
7. Internet users can set up their websites containing Java applet
that can be used by other remote users of the internet. The
ability of Java applet to ride on the information super highway
has made Java a unique programming language.
8. We can create the Servlets in Java. Servlets are small programs
that execute on the server side of a Web connection. Just as
applets dynamically extend the functionality of a Web browser,
servlets dynamically extend the functionality of a Web server.
Servlets are generic extensions to Java-enabled servers. They are
secure, portable, and easy to use replacement for CGI.
Comments
18
Chapter 1 Introduction to Java
Class Declaration
class MyProg
Every class and method in Java is enclosed within the curly braces
(‘{’ and ‘}’) same as in C++. Remember, number of opening braces
must be equal to number of closing braces in a program. In class
declaration, after closing brace of a class, there is no semicolon given.
But, in C++ class definition, semicolon is in the syntax.
19
Chapter 1 Introduction to Java
System.out.println(“Hello World”);
This is the only executable statement inside the program and just
similar to the printf( ) statement in C as well as cout<< construct in
C++. As Java in strictly object oriented language, every user defined
method or library method must be the part of an object of class. In
above line, the println method is member of the out object, which is
static data member of System class. This line will print the string
Hello World
When you compile this program, you will get the output:
Value :
22
The declaration and expression statements written in main( )
method are just same as that in C/C++. Only output statements are
different. By which Java is following the concept of strictly object
oriented programming.
20
Chapter 1 Introduction to Java
integer numbers. The variable num is declared with value, thus called as
valued declaration. The value to the variable prog is given in next line.
In the expression statement,
both the variables num and prog are having the values. Before using the
variables in the expression the value must be given to them. If we
eliminate the line,
prog = 5;
Creating a program
//Test program
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello...");
21
Chapter 1 Introduction to Java
We must save this file with the name HelloWorld.java. That is, the
name of the Java application program is just same as name of the class
which contains main() method. All the Java programs have the extension
.java. This file is called as the source file. Remember that, if the
program has multiple classes in it then name of the file will be the name
of main method’s class only.
Compiling a program
javac HelloWorld.java
If there is no any error in the program, the javac creates a file named
HelloWorld.class, which contains bytecode of the program. The compiler
will automatically give the name to the class file.
Running a program
java HelloWorld
Now interpreter looks for the main method in the program and
begins execution from there. When we execute the program, we will get
following output.
Hello...
Welcome to the world of JAVA PROGRAMMING
Use of bytecode
22
Chapter 1 Introduction to Java
Source code
Java Compiler
bytecode
23
Chapter 1 Introduction to Java
Real machine
Operating system
Compiler Interpreter
Users
24
Chapter 1 Introduction to Java
Documentation Section
Package Statements
Import Statements
Interface Statements
Class Definitions
Documentation Section
25
Chapter 1 Introduction to Java
Package Statement
package college;
After this statement, all the classes used in the Java program may
become the part of user defined package, college. This statement is
optional.
Import Statement
import java.io.*;
This statement will instruct the compiler to import all the classes
contained in the package java.io in our program in order to use them.
Import can also be used to import the user defined packages.
Interface Statements
Class Definitions
26
Chapter 1 Introduction to Java
Java Tokens
Alphabets, Constants,
Digits, Variables, Instructions Program
Special And
Symbols Keywords
Tokens
Fig. 1.16 Forming a Java Program
27
Chapter 1 Introduction to Java
Identifiers
28
Chapter 1 Introduction to Java
Literals
29
Chapter 1 Introduction to Java
Constants
Constants
i. Integer Constants
30
Chapter 1 Introduction to Java
mantissa e exponent
Escape Meaning
\n New Line
\t Tab
\b Backspace
\r Carriage Return
\\ Form feed
31
Chapter 1 Introduction to Java
\’ Single quote
\” Double quote
“Hello World”
“This is first and \nThis is second”
“\”I love Java Programming\””
“156….+856”
“India@hotmail.com”
v. Boolean Constants
There are only two logical values that a boolean value can have
i.e. true and false. The values of true and false do not convert into any
numerical representation. The true constant in Java does not equal 1,
nor does the false constant equal 0. In Java, they can only be assigned
to variables declared as boolean, or used in expressions with Boolean
operators.
Separators
These are the symbols which are used to indicate where groups of
codes are divided and arranged. They basically used to define the shape
and function of the program code. The most commonly used separator
is semicolon. All these separators are listed in the table 1.4.
32
Chapter 1 Introduction to Java
Variables
Data Types
33
Chapter 1 Introduction to Java
Data Types
Primitive Derived
Integer type can hold the whole number such as 1822, -521 and
956 etc. Java supports four different type of integer data type as shown
in the table 1.5.
The integer data types supported by Java are byte, short, int and
long. The maximum and minimum values that can be stored in these
are shown in the table. The concept of unsigned data type is discarded
in Java. According the requirement of the programmer he/she can select
the data type in programming.
34
Chapter 1 Introduction to Java
Wider data types require more space and time for manipulation
and it is advisable to use smaller data types, whenever possible. For
example, we are storing a number 100 in integer data type will require
more time and space for manipulation. It can also be stored in a byte
data type. This will improve the speed of execution of program. We can
make the integer long by appending the letter L at the end of the
number. For example: 145L or 145l.
These are generally called as floating point data types. These are
used to hold the numbers containing fractional parts such as 45.23 or
8966.120 etc. In short, real data types are used to store the floating
point constants.
Table 1.6 shows the real data type supported by Java. The float
data type is called as single-precision real number and double is called
as double-precision real number. They require four and eight bytes of
memory respectively.
All the numbers written in a program with fractional point are
treated as double precision numbers. In order to convert them into
single precision, the letter f or F must be appended at the end of the
number. Example:
45852.966f or 45852.966F
35
Chapter 1 Introduction to Java
This is one of the most useful data types of Java. Like bool data
type of C++, Boolean data type is used to store two different values.
But, values stored inside the boolean type will only be true and false. It
cannot have values like 0 or 1. It is used in program to test a particular
condition during the execution. Boolean is denoted by keyword boolean
and uses only one bit of storage. All relational operators (i.e.
comparison operators like <, > etc.) return these boolean values.
Example:
int x;
float avg, cal, s;
char m, yes;
boolean k, jack;
36
Chapter 1 Introduction to Java
variablename = value;
For example:
Pi = 3.14f;
yes = ‘y’;
first = 150;
For example:
float Pi = 3.14f;
char yes = ‘y’;
short first = 150;
37
Chapter 1 Introduction to Java
reference null
int x, y, z;
z = x * y;
System.out.println(z);
After compilation of this code, the compiler will flash following error.
import java.util.Scanner;
After this, the class Scanner will be available for our use in the
program. We have to create the object of scanner in following way.
38
Chapter 1 Introduction to Java
For example:
Scope of variable
39
Chapter 1 Introduction to Java
{ Block1
int x = 0;
{ Block2
-------;
int m = 10;
}
{ Block3
-------;
int y = 55;
}
Operators
1. Arithmetic Operators
2. Assignment Operators
3. Increment / Decrement Operators
4. Relational Operators
5. Logical Operators
6. Conditional Operators
40
Chapter 1 Introduction to Java
7. Special Operators
Arithmetic Operators
These include all the operators which are used to perform basic
arithmetic operations. These are listed in table1.7.
Whereas,
41
Chapter 1 Introduction to Java
Relational Operators
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
36 > 42 true
52.14 < 45 false
10 < 8+9 false
-74 != 0 false
42
Chapter 1 Introduction to Java
Logical Operators
There are only three logical operators which are related with the
logical decisions. These are listed in the table 1.9.
Operator Meaning
&& Logical AND
||Logical OR
!Logical NOT
First two operators are used to combine the conditions i.e. to form a
compound conditional expression. Literally, they have same meaning as in
the digital techniques. Third operator is used to inverse the condition.
For example,
m == 99 || j <= 10
x = 36 then
!(x>40) will return true
!(x==36) will return false
The following program will clear the idea of logical operators and
expressions.
Assignment operators
43
Chapter 1 Introduction to Java
Like C and C++, Java is also having the increment and decrement
operators’ i.e.
++ and ––
x++ or x—-
++x or --x
44
Chapter 1 Introduction to Java
z = 14;
y = z++;
y = ++z;
Conditional Operator
x = 45;
y = 22;
x = (y>25) ? y : 50;
// Conditional operator.
class Conditional
{
public static void main(String args[])
45
Chapter 1 Introduction to Java
{
int x = 25, y = 22;
System.out.println("x = "+x);
System.out.println("y = "+y);
x = (y>25) ? y : 50;
System.out.println("Now, x = "+x);
}
}
Program: Conditional operator.
Output:
x = 25
y = 22
x = (y>25) ? y : 50
Now, x = 50
x = (y>25) ? y : 50;
With
y>25 ? x = 22 : x = 25;
The unexpected type error will occur. This will only work in C/C++
but not in Java.
Bitwise Operators
In order to manipulate the data at the bit level, the bitwise operators
are provided in Java. These operators are used for testing the bits as well
as shifting them to left or right etc. These can be applied to integer types
only. That is, they can not be used along with float or double value. Table
1.11 shows the bitwise operators and their meaning.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise EX-OR
~ One’s complement
<< Left shift
>> Right shift
>>> Right shift with zero fill
46
Chapter 1 Introduction to Java
Special Operators
instanceof operator:
instanceof is the keyword called as an object reference binary
operator. It returns true if the object on the left-hand side is an instance
or object of the class given on the right-hand side. This operator allows
us to determine whether the object belong to particular class or not.
For example:
This operator is also used to access the classes and sub-packages from
packages.
Arithmetic Expressions
47
Chapter 1 Introduction to Java
Arithmetic
Expression Java expression
2
(x+y) (x + y)*(x + y)
2 2
x + y + 5 x * x + y * y + 5
(xy)(m-n) x * y * (m – n)
ab
c a * b / c
x + c
Y (x / y) + c
variable = expression;
a = (x + y)*(x + y);
b = (x / y) + c;
x = a * b / c;
Precedenc Associatio
Operator Description n
e
L to R
1 . Member selection
L to R
() Function call
L to R
[] Array element reference
Postincrement, R to L
2 ++,--
Postdecrement
R to L
3 ++,-- Preincrement, Predecrement
48
Chapter 1 Introduction to Java
x = 10;
y = 22;
z = x++ * 10/y++ - x + y;
49
Chapter 1 Introduction to Java
like, z = 11 * 10/23 – 11 + 23
z = 110/23 – 11 + 23
z = –7 + 23
z = 16
Type conversion
50
Chapter 1 Introduction to Java
// Type promotion
rules class Types
{
public static void main(String args[])
{
byte b = 12; short
s = 866; char c =
'm'; int i =
25397; float f =
145.21f; long l =
865423L; double d
= 6562.24;
double value = (b*s) + (i/c) + (l+d) *
f; System.out.println("b = "+b);
System.out.println("s = "+s);
System.out.println("c = "+c);
System.out.println("i = "+i);
51
Chapter 1 Introduction to Java
System.out.println("f = "+f);
System.out.println("l = "+l);
System.out.println("d = "+d);
System.out.println("b*s = "+(b*s));
System.out.println("i/c = "+(i/c));
System.out.println("l+d = "+(l+d));
System.out.print("(b*s)+(i/c)+(l+d)*f :
"); System.out.print(value);
}
}
Program 1.10 Type Promotion Rules
Output:
b = 12
s = 866
c = m
i = 25397
f = 145.21
l = 865423
d = 6562.24
b*s = 10392
i/c = 233
l+d = 871985.24
(b*s)+(i/c)+(l+d)*f : 1.2663160755479309E8
Type casting
Although the automatic type conversions are helpful, they will not
fulfill all our needs. We often encountered the situation where there is
need to store the value of one type into variable of another type. In
such situations, it is necessary to cast or temporary convert the variable
of one type into another type. It is performed by type casting.
In automatic type conversion always lower type is converted to
higher type. If we want to convert higher type to lower type then type
casting is necessary. For that purpose the type casting operator is used.
This type of conversion is called as narrowing the conversion. It
takes the following form.
(target_type) variable_name;
52
Chapter 1 Introduction to Java
byte b;
int val = 63;
b = (byte) val;
After this both b and val contain value 63. If we write the
statement,
b = val;
// Type casting
class Casting
{
public static void main(String args[])
{
byte b;
int val = 163; b =
(byte) val;
System.out.println(b);
}
}
Program 1.11 Concept of type casting
Output:
-93
Four integer type can be cast to any other type except boolean.
Casting into a smaller type may result in the loss of data. Similarly, float
and double can be cast to nay other except boolean. Casting a floating
point value to an integer will result in the loss of fractional part. Table
1.13 gives the casts that result in no loss of information.
From To
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
53
Chapter 1 Introduction to Java
// Type casting
class TypeCasting
{
public static void main(String args[])
{
byte b;
int val = 263;
double d = 9563.25;
long l = 56322145;
System.out.println("int val = "+val);
System.out.println("double d = "+d);
System.out.println("long l = "+l);
System.out.println("\nint to byte ");
b = (byte) val;
System.out.println(val+" to "+b);
System.out.println("\ndouble to int ");
System.out.println(d+" to "+(int)d);
System.out.println("\nlong to double ");
System.out.println(l+" to "+(double)l);
System.out.println("\nlong to short ");
System.out.println(l+" to "+(short)l);
System.out.println("\ndouble to byte ");
System.out.println(d+" to "+(byte)d);
}
}
Program: More type casting
Output:
54
Chapter 1 Introduction to Java
double to int
9563.25 to 9563
long to double
56322145 to 5.6322145E7
long to short
56322145 to 26721
double to byte
9563.25 to 91
Symbolic Constants
#define Pi 3.145 or
const float Pi = 3.145
The value assigned to the variable name is constant and can not
be changed in any case in the program. At the time of declaration, it is
necessary to assign the value to the variable.
For example:
Programming Style
Java is form-free language. That is, we do not have to indent any
lines to make the program work properly. The Java system does not
take care where on the line we begin typing. This may be the license of
bad programming but can be one of the advantages also.
For example,
55
Chapter 1 Introduction to Java
System.out.println(“Welcome to Java”);
System.out.println
(“Welcome to Java”);
Or even as,
System.
out
.
println(“Welcome
to Java”);
if (condition)
statement;
or
if (condition)
{
statement1;
statement2;
statement3;
56
Chapter 1 Introduction to Java
false
condition
true
1. if(number < 0)
System.out.println(“The number is negative”);
2. if(ch > ‘A’ && ch < ‘Z’)
System.out.println(“It is upper case letter”);
3. if(sell_price > cost_price)
System.out.println(“You made profit”);
57
Chapter 1 Introduction to Java
1. if(condition1)
if(condition2)
statement;
2. if(condition1)
if(condition2)
{
statement1;
statement2;
statement3;
}
3. if(condition1)
{
if(condition2)
{
statement1;
statement2;
statement3;
}
statement4;
}
// Nested ifs
class NestedIf
{
public static void main(String args[])
{
int number = -52;
System.out.println("Number is : "+number);
58
Chapter 1 Introduction to Java
Number is : -52
It is negative & even
The if-else statement defines both the actions which are to be taken
on when condition is true and when condition is false. It is an extension of
general if statement. The general form of if-else statement is:
if(condition)
{
statements for condition is true;
}
else
{
statements for condition is false;
}
Statements after the blocks;
If the condition given is true then the statements inside the if-
block are executed otherwise statement inside else-block are executed.
That is, any one of the statements is executed depending upon the
status of the condition (i.e. true or false).
59
Chapter 1 Introduction to Java
After all the statements written after the blocks are executed
though the condition is true or false. This concept is illustrated in fig.
1.21 with flowchart.
Entry
false
condition
true
Statements under
‘else’ statement
Statements under ‘if’
statement
‘if-else’ structure can also be nested but in such cases ‘if’s must be
matched with respective else. It follows the following syntax:
60
Chapter 1 Introduction to Java
}
}
else //first ‘else’
{
statement6;
}
Statements after the if-else;
false
condition1
true
Statement1 Statement6
false
condition2
true
Statement4
Statement5
Statement2
Statement3
Statements
after the blocks
61
Chapter 1 Introduction to Java
15 is largest
This program finds the largest number among three integers. The
conditions and statements are nested appropriately to find the output.
In any case only one the statements is executed.
The if-else ladder is another way of putting the ‘if’s together when
multi-path decisions are involved. A multi-path decision is a chain of ‘if’s
in which statements are associated with each ‘else’ is an ‘if’. This
construct is known as if-else ladder.
62
Chapter 1 Introduction to Java
if(condition1)
statement1;
else
if(condition2)
statement2;
else
if(condition3)
statement3;
else
statement4;
The conditions are evaluated from top of the ladder to the bottom.
The very familiar example of this construct is to find the grade of the
student according to marks. Such as,
For example examination board is giving grade according to marks
as below:
Marks Grade
Above 75 Distinction
60 to 74 First class
50 to 59 Second class
40 to 49 Pass class
Below 40 Fail
This can be done by applying the if-else ladder as,
if(marks>=75)
grade = “distinction”;
else
if(marks >= 60)
grade = “First class”;
else
if(marks >= 50)
grade = “Second class”;
else
if(marks >= 40)
grade = “Pass class”;
else
grade = “fail”;
63
Chapter 1 Introduction to Java
System.out.println("Marks :
"+marks); System.out.print("Your
grade is : "); if(marks >= 75)
System.out.print("Distinction");
else
if(marks >= 60)
System.out.print("First class");
else
if(marks >= 50)
System.out.print("Second class");
else
if(marks >= 40)
System.out.print("Pass class");
else
System.out.print("Fail");
}
}
Simple if-else ladder
Output:
Marks : 62.12
Your grade is : First class
switch(variable)
{
case value-1:
statements-1;
break;
case value-2:
statements-2;
break;
- - - - - - - - -
- - - - - - - - -
default:
default block;
}
statement-out;
64
Chapter 1 Introduction to Java
variable
default
value-1
value-2
Statement -out
65
Chapter 1 Introduction to Java
System.out.print("It is ");
switch(x)
{
case 1: System.out.println("One");
break;
case 2: System.out.println("Two");
break;
case 3: System.out.println("Three");
break;
case 4: System.out.println("Four");
break;
case 5: System.out.println("Five");
break;
case 6: System.out.println("Six");
break;
case 7: System.out.println("Seven");
break;
case 8: System.out.println("Eight");
break;
case 9: System.out.println("Nine");
break;
case 0: System.out.println("Zero");
break;
default: System.out.println("No. not correct");
}
}
}
The switch-case statement
Output:
x = 6
It is Six
The program displays name of the number of the value of variable ‘x’.
Value of the variable ‘x’ is previously set to 6. When its value is matched
with any of the constants written in front of case label the respective
statements are executed. Always we will get the output as per the value of
variable ‘x’. At least the ‘default’ statement will be executed.
Observe another application based program.
66
Chapter 1 Introduction to Java
System.out.println("2. Odd/Even");
System.out.println("Enter the choice :
"); choice = n.nextInt(); switch(choice)
{
case 1:
System.out.println("Enter number : ");
num = n.nextInt();
if(num > 0)
System.out.println("Positive...");
else
System.out.println("Negative...");
break;
case 2:
System.out.println("Enter number :
"); num = n.nextInt();
if(num%2 == 0)
System.out.println("Even...");
else
System.out.println("Odd...");
break;
default:
System.out.println("Wrong choice..");
}
}
}
Application based switch-case program
Output1:
Menu....
1. Find positive
2. Odd/Even
Enter the choice :
1
Enter number :
-20
Negative...
Output2:
Menu....
1. Find positive
2. Odd/Even
Enter the choice :
2
Enter number :
63
Odd...
67
Chapter 1 Introduction to Java
Remember: When the ‘break’ is not given after any case statement, all
the cases are executed after that until a ‘break’ is not found. Try it.
initialization;
while (condition)
{
//body of the loop;
}
int i = 0;
while(i<10)
{
System.out.println(“I Love Java”);
i++;
68
Chapter 1 Introduction to Java
Initialization
false
condition
true
1. int i = 10;
while(i>0)
{
System.out.println(“I Love
Java”); i--;
}
2. int i = 1;
boolean b =
true; while(b)
{
System.out.println(“I Love
Java”); i++;
if(i>=10)
b = false;
69
Chapter 1 Introduction to Java
Output:
Addition is 55
do
{
//body of the loop;
}
while(condition);
70
Chapter 1 Introduction to Java
Initialization
true
condition
false
int a = 0;
do
{
System.out.println(“I Love Java”);
a++;
}
while(a<10);
This will give the same output as above first example of the while
loop gives to print “I Love Java” for 10 times. Here, if we change the
value of variable ‘a’ to any other value then also the loop will execute as
least once.
Observe another example of do-while which prints the squares of
numbers from 1 to 10.
71
Chapter 1 Introduction to Java
System.out.print("Square of ");
System.out.print(num+" : ");
System.out.println(num*num);
num++;
}
while(num<=10);
}
}
Program using simple do-while loop
Output:
Square of 1 : 1
Square of 2 : 4
Square of 3 : 9
Square of 4 : 16
Square of 5 : 25
Square of 6 : 36
Square of 7 : 49
Square of 8 : 64
Square of 9 : 81
Square of 10 : 100
72
Chapter 1 Introduction to Java
Initialization
false
condition
true
Increment/decrement
73
Chapter 1 Introduction to Java
the value of counter by 1. Each time the value of variable ‘a’ gets
printed onto the screen. When the body of the loop contains only one
statement then it is not necessary to give the curly braces. Same
statement can also be written as,
74
Chapter 1 Introduction to Java
Output:
Enter number : 5
Factorial : 120
n * (n-1) * (n-2) …… 1
So, we have started our loop counter from ‘n’ itself and
decremented it by one until its value becomes less than 1. For storing
the values we have taken one variable ‘fact’ which is initialized to 1 at
the start. After all, in the loop we have just multiplied the loop counter
in the variable ‘fact’. At the end of the loop, the ‘fact’ will contain final
value of factorial of the number ‘n’.
The ‘for’ loop have several additional capabilities which has made
is more beneficial over other looping controls.
1. More than one initialization statements can be written in the ‘for’
statement at a time. But they must be separated by a comma.
For example,
int x = 10;
for(y=0;y<10;y++)
for(x=10, y=0;y<10;y++)
2. A variable can be declared and initialized in the ‘for’ loop itself. But
its scope remains within that loop only.
For example,
for(int y=0;y<10;y++)
here the variable ‘y’ can only be used in the respective ‘for’ loop
only. There is no scope and visibility of this variable outside of the
loop.
75
Chapter 1 Introduction to Java
int x = 5;
for(int a = 10;a<100 || x > 0; a++, y--)
a = 12;
for(;a<100;)
{
a++;
System.out.println(“Welcome”);
}
for(; ;)
{
}
76
Chapter 1 Introduction to Java
-------;
-------;
for(int x = 0;x<10;x++)
{
y = 0;
while(y<10)
{
------;
------;
}
}
-------;
-------;
Here, the ‘for’ loop is called as outer loop and ‘while’ loop is
referred as inner loop. For every iteration of the outer loop, all the
iterations of inner loops are completed. Nesting of the loops is
depending upon the application.
For example, we want to print the following output using ‘for’ loop.
* ****
* ***
* **
* *
*
In this case, the nesting of the loop is must. That is, the outer loop
will have a decrement counter whose value starts from five and moves to
zero. And the inner loop will use this value to print that specific number of
asterisks. This has been solved in the following program.
77
Chapter 1 Introduction to Java
int x, y;
for(x=5;x>0;x--)
{
for(y=x;y>0;y--)
System.out.print("* ");
System.out.println();
}
}
}
Program 1.29 Program to print given asterisks
Output:
* * * * *
* * * *
* * *
* *
*
Jump statements
1. while(condition)
{
------;
------;
if(condition)
break;
------;
------;
}
------;
2. do
{
78
Chapter 1 Introduction to Java
------;
------;
if(condition)
break;
------;
------;
} while(condition);
------;
3. for(;;)
{
------;
------;
if(condition)
break;
------;
------;
}
------;
4. for(;;)
{
------;
while(condition)
{
if(condition)
break;
------;
------;
}
------;
}
------;
Note: When the ‘break’ statement is used in the nested loops. It will
only exit the loop in which it is actually encountered.
79
Chapter 1 Introduction to Java
break;
}
System.out.println("Loop completed...");
}
}
Demonstration of break statement
Output:
10
11
12
13
14
15
Loop completed...
In addition to its uses with the switch statement and loops, the
break statement can also be used to provide a “civilized” form of the
goto statement. Java does not have a goto statement, because it
provides a way to branch in an arbitrary and unstructured manner. This
usually makes goto-ridden code hard to understand and hard to
maintain. It also prohibits certain compiler optimizations. There are,
however, a few places where the goto is a valuable and legitimate
construct for flow control. For example, the goto can be useful when we
are exiting from a deeply nested set of loops. To handle such situations,
Java defines an expanded form of the break statement. By using this
form of break, we can break out of one or more blocks of code. These
blocks need not be part of a loop or a switch. They can be any block.
Further, you can specify precisely where execution will resume, because
this form of break works with a label. As you will see, break gives you
the benefits of a goto without its problems.
The general form of the labeled break statement is,
break label;
80
Chapter 1 Introduction to Java
if(y==5)
break outer;
System.out.print(" "+y+" ");
}
}
System.out.println("Program finished...");
81
Chapter 1 Introduction to Java
}
}
Program to demonstrate the break
Output:
continue;
Initialization
false
condition
true
Statement1
continue
Statements 2
Statements 3
82
Chapter 1 Introduction to Java
1
3
5
7
9
83
Chapter 1 Introduction to Java
0
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
----------------
Review Questions:
• Explain how you are going to compile and execute a Java source file?
• Why Java is called as strictly object-oriented?
• Which are the distinct features which made Java as a platform independent
language?
• What will be the purpose of Java program to be compiled and interpreted?
Give the meaning of following terms:
Java virtual machine
bytecode
• Describe the terms which makes a programming language as object-
oriented?
• Differentiate between object-oriented programming and procedure oriented
programming.
• List any five major C++ features which are removed in the Java.
• Explain any two differences between >> and >>>.
• How to declare symbolic constants in Java?
• Explain the concept of manual and automatic type casting. Why it is
required in the programming?
• Describe the scopes that a Java variable can have.
• Illustrate the use of instanceOf and dot operator with example.
• What are the naming convention rules for a Java identifier?
• Describe different logical and relational operators with example.
• What do you mean by operator precedence and association?
• Differentiate between while and do-while loops.
• Which are the type promotions rules used in the Java expression? Illustrate
with appropriate example.
• Enlist different forms of creating the if-else structure.
• Explain switch-case with the help of flow diagram.
Programming exercise:
1. Input two integer values from keyboard and swap their contents without
using any other temporary variable.
2. Read the price of an item (rupees) in float and display number of paise.
3. Convert the Celsius temperature input from keyboard into its Fahrenheit
equivalent using following formula:
C = (F – 32) /1.8
4. Accept the value of money in rupees and convert it into dollars.
5. Determine the sum of following series:
+ 1/2 + 1/3 + …….. 1/n. take n as input
6. Print the Fibonacci series on the screen by taking n as input from
keyboard:
a. 1 2358……. n
7. Find squares of all the numbers from 1 to n.
8. Accept a number as input and find its sum of digits.
9. Input a number and print it in reverse order.
10. Input a long number from keyboard and count total number of
even digits in it.
11. Find the number of and sum of all the integers greater than 100
and less than 200 that are divisible by 7.
12. Accept marks of 10 different students from keyboard and
analyze it. That is, count total first, second and pass class students.
13. Making the use of continue statement find whether the entered
number is prime or not?
14. Count how many perfect square numbers are also perfect cube
numbers from 1 to 1000.
15. Determine whether the entered number is palindrome or not? (A
palindrome number is read same from both front and back sides such
as 56365, 812218, 121 etc.)
16. Print following output using for loops:
*
**
***
****
17. Count how many perfect square numbers are palindrome
numbers from 1 to 10000.
18. Input the clock time and find the angle made between the ticks
of the analog clock.
19. Accept a number from keyboard and find its roman and binary
equivalent.
20. Find all the natural Armstrong numbers For example: 153 is an
3 3 3
Armstrong number satisfies this property: 153 = 1 + 5 + 3 .