0% found this document useful (0 votes)
34 views189 pages

JPR Chapter 1

The document provides an introduction to basic syntactical constructs in Java, covering features, data types, operators, decision-making, and looping. It outlines the syllabus, objectives, and importance of learning Java, along with assignments and programming exercises. Additionally, it discusses the Java programming environment, including the Java Virtual Machine (JVM), bytecode, and the distinction between Java applications and applets.

Uploaded by

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

JPR Chapter 1

The document provides an introduction to basic syntactical constructs in Java, covering features, data types, operators, decision-making, and looping. It outlines the syllabus, objectives, and importance of learning Java, along with assignments and programming exercises. Additionally, it discusses the Java programming environment, including the Java Virtual Machine (JVM), bytecode, and the distinction between Java applications and applets.

Uploaded by

pratusathe16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 189

SVERI’s

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.

3 1. How java is different than other programming language ? (4m)


2. What is scope of variable ? Give example of class variable, instance variable and
local variable. (4m)
3. Explain break and continue statements with example.(4m)
4. State syntax and describe working of ‘for each’ version of for loop with one
example. (4m)
5. Describe any two relational and any two logical operators in Java with simple
example. (4m)
6. State and explain any four features of Java. (4m)
7. In what ways does a switch statement differ from an if statements ? (4m)
8. Describe?, : (Ternary operator) in Java with suitable example. (4m)
9. Explain any two bit-wise operators with example. . (4m)
10. What is JVM ? What is byte code ? (4m)
11. Differentiate applet and application with any four points (4m) 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

The title of chapter “Introduction to Java” gives idea that in this


chapter students are going to learns basic things needed for
creating any type of JAVA Programs.

Also Student are going to learn features of JAVA which are used
by every Object oriented programming .
Mr. Bhandare P.S.

6 About Central Idea of Chapter

The central idea of the chapter is that the concept of OOP


languages are discussed here and implemented in further
chapters.

Also basic of every programming are included in this chapter


like tokens, loos, decision making statements etc.
Mr. Bhandare P.S.

7 Importance of Chapter

This chapter is important because it gives introduction to new


programming language JAVA.

Also this chapter is important as it includes every basic things


needed for creating programming in JAVA language.

Also it includes study of different java environments.


Mr. Bhandare P.S.

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

Java was conceived by James Gosling, Patrick Naughton, ChrisWarth, Ed


Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991.

It took 18 months to develop the first working version..

This language was initially called “Oak” but was renamed “Java”in
1995.
1. Java Applets and Applications Mr. Bhandare P.S.

10  Java can be used to create two types of programs: applications and


applets.

 An application is a program that runs on your computer, under the


operating system of that computer.

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

 An applet is actually a tiny Java program, dynamically downloaded


across the network, just like an image, sound file, or video clip.

 The important difference is that an applet is an intelligent program,


not just an animation or media file.

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

13  The Java programming language is popular on internet due to the following


reasons:

 1. Java is meant to be used in distributed environments such as internet.


Since both web and Java share the same philosophy, Java could be easily
incorporated into the web system.

 2. Java is a platform independent language. Its all applications can run as it on


various operating systems.

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

 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.
Java’s Magic: The Bytecode Mr. Bhandare P.S.

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.

 Bytecode is a highly optimized set of instructions designed to be


executed by the Java run-time system, which is called the Java Virtual
Machine (JVM).

 In essence, the original JVM was designed as an interpreter for


bytecode.
Mr. Bhandare P.S.

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.

 The Java compiler creates a bytecode. This is the machine independent


code so; it can be executed on any machine.

 That is if you have created this bytecode on Windows operating system


then it can be executed on Linux operating system.
Mr. Bhandare P.S.

19
API Packages Mr. Bhandare P.S.

20  Java APl(Application Program Interface) provides a large


numbers of classes grouped into different packages according to
functionality.

 Most of the time we use the packages available with the the Java API.

 Following figure shows the system packages that are frequently


used in the programs.
Mr. Bhandare P.S.
Java System Packages and Their Classes
21
java.lang Language support classes. They include classes for primitive types,
string, math functions, thread and exceptions.
java.util Language utility classes such as vectors, hash tables, random
numbers, data, etc.
java.io Input/output support classes. They provide facilities for the input
and output of data.
java.applet Classes for creating and implementing applets.
java.net Classes for networking. They include classes for communicating
with local computers as well as with internet servers.
java.awt Set of classes for implementing graphical user interface. They
include classes for windows, buttons, lists, menus and so on.
Mr. Bhandare P.S.
JRE and JDK
22
 Oracle provides two principal software products in the Java™ Platform, Standard
