0% found this document useful (0 votes)
6 views22 pages

Java 1

The document provides an overview of Object-Oriented Programming (OOP) principles and contrasts them with Procedural-Oriented Programming (POP). It discusses key concepts such as classes, encapsulation, inheritance, polymorphism, and data abstraction, highlighting the advantages of OOP in software development. Additionally, it outlines the history and evolution of the Java programming language, its applications, and the different Java platforms available.

Uploaded by

Bhaskara Reddy
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)
6 views22 pages

Java 1

The document provides an overview of Object-Oriented Programming (OOP) principles and contrasts them with Procedural-Oriented Programming (POP). It discusses key concepts such as classes, encapsulation, inheritance, polymorphism, and data abstraction, highlighting the advantages of OOP in software development. Additionally, it outlines the history and evolution of the Java programming language, its applications, and the different Java platforms available.

Uploaded by

Bhaskara Reddy
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/ 22

Java Programming (R19) Unit-I Java Programming (R19) Unit-I

1.0 Introduction to Object OrientedProgramming Most function uses Global datafor Data cannot move easily from function
The 1960s gave birth to structured programming. This is the method of programming sharing that can be accessed freely to function, it can be kept public or
Data Access
championed by languages such as C. With the advent of languages such as c, structured from function to function inthe private so we can control the access of
programming became very popular and was the main technique of the 1980‟s. Structured system. data.
It does not have any proper way for It supports data hiding so provides
programming was a powerful tool that enabled programmers to write moderately complex Data Hiding hiding data so it is less secure. more security.
programs fairly easily. However, as the programs grew larger, even the structured approach In OOP, overloading is possible in the
failed to show the desired result in terms of bug-free, easy-to- maintain, and reusable programs. Overloading In POP, Overloading is not possible. form of Function Overloading and
To solve these problems, a new way to program was invented, called object-oriented Operator Overloading.
programming(OOP). Inheritance No such concept of inheritance in POP Inheritance is allowed in OOP
Access It has access specifiers named Public,
It does not have any access specifiers.
Object Oriented Programming (OOP) is an approach to program organization and Specifiers Private, Protected.
development that attempts to eliminate some of the pitfalls of conventional programming C, BASIC, FORTRAN, Pascal, C++, JAVA, C#, Smalltalk, Action
Examples COBOL. Script.
methods by incorporating the best of structured programming features with several powerful new
concepts. It is a new way of organizing and developing programs and has nothing to do with any
1.2 Principles ofOOP
particular language. However, not all languages are suitable to implement the OOP concepts It is necessary to understand some of the concepts used extensively in object-oriented
easily. programming. Theseinclude:
 Object  Inheritance
1.1 PO Programming Vs OOProgramming  Class  Polymorphism
All computer programs consist of two elements: code and data. Furthermore, a program  Encapsulation  Dynamicbinding
can be conceptually organized around its code or around its data. That is, some programs are  Dataabstraction  Messagepassing
written around ― “what is happening” and others are written around ―“who is being affected”.
These are the two paradigms that govern how a program is constructed. The first way is called Object
Object is the basic run time entity in an object-oriented system. It may represent a person,
the process- oriented model or procedural language. This approach characterizes a program as a
a place, a bank account, a table of data, vectors, time and lists. Objects have states and behaviors.
series of linear steps (i.e. code). The process-oriented model can be thought of as code acting on Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking,
data. Procedural languages such as C employ this model to considerablesuccess. eating. An object is an instance of a class.

To manage increasing complexity, the second approach, called object-oriented In OOP, A problem is analyzed in term of objects and the nature of communication
programming, was designed. Object-oriented programming organizes a program around its data between them. Objects should be chosen such that they match closely with the real-world
(i.e. objects) and a set of well-defined interfaces to that data. An object-oriented program can be objects.Objectstakeupspaceinthememoryandhaveanassociatedaddresslikeastructurein
C. When a program is executed, the objects interact by sending messages to oneanother.
characterized as data controlling access to code.
For example, if “customer” and “account” are to object in a program, then the customer
Difference between POP and OOP object may send a message to the account object requesting for the bank balance. Each object
Procedure Oriented Programming Object Oriented Programming contain data, and code to manipulate data. Below figure shows two notations that are popularly
Program is divided into small parts Program is divided into parts used in object oriented analysis and design.
Divided Into
called functions. called objects.
Importance is given to the data rather
Importance is given to functions as
Importance than procedures or functions because it
well as sequence of actions to be done.
works as a real world.
Approach It follows Top-down approach. It follows Bottom-up approach.
Data Data can move freely from function to Objects can communicate with each
Moving function in the system. other through member functions.
To add new data and function in POP It provides an easy way to add new data
Expansion
is not so easy. and function.

MVR@Dept. Of CSE 1 MVR@Dept. Of CSE 2


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
Class acquires the properties is called subclass. This is mainly used for Method Overloading and Code
A class is a collection of similar objects that share the same properties, methods, relationships reusability.
and semantics. A class can be defined as a template/blueprint that describes the behavior/state of
theobject.

Encapsulation
Definition: The process binding (or wrapping) code and data together into a single unit is known
as Encapsulation. For example: capsule, it is wrapped with different medicines.

 Java supports the feature of Encapsulation usingclasses.


 The data in the class is not accessed by outsideworld.
 The functions that are defined along with the data within the same class are allowed to
access thedata.
 These functions provide the interface between the object‟s data and the program. This
insulation of the data from direct access by the program is called data hiding or
information hiding.
 A class defines the structure and behavior (data and code) that will be shared by a set of
objects. Each object of a given class contains the same structure and behavior defined by
Polymorphism
theclass.
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means
 The objects are referred to as instances of a class. Thus, a class is a logical construct; an
the ability to take more than one form. An operation may exhibit different behavior is different
object is physicalreality.
instances. The behavior depends upon the types of data used in the operation.
In Java, we use method overloading and method overriding to achieve polymorphism.
Data abstraction
Definition: It a process of providing essential features without providing the background or For example can be to speak something e.g. cat speaks meow, dog barks woof , duck speaks
implementation details. For example: It is not important for the user how TV is working quack, etc.
internally, and different components are interconnected. The essential features required to the
user are how to start, how to control volume, and change channels.
In java, we use abstract class and interface to achieve abstraction.

Inheritance
It a process by which an object of one class acquires the properties and methods of
another class. It supports the concept of hierarchical classification. For example, the bird,
„robin‟ is a part of class „flying bird‟ which is again a part of the class „bird‟. The principal
behind this sort of division is that each derived class shares common characteristics with the
class from which it is derived as illustrated in belowfigure.

In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it. This is possible by deriving Advantages of OOP
a new class from the existing one. The new class will have the combined feature of both the OOP offers several benefits to both the program designer and the user. Object-Orientation
classes. The Class from which the properties are acquired is called super class, and the class that contributes to the solution of many problems associated with the development and quality of

MVR@Dept. Of CSE 3 MVR@Dept. Of CSE 4


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
software products. The new technology promises greater programmer productivity, better quality 4. MobileApplications
of software and lesser maintenance cost. The principal advantages are: 5. EmbeddedSystems
 It presents a simple, clear and easy to maintainstructure. 6. SmartCards
7. Robotics
 Software complexity can be easilymanaged.
8. Gamesetc.
 It enhances program modularity since each object existsindependently.
 New features can be easily added without disturbing the existingone.
Types of Java Applications
 Objects can be reused in otherprogram. There are mainly 4 types of applications that can be created using java programming:
 It allows designing and developing safe programs using the datahiding. 1. StandaloneApplication
 Through inheritance, we can eliminate redundant code extend the use of existingclasses. It is also known as desktop application or window-based application. An application that
 It is easy to partition the work in a project based onobjects. we need to install on every machine such as media player, antivirus etc. AWT and Swing
 Object-oriented system can be easily upgraded from small to largesystem. are used in java for creating standalone applications.
 Message passing techniques for communication between objects makes to interface 2. WebApplication
