JPR Chapter 1
JPR Chapter 1
College of Engineering(Polytechnic),Pandharpur
Chapter 1
Basic Syntactical constructs in Java
-By
Prashant Shivaji Bhandare
Computer Engineering
SVERI’s College of Engineering(Poly), Pandharpur
Mob: 9579307314 / 7841880095
Email: [email protected]
Syllabus Mr. Bhandare P.S.
2 & Name
Unit no Content
Hours &
Marks
1.1 Java Features and the Java Programming Environment, Object Oriented,
Compiled, Interpreted, Platform independent, Portable, Robust and Secure,
Dynamic.
1.2 Defining a class, creating object, accessing class members
1.3 Java Tokens and Data types, Constants and Symbolic Constants, variables,
dynamic initialization, data types, array and string, scope of variable, typecasting,
Unit I - and standard default values.
Basic Syntactical 1.4 Operators and Expressions, Arithmetic Operators. Relational Operators.
06 Hrs.
constructs in Logical Operators, Increment and Decrement, Conditional Operators, Bit wise
Java 10 Mks.
Operators, Instance of Operators, Dot Operators, Operator precedence and
associativity, Evaluation of Expressions, Type conversions in expressions,
Mathematical Functions - min(),max(), sqrt(), pow(), exp(), round(), abs().
1.5 Decision making and looping: If statement, if else statement, nested if else
statement, if else if ladder, the switch statement, nested switch statement, The
?:operator, The while statement, the Do while statement, the 'for' statement,
break, continue and return statement, nested loops, labeled loops, for-each
version of the for loop.
Assignment no. 1 Mr. Bhandare P.S.
12. Define JDK. List the tools available in JDK explain any one in detail.
4
13. Explain :1) Platform independence 2) Compiled and interpreted features of
Java. (4m)
14. What do mean by typecasting ? When it is needed ?(4M)
Program List
1. Write a program to find sum of digits of number. (4M)
2. Write a program to generate Fibonacci series : 1 1 2 3 5 8 13 21 34 55 89. (4M)
3. Write a program to print reverse of a number. (4M)
4. Write a program to check whether an entered number is prime or not.(4m)
5. Write a program to compute the sum of the digits of a given integer numbers. (4m)
6. Write a program to accept a number as command line argument and print the
number is even or odd (4m)
7. Write a program to accept two numbers as command line arguments and print the
addition of those numbers. (4m)
Mr. Bhandare P.S.
5
About Title of Chapter
Also Student are going to learn features of JAVA which are used
by every Object oriented programming .
Mr. Bhandare P.S.
7 Importance of Chapter
8 Objectives of chapter
By studying this chapter student will able to learn.
1. Write programs to create classes and objects for the given problem.
2. Explain the characteristics of the given Java token.
3. Explain the function of the given operator with example.
4. Construct the expressions using implicit and explicit type conversions to solve the
given problem.
5. Develop the programs using relevant control structure to solve the given problem.
Mr. Bhandare P.S.
Introduction
9
This language was initially called “Oak” but was renamed “Java”in
1995.
1. Java Applets and Applications Mr. Bhandare P.S.
That is, an application created by Java is more or less like one created
using C or C++.
When used to create applications, Java is not much different from any
other computer language.
Rather, it is Java’s ability to create applets that makes it important.
Mr. Bhandare P.S.
An applet is an application designed to be transmitted over the
11 Internet and executed by a Java-compatible Web browser.
In other words, an applet is a program that can react to user input and
dynamically change—not just run the same animation or sound over
and over.
Differentiate between Applet and Application Mr. Bhandare P.S.
12
Java is popular on internet Mr. Bhandare P.S.
3. Before Java World Wide Web was limited to display of still images only.
However, incorporation of Java into web pages has made it capable of
supporting animation graphics, games and wide ranges of special effects.
Mr. Bhandare P.S.
14 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
Mr. Bhandare P.S.
7. Internet users can set up their websites containing Java applet that can be
15 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.
16
The key that allows Java to solve both the security and the portability
problems just described is that the output of a Java compiler is not
executable code.
Rather, it is bytecode.
17
Translating a Java program into bytecode makes it much easier to run
a program in a wide variety of environments because only the JVM
needs to be implemented for each platform.
Once the run-time package exists for a given system, any Java program
can run on it.
Remember, although the details of the JVM will differ from platform to
platform, all understand the same Java bytecode.
the execution of bytecode by the JVM is the easiest way to create truly
portable programs.
Mr. Bhandare P.S.
18 The fact that a Java program is executed by the JVM also helps to make
it secure.
Because the JVM is in control, it can contain the program and prevent it
from generating side effects outside of the system.
19
API Packages Mr. Bhandare P.S.
Most of the time we use the packages available with the the Java API.
The JRE provides the libraries, Java virtual machine, and other components
necessary for you to run applets and applications written in the Java programming
language.
24
Java Virtual Machine (JVM) Mr. Bhandare P.S.
However, the difference between Java and the other compilers is that
Java compiler produces the intermediate code known as bytecode for
the machine that does not exist.
26
Figure shows the process of compilation of a Java program into
bytecode. This is also referred to as virtual machine code.
27
All programming language programs have their own structure of
Mr. Bhandare P.S.
coding.
28
Java is also having its own structure. A Java program may contain many
classes of which only one class defines main method.
Classes contain data members and methods that operate on the data
members of the class.
Documentation Section Mr. Bhandare P.S.
29 This section consists of the set of comments giving name and descriptions of
the program.
It may contain anything that describes the program details but enclosed in
comments. Comment can explain why and what classes and how related to
algorithms.
30
The first statement allowed in a Java program is package statement. Java has
organized library (in-built) classes in the form of packages.
It informs the compiler that the classes defined in the program belong to this
package.
Example: 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.
Mr. Bhandare P.S.
Import Statement
31
This statement is similar to #include statement in C/C++.
As Java has organized the classes in the form of packages, if we want to use
any special class from Java’s library we have to import that class or package
using import statement.
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.
32
Interface can be called as an ‘Abstract Class’ in Java.
35
Simple
Object-oriented
Robust
Multithreaded
Architecture-neutral
Portable
Secure
Interpreted
High performance
Distributed
Dynamic
Simple Mr. Bhandare P.S.
36 Java was designed to be easy for the professional programmer to learn and use
effectively.
Assuming that you have some programming experience, you will not find Java
hard to master.
Best of all, if you are an experienced C++ programmer, moving to Java will
require very little effort.
Because Java inherits the C/C++ syntax and many of the object-oriented
features of C++.
Object-Oriented Mr. Bhandare P.S.
2. The object model in Java is simple and easy to extend, while simple
types, such as integers, are kept as high-performance non objects.
39
8. Java does not support the concept of global variables in any case.
Thus data encapsulation is strictly supported.
Robust Mr. Bhandare P.S.
Thus, the ability to create robust programs was given a high priority
in the design of Java.
To gain reliability, Java restricts you in a few key areas to force you to
find your mistakes early in program development
To better understand how Java is robust, consider two of the main reasons for
Mr. Bhandare P.S.
The Java run-time system comes with an elegant yet sophisticated solution
for multiprocess synchronization that enables you to construct smoothly
running interactive systems.
A multithreaded program contains two or more parts that can run concurrently.
43
Each part of such a program is called a thread, and each thread defines a separate
path of execution.
44 A central issue for the Java designers was that of code longevity and
portability.
At the time of Java’s creation, one of the main problems facing programmers
was that no guarantee existed that if you wrote a program today, it would run
tomorrow—even on the same machine.
Operating system upgrades, processor upgrades, and changes in core system
resources can all combine to make a program malfunction.
The Java designers made several hard decisions in the Java language and the
Java Virtual Machine in an attempt to alter this situation.
Their goal was “write once; run anywhere, any time, forever.” To a great extent,
this goal was accomplished.
Compiled and Interpreted Mr. Bhandare P.S.
45 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.
The only restriction is that the int type must have at least as many bytes as a
short int and cannot have more bytes than a long int. Having a fixed size for
number types eliminates a major porting headache.
Binary data is stored and transmitted in a fixed format, eliminating the “big
endian/little endian” confusion. Strings are saved in a standard Unicode
format.
Mr. Bhandare P.S.
Security
47 Security becomes an important issue for a language that is used for
programming on Internet.
So, Java enables the construction of virus-free, tamper-free systems. Java
systems not only verify all memory access but also ensure that no viruses
are communicated with an application or an applet.
The absence of pointers in Java ensures that programs cannot gain access
to memory locations without proper authorization.
Java has a far stronger security model than ActiveX since it controls the
application as it runs and stops it from wreaking havoc.
48
Java is designed for the distributed environment of the Internet because it
handles TCP/IP protocols.
49
Interpretation of bytecode slowed performance in early versions of Java,
but advanced virtual machines with adaptive and just-in-time (JIT)
compilation and other techniques now typically provide performance up
to 50% to 100% the speed of C++ programs.
50
Java programs carry with them substantial amounts of run-time
type information that is used to verify and resolve accesses to
objects at run time.
51
52 Global Variables
Global variables in C++ program are the sign of a program that was not
designed well enough to encapsulate the data in a sensible way.
Goto
Powerful, well defined exception-handling embedded in Java removed
the need for goto.
Pointers
53
Improper arithmetic of pointers causes most of the bugs in today’s code.
It is trivial error to be “off by one” and smash an errant word past the end
of the intended piece of memory.
You can not dereference an arbitrary memory address. Arrays are real
defined objects, not merely addresses in memory.
Memory Allocation Mr. Bhandare P.S.
55
Liberal use of struct is C’s poor excuse for a compound data type. Types
like int, char * lead to impossibly non-portable code.
Different C++ compilers will reserve 16, 32 or 64 bits for a given type
depending on the natural size of the machine word.
Java object handles include complete information about the class that an
object is an instance of, so it can do a runtime check for type
compatibility, and issue an exception when it fails.
Mr. Bhandare P.S.
Unsafe Arguments List
56 C++ has variable arguments facility (varargs) for the function.
Varargs are a simple extension on the premise that any address can
be mapped to any type leaving the task of checking type up to the
programmer.
Unsafe Structures
57
C attempts to provide encapsulation of data via structure declaration
called struct and polymorphism via a mechanism via union.
These two constructs provide a thin veneer over critical and disastrous
machine dependant alignment and size restrictions.
Preprocessor Hacks
Java manages to do without a preprocessor, relaying on the final
keyword to declare constants formerly created with #define.
Mr. Bhandare P.S.
A Closer Look at the First Sample Program
58
/* This is a simple Java program.
Call this file "Example.java". */
class Example
{
// Your program begins with a call to main().
public static void main(String args[])
{
System.out.println("This is a simple Java
program.");
}
}
Comments Mr. Bhandare P.S.
59
The program begins with the following lines:
/* This is a simple Java program. Call this file "Example.java". */
This is a comment. The contents of a comment are ignored by the compiler.
Instead, a comment describes or explains the operation of the program to anyone
who is reading its source code.
Java supports three styles of comments. The one shown at the top of the program
is called a multiline comment. This type of comment must begin with /* and end
with */.
Anything between these two comment symbols is ignored by the compiler. As the
name suggests, a multiline comment may be several lines long.
Mr. Bhandare P.S.
The next line in the program is the single-line comment, shown here:
60 // Your program begins with a call to main().
The documentation comment begins with a /** and ends with a */.
Class Declaration Mr. Bhandare P.S.
61
The entire class definition, including all of its members, will be between the
opening curly brace ({) and the closing curly brace (}).
The use of the curly braces in Java is identical to the way they are used in C,
C++, and C#.
Mr. Bhandare P.S.
The main line
62
This is necessary since main( ) is called by the Java interpreter before any
objects are made.
The keyword void simply tells the compiler that main( ) does not return a
value.
Mr. Bhandare P.S.
64 The next line of code is shown here. Notice that it occurs inside main( ).
System.out.println("This is a simple Java program.");
This line outputs the string “This is a simple Java program.” followed by
a new line on the screen. Output is actually accomplished by the built-in
println( ) method.
In this case, println( ) displays the string which is passed to it. As you
will see, println( ) can be used to display other types of information,
too.
The line begins with System.out. While too complicated to explain in
detail at this time, briefly, System is a predefined class that provides
access to the system, and out is the output stream that is connected to
the console.
Mr. Bhandare P.S.
65
Notice that the println( ) statement ends with a semicolon.
The reason that the other lines in the program do not end in a
semicolon is that they are not, technically, statements.
Compiling a program Mr. Bhandare P.S.
66
Java Development Kit(JDK) has provided different tools for various
activities.
Among that javac is one of the tool called Java compiler which is used
to compile the Java source file as,
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.
Mr. Bhandare P.S.
Running a program
67 As we have studied, that Java uses compiler san interpreter both.
Our program whose class file is created can be compiled like this,
java HelloWorld
Now interpreter looks for the main method in the program and begins
execution from there.
Java Tokens Mr. Bhandare P.S.
They are:
Identifiers
Keywords
Literals
Operators
Separators
Mr. Bhandare P.S.
The Java character set
70
Smallest units in Java language is characters which are used to write
the tokens.
These characters are defined by the Unicode character set, which is and
emerging standard that tries to create characters for large number of
scripts used worldwide.
In order to give the name for the identifiers, we have to follow following rules:
1. They can have only alphabets, digits, underscore ( _ ) and dollar sign ( $ )
characters.
2. They must not begin with digit. Digit can be placed anywhere except
starting position.
3. Uppercase and lowercase letters are different.
4. They can be of any length.
5. They must not be the keywords.
6. They can have any special symbol in it.
Mr. Bhandare P.S.
2. When the name contains more than one word, the second and
73
subsequent words are marked with leading uppercase characters.
Examples:
findAverage
isLeapYear
grandTotal
3. All private and local variables use only lowercase letters combined
with underscores.
Example:
birth_day
total
avg_marks
Mr. Bhandare P.S.
4. All class and interface names starts with an uppercase letter and each
74 subsequent letter of the word with uppercase letter.
Examples:
HelloJava
FirstClass
Example1
5. Variables that represent constant values use all uppercase letters and
underscores between words.
Examples:
MAX_MARKS
VALUE_OF_PI
GRADE
Generally these Hungarian notations are used to make the Java program
as unique one. These are not considered as ‘rules’.
Literals Mr. Bhandare P.S.
Left to right, the first literal specifies an integer, the next is a floating-
point value, the third is a character constant, and the last is a string. A
literal can be used anywhere a value of its type is allowed.
These are the sequence of characters (i.e. digits, letters and symbols)
that represent constant values to be stored in variables.
Mr. Bhandare P.S.
76
Java specifies five major types of literals.
They are:
I. Integer literals
II. Real literals
III.Character literals
IV.String literals
V. Boolean literals
Constants Mr. Bhandare P.S.
77 Constants are the values which do not change during the execution of
program. Java supports several types of constants as shown in figure
below.
Integer Constants Mr. Bhandare P.S.
78 Integers are probably the most commonly used type in the typical
program.
Examples are 1, 2, 3, and 42. These are all decimal values, meaning they
are describing a base 10 number.
There are two other bases which can be used in integer literals, octal
(base eight) and hexadecimal (base 16).
Octal values are denoted in Java by a leading zero. Examples are 025,
041, 02 etc.
Mr. Bhandare P.S.
Normal decimal numbers cannot have a leading zero.
79 Thus, the seemingly valid value 09 will produce an error from the compiler,
since 9 is outside of octal’s 0 to 7 range.
mantissa e exponent
They are 16-bit values that can be converted into integers and manipulated
with the integer operators, such as the addition and subtraction operators.
All of the visible ASCII characters can be directly entered inside the quotes,
such as ‘x’, ‘k’, and ‘@’.
For characters that are impossible to enter directly, there are several escape
sequences, which allow you to enter the character you need, such as ‘\’’ for
the single-quote character itself, and ‘\n’ for the new-line character.
Mr. Bhandare P.S.
Escape Meaning
\n New Line
\t Tab
\b Backspace
\r Carriage Return
\\ Form feed
\’ Single quote
\” Double quote
String Constants Mr. Bhandare P.S.
One important thing to note about Java strings is that they must begin
and end on the same line. There is no line-continuation escape sequence
as there is in other languages.
85 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.
86 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.
87
Variables Mr. Bhandare P.S.
All keywords are to be written only in lower case letters. Since, Java is
case sensitive; we can use these words as name of variables, classes or
methods by changing their case.
Mr. Bhandare P.S.
90
Whitespace Mr. Bhandare P.S.
This means that you do not need to follow any special indentation rules.
For example, the Example program could have been written all on one
line or in any other strange way you felt like typing it, as long as there
was at least one whitespace character between each token that was not
already delineated by an operator or separator.
92
Primitive types are also called as built in data types and derived
data types are called as reference types.
Integer Data Types Mr. Bhandare P.S.
93 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.
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.
94
Real Data Types Mr. Bhandare P.S.
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.
Character Data Type Mr. Bhandare P.S.
Like C/C++, the keyword char is used to declare character data type
variable.
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 can
not have values like 0 or 1.
In order to use the variables in the program they must declared. The
declaration does three things:
1. It tells the compiler what variable name is.
2. It specifies the data type of the variable.
3. Place of declaration in the program decides the scope of the variable.
A variable must be given a value after it has been declared but before it is used in
100 the expression.
The simple method of giving a value to the variable name is through the
assignment statement as given below:
variablename = value;
For example:
Pi = 3.14f;
yes = ‘y’;
first = 150;
Mr. Bhandare P.S.
It is also possible to assign a value to a variable at the time of declaration.
101 This takes the following form:
datatype variablename = value;
For example:
float Pi = 3.14f;
char yes = ‘y’;
short first = 150;
These default values of various data types are listed in following table.
By reading from the keyboard Mr. Bhandare P.S.
103 We may also give values to the variables through by using various
classes and their methods.
This class is defined in one of the library package of Java i.e. java.util.
105
For example:
Scanner in = new Scanner(System.in);
int x;
System.out.println(“Enter a number: ”);
x = in.nextInt();
Other useful classes are also there which are used for reading the data
from keyboard such as, DataInputStream, BufferedInputStream,
BufferedReader etc.
Scope of variable Mr. Bhandare P.S.
106 Basically, the Java variables are categorized into three types:
Instance variables
Local variables
Class variables
They are created when the objects of the class are created and therefore they
are associated with the objects.
It is not necessary to initialize all the instance variables; they will contain the
default values.
Mr. Bhandare P.S.
The scope defined by a method begins with its opening curly brace.
107
However, if that method has parameters, they too are included within
the method’s scope.
Asa general rule, variables declared inside a scope are not visible (that
is, accessible) to code that is defined outside that scope.
Thus, when you declare a variable within a scope, you are localizing
that variable and protecting it from unauthorized access and/or
modification.
Scopes can be nested. For example, each time you create a block of
code, you are creating a new, nested scope.
108 According to the types of variables, the
scopes of the Java program have
following types:
Block scope
Class scope
109 An operator is the symbol that takes one or more arguments and
operates on them to produce a result.
Types of Operator:
1. Unary: Required one operand.
2.Binary : required two operands
3.Ternary : required 3 operands
Mr. Bhandare P.S.
Different operators available in java
110
1. Arithmetic Operators
2. Assignment Operators
3. Increment / Decrement Operators
4. Relational Operators
5. Logical Operators
6. Conditional Operators
7. Special Operators
Arithmetic Operators Mr. Bhandare P.S.
111
Mr. Bhandare P.S.
Assignment operators
Increment and Decrement operators Mr. Bhandare P.S.
114 Like C and C++, Java is also having the increment and decrement
operators’ i.e.
++ and – –
Both of these are unary operators. The operator ++ adds 1 to the
operand and – – subtracts 1 from the operand.
They are only associated with the variable name, not with the constant
or the expression.
115 The only ternary operator (operator having three operands) is defined
in Java called as conditional operator.
116 Programming languages such as C and C++ are also having this operator.
But, there is some difference between them.
The conditional expression used in C++ and C, will not be assigned or
used anywhere. But in Java, the independent conditional expression’s
return value must be assigned or used in the program.
For example,
x = 45;
y = 22;
x = (y>25) ? y : 50;
After completion of third statement execution, value of x will become 50.
Because, the condition y>25 is false so first expression will not be
executed.
Only second expression is evaluated. That is, 50 will be assigned to
variable x.
// Conditional operator. Mr. Bhandare P.S.
117
class Conditional
{
public static void main(String args[])
{
int x = 25, y = 22;
System.out.println("x = "+x);
System.out.println("y = "+y);
x = (y>25) ? y : 50;
System.out.println("x = (y>25) ? y : 50");
System.out.println("Now, x = "+x);
}
}
Bitwise Operators Mr. Bhandare P.S.
118 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.
Mr. Bhandare P.S.
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:
maharashtra instanceof India
Returns true if the object ‘maharashtra’ is the object of class ‘India’.
Otherwise it will return false.
Mr. Bhandare P.S.
For example:
company.salary() //reference to method salary
company.employee //reference to variable employee
This operator is also used to access the classes and sub-packages from
packages.
Mr. Bhandare P.S.
Precedence and Associativity of operators
122 Precedence Operator Description Associativity
[] array index
1 () method call Left -> Right
. member access
pre or postfix increment
++
pre or postfix decrement
--
unary plus, minus
2 +- Right -> Left
bitwise NOT
~
logical NOT
!
type cast
(type cast)
3 object creation Right -> Left
new
* multiplication
4 / division Left -> Right
% modulus (remainder)
+- addition, subtraction
5 Left -> Right
+ string concatenation
Mr. Bhandare P.S.
left shift
123 <<
signed right shift
6 >> Left -> Right
unsigned or zero-fill
>>>
right shift
< less than
<= less than or equal to
7 > greater than Left -> Right
>= greater than or equal to
instanceof reference test
== equal to
8 Left -> Right
!= not equal to
9 & bitwise AND Left -> Right
10 ^ bitwise XOR Left -> Right
11 | bitwise OR Left -> Right
12 && logical AND Left -> Right
13 || logical OR Left -> Right
14 ?: conditional (ternary) Right -> Left
Type conversion (Type Casting) Mr. Bhandare P.S.
124
Java permits mixing of constants and variables of different types in an
expression.
But during the evaluation is follows very strict rules of type conversion as we
have already studies that Java is strictly types language.
126 When one type of the data is assigned to another type of variable, automatic
type conversion takes place if following two conditions are met.
1. Two types are compatible.
2. Destination type is larger than source type.
When these two conditions are met, a widening conversion takes place. While
automatic type conversion, following factors are to be considered.
128 In Java, type casting is a method or process that converts a data type into
another data type in both ways manually and automatically. The automatic
conversion is done by the compiler and manual conversion performed by the
programmer.
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.
byte -> short -> char -> int -> long -> float -> double
Mr. Bhandare P.S.
Narrowing Type Casting
131 Converting a higher data type into a lower one is called narrowing type casting.
double -> float -> long -> int -> char -> short -> byte
Here, target_type specifies the desired type to convert the specified value to.
Mr. Bhandare P.S.
132 For example, if we want to convert byte to int or long it will take following
form.
byte b;
int val = 63;
b = (byte) val;
After this both b and val contain value 63. If we write the statement,
b = val;
Then the following error will occur,
possible loss of precision
found : int
required: byte
Decision making and branching Mr. Bhandare P.S.
133 Control flow is the heart of any program. It is the ability to adjust (or to
control) the way that program progresses.
136
Nested ifs Mr. Bhandare P.S.
138
The if-else-if Ladder Mr. Bhandare P.S.
A common programming construct that is based upon a sequence of nested ifs is the
139
if-else-if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
Mr. Bhandare P.S.
If none of the conditions is true, then the final else statement will be
executed.
The final else acts as a default condition; that is, if all other conditional tests
fail, then the last else statement is performed.
If there is no final else and all other conditions are false, then no action will
take place
switch Mr. Bhandare P.S.
Generally, it is used to create the menu driven program to select from the
multiple choices.
143 The expression must be of type byte, short, int, or char; each of the values
specified in the case statements must be of a type compatible with the expression.
Each case value must be a unique literal (that is, it must be a constant, not a
variable). Duplicate case values are not allowed.
The switch statement works like this: The value of the expression is compared
with each of the literal values in the case statements.
If a match is found, the code sequence following that case statement is executed.
If none of the constants matches the value of the expression, then the default
statement is executed
Mr. Bhandare P.S.
144
Nested switch Statements Mr. Bhandare P.S.
145 You can use a switch as part of the statement sequence of an outer switch.
This is called a nested switch.
Since a switch statement defines its own block, no conflicts arise between
the case constants in the inner switch and those in the outer switch
switch(count) { System.out.println("target is one");
case 1: break;
switch(target) { // nested switch }
case 0: break;
System.out.println("target is zero"); case 2: // ...
break;
case 1: // no conflicts with outer
switch
Mr. Bhandare P.S.
Iteration Statements (Decision making and looping )
146
Java’s iteration statements are for, while, and do-while.
These statements create what we commonly call loops.
As you probably know, a loop repeatedly executes the same set of
instructions until a termination condition is met.
Java has a loop to fit any programming need.
In the process of looping, a sequence of statement is executed until some
condition of termination of the loop is satisfied.
Types of Loops:
1. Entry controlled loop: for, while
2. Exit controlled l lop: do-while
while Mr. Bhandare P.S.
When condition becomes false, control passes to the next line of code
immediately following the loop.
The body of the while (or any other of Java’s loops) can be empty.
148
This is because a null statement (one that consists only of a semicolon) is
syntactically valid in Java.
For example, consider the following program:
// The target of a loop can be empty.
class NoBody {
public static void main(String args[]) {
int i, j; i = 100; j = 200;
// find midpoint between i and j
while(++i < --j) ; // no body in this loop
System.out.println("Midpoint is " + i);
}}
This program finds the midpoint between i and j. It generates the following
output: Midpoint is 150
Mr. Bhandare P.S.
149
do-while Mr. Bhandare P.S.
150 As you just saw, if the conditional expression controlling a while loop is
initially false, then the body of the loop will not be executed at all.
In other words, there are times when you would like to test the
termination expression at the end of the loop rather than at the beginning.
The do-while loop always executes its body at least once, because its
conditional expression is at the bottom of the loop.
Mr. Bhandare P.S.
Its general form is
151 do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop
and then evaluates the conditional expression.
If this expression is true, the loop will repeat. Otherwise, the loop
terminates.
152
for Mr. Bhandare P.S.
153 The ‘for’ loop is another entry-controlled loop, that provides a more concise loop
control structure.
154
Mr. Bhandare P.S.
157 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++)
this can also be written as,
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.
E.g. 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.
Mr. Bhandare P.S.
3. The condition part can also have combination of the conditions using
158 logical operators which returns values true or false. They can not be
separated using comma as in the initialization section.
E.g. for(int i=0, a = 10;i<10 && a >0;a++)
in this example if both of the conditions are evaluated to true then only
the loop is executed.
this statement of the loop will work properly in these languages. It will
be executed for 10 times. That is, it will be executed until value of the
variable ‘a’ reaches to zero.
For-each version of for loop Mr. Bhandare P.S.
163 Sometimes while executing the loop it is necessary to skip some part of
the loop or exit from the loop when certain conditions are met.
Java supports three jump statements: break, continue, and return. These
statements transfer control to another part of your program.
1. break statement.
2. continue statement.
3. Return
Using break Mr. Bhandare P.S.
3. Third, it can be used as a “civilized” form of goto. The last two uses
are explained here.
Using break to Exit a Loop Mr. Bhandare P.S.
165
By using break, you can force immediate termination of a loop, bypassing the
conditional expression and any remaining code in the body of the loop.
When a break statement is encountered inside a loop, the loop is terminated and
program control resumes at the next statement following the loop.
Here are two other points to remember about break. First, more than one break
statement may appear in a loop.
Second, the break that terminates a switch statement affects only that switch
statement and not any enclosing loops.
Generally, the ‘break’ statement is associated with an ‘if’ statement. That is, when
the condition is satisfied, the jump will occur.
Mr. Bhandare P.S.
167
In addition to its uses with the switch statement and loops, the break statement can
also be employed by itself 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.
The goto is a valuable and legitimate construct for flow control. The goto can be
useful when you are exiting from a deeply nested set of loops.
By using this form of break, you 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.
Mr. Bhandare P.S.
Further, you can specify precisely where execution will resume, because
168 this form of break works with a label.
The labeled block must enclose the break statement, but it does not
need to be the immediately enclosing block.
Mr. Bhandare P.S.
And, the control goes to the first statement right after the loop.
Syntax of Labelled loop Mr. Bhandare P.S.
170
Mr. Bhandare P.S.
That is, you might want to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration.
This is, in effect, a goto just past the body of the loop, to the loop’s end.
The continue statement performs such an action. In while and do-while loops,
a continue statement causes control to be transferred directly to the
conditional expression that controls the loop.
In a for loop, control goes first to the iteration portion of the for statement and
then to the conditional expression.
For all three loops, any intermediate code is bypassed.
Mr. Bhandare P.S.
// Demonstrate continue.
174 class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}
Labelled Continue Mr. Bhandare P.S.
175
When this continue statement is encountered with the label/name
of the loop, it skips the execution any statement within the loop for
the current iteration and continues with the next iteration and
condition checking in the labelled loop.
As with the break statement, continue may specify a label to describe which
Mr. Bhandare P.S.
Here, return causes execution to return to the Java run-time system, since
it is the run-time system that calls main().
// Demonstrate return. Mr. Bhandare P.S.
180 Java Math class provides several methods to work on math calculations like
min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
Unlike some of the StrictMath class numeric methods, all implementations of the
equivalent function of Math class can't define to return the bit-for-bit same
results.
Math.pow() It returns the value of first argument raised to the power to second
argument.
Math.signum() It is used to find the sign of a given value.
Math.ceil() It is used to find the smallest integer value that is greater than or
equal to the argument or mathematical integer.
Mr. Bhandare P.S.
Method Description
Math.log1p() It returns the natural logarithm of the sum of the argument and 1.
Math.expm1() It is used to calculate the power of E and subtract one from it.
Trigonometric Math Methods Mr. Bhandare P.S.
183
Method Description
Math.sin() It is used to return the trigonometric Sine value of a Given double value.
Math.cos() It is used to return the trigonometric Cosine value of a Given double value.
Math.asin() It is used to return the trigonometric Arc Sine value of a Given double value
Math.acos() It is used to return the trigonometric Arc Cosine value of a Given double
value.
Math.atan() It is used to return the trigonometric Arc Tangent value of a Given double
value.
Mr. Bhandare P.S.
Summer 2017
184 State and explain any four features of Java. (4m)
Explain any two relational operators in Java with example. (4m)
Write a program to find sum of digit of number entered by user.(4m)
Write all primitive data types available in Java with their storage sizes in
bytes.(4m)
Write a program to generate Fibonacci series 1 1 2 3 5 8 13 21 34 55 89.
(4m)
Differentiate between Applet and Application (any 4 points).
Mr. Bhandare P.S.
Winter 2016
185 How java is different than other programming language ? (4m)
State syntax and describe working of ‘for each’ version of for loop with one
example. (4m)
Mr. Bhandare P.S.
Summer 2016
186 Describe any two relational and any two logical operators in Java with simple
example. (4m)
Write general syntax of any two decision making statements and also give its
examples.(4m)
Write a program to compute the sum of the digits of a given integer numbers.
(4m)
Write any two methods of file and file input stream class each.(4m)
Write a program to accept a number as command line argument and print the
number is even or odd.(4m)
Define JDK. List the tools available in JDK explain any one in detail. (4m)
Winter 2014 Mr. Bhandare P.S.