Edition (Java™ SE) family: Java SE Runtime Environment (JRE)

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

 This runtime environment can be redistributed with applications to make them


free-standing.
Mr. Bhandare P.S.
Java SE Development Kit (JDK)
23  The JDK includes the JRE plus command-line development tools such as compilers
and debuggers that are necessary or useful for developing applets and applications.
Tool name Description
javac The compiler for the Java programming language.
java The launcher for Java applications. In this release, a single launcher is used both for
development and deployment. The old deployment launcher, jre, is no longer
provided.
javadoc API documentation generator.
appletviewer Run and debug applets without a web browser.

jar Manage Java Archive (JAR) files


jdb The Java Debugger.
javah C header and stub generator. Used to write native methods.
javap Class file disassembler
Description of Java Conceptual Diagram Mr. Bhandare P.S.

24
Java Virtual Machine (JVM) Mr. Bhandare P.S.

25  All the programming language compilers translate the source code


into machine code. Java compiler also performs the same function.

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

 This machine is called as Java Virtual Machine. It exists only inside


the computer memory.

 It is a simulated computer within the computer and does all the


functions of the computer.
Mr. Bhandare P.S.

26
 Figure shows the process of compilation of a Java program into
bytecode. This is also referred to as virtual machine code.

Process of compilation of Java program


The virtual machine code is not machine specific. Java interpreter generates this
code by acting as an intermediary between the virtual machine and real
machine as shown in the figure.

Process of converting bytecode into machine code


Java Program Structure Mr. Bhandare P.S.

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.

 This helps to maintain ‘program’. In addition to single line and multi-line


comments discussed earlier Java add third style of comments (/**……*/)
called as documentation comments.

 This form of comments is used for generating the documentation


automatically. Documentation section is not compulsory for all programs but
suggested to use to increase the readability of program.
Package Statement Mr. Bhandare P.S.

30
 The first statement allowed in a Java program is package statement. Java has
organized library (in-built) classes in the form of packages.

 Thus, package can be called as a group of classes. If we want to declare our


program as one of the part of the package, package statement is used.

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

 Example: 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 Mr. Bhandare P.S.

32
 Interface can be called as an ‘Abstract Class’ in Java.

 It contains group of method declarations.

 This is also optional statement and used only when we wish to


implement the multiple inheritance feature in the program.
Class Definitions Mr. Bhandare P.S.

33  A Java program may contain multiple class definitions.

 Classes are the primary and essential elements of a Java program.

 All methods and variables that we declare in program must be the


part of a class.

 By creating objects of it, we can call method with particular object.

 The number of classes used depends on the complexity and deepness


of the problem.
Main method class Mr. Bhandare P.S.

34  Programs in all programming languages are having the starting point.


Since, every Java program requires a main method as the starting
point.

 This class is the essential part of a Java program.

 A simple Java application program may contain only this part.

 The main method creates objects of various classes and establishes


communication between them.

 Program execution starts in main and also ends in main.


Features of Java Mr. Bhandare P.S.

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.

 If you already understand the basic concepts of object-oriented programming,


learning Java will be even easier.

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

37  Java is strictly or truly object-oriented language due to the following


reasons.
1. Everything in Java is considered as the object including the source
program because it is written in a class itself.

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.

3. Java implements all of the features of Object oriented programming


including inheritance, polymorphism, dynamic binding etc. An
extensive class library is also available in the core language packages
Mr. Bhandare P.S.

4. The library of Java is created in terms of package. It is a collection of


38
similar working classes. The methods are defined in the classes. In
order to use these methods we need to import the package in our
program.

5. The Java class library (API) itself implemented inheritance of classes


in order to re-use the code. Thus simplifying the program also.

6. Most of the methods and constructors of the Java classes are


overloaded. That is, Java itself implements the property of
polymorphism in large extent.
Mr. Bhandare P.S.

39

7. Java does not support the multiple inheritance to avoid the


duplication of data. But multiple inheritance in supported by the
way of ‘interface’. Using interface, we can create the multiple
inheritance by avoiding duplication of data.

8. Java does not support the concept of global variables in any case.
Thus data encapsulation is strictly supported.
Robust Mr. Bhandare P.S.

40  The multiplatformed environment of the Web places extraordinary


demands on a program, because the program must execute reliably
in a variety of systems.

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

program failure: memory management mistakes and mishandled exceptional


41 conditions (that is, run-time errors).

 Memory management can be a difficult, tedious task in traditional


programming environments. For example, in C/C++, the programmer will often
manually allocate and free all dynamic memory.

 Java virtually eliminates these problems by managing memory allocation and