descriptions with external systems muchsimpler. An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web
Applications of OOP applications in java.
Applications of OOP are beginning to gain importance in many areas. The most popular 3. EnterpriseApplication
application of object-oriented programming, up to now, has been in the area of user interface An application that is distributed in nature such as banking applications etc. It has the
design such as window. Hundreds of windowing systems have been developed, using the OOP advantage of high level security, load balancing and clustering. In java, EJB is used for
techniques. The promising areas of application of OOP include: creating enterprise applications.
4. MobileApplication
 Real-timesystems An application that is created for mobile devices. Currently Android and Java ME are
 Simulation andmodeling used for creating mobile applications.
 Object-oriented databases Java Platforms / Editions
 Hypertext, Hypermedia, andExpertext There are 4 platforms or editions of Java:
 AI and expertsystems 1. Java SE (Java StandardEdition)
 Neural networks and Parallelprogramming It is a java programming platform. It includes Java programming APIs such as java.lang,
 Decision support and Office automationsystems java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs,
 CAM/CADSystems String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT,
Swing, Reflection, Collection etc.
1.3 What isJava? 2. Java EE (Java EnterpriseEdition)
Java is a programming language and a platform. Java is a high level, robust, secured and object- It is an enterprise platform which is mainly used to develop web and enterprise
oriented programming language. applications. It is built on the top of Java SE platform. It includes topics like Servlet, JSP,
Web Services, EJB, JPA etc.
Platform: Any hardware or software environment in which a program runs, is known as a platform. Since
3. Java ME (Java MicroEdition)
Java has its own runtime environment (JRE) and API, it is called platform.
It is a micro platform which is mainly used to develop mobile applications.
4. JavaFx
Where it is used (Applications)?
It is used to develop rich internet applications. It uses light-weight user interface API.
According to Sun, 3 billion devices run java. There are many devices where Java is currently used. Some
of them are as follows: History of Java
1. Desktop GUI Applications such as acrobat reader, media player, antivirusetc. The history of java starts from Green Team. Java team members (also known as Green
2. Web Applications such as irctc.co.in, javabay.cometc. Team), initiated a revolutionary task to develop a language for digital devices such as set-top
3. Enterprise Applications such as bankingapplications. boxes, televisions etc.
MVR@Dept. Of CSE 5 MVR@Dept. Of CSE 6
Java Programming (R19) Unit-I Java Programming (R19) Unit-I
For the green team members, it was an advance concept at that time. But, it was suited for 3. J2SE 1.2 (Commonly called as Java 2) was released in the year1998.
internet programming. Later, Java technology as incorporated by Netscape. 4. J2SE 1.3 codename Kestrel was released in the year2000.
5. J2SE 1.4 codename Merlin was released in the year2002.
6. J2SE 5.0 codename „Tiger‟ was released in the year2004.
7. Java SE 6 codename „Mustang‟ was released in the year2006.
8. Java SE 7 codename „Dolphin‟ was released in the year2011.
9. Java SE 8 is the current stable release which was released this year2014.

James Gosling Five Goals which were taken into consideration while developing Java
1. Keep it simple, familiar and objectoriented.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. 2. Keep it Robust andSecure.
There are given the major points that describe the history of java. 3. Keep it architecture-neural andportable.
4. Executable with HighPerformance.
1. James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language 5. Interpreted, threaded anddynamic.
project in June 1991 at Sun Microsystems. The small team of sun engineers called Green
Team. Why we call it Java 2, Java 5, Java 6, Java 7 and Java 8, not their actual version numbers
2. Originally designed for small, embedded systems in electronic appliances like set-top which 1.2, 1.5, 1.6, 1.7 and 1.8?
boxes. Java 1.0 and 1.1 were Java. When Java 1.2 was released it had a lots of changes and marketers /
3. Firstly, it was called "Greentalk" by James Gosling and file extension was“.gt”. developers wanted a new name so they called it Java 2 (J2SE), remove the numeric before
4. After that, it was called Oak and was developed as a part of the Greenproject. decimal. This was not the condition when Java 1.3 and Java 1.4 were released hence they were
5. Why Oak? Oak is a symbol of strength and chosen as a national tree of manycountries never called Java 3 and Java 4, but they were still Java 2.
like U.S.A., France, Germany, Romaniaetc.
6. In 1995, Oak was renamed as "Java" because it was already a trademark byOak When Java 5 was released, once again it was having a lots of changes for the developer /
Technologies. marketers and need a new name. The next number in sequence was 3, but calling Java 1.5 as
Why "Java" name Java 3 was confusing hence a decision was made to keep the naming as per version number and
7. Why had they chosen Java name for java language? The team gathered to choose a new till now the legacycontinues.
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA"etc.
They wanted something that reflected the essence of the technology: revolutionary, 1.4 Java Features / Buzzwords
dynamic, lively, cool, unique, and easy to spell and fun tosay. There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
According to James Gosling "Java was one of the top choices along with Silk". Since
java was so unique, most of the team members preferred Java. 1. Simple
8. Java is an island of Indonesia where first coffee was produced (called javacoffee). 2. Secure
9. Notice that Java is just a name not anacronym. 3. Portable
10. Originally developed by James Gosling at Sun Microsystems (which is now asubsidiary 4. Object-oriented
of Oracle Corporation) and released in1995. 5. Robust
11. In 1995, Time magazine called Java one of the Ten Best Products of1995. 6. Multithreaded
12. JDK 1.0 released in(January 23,1996). 7. Architecture-neutral
Java Version History 8. Interpreted
There are many java versions that have been released. Current stable release of Java is Java SE 8. 9. Highperformance
1. JDK Alpha and Beta(1995) 10. Distributed
2. Initial Java Versions 1.0 and 1.1 were released in the year 1996 for Linux, Solaris,Mac 11. Dynamic
and Windows.

MVR@Dept. Of CSE 7 MVR@Dept. Of CSE 8


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
 Memorymanagement
 ExceptionHandling

Multithreaded
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 thingssimultaneously.

Architecture-neutral
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,
anytime, forever. To a great extent, this goal was accomplished.

Interpreted and High Performance


Java enables the creation of cross-platform programs by compiling into an intermediate
Fig. Java features representation called Java byte code. This code can be executed on any system that
Simple implements the Java Virtual Machine. Most previous attempts at cross-platform solutions
Java inherits all the best features from the programming languages like C, C++ and thus have done so at the expense of performance. As explained earlier, the Java byte code was
makes it really easy for any developer to learn with little programming experience. Removed carefully designed so that it would be easy to translate directly into native machine code for
many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc. very high performance by using a just-in-time compiler.
No need to remove unreferenced objects because there is Automatic Garbage Collection in
java. Distributed
Java is designed for the distributed environment of the Internet because it handles TCP/IP
Secure protocols. In fact, accessing a resource using a URL is not much different from accessing a
When Java programs are executed they don‟t instruct commands to the machine directly.
file. Java also supports Remote Method Invocation (RMI). This feature enables a program to
Instead Java Virtual machine reads the program (Byte code) and convert it into the machine
invoke methods across a network.
instructions. This way any program tries to get illegal access to the system will not be
allowed by the JVM. Allowing Java programs to be executed by the JVM makes Java
Dynamic
program fully secured under the control of theJVM.
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
Portable link code in a safe and expedient manner.
Java programs are portable because of its ability to run the program on any platform and no
dependency on the underlying hardware / operating system.
1.5 Java Virtual Machine(JVM)
The key that allows Java to solve both the security and the portability problems is the byte
Object Oriented code. The output of Java Compiler is not directly executable file. Rather, it contains highly
Everything in Java is an Object. The object model in Java is simple and easy to extend, while
optimized set of instructions. This set of instructions is called, "byte code". This byte code is
primitive types, such as integers, are kept as high-performance non-objects.
designed to be executed by Java Virtual Machine (JVM). The JVM also called as the
interpreter for byte code.
Robust
The multi-platformed environment of the Web places extraordinary demands on a program,
JVM also helps to solve many problems associated with web-based programs.
because the program must execute reliably in a variety of systems. Thus, the ability to create
Translating a Java program into byte code makes it much easier to run a program in a wide
robust programs was given a high priority in the design of Java. Following features of Java
variety of environments because only the JVM needs to be implemented for each platform.
make it Robust.
Once the run-time package exists for a given Figure 2 JVM system, any Java program
 PlatformIndependent can run on it. Remember, although the details of the JVM will differ from platformto
 Object Oriented ProgrammingLanguage