deallocation for you.

 Exceptional conditions in traditional environments often arise in situations


such as division by zero or “file not found,” and they must be managed with
clumsy and hard-to-read constructs.

 Java helps in this area by providing object-oriented exception handling.


Mr. Bhandare P.S.
Multithreaded
42  Java was designed to meet the real-world requirement of creating
interactive, networked programs.

 To accomplish this, Java supports multithreaded programming, which


allows you to write programs that do many things simultaneously.

 The Java run-time system comes with an elegant yet sophisticated solution
for multiprocess synchronization that enables you to construct smoothly
running interactive systems.

 Java’s easy-to-use approach to multithreading allows you to think about the


specific behavior of your program, not the multitasking subsystem
Mr. Bhandare P.S.

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

 Thus, multithreading is a specialized form of multitasking.

 Java has a strong support of multithreaded programming.

 Implementation of multithreading in Java is simpler than any other languages that


implements it.

 It makes the use of multithreading features of current platform or operating


system
Architecture-Neutral (Platform independance) Mr. Bhandare P.S.

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.

 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.
Portable Mr. Bhandare P.S.

46  Unlike C and C++, there are no “implementation-dependent” aspects of the


specification in Java.
 The sizes of the primitive data types are specified, as is the behavior of
arithmetic on them.
 For example, an int in Java is always a 32-bit integer.
 In C/C++, int can mean a 16-bit integer, a 32-bit integer, or any other size that
the compiler vendor likes.

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

 It also contains security manager class that determines what resources a


class can access such as reading and writing to the local disk.
Distributed Mr. Bhandare P.S.

48
 Java is designed for the distributed environment of the Internet because it
handles TCP/IP protocols.

 In fact, accessing a resource using a URL is not much different from


accessing a file.

 Java also supports Remote Method Invocation (RMI).

 This feature enables a program to invoke methods across a network.

 The original version of Java (Oak) included features for intra-address


space messaging. This allowed objects on two different computers to
execute procedures remotely.
High Performance Mr. Bhandare P.S.

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.

 This technology is being improved continuously and may eventually yield


results that cannot be matched by traditional compilation systems.

 Java architecture is also designed to reduce overheads during runtime.


Dynamic Mr. Bhandare P.S.

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.

 This makes it possible to dynamically link code in a safe and


expedient manner.

 This is crucial to the robustness of the Java environment, in which


small fragments of bytecode may be dynamically updated on a
running system.
Extensible Mr. Bhandare P.S.

51

 Java program supports function written in other languages such as


C/C++. These functions are known as native methods.

 This facility enables the programmer to use efficient functions available


in other languages.

 Native methods are linked dynamically at run time.


How Java is better than C++ Mr. Bhandare P.S.

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.

 In Java, the only global name space is the class hierarchy. It is


impossible to create global variables outside the classes.

 Goto
Powerful, well defined exception-handling embedded in Java removed
the need for goto.

This lack of an arbitrary branch statement allows the compiler to


create more optimal code while still maintaining robustness and safety.
Mr. Bhandare P.S.

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

 A “memory smash” is one of the most egregious of errors to detect and


debug.

You can not convert an integer to pointer.

You can not dereference an arbitrary memory address. Arrays are real
defined objects, not merely addresses in memory.
 Memory Allocation Mr. Bhandare P.S.

54 Memory Management in C and thus C++, is realized the malloc() and


free() library functions.
Memory leaks with these functions causes a gradual slowdown of your
program as it runs, while these unused garbage pages of memory are
swapped to disk by the virtual memory system.
 Java has no malloc() and free() functions.
Since, every complex data structure is an object, they are allocated via
the new operator, which allocates space for an object on the heap of
memory.
You don’t have to call free or delete.
The garbage collector Chapter 1 Introduction to Java runs whenever the
system is idle, or when a requested allocation fails to find enough
memory.
 Fragile Data Types 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.

 Unsafe Type Casting


Since objects in C++ are merely pointers to memory addresses, there is
no way at runtime to detect if type cast is incompatible.

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

 Separate Header Files


There are no header files in Java.
 The type and visibility of class members is compiled into the Java
class file.
The Java interpreter enforces access control at runtime. So, there is
no way to access the private variables outside the class.
Mr. Bhandare P.S.

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

Java does not have struct or union construct.

 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().

 This is the second type of comment supported by Java. A single-line


comment begins with a // and ends at the end of the line.

 As a general rule, programmers use multiline comments for longer