MVR@Dept. Of CSE 9 MVR@Dept. Of CSE 10
Java Programming (R19) Unit-I Java Programming (R19) Unit-I
platform, all understand the same Java byte code. Thus, the execution of byte code by the Let's understand the internal architecture of JVM. It contains class loader, memory area,
JVM is the easiest way to create truly portable programs. execution engine etc.
1. Classloader
Classloader is a subsystem of JVM that is used to load class files.

2. Class(Method)Area
Class (Method) Area stores per-class structures such as the runtime constant pool,
field and method data, the code for methods.

Internal Architecture of JVM


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed. Fig. Internal architecture of JVM
 JVMs are available for many hardware and software platforms (i.e. JVM isplatform 3. Heap
dependent). It is the runtime data area in which objects are allocated.
 It is a specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its implementation 4. Stack
has been provided by Sun and othercompanies. Java Stack stores frames. It holds local variables and partial results, and plays a part in
 Its implementation is known as JRE (Java RuntimeEnvironment). method invocation and return. Each thread has a private JVM stack, created at the
 Whenever you write java command on the command prompt to run the java class, an same time as thread. A new frame is created each time a method is invoked. A frame
instance of JVM iscreated. is destroyed when its method invocation completes.
What it does
The JVM performs following operations: 5. Program Counter (PC)Register
 Loadscode PC (program counter) register. It contains the address of the Java virtual machine
 Verifiescode instruction currently being executed.
 Executescode
 Provides runtimeenvironment 6. Native MethodStack
It contains all the native methods used in the application. A native method is a Java
JVM provides definitions for the: method (either an instance method or a class method) whose implementation is
 Memoryarea written in another programming language such as C.
 Class fileformat
7. Execution Engine
 Registerset
It contains:
 Garbage-collectedheap
a. A virtualprocessor
 Fatal error reportingetc.
MVR@Dept. Of CSE 11 MVR@Dept. Of CSE 12
Java Programming (R19) Unit-I Java Programming (R19) Unit-I
b. Interpreter: Read bytecode stream then execute theinstructions. Requirement for Welcome Java Example
c. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT For executing any java program, you need to
compiles parts of the byte code that have similar functionality at the same  Install the JDK if you don't have installed it, download the JDK and installit.
time, and hence reduces the amount of time needed forcompilation.  Set path of the jdk/bindirectory.
 Create the javaprogram