remarks and single-line comments for brief, line-by-line descriptions.

 The third type is called a documentation comment.

 This type of comment is used to produce an HTML file that documents


your program.

 The documentation comment begins with a /** and ends with a */.
Class Declaration Mr. Bhandare P.S.

61

 The next line of code in the program is shown here:


class Example {
 This line uses the keyword class to declare that a new class is being defined.

 Example is an identifier that is the name of the class.

 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

 The next line of code is shown here:


public static void main(String args[]) {

 All Java applications begin execution by calling main( ).

The public keyword is an access specifier, which allows the


programmer to control the visibility of class members.

When a class member is preceded by public, then that member


may be accessed by code outside the class in which it is declared.
Mr. Bhandare P.S.

63  (The opposite of public is private, which prevents a member from being


used by code defined outside of its class.)

 In this case, main( ) must be declared as public, since it must be called by


code outside of its class when the program is started.

 The keyword static allows main( ) to be called without having to


instantiate a particular instance of the class.

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

 All statements in Java end 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.

 In the second stage of execution, we need to execute the program using


Java interpreter.

 Java interpreter is a stand-alone program.

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

68  A smallest individual element in a program is called as token.

 A Java application program is collection of classes.

 A class is defined by a set of declaration statements and methods


containing executable statements.

 Most of the statements contain expressions, which describes the


action carried out on data.

 The compiler recognizes the tokens for building up expressions and


statements.
Mr. Bhandare P.S.

69  In general, a Java program is collection of different tokens, comments,


separators and white spaces.

 Java includes five different types of tokens.

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

Forming a Java Program


Identifiers Mr. Bhandare P.S.

71  Identifiers are the programmer-designed tokens.


 They are used for naming variables, classes, methods, objects, labels, packages
and interfaces in a program.

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

72  Identifier’s name must be meaningful, short enough to be quickly and


easily typed and long enough to be easily read.

 Java developers have followed some naming conventions rules which


are also called as Hungarian notations.

 Java library has also implemented these notations.

1. Name of all public methods and instance variables start with a


lowercase letter.
Examples:
 calculate
 string
 display
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.

75  A constant value in Java is created by using a literal representation of it.

 For example, here are some literals:


100 98.6 ‘X’ “This is a test”

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

 Any whole number value is an integer literal.

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

 A more common base for numbers used by programmers is hexadecimal,


which matches cleanly with modulo 8 word sizes, such as 8, 16, 32, and 64
bits.

 You signify a hexadecimal constant with a leading zero-x, (0x or 0X).

 The range of a hexadecimal digit is 0 to 15, so A through F (or a through f )


are substituted for 10 through 15.

 Examples are 0x4A, 0x85, 0xF9 etc.


Floating-point Constants Mr. Bhandare P.S.

80  These are also called as real constants.


 Floating-point numbers represent decimal values with a fractional
component.
 They can be expressed in either standard or scientific notation.

 Standard notation consists of a whole number component followed by a


decimal point followed by a fractional component.

 For example, 2.000, 53.19259, and 0.6667 represent valid standard-


notation floating-point numbers.

 Scientific notation uses a standard-notation, floating-point number plus a


suffix that specifies a power of 10 by which the number is to be multiplied.
Mr. Bhandare P.S.

 The exponent is indicated by an E or e followed by a decimal number,


81 which can be positive or negative.

 It is expressed in following format:

mantissa e exponent

 Where mantissa is either a real number expressed in decimal notation


or integer.

 The exponent is an integer with an optional + or – sign.

 Examples: 6.0032E23, 314159E–05, and 2e+100.


Character Constants Mr. Bhandare P.S.

82  Characters in Java are indices into the Unicode character set.

 They are 16-bit values that can be converted into integers and manipulated
with the integer operators, such as the addition and subtraction operators.

 A literal character is represented inside a pair of single quotes.

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

 Following are the escape sequences used in Java.


83

Escape Meaning
\n New Line

\t Tab

\b Backspace

\r Carriage Return

\\ Form feed

\’ Single quote

\” Double quote
String Constants Mr. Bhandare P.S.

84  String constants in Java are specified as they are in most other


languages—by enclosing a sequence of characters between a pair of
double quotes.
 Examples of string literals are:
 “Hello World”
“This is first and \nThis is second”

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

 C/C++ implements the string as array of characters, but in Java it is not


the case. Here, string is the object type.
Boolean Constants Mr. Bhandare P.S.

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.

 In Java, they can only be assigned to variables declared as boolean, or


used in expressions with Boolean operators.
Separators Mr. Bhandare P.S.

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.

 The most commonly used separator is semicolon.

 All these separators are listed in the table


Mr. Bhandare P.S.

87
Variables Mr. Bhandare P.S.

88  A variable is an identifier that denotes a storage location used to store


the data value. Unlike constants that may remain unchanged during
execution of the program, a variable may take different values at
different times during execution of program.

 A variable name is chosen by the programmer in meaningful way so as


to reflect what it represents in the program.
Example:
 total_marks , calci , average , inventory etc.

 Remember a variable must be a valid identifier name which will follow


all the rules of its creation as studied earlier.
The Java Keywords Mr. Bhandare P.S.

89  There are 49 reserved keywords currently defined in the Java language.

 These keywords, combined with the syntax of the operators and


separators, form the definition of the Java language.

 These keywords cannot be used as names for a variable,

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

91  Java is a free-form language.

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

 In Java, whitespace is a space, tab, or newline


Data Types Mr. Bhandare P.S.

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.

 The concept of unsigned data type is discarded in Java.


Mr. Bhandare P.S.

94
Real Data Types Mr. Bhandare P.S.

95  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.
Character Data Type Mr. Bhandare P.S.

96  In order to store single character constant in a variable, character data


type is used.

 Like C/C++, the keyword char is used to declare character data type
variable.

 Two bytes are required to store a single character in memory.

 Because, the characters in Java use Unicode system, in which each


character is represented by 16 bits i.e. 2 bytes.

 All characters in Unicode can be stored in a character data type variable.


Boolean Data Type Mr. Bhandare P.S.

97  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 can
not 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.
Declaring the variables Mr. Bhandare P.S.

98  Variables are the names given to the storage locations.

 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 declared before used anywhere in the program.

 It can be used to store the value of any type studied earlier.


 General form of the declaration of the variable is: Mr. Bhandare P.S.

data_type variable1, variable2, variable3……..variableN;


99

 Variable names are separated by commas. It must be a valid identifier


name.
Example:
int x;
float avg, cal, s;
char m, yes;
boolean k, jack;
Giving values to variables Mr. Bhandare P.S.

 A variable must be given a value after it has been declared but before it is used in
100 the expression.

 This can be done in two ways.


 1. By using assignment statement
 2. By reading from the keyboard
 1. By using assignment statement

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

 The process of giving initial values to variables is known as initialization.


Mr. Bhandare P.S.

 Remember, we must give a value to the variable before it is used in the


102
expression.

 But when we declare a variable as an instance variable (class variable), it is


not necessary to give default values to it. It contains a default value.

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

 One of the useful classes among them is Scanner. It is added by jdk1.5.

 This class is defined in one of the library package of Java i.e. java.util.

 So in order to use is in our program we have to use following import


statement at the top of our program.
 import java.util.Scanner;
 After this, the class Scanner will be available for our use in the
Mr. Bhandare P.S.

104 program. We have to create the object of scanner in following way.


 Scanner in = new Scanner(System.in);
 System.in is standard input handle i.e. keyboard.
 ‘in’ is the object of the Scanner class, which is then used to read any
type of the data from keyboard in it.
 We have to use any of the following methods according to the
requirement.
Mr. Bhandare P.S.

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

 The instance variables are declared inside the class.

 They are created when the objects of the class are created and therefore they
are associated with the objects.

 They will have different values for different 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

 The instance variables are said to have


class scope and local variables are said
to have block scope.

Mr. Bhandare P.S.


Operators Mr. Bhandare P.S.

109  An operator is the symbol that takes one or more arguments and
operates on them to produce a result.

 The constants, variables or expression on which operator operates are


called as operands.

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

112 Relational Operators


Mr. Bhandare P.S.
Logical Operators
113

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.

 They can be written in following from:


 x++ or x--
 ++x or --x
Conditional Operator Mr. Bhandare P.S.

115  The only ternary operator (operator having three operands) is defined
in Java called as conditional operator.

 The character pair ? : is termed as conditional operator. This is used to


construct the conditional expression of the following form:
 condition ? expression2 : expression3
 When the condition written is true then the expression1 is evaluated
else expression2 is executed.

 Means, any one of the expression1 and 2 is executed in any case.

 It can also be called as if-then-else operator.


Mr. Bhandare P.S.

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.

 All these operators except one’s complement operator are binary


119 operators.

 These perform the given bitwise operation on the operands.

 Accordingly, the result is obtained. Shift operators shift the binary


equivalent bits of the operand to respective left or right position. >>>

 operator is one of the special type of bitwise operator which is


generally used for the negative values which will be shifted to right by
filling the zeroes to leftmost positions.
Special Operators Mr. Bhandare P.S.

 Special operators are always unique to the programming language. Java


120
supports two special operators.
 That is, instanceof and member selection operator or dot operator (.).

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.

Member selection operator


121
 This is also called as dot operator (.). It is used to access the instance
variable and methods of the class using objects.

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

 If the operands are of different type, the lower type is automatically


converted to the higher type and the result is higher type.

 For example, if expression contains int, float and byte operands, then the int
and byte will automatically converted to float which is the higher type.

 Result of operations will also be float type.


Mr. Bhandare P.S.
Following table gives automatic type conversion chart.
125
char byte short int long float double
char int int int int long float double
byte int int int int long float double
short int int int int long float double
int int int int int long float double
long long long long long long float double
float float float float float float float double
double double double double double double double double
Mr. Bhandare P.S.

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.

 1. Conversion of float to int causes truncation of fractional part.


 2. double to float conversion causes rounding of digits.
 3. long to int conversion causes dropping of the excess higher order bits.
 4. Type conversion can not be applied to boolean data type.
The type promotion rules Mr. Bhandare P.S.

127  Java defines type promotion rules that apply to expressions.

 They are as follows:


1. All byte, short and char values are promoted to int.
2. If one operand in the expression is long then the whole
expression will be promoted to long.
3. If one operand is float then the whole expression will be
promoted to float.
4. If any of the operands is double, the result is double
Type casting Mr. Bhandare P.S.

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.

 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.
Types of Type Casting Mr. Bhandare P.S.

129  There are two types of type casting:


 Widening Type Casting
 Narrowing Type Casting
Mr. Bhandare P.S.
Widening Type Casting
130
 Converting a lower data type into a higher one is called widening type casting.

 It is also known as implicit conversion or casting down.

 It is done automatically. It is safe because there is no chance to lose data. It takes


place when:
 Both data types must be compatible with each other.
 The target type must be larger than the source 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.

 It is also known as explicit conversion or casting up.

 It is done manually by the programmer. If we do not perform casting then the


compiler reports a compile-time error.

 double -> float -> long -> int -> char -> short -> byte

 It takes the following form.


 (target_type) variable_name;

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

 By adjusting the direction of flow programs can become dynamic.


Without control flow, programs would not be able to do anything more
than several sequential operations.

 Java supports different control flow and branching statements given


below.
1. if statement
2. if-else statement
3. switch-case statement
4. Conditional operator statement
If statement: Mr. Bhandare P.S.

134  The if statement is Java’s conditional branch statement.

 It can be used to route program execution through two different paths.


Here is the general form of the if statement:
if (condition) statement1;
else statement2;
 Here, each statement may be a single statement or a compound
statement enclosed in curly braces (that is, a block).

 The condition is any expression that returns a boolean value.

 The else clause is optional.


Mr. Bhandare P.S.
 The if works like this: If the condition is true, then statement1 is executed.
135
Otherwise, statement2 (if it exists) is executed.

 In no case will both statements be executed.

 For example, consider the following:


int a, b;
if(a < b) a = 0;
else b = 0;
 100 Java™ 2: The Complete ReferenceHere, if a is less than b, then a is set
to zero. Otherwise, b is set to zero.

 In no case are they both set to zero.


Mr. Bhandare P.S.

136
Nested ifs Mr. Bhandare P.S.

137  A nested if is an if statement that is the target of another if or else.


 Nested ifs are very common in programming.
 When you nest ifs, the main thing to remember is that an else statement
always refers to the nearest if statement that is within the same block as the
else and that is not already associated with an else.
 Here is an example:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d;
else a = c;
}
else a = d;
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.