1.6 Basic Structure of JavaProgram  Compile and Run the javaprogram
Basically, a Java program involves the following sections:
 DocumentationSection Sample Code of “Welcome” Java program
 PackageStatement Example: Welcome.java
 ImportStatements
 InterfaceStatement class Welcome
{
 ClassDefinition public static void main(String[] args)
 Main MethodClass {
 Main MethodDefinition System.out.println("Welcome to Java");
}
}
Section Description
Output:
It comprises of a comment line which gives the names program, the
Welcome to Java
programmer‟s name and some other brief details. Java provides 3 styles of
Documentation comments Entering the Program
Section 1. Single line(//)  We can use any text editor such as "notepad' or "dos texteditor".
2. Multi-line(/**/)
 The source code is typed and is saved with ".java" asextension.
3. Documentation comment( /**….*/)
 The source code contains one or more class definitions. The program name will be
The first statement allowed in Java file is the Package statement which is
Package used to declare a package name and it informs the compiler that the classes same as class name in which main function is written. This in not compulsory, but by
statement defined within the program belong to this package. It is declared as: convention this isused.
package package_name;  The source file is officially called as compilationunit.
The next is the number of import statements, which is equivalent to the  We can even uses our choice of interest name for the program. If we use a different
Import #include statement in C++. name than the class name, then compilation is done with program name, and running
statements Example: is done with class file name. To avoid this confusion and organize the programs well,
import java.util.Scanner;
it is suggested to put the same name for the program and class name, but not
Interfaces are like a class that includes a group of method declarations. compulsory.
Interface
This is an optional section and can be used only when programmers want
statement Compiling the Program
to implement multiple inheritances within aprogram.
To compile the program, specifying the name of the source file on the command line,
A Java program may contain multiple class definitions. Classes are the as shown below:
Class
main and important elements of any Java program. These classes are used C:/>javac Welcome.java
Definition
to plot the objects of the real worldproblem.
The javac compiler creates the file called "Welcome.class” that contains the byte code
Since every Java stand-alone program requires the main method as the version of the source code. This byte code is the intermediate representation of the source
Main Method
starting point of the program. This class is essentially a part of Java code that contains the instructions that the Java Virtual Machine (JVM) will execute. Thus
Class
program. A simple Java program contains only this part of the program. the output of the javac is not the directly executablecode.
Running the Program
To create a simple java program, you need to create a class that contains main method. Let's To run the program, we must use Java interpreter, called "java". This is interpreter the
understand the requirement first. "Welcome.class" file given as input.
C:/>java Welcome
MVR@Dept. Of CSE 13 MVR@Dept. Of CSE 14
Java Programming (R19) Unit-I Java Programming (R16) Unit-I
When the program is run with java interpreter, the following output is produced: Welcome to AvgTemp count a4 $test this_is_ok
Java
Invalid identifier names include these:
Description of the program
The first line contains the keyword class and class name, which actually the basic unit for High-temp 2count 4a Not/ok
Literals
encapsulation and is used to declare a class in java, in which data and methods are declared.
A constant value in Java is created by using a literal representation of it. For example, here
Second line contains "{" which indicates the beginning of the class.
are some literals:
Third line contains the public static void main(String args[]) 100 98.6 „C‟ “This is a test”
where
 public keyword is an access modifier which represents visibility, it means it is visible Left to right, the first literal specifies an integer, the next is a floating-point value, the third
to all. is a character constant, and the last is a string.
 static is a keyword, if we declare any method as static, it is known as static method. A literal can be used anywhere a value of its type is allowed.
The core advantage of static method is that there is no need to create object to invoke
the static method. The main method is executed by the JVM, so it doesn't require to Comments
create object to invoke the main method. So it savesmemory. As mentioned, there are three types of comments defined by Java. You have already seen
 void is the return type of the method, it means it doesn't return anyvalue. two: single-line and multiline. The third type is called a documentation comment. This type
 main represents startup of the program where executionstarts. of comment is used to produce an HTML file that documents your program. The
 String[] args is used to read command lineargument. documentation comment begins with a /** and ends with a*/.

Fourth line contains the "{", which is the beginning of the main function. Separators
Fifth line contains the statement In Java, there are a few characters that are used as separators. The separators are shown in the
System.out.println("Hello World"); following table:
Symbol Name Purpose
Here "System" is the predefined class, that provides access to the system, and out is the output () Parentheses Used to contain lists of parameters in method definition and
stream that is used to connect to the console. The println(), is used to display string passed to invocation. Also used for defining precedence inexpressions,
expressions in control statements, and surrounding casttypes.
it. This can even display other information to.
{} Braces Used to contain the values of automatically initialized arrays.
Used to define a block of code, for classes, methods, and local
1.7 Lexicalissues scopes
Java programs are a collection of whitespace, identifiers, literals, comments, operators, [] Brackets Used to declare array types and to dereferencing array values.
separators, and keywords. ; Semicolon Terminates statements.
, Comma Separates consecutive identifiers in a variable declaration.
Whitespace . Period Used to separate package names from sub-packages and classes
and used to separate a variable or method from a reference
Java is a free-form language. This means that you do not need to follow any special
variable.
indentation rules. For example, the Java program could be 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
The Java Keywords
character between each token that was not already delineated by an operator or separator. In
 There are 50 keywords currently defined in the Java language (see below Table).
Java, whitespace is a space, tab, ornewline.
 These keywords, combined with the syntax of the operators and separators, form the
foundation of the Javalanguage.
Identifiers
 These keywords cannot be used as identifiers. Thus, they cannot be used as names for
Identifiers are used to name things, such as classes, variables, and methods. An identifier may
a variable, class, ormethod.
be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore
 The keywords const and goto are reserved but notused.
and dollar-sign characters. They must not begin with a number. Java is case-sensitive, so
 In addition to the keywords, Java reserves the following: true, false, and null. These
VALUE is a different identifier than Value. Some examples of valid identifiers are
are values defined byJava.

MVR@Dept. Of CSE 15 MVR@Dept. Of CSE 16


Java Programming (R16) Unit-I Java Programming (R19) Unit-I
abstract continue for new switch  A block begins with opening curly brace( { ) and ended with end curly brace ( }).
assert default goto package synchronized  Thus, each time we start new block, we create newscope.
boolean do if private this
 Many programming languages define two scopes: Local andGlobal
break double implements protected throw
byte else import public throws  As a general rule a variable defined within one scope, is not visible to code defined
case enum instanceof return transient outside of thescope.
catch extends int short try  Scopes can be also nested. The variable defined in outer scope are visible to the inner
char final interface static void scopes, but reverse is notpossible.
class finally long strictfp volatile Example code
const float native super while
void method1( )
Table: Java Keywords
{ //outer block
Operators
int a =10;
An operator performs an operation on one or more operands. Java provides a rich set of
if(a==10)
operators. An operator that performs an operation on one operand is called unary operator.
{ // inner block and here a,b,c are visible to the inner scope
An operator that performs an operation on two operands is called binaryoperator.
int b=a*20;
int c=a+30;
1.8 Variables
} //end of inner block
The variable is the basic unit of storage in a Java program. A variable is defined by the
b=20*2; // b is not known here, which declared in inner scope
combination of an identifier, a type, and an optional initializer. In addition, all variables have
} //end of the outer block
a scope, which defines their visibility, and alifetime.

1.9 Identifiers
Declaring a Variable
Identifiers are used for class names, method names, and variable names. An identifier may be
any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and
In Java, all variables must be declared before they can be used. The basic form of a variable
dollar-sign characters. They must not begin with a number, lets they be confused with a
declaration is shown here:
numeric literal. Java is case-sensitive, so VALUE is a different identifier than Value. Some
type identifier [ = value/literal][, identifier [= value/literal] ...] ; examples of valid identifiers are:
Here the type is any primitive data type, or class name. The identifier is the name of the
variable. We can initialize the variable by specifying the equal sign and value. Rules for Naming Identifier:
Example 1. The first character of an identifier must be a letter, or dollar($)sign.
int a,b,c; // declares three ints, a, b, andc. 2. The subsequent characters can be letters, an underscore, dollar sign ordigit.
int d = 3, e, f=5; // declares three more ints, initializing d and f. 3. White spaces are not allowed withinidentifiers.
byte z=22; // initializes z with22. 4. Identifiers are case sensitive so VALUE is a different identifier thanValue
double pi =3.1415; // declares an approximation of pi.
char c= 'x'; // variable c has the value'x' Valid Identifiers are as follows:
Average Temperature A1 Total_Score
Dynamic Initialization of the variable
We can also assign a value to the variable dynamically as follow: Invalid Identifiers are as follows:
int x = 12, y=13; 2a Area-circle Not/ok
float z = Math.sqrt (x+y);
Naming Convention for Identifiers
The Scope and Lifetime of Variables  Class or Interface - These begin with a capital letter. The first alphabet of every
 A scope determines what objects are visible to parts of your program. It also internal word is capitalized. Ex: classMyclass
determines the life time of theobjects.  Variable or Method – These start with lower case letters. The first alphabet of every
 Java allows, declaring a variable within anyblock. internal word is capitalized. Ex: inttotalPay;

MVR@Dept. Of CSE 17 MVR@Dept. Of CSE 18


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
 Constants - These are in upper case. Underscore is used to separate the internal word.  This makes it useful when big, whole numbers are needed.
Ex:-final doublePI=3.14; Example: longx=123456;
 Package – These consist of all lower-case letters. Ex: importjava.util.*;
2. Floating-PointGroup
Floating-point numbers, also known as real numbers, are used when evaluating
1.10 DataTypes
expressions that require fractional precision. These are used with operations such as square
Java is strongly typed language
root, cosine, and sine etc. There are two types of Floating-Point numbers:
Java is strongly typed language. The safety and robustness of the Java language is in fact
1. float
provided by its strict typing. There are two reasons for this: First, every variable and
2. double.
expression must be defined using any one of the type. Second, the parameters to the method
The float type represents single precision and double represents double precision.
also should have some type and also verified for type compatibility.
float
Java language has 8 primitive data types: They are: char, byte, short, int, long, float, double,  The type float specifies a single-precision value that uses 32 bits ofstorage.
boolean. These are again categorized into 4 groups.  The range of a float is 1.4e–045 to3.4e+038
 Single precision is faster on some processors and takes half as much space as double
1. Integer Group: The integer group contains byte, short, int, long. These data types will precision.
need different sizes of the memory. These are assigned positive and negative values. The  Variables of type float are useful when you need a fractional component, but don‟t
width and ranges of these values are asfollow: require a large degree ofprecision.
byte Example
 The smallest integer type is byte. float height, price;
 This is a signed 8-bit type that has a range from –128 to127. double
 Variables of type byte are especially useful when you‟re working with a stream of  Double precision, as denoted by the double keyword, uses 64 bits to store avalue.
data from a network or file and working with raw binary data that may not be directly  The range of a double is 4.9e–324 to1.8e+308
compatible with Java‟s other built-intypes.  Double precision is actually faster than single precision on some modern processors
 Byte variables are declared by use of the bytekeyword. that have been optimized for high-speed mathematicalcalculations.
For example, the following declares two byte variables called b and c:  All the math functions, such as sin( ), cos( ), and sqrt( ), return double values.
byteb,c; // where b and c areidentifiers Example:
short double area, pi;
 short is a signed 16-bittype. Example program to calculate the area of a circle
 It has a range from –32,768 to32,767. import java.io.*;
 It is probably the least-used Javatype. class Circle {
Here are some examples of short variable declarations: public static void main(String args[ ] ) {
short s, t; double r, area, pi;
int r=2.5;
 The most commonly used integer type isint. pi=3.14;
 It is a signed 32-bit type that has a range from – 2,147,483,648 to2,147,483,647. area=pi*r*r;
 In addition to other uses, variables of type int are commonly employed to control System.out.println("The Area of the Circle is:"+area);
loops and to indexarrays. }
 We can store byte and short values in anint. }
Example: int x=12; Output
The Area of the Circle is: 19.625
long 3. CharactersGroup
 long is a signed 64-bit type and is useful for those occasions where an int type is not In Java, the data type used to store characters is char. Java uses Unicode to represent
large enough to hold the desiredvalue. characters. Unicode defines a fully international character set that can represent all of the
 The range of a long is -9,223,372,036,854,775,808 to9,223,372,036,854,775,807. characters found in all human languages.
MVR@Dept. Of CSE 19 MVR@Dept. Of CSE 20
Java Programming (R19) Unit-I Java Programming (R19) Unit-I
1.11 Literals/Constants
Java char is a 16-bit type. The range of a char is 0 to 65,536. The standard set of characters A literal is a value that can be passed to a variable or constant in a program. Literals can be
known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, numeric, boolean, character, string or null.
ISO-Latin-1, ranges from 0 to 255. Integer Literals
 Integers are the most commonly used type in the typicalprogram.
Here is a program that demonstrates char variables:  Any whole number value is an integerliteral.
class CharDemo{  Examples are 1, 2, 3, and 42. These are all decimal values, meaning they are
public static void main(String args[ ]) { describing a base 10number.
char ch1, ch2;  Octal values are denoted in Java by a leadingzero.
ch1=88; // code for X  Octal numbers are ranging from 0 to 7 range. A more common base for numbers used
ch2 = 'Y'; by programmers ishexadecimal,
System.out.print("ch1 and ch2: "); which matches cleanly with modulo 8 word sizes, such as 8, 16, 32, and 64 bits. You signify
System.out.println(ch1 + " " + ch2); 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 through15.
} Integer literals create an int value, which in Java is a 32-bit integer value. Since Java is
Output strongly typed, you might be wondering how it is possible to assign an integer literal to one
ch1 and ch2: XY of Java‟s other integer types, such as byte or long, without causing a type mismatch error.
4. Booleans Group Fortunately, such situations are easily handled. When a literal value is assigned to a byte or
Java has a primitive type, called boolean, for logical values. It can have only one of two short variable, no error is generated if the literal value is within the range of the target type.
possible values, true and/or false. An integer literal can always be assigned to a long variable. However, to specify a long
literal, you will need to explicitly tell the compiler that the literal value is of type long. You
Here is a program that demonstrates the boolean type: do this by appending an upper- or lowercase L to the literal. For example, 0x7ffffffffffffffL
class BoolTest { or 9223372036854775807L is the largest long. An integer can also be assigned to a char as
public static void main(String args[]) long as it is within range.
{
boolean b; 1.12 Operators
b = false; An operator is defined as a symbol that operates on operands and does something. The
System.out.println("b is " + b); something may be mathematical, relational or logical operation. Java supports a lot of
b = true; operators to be used in expressions. These operators can be categorized into the following
System.out.println("b is " + b); groups:
// a boolean value can control the if statement 1. Arithmeticoperators
if(b) 2. Bitwiseoperators
System.out.println("This is executed."); 3. Relational operatorsand
else 4. Logical operators
System.out.println("This is not executed."); 5. Miscellaneousoperators
// outcome of a relational operator is a boolean value Arithmetic Operators
System.out.println("10 > 9 is " + (10 > 9));  These are used to perform mathematicaloperations.
}  Most of them are binary operators since they operate on two operands at a time except
} unary minus andplus.
Output  They can be applied to any integers, floating-point number orcharacters.
b is false  Java supports 5 arithmetic operators. They are +, -, *, /,%.
b is true  The modulo (%) operator can only be applied to integer operands as well as double
This is executed. operands.
10>9 is true

MVR@Dept. Of CSE 21 MVR@Dept. Of CSE 22


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
The following table lists the arithmetic operators: // Demonstrate the % operator. (Modulus.java)
Operator Result class Modulus
+ Addition (also unary plus) {
- Subtraction (also unary public static void main(String args[])
minus) {
* Multiplication int x = 42;
/ Quotient division double y = 6.25;
% Modulo Division System.out.println("x mod 10 = " + x % 10);
++ Increment System.out.println("y mod 2.5 = " + y % 2.5);
-- Decrement
}
+= Addition assignment
-= Subtraction assignment }
*= Multiplication assignment Output
/= Division assignment x mod 10 = 2
%= Modulus assignment y mod 2.5 = 1.25

Example program to perform all the arithmetic operations (Arith.java ) Arithmetic Compound Assignment Operators
import java.io.*; Java provides special operators that can be used to combine an arithmetic operation with an
class Arith assignment. As you probably know, statements like the following are quite common in
{ programming:
public static void main(String args[]) a = a + 4;
{ In Java, you can rewrite this statement as shown here: a += 4;
int a,b; This version uses the += compound assignment operator. Both statements perform the same
a=5; action: they increase the value of a by 4.
b=6;
intc=a+b; //arithmeticaddition Here is another example, a = a % 2; which can be expressed as a %= 2;
int d=a-b; //aritmeticsubtraction
inte=a/b; //arithmeticdivision Increment and Decrement Operators
intf=a*b; //arithmetic multiplication  The ++ and the – – are Java‟s increment and decrementoperators.
System.out.println("The Sum is :"+c);  The increment operator is unary operator that increases value of its operand by1.
System.out.println("The Subtraction is :"+d); Similarly, the decrement operator decreases value of its operand by1.
System.out.println("The Division is :"+e);  These operators are unique in that they work only on variables not onconstants.
 These are used in loops like while, do-while and forstatements.
System.out.println("The Multiplication is:"+f);
} There are two ways to use increment or decrement operators in expressions. If you put the
} operator in front of the operand (prefix), it returns the new value of the operand (incremented or
Output decremented). If you put the operator after the operand (postfix), it returns the original value of
The Sum is : -1 the operand (before the increment ordecrement)
The Subtraction is : -1 For example, this statement:
The Division is : 0 x = x + 1;
The Multiplication is : 30 can be rewritten like this by use of the increment operator: x++;
Operator Name Value returned Effect on variable
The Modulus Operator ( % ) x++ Post-increment x Incremented
The modulus operator returns the remainder of a division operation. It can be applied to ++x Pre-increment x+1 Incremented
integer types as well as floating-point types. The following program demonstrates the % x-- Post-decrement x Decremented
operator. --x Pre-decrement x+1 Decremented

MVR@Dept. Of CSE 23 MVR@Dept. Of CSE 24


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
The following program demonstrates the increment and decrement operator. (IncDec.java)
class IncDec
{
public static void main(String args[])
{
int x=5;
System.out.println("x="+(x++)); // post increment The Bitwise NOT ( ~ )
System.out.println("x="+(++x)); // pre increment One‟s complement operator (Bitwise NOT) is used to convert each 1 to 0 and 0 to 1, in the
System.out.println("x="+(x--)); // post decrement given binary pattern. It is a unary operator i.e. it takes only one operand. For example, the
System.out.println("x="+(--x)); // predecrement number 56, which has the following bit pattern:
} ~00111000  56
} 11000111 -57
Output
x=5 The Bitwise AND (&)
x =7 The Bitwise AND operator produces a 1 bit if both operands are also 1. A zero is produced in
x =7 all other cases. Here is an example:
x =5 00111000  56
&00010100  20
The Bitwise Operators 00010000  16
Java defines several bitwise operators that can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands. They are The Bitwise OR( | )
summarized in the following table: The Bitwise OR operator combines bits such that if either of the bits in the operands is a 1,
then the resultant bit is a 1, as shown here:
Operator Result 00111000  56
~ Bitwise unary NOT (Complement) |00010100  20
& Bitwise AND 00111100  60
| Bitwise OR The Bitwise XOR (^)
^ Bitwise exclusive OR
The bitwise XOR operator combines bits such that if both operands are different then the
>> Shift right
result is 1. Otherwise, the result is zero. The following example shows the effect of the ^.
>>> Shift right zero fill
<< Shift left 00111000  56
&= Bitwise AND assignment ^00010100  20
|= Bitwise OR assignment 00101100  44
^= Bitwise exclsive OR assignment
>>= Shift right assigment The following program demonstrates the bitwise logical operators:
>>>= Shift right zero fill assigment Example: ( BitwiseOp.java )
<<= Shift left assigment
class BitwiseOp
These operators are again classified into two categories: Logical operators, and Shift {
operators. public static void main(String args[])
{
The Bitwise Logical Operators int x = 56,y=20,z;
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of int a = x&y;
each operation. The bitwise operators are applied to each individual bit within each operand. int b = x|y;
int c = x^y;

MVR@Dept. Of CSE 25 MVR@Dept. Of CSE 26


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
int d = ~x;
System.out.println("x = " +Integer.toBinaryString(x));
System.out.println("y = "+Integer.toBinaryString(y));
System.out.println("x&y = "+Integer.toBinaryString(a));
System.out.println("x|y = "+Integer.toBinaryString(b));
System.out.println("x^y = "+Integer.toBinaryString(c));
System.out.println("~x = "+Integer.toBinaryString(d)); Right-shift is equals to division by 2.
}
} The following program demonstrates the bitwise logical operators:
Output Example: (ShiftOp.java )
x = 00111000 class ShiftOp
y =00010100 {
x&y = 00010000 public static void main(String args[])
x|y = 00111100 {
x^y = 00101100 int x = 4;
~x = 11000111 System.out.println("x<<1 = " +x);
System.out.println("x<<1 = " +(x<<1));
Bitwise Shift Operators System.out.println("x>>1 = "+(x>>1));
Java supports three bitwise shift operators. They are shift-left (<<) and shift-right (>>) and x=-4;
unsigned shift-right(>>>). These operations are simple and are responsible for shifting bits System.out.println("x>>>1 = "+(x>>>1));
either to left or to the right. The syntax for shift operation can be given as: }
operand operator num }
Output
where the bits in operand are shifted left or right depending on the operator (<<, >>) by the
x=4
number of places denoted by num.
x<<1 =8
x>>1 =2
The Left Shift (<<)
x>>>1 = 2147483646
When we apply left-shift, every bit in x is shifted to left by one place. So, the MSB (Most
Significant Bit) of x is lost, the LSB (Least Significant Bit) of x is set to 0.
Let us consider int x=4; Relational Operators
A relational operator, also known as a comparison operator, is an operator that
compares two operands. The operands can be variables, constants or expressions. Relational
operators always return either true or false depending on whether the conditional relationship
between the two operands holds or not.
The outcome of these operators is a Boolean value. The relational operators are most
frequently used in the expressions to control if and loop statements.

Left-shift is equals to multiplication by 2. Java has six relational operators. The following table shows these operators along with their
The Right Shift( >> ) meanings
When we apply right-shift, every bit in x is shifted to right by one place. So, the LSB (Least Operator Meaning Example
Significant Bit) of x is lost, the MSB (Most Significant Bit) of x is set to previous value. This < Less than 4<5 return true
preserves the sign of the value. > Greater than 4>5 return false
<= Less than or equal to 100<=100 return true
>= Greater than or equal to 50>=100 return false
Let us considerintx=4; Now shifting the bits towards right for 1 time, will give the = =+ Equal to 4==5 return false
followingresult. != Not equal to 4!=5 return true
The following program demonstrates the Relational operators:
MVR@Dept. Of CSE 27 MVR@Dept. Of CSE 28
Java Programming (R19) Unit-I Java Programming (R19) Unit-I
Example: ( RelOp.java ) The ? Operator
class RelOp Java includes a special ternary (three-way) operator that can replace certain types of if-then-
{ else statements. The ? has this general form:
public static void main(String args[])
{ var = expr1 ? expr2 : expr3
int x = 4,y=5; Here, expr1 can be any expression that evaluates to a boolean value. If expr1 is true, then
System.out.println(x + "<" + y +" = " + (x<y)); expr2 is evaluated; otherwise, expr3 is evaluated and its value is assigned to var.
System.out.println(x + ">" + y +" = " + (x>y));
System.out.println(x + "<=" + y +" = " + (x<=y)); The following program demonstrates the Relational operators: ( Ternary.java )
System.out.println(x + ">=" + y +" = " + (x>=y)); class Ternary
System.out.println(x + "==" + y +" = " + (x==y));
{
System.out.println(x + "!=" + y +" = " + (x!=y));
public static void main(String args[])
}
{
}
int x=4,y=6;
Output
int res= (x>y)?x:y;
4<5 = true
System.out.println("The result is :"+res);
4>5 = false
4<=5 = true }
4>=5 =false }
4==5 =false Output
4!=5 = true The result is : 6

Logical Operators (|| and &&) 1.13 Expressions


Operators which are used to combine two or more relational expressions are known as In Java programming, an expression is any legal combination of operators and operands that
logical operators. Java supports three logical operators – logical AND(&&), logical OR(||), evaluated to produce a value. Every expression consists of at least one operand and can have
logical NOT( !). These are also known as short-circuit logical operators. one or more operators. Operands are either variables or values, whereas operators are
 Logical && and logical || are binary operators whereas logical ! is an unaryoperator. symbols that represent particularactions.
 All of these operators when applied to expressions yield either true orfalse.
 When we use || operator if left hand side expression is true, then the result will be true, In the expression x + 5; x and 5 are operands, and + is an operator.
no matter what is the result of right hand sideexpression. In Java programming, there are mainly two types of expressions are available. They are as
 In the case of && if the left hand side expression results false, then the result will be follows:
false, no matter what is the result of right hand sideexpression. 1. Simple expression
2. Complexexpression
Example 1: (expr1 || expr2) Example2: (expr1 && expr2)
Simple expression: It contains one operator and two operands or constants.
Miscellaneous Operators
Example: x+y; 3+5; a*b; x-y etc.
The Assignment Operator
The assignment operator is the single equal sign, =. The assignment operator works in Java
Complex expression: It contains two or more operators and operands or constants.
much as it does in any other computer language. It has this general form:
Example: x+y-z; a+b-c*d; 2+5-3*4; x=6-4+5*2 etc.
var = expression; Operators provided mainly two types of properties. They are as follows:
Here, the type of var must be compatible with the type of expression. The assignment 1. Precedence
operator allows you to create a chain of assignments. For example, consider thisfragment: 2. Associativity
int x, y, z; Operator Precedence
x = y = z = 52; // set x, y, and z to 52 It defines the order in which operators in an expression are evaluated depends on their
relative precedence. Example: Let us seex=2+2*2

MVR@Dept. Of CSE 29 MVR@Dept. Of CSE 30


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
1st pass -- 2+2*2 1.14 Type Conversion andcasting
2nd pass -- 2+4 Type casting is a way to convert a variable from one data type to another data type. It can be
3rd pass -- 6 that isx=6. of two types: They are
1. ImplicitConversion
Associativity defines the order in which operators with the same order of precedence are 2. ExplicitConversion.
evaluated. Let us see x=2 / 2 *2
1st pass -- 2 / 2 * 2 Implicit Conversion
2nd pass -- 1*2 When the type conversion is performed automatically by the compiler without programmer‟s
3rd pass -- 2 that is x=2 intervention, such type of conversion is known as implicit type conversion or automatic type
promotion. In this, all the lower data types are converted to its next higher data type.
Below Table shows the order of precedence for Java operators, from highest to
lowest. Operators in the same row are equal in precedence. In binary operations, the order of In the case of Java, An automatic type conversion will take place if the following two
evaluation is left to right (except for assignment, which evaluates right to left). The [ ], ( ), conditions are met:
and . would have the highestprecedence.  The two types arecompatible.
 The destination type is larger than the sourcetype.
Highest(↓) Associativity When these two conditions are met, a widening conversion takes place. For example, the int
-- type is always large enough to hold all valid byte values,
++(postfix) L to R
(postfix)
-- (-) (type
++(prefix) ~ ! + (unary) L to R For widening conversions, the numeric types, including integer and floating-point types, are
(prefix) unary cast)
* / % L to R compatible with each other. However, there are no automatic conversions from the numeric
+ - L to R types to char or boolean. Also, char and boolean are not compatible with each other.
>> >>> << L to R
> >= < <= instanceof L to R The Type Promotion Rules
== != L to R Java defines several type promotion rules that apply to expressions. They are as follows:
& L to R  First, all byte, short, and char values are promoted to int, as justdescribed.
^ L to R  Then, if one operand is a long, the whole expression is promoted tolong.
| L to R
&& L to R  If one operand is a float, the entire expression is promoted tofloat.
|| L to R  If any of the operands is double, the result isdouble.
?: L to R
= op= R to L Example ( TypePromo.java )
Lowest L to R class TypePromo
{
Using Parentheses public static void main(String args[])
Parentheses raise the precedence of the operations that are inside them. This is often {
necessary to obtain the result you desire. For example, consider the followingexpression: int num=10;
a >> b + 3 float sum,f =10;
This expression first adds 3 to b and then shifts a right by that result. That is, this expression char ch='A';
can be rewritten using redundant parentheses like this: sum=num+ch+f;
a >> (b + 3) System.out.println("The value of sum = "+sum);
However, if you want to first shift a right by b positions and then add 3 to that result, you will }
need to parenthesize the expression like this: }
(a >> b) + 3 Output
The value of sum = 85.0
In addition to altering the normal precedence of an operator, parentheses can sometimes be
used to help clarify the meaning of an expression.
MVR@Dept. Of CSE 31 MVR@Dept. Of CSE 32
Java Programming (R19) Unit-I Java Programming (R19) Unit-I
Explicit Conversion (Type casting) Here the statements inside the block can be single statement or composite statements. The
It is intentionally performed by the programmer for his requirement in a Java conditional expression is any expression that returns the Boolean value. The else clause is
program. The explicit type conversion is also known as type casting. This kind of conversion optional. The if works as follows: if the conditional expression is true, then statement1 will be
is sometimes called a narrowing conversion, since you are explicitly making the value executed. Otherwise statement2 will be executed.
narrower so that it will fit into the targettype.
Example:
To create a conversion between two incompatible types, you must use a cast. A cast is Write a java program to find whether the given number is even or odd? (EvenOdd.java)
simply an explicit type conversion. It has this general form: import java.io.*;
class EvenOdd{
(target - type ) value;
public static void main(String args[])throws IOException {
Here the target type specifies the destination type to which the value has to be converted. DataInputStream dis =new DataInputStream(System.in);
Example System.out.print("Enter the value ofn:");
int a=1234; int n=Integer.parseInt(dis.readLine());
byte b=(byte)a; if(n%2==0)
The above code converts the int to byte. If the integer‟s value is larger than the range System.out.println(n+" is Even Number");
of a byte, it will be reduced modulo (the remainder of an integer division by the) byte‟s else
range. System.out.println(n+"is ODD Number");
}
A different type of conversion will occur when a floating-point value is assigned to an integer
}
type: truncation. When a floating-point value is assigned to an integer type, the fractional
Output
component is lost. For example, if the value 1.23 is assigned to an integer, the resulting value
Enter the value of n: 5
will simply be 1.The 0.23 will have been truncated.
5 is ODD Number

1.15 Flow of Control (ControlStatements)


Nested if
Control statements are used to control the flow of execution to advance and branch based on
The nested if statement is if statement, that contains another if and else inside it. When we
changes to the state of a program. Java control statements can be put into the three categories:
nest ifs, the else always associated with the nearest if. The general form of the nested if will
1. Selection
be asfollow:
2. Iteration if(conditional expr1) {
3. Jump if(conditional expr2){
statement1;
}
Iteration statements enable program execution to repeat one or more statements (that is, else { statement2; }
}
iteration statements form loops). Jump statements allow your program to execute in a }
nonlinear fashion else { statement3; }
Example
Write a java Program to test whether a given number is positive or negative. (Positive.java)
1.15.1 Selectionstatements import java.io.*;
They allow your program to choose different paths of execution based upon the outcome of
class Positive
an
{
expression or the state of a variable. They are also called as Conditional or Decision Making
public static void main(String args[]) throws IOException
Statements. These include if and switch.
{
if..else statement DataInputStream dis=new DataInputStream(System.in);
This is the Java's conditional branch statement. This is used to route the execution through
System.out.print("Enter a number to test:");
two different paths. The general form of if statement will be as follow:
int n=Integer.parseInt(dis.readLine());
if (conditional expression) { if(n>-1){
statement1;
} if(n>0)
else { System.out.println(n+ " is Positive");
statement2;
}
MVR@Dept.Of CSE 33 MVR@Dept. Of CSE 34
Java Programming (R19) Unit-I Java Programming (R19) Unit-I
} System.out.println("Vowel");
else else
System.out.println(n+ " is Negative"); System.out.println("Consonant");
} }
} }
Output Output
Enter a number to test: -1 Enter character to test:a
-1 is Negative Vowel
Enter character to test:r
The if-else-if Ladder Consonant
A common programming construct that is based upon a sequence of nested ifs is the if-else-if
ladder. It looks like this: The Switch statement
if(condition1) The switch statement is Java‟s multi-way branch statement. It provides an easy way to
statement1; dispatch execution to different parts of your code based on the value of an expression. As
else if(condition2) such, it often provides a better alternative than a large series of if-else-if statements. Here is
statement2; the general form of a switch statement:
switch(expr)
.
{
.
elseif(conditionN) case value1:
statementN; // statement sequence
else break;
case value2:
statement;
// statement sequence
break;
The if statements are executed in a sequential manner. As soon as one of the condition is true,
case valueN:
the statement associated with that if is executed, and the rest of the ladder is bypassed. If none
// statement sequence
of the conditions is true, then the final else statement will be executed.
break;
default:
Example Program:
// default statement sequence
Write a Java Program to test whether a given character is Vowel or Consonant? (Vowel.java)
}
import java.io.*;
class Vowel {  The expression must be of type byte, short, int, char orstring;
public static void main(String args[]) throws IOException  Each of the values specified in the case statements must be of a type compatible with
{ theexpression.
System.out.print("Enter character to test:");  Each case value must be a unique literal (that is, it must be a constant, not avariable).
char ch=(char)System.in.read();  Duplicate case values are not allowed.
if(ch=='a')
System.out.println("Vowel"); The switch statement works like this: The value of the expression is compared with each of
else if(ch=='e') the literal values in the case statements. If a match is found, the code sequence following that
System.out.println("Vowel"); case statement is executed. If none of the constants matches the value of the expression, then
else if(ch=='i') the default statement is executed. However, the default statement is optional. If no case
System.out.println("Vowel"); matches and no default is present, then no further action is taken.
elseif(ch=='o')
System.out.println("Vowel");
elseif(ch=='u')

MVR@Dept. Of CSE 35 MVR@Dept. Of CSE 36


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
The break statement is used inside the switch to terminate a statement sequence. When a  A switch statement is usually more efficient than a set of nestedifs.
break statement is encountered, execution branches to the first line of code that follows the
entire switch statement. This has the effect of ―jumping out of theswitch. 1.15. 2 Loops (IterationStatements)
Java‟s iteration statements are for, while, and do-while. These statements create what we
Write a Java Program to test whether a given character is Vowel or Consonant using switch? commonly call loops. A loop repeatedly executes the same set of instructions until a
importjava.io.*; termination condition is met.
classSwitchTest Advantages
{  Reduce length ofCode
public static void main(String args[]) throws IOException  Take less memoryspace.
{  Burden on the developer isreducing.
System.out.print("Enter achatacter to test:");  Time consuming process to execute the program isreduced.
char ch=(char)System.in.read();
switch(ch) while
{ The while loop is a pre-test or entry-controlled loop. It uses conditional expression to control the
//test for small letters loop. The while loop evaluates (checking) the test expression before every iteration of the loop,
so it can execute zero times if the condition is initially false. The initialization of a loop control
case 'a':
variable is generally done before the loopseparately.
System.out.println("vowel");
break; while (test expression)
case 'e': {
System.out.println("vowel"); // body of loop
break; inc/dec statement
}
case 'i':
System.out.println("vowel"); How while loop works?
break;  Initially the while loop evaluates (checking condition) the testexpression.
case 'o':  If the test expression is true , statements inside the body of while loop is evaluated.
System.out.println("vowel"); Then, again the test expression is evaluated. The process goes on until the test
break; expression isfalse.
case 'u':  When the test expression is false, the while loop isterminated.
System.out.println("vowel"); Example : Program to print 1 to 10 numbers using while loop.
break; class Test {
default: public static void main(String[] args)
System.out.println("Consonant"); {
} int n=1;
while(n<=10)
} {
} System.out.print(n+" ");
Output n++;
Enter character to test: i }
Vowel }
}
Enter character to test: x Output:
Consonant 1 2 3 4 5 6 7 8 9 10
There are three important features of the switch statement to note: do - while statement
 The switch differs from the if in that switch can only test for equality, whereas if can do-while loop is similar to while loop, however there is one basic difference between them.
evaluate any type of Booleanexpression. do-while runs at least once even if the test condition is false at first time. Syntax of do while
 No two case constants in the same switch can have identicalvalues. loop is:

MVR@Dept. Of CSE 37 MVR@Dept. Of CSE 38


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
The loop header contains three parts:
do
 aninitialization,
{
// body of loop  a test condition,and
inc/dec statement  incrementation(++) / decrementation(˗ ˗)/update.
} while (test expression);
How do-while loop works? Initialization: This part is executed only once when we are entering into the loop first time.
 First the code block (loop body) inside the braces ({….}) is executedonce. This part allows us to declare and initialize any loop control variables.
 Then, the test expression is evaluated (checking condition). If the test expression is
true, the loop body is executed again. This process goes on until the test expression is
Condition: if it is true, the body of the loop is executed otherwise program control goes
evaluated to false(0).
 When the test expression is false, the do...while loop isterminated. outside the for loop.

Example Iteration: After completion of initialization and condition steps loop body code is executed
Write a java program to add all the number from 1 to 10. (using do-while) and then increment or decrements steps is execute. This statement allows to us to update any
classTest loop controlvariables.
{
public static void main(String[] args) How for loopworks?
{  First the loop initialization statement isexecuted.
int n=1;  Then, the test expression is evaluated. If the test expression is false, for loop is
do terminated. But if the test expression is true, codes inside the body of for loop is
{ executed and the update expression is executed. This process repeats until the test
System.out.print(n+" "); expression becomesfalse.
n++;
} while (n<=10); Note: In for loop everything is optional but mandatory to place two semicolons (; ;)
} Example program: same program using the for loop
} class Test
Output: {
1 2 3 4 5 6 7 8 9 10 public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.print(i+"");
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10

for statement For each version of the for loop:


It is the most general looping construct in Java. The for loop is commonly used when the A for loop also provides another version, which is called Enhanced Version of for loop. The
number of iterations are exactly known. The syntax of a for loop is: general form of the for loop will be as follow:
for ( initialization; condition; iteration) for ( type itr_var : collection)
{ {
// body of loop // body of loop
} }

MVR@Dept. Of CSE 39 MVR@Dept. Of CSE 40


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
System.out.print(" "+i);
Here, type is the type of the iterative variable of that receives the elements from collection, i = i + 1;
}
one at a time, from beginning to the end. The collection is created using the array.
} }
Output
Example: Write a java program to print all the elements in an array? 1 2
class Test Using break as a Form of Goto
{ For example, the goto can be useful when you are exiting from a deeply nested set of loops.
public static void main(String[] args) To handle such situations, Java defines an expanded form of the break statement. By using
{ this form of break, you can, for example, break out of one or more blocks of code.
int a[ ] = {12,13,14,15,16}; The general form of the labeled break statement is shown here:
for(int x:a)
break label;
{
System.out.print(x+""); 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 enclosingblock.
Output
12 13 14 15 16 To name a block, put a label at the start of it. A label is any valid java identifier followed by a
colon. Once you have labeled a block, you can then use this label as the target of a break
1.15.3 The Jump/Branching Statements statement.
Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program. Example code:
class Break{
break statement public static void main(String args[]) {
In Java, the break statement has three uses. boolean t = true;
1. It terminates a statement sequence in a switchstatement. first: {
2. It can be used to exit aloop. second: {
3. It can be used as civilized form of gotostatement. third: {
System.out.println("Before the break.");
Using break to Exit a Loop if (t)
In Java, when break statement is encountered inside a loop, the loop is immediately breaksecond; // break out of second
terminated, and program control is transferred to nest statement following the loop. The block
break statement is widely used with for loop, while loop, do-while loop and switch statement. System.out.println("This won't execute");
Its syntax is quite simple, just type keyword break followed with asemicolon. }
break; System.out.println("This won'texecute");
}
System.out.println("This is after secondblock.");
The following example illustrates the use of break;
}
class Test { }
public static void main(String[] args) { }
int i=1; Running this program generates the following output:
while( i <= 5)
Before the break.
{
if (i==3) This is after second block.
break; continue statement

MVR@Dept. Of CSE 41 MVR@Dept. Of CSE 42


Java Programming (R19) Unit-I Java Programming (R19) Unit-I
In Java, when continue statement is encountered inside a loop, it stops the current iteration
and places the loop in next iteration. 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
Command Linearguments
loop, control goes first to the iteration portion of the for statement and then to the conditional
 The java command-line argument is an argument i.e. passed at the time of running the
expression. For all three loops, any intermediate code is bypassed. Its syntax is quite simple, java program.
just type keyword continue followed with a semicolon.  The arguments passed from the console can be received in the java program and it can
continue; be used as aninput.
 You can pass N (1,2,3 and so on) numbers of arguments from the commandprompt.
class Test {  They are stored as Strings in String array passed to the args in the mainmethod.
public static void main(String[] args) {
int i=1;  The first command line argum0ent is stored in args[0], the second argument is stored in
while( i <= 5) args[1], the third argument is stored in args[2], and soon.
{
i = i + 1; Example program:
if (i==3)
Write a Java program to read all the command line arguments.
continue;
import
System.out.print(" "+i); java.io.*;
} class CLine
} {
} public static void main(String args[])
Output {
2 4 5 6 for(int i=0;i<args.length();i++)
System.out.println("args["+i+"]:"+args[
return statement i]);
The last control statement is return. The return statement is used to explicitly return from a }
method. That is, it causes program control to transfer back to the caller of the method. As }
Output
such, it is categorized as a jump statement.
C:/>javac CLine.java
return expr/value; C:/>java Cline Vijay Anand
Example: Chintapalli args[0]: Vijay
class Test { args[1]: Anand
public static void main(String[]args) { //Caller Method args[2]:
inta=3,b=4; Chintapalli
intx=add(a,b); //function call
System.out.println("The sum is"+x);
} 0000

static int add(intx,inty) // called method


{
return (x+y);
}
}

Output
The sum is 7
After computing the result the control is transferred to the caller method, that main in this
case.

MVR@Dept. Of CSE 43 MVR@Dept. Of CSE 44

You might also like