 The if statements are executed from the top down.


140

 As soon as one of the conditions controlling the if is true, the statement


associated with that if is executed, and the rest of the ladder is bypassed.

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

 The switch statement is Java’s multiway branch statement. It provides an


141
easy way to dispatch execution to different parts of your code based on the
value of an expression.

 As such, it often provides a better alternative than a large series of if-else-if


statements.

 It is applicable when it is impossible to write the ‘if’ statement many times


in the programs.

 Generally, it is used to create the menu driven program to select from the
multiple choices.

 Here is the general form of a switch statement:


Mr. Bhandare P.S.
switch (expression) {
case value1:
142
// statement sequence
break;
case value2:
// statement sequence
break;
------------------------
-------------------------------------
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
Mr. Bhandare P.S.

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.

 The while loop is Java’s most fundamental looping statement.


147
 It repeats a statement or block while its controlling expression is true.
Here is its general form:
while(condition) {
// body of loop
}
 The condition can be any Boolean expression. The body of the loop will be
executed as long as the conditional expression is true.

 When condition becomes false, control passes to the next line of code
immediately following the loop.

 The curly braces are unnecessary if only a single statement is being


repeated.
Mr. Bhandare P.S.

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

 However, sometimes it is desirable to execute the body of a while loop at


least once, even if the conditional expression is false to begin with.

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

 Remember, there is a terminating semicolon given at the end of the


while statement.
Mr. Bhandare P.S.

152
for Mr. Bhandare P.S.

153  The ‘for’ loop is another entry-controlled loop, that provides a more concise loop
control structure.

 That is, initialization, condition and increment/decrement can be done in the


single loop statement as given below.
 for(initialization; condition; increment/decrement)
 {
 Body of the loop;
 }
 If only one statement is being repeated, there is no need for the curly braces.

 Operation of the ‘for’ loop is shown in the flowchart .


Mr. Bhandare P.S.

154
Mr. Bhandare P.S.

155  This loop control structure works as below.

 1. Initialization part is executed first. Here, we can do the initialization of the


loop control variables. This statement is executed only once i.e. before the start
of execution of the loop.

 2. In the second stage, the condition given is tested. If it is evaluated to true,


then body of the loop is executed. Generally, the condition is related with the
loop counter. But it is not necessary to give condition related to loop counter
only. The condition is tested for each iteration of the loop. When it becomes
false the loop gets terminated.

 3. After completion of execution of the body of the loop, increment / decrement


statement is executed. Any action we can write in this statement. Then again
control gets transferred to the condition to execute the next iteration.
Mr. Bhandare P.S.
Comparison of three loop structures
156
Some ‘for’ Loop Variations 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.

 4. Increment / decrement section can have multiple statements


separated by a comma. Such as,
int x = 5;
for(int a = 10;a<100 || x > 0; a++, y--)
 here, on each iteration of the loop, value of ‘a’ is incremented and ‘y’ is
decremented as shown in the last section of the ‘for’ loop.
 5. Any of the statements of initialization, condition and increment
Mr. Bhandare P.S.
/
decrement can be eliminated by keeping it blank.
159
 E.g a = 12;
for(;a<100;){
a++;
System.out.println(“Welcome”);
}
 6. All the statements in the loop can be eliminated just by keeping two
semicolons in the brackets such as,
 for(; ;)
{
}
 but this loop will run infinitely.
 7. When the following statement is executed. Mr. Bhandare P.S.

160  for(int x = 0;x<10;x++);


 compiler will not show any error. This is called as empty statement.
Many times by mistake we give semicolon at the end. One must take
care of that. But in several cases this feature is most applicable. We will
see it in upcoming chapters.

 8. See one loop statement in programming languages such as C/C++.


 for(int a = 10;a;a--)

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

161 The for-each loop introduced in Java5.


It is mainly used to traverse array or collection elements.
The advantage of for-each loop is that it eliminates the possibility
of bugs and makes the code more readable.

Advantage of for-each loop:


It makes the code more readable.
It eliminates the possibility of programming errors.

Syntax of for-each loop:


for(data_type variable : array | collection){ }
Mr. Bhandare P.S.
Simple Example of for-each loop for traversing the array
162 elements:
class ForEachExample1
{
 public static void main(String args[])
{
 int arr[]={12,13,14,44};
 for(int i:arr){
 System.out.println(i);
 }
 }
}
Jump statements 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.

 In these cases the jump statements are used.

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

164  In Java, the break statement has three uses.

1. First, as you have seen, it terminates a statement sequence in a


switch statement.

2. Second, it can be used to exit a loop.

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.

166  // Using break to exit a loop.


 class BreakLoop {
 public static void main(String args[]) {
 for(int i=0; i<100; i++) {
 if(i == 10) break; // terminate loop if i is 10
 System.out.println("i: " + i);
 }
 System.out.println("Loop complete.");
 }
}
Using break as a Form of Goto 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 general form of the labeled break statement is shown here:


 break label;
 Most often, label is the name of a label that identifies a block of code.
This can be a stand-alone block of code but it can also be a block that is
the target of another statement.

 When this form of break executes, control is transferred out of the


named block.

 The labeled block must enclose the break statement, but it does not
need to be the immediately enclosing block.
Mr. Bhandare P.S.

When this break statement is encountered with the label/name of


169
the loop, it skips the execution any statement after it and takes the
control right out of this labelled loop.

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.

 //Labelled break example with while  i++;


171 loop }
 public class LabelledBreak  System.out.println("Out of the loop");
{  } //main method ends
 public static void main(String... ar)  } //class ends
{
 int i=7;
 loop1:
 while(i<20)
{
 if(i==10)
 break loop1;
 System.out.println("i ="+i);
 // Using break as a form of goto.  if(t) Mr. Bhandare P.S.

172  class BreakGoto  break second;


 {  System.out.println("This won't
 public static void main(String execute");
args[])  }
 {  System.out.println("This won't
 boolean t = true; execute");
 first:  }
 {  System.out.println("This is after
 second: second block.");
 {  }
 }
 third:
 {  }
 System.out.println("Before the
break.");
Using continue Mr. Bhandare P.S.

 Sometimes it is useful to force an early iteration of a loop.


173

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

enclosing loop to continue.


176  See the example program that uses continue to print a triangular multiplication
table from 0 through 9.

 // Using continue with a label.  continue outer;


 class ContinueLabel  }
 {  System.out.print(" " + (i * j));
 public static void main(String args[])  }
{  }
 outer: for (int i=0; i<10; i++) {  System.out.println();
 for(int j=0; j<10; j++) {  }
 if(j > i) {  }
 System.out.println();
 //Labelled continue example  System.out.println("j ="+j);
Mr. Bhandare P.S.

177  class LabelledContinue }


{  System.out.println("Out of the
 public static void main(String... loop");
ar)  } //main method ends
{  } //class ends
 loop:
 for(int i=0;i<2;i++)
 for(int j=0;j<5;j++)
{
 if(j==2)
 continue loop;
 System.out.println("i ="+i);
return Mr. Bhandare P.S.

 The last control statement is return. The return statement is used to


178
explicitly return from a method.
 That is, it causes program control to transfer back to the caller of the
method. As such, it is categorized as a jump statement.

 At any time in a method, the return statement can be used to cause


execution to branch back to the caller of the method.

 Thus, the return statement immediately terminates the method in which it


is executed. The following example illustrates this point.

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

179  class Return {


 public static void main(String args[]) {
 boolean t = true;
 System.out.println("Before the return.");
 if(t) return; // return to caller
 System.out.println("This won't execute.");
 }
}

 The output from this program is shown here:


 Before the return.
Mathematical Functions 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.

 This relaxation permits implementation with better-performance where strict


reproducibility is not required.
Basic Math methods Mr. Bhandare P.S.

181 Method Description


Math.abs() It will return the Absolute value of the given value.
Math.max() It returns the Largest of two values.
Math.min() It is used to return the Smallest of two values.
Math.round() It is used to round of the decimal numbers to the nearest value.
Math.sqrt() It is used to return the square root of a number.
Math.cbrt() It is used to return the cube root of a number.

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.

Logarithmic Math Methods


182

Method Description

Math.log() It returns the natural logarithm of a double value.

Math.log10() It is used to return the base 10 logarithm of a double value.

Math.log1p() It returns the natural logarithm of the sum of the argument and 1.

Math.exp() It returns E raised to the power of a double value, where E is Euler's


number and it is approximately equal to 2.71828.

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.tan() It is used to return the trigonometric Tangent 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)

 What is scope of variable ? Give example of class variable, instance variable


and local variable. (4m)

 Write a program to check whether an entered number is prime or not.(4m)

 Explain break and continue statements with example.(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)

 In what ways does a switch statement differ from an if statements ? (4m)


Mr. Bhandare P.S.
Winter 2015
187  Explain any four features of Java. (4m)

 Describe break and continue statement with example. (4m)

 Describe?, : (Ternary operator) in Java with suitable example. (4m)

 Write a program to check whether the entered number is prime or not.(4m)

 Explain any two bit-wise operators with example. (4m)


Mr. Bhandare P.S.
Summer 2015
188  What is JVM ? What is byte code ? (4m)

 Write any two methods of file and file input stream class each.(4m)

 ‘?:’ what this operator is called ? Explain with suitable example.(4m)

 Write a program to accept a number as command line argument and print the
number is even or odd.(4m)

 Differentiate applet and application with any four points.(4m)

 Define JDK. List the tools available in JDK explain any one in detail. (4m)
Winter 2014 Mr. Bhandare P.S.

189 1. Explain :1) Platform independence 2) Compiled and interpreted features of


Java. (4m)

2. Write any four mathematical functions used in Java.(4M)

3. Write a program to find sum of digits of number. (4M)

4. What do mean by typecasting ? When it is needed ?(4M)

5. Write a program to generate Fibonacci series : 1 1 2 3 5 8 13 21 34 55 89.


(4M)

6. Write a program to print reverse of a number. (4M)

You might also like