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

Java UNIT 1 Notes-Kumar

The document provides an overview of Java programming with a focus on Object-Oriented Programming (OOP) principles, including concepts such as classes, objects, inheritance, encapsulation, and polymorphism. It contrasts procedural programming with OOP, highlighting the advantages of OOP in terms of data management and code reusability. Additionally, it discusses the applications of OOP in real-time systems, simulation, and decision support systems.
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 views40 pages

Java UNIT 1 Notes-Kumar

The document provides an overview of Java programming with a focus on Object-Oriented Programming (OOP) principles, including concepts such as classes, objects, inheritance, encapsulation, and polymorphism. It contrasts procedural programming with OOP, highlighting the advantages of OOP in terms of data management and code reusability. Additionally, it discusses the applications of OOP in real-time systems, simulation, and decision support systems.
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/ 40

JAVA PROGRAMMING

UNIT-I
Introduction to OOP, procedural programming language and object oriented language,
principles of OOP, applications of OOP, history of java, java features, JVM, program
structure. Variables, primitive data types, identifiers, literals, operators, expressions,
precedence rules and associativity, primitive type conversion and casting, flow of control.
INTRODUCTION TO OOP

TS
Object-oriented programming System (OOPs) is a programming paradigm based on the
concept of “objects” that contain data and methods. The primary purpose of object-oriented
programming is to increase the flexibility and maintainability of programs. Object oriented
programming brings together data and its behavior (methods) in a single location(object) makes it
easier to understand how a program works.

OOP is a technique that helps in designing a program more effectively using classes and
objects.Classes and objects are the basics of objected oriented programming. In an objected
oriented model, the focus is on data (contained in objects) and not on the code that manipulates
the data. A class contains instance variables, constructors and methods. We instantiate (create)
objects from these classes by invoking (calling) the constructors. Each object created from a class
has a copy of the instance variables. Each object manipulates its instance variables independently

CI
using the methods of the class. While variables represent an object, the methods help in
modification of these variables and accomplishment of tasks.

Object oriented model of programming helps to simulate real world objects in a better
way. Let's discuss how this is done by considering a 'Car' class as an example. The class can have
instance variables such as current Speed, quantityOfPetrol, and so on. We can provide methods
such as startCar(), stopCar(), chageSpeed() and so on. Some of these methods do not require any
additional information while a few others do require. For instance, startCar() and stopCar() doesn't
require any additional information while changeSpeed() requires the speed to which the car is to
be raced. This information that is to be passed is known as an argument. In conclusion, we have
BV
designed the 'Car' class and we are now capable of building a number of Car objects from them
such as 'Car1', 'Car2' and so on. Each of these objects function independently from each other by
maintaining their own sets of variables. We can, of course, make different objects such as 'Car1'
and 'Car2' interact with each other. We have now a world of cars. We have been able to
successfully build a virtual world. That is what object oriented programming is all about-
simulating the real world using objects built from classes.

The first step in OOP is to identify all the objects the programmer wants to manipulate and
how they relate to each other, an exercise often known as data modeling. Once an object has
been identified, it is generalized as a class of objects which defines the kind of data it contains and
any logic sequences that can manipulate it. Each distinct logic sequence is known as a method.
Objects communicate with well-defined interfaces called messages.

Classes and Objects:A class is said to be a blueprint for an object or collection of objects. It is a
logical entity. And object is an instance of a class. It is a physical entity. For example: chair, pen,
table, keyboard, bike etc.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
Imagine that you are an engineer, and you are drawing the plan for building a house. A plan in
itself is not the house, and it cannot be used as one. However, you can use the same plan to build
multiple houses, all sharing the same schematics. That’s the same with classes and objects. The
class is the plan. To use it, you have to instantiate an object from this class. This is done by using
the keyword new.

Example :
Object: House
State: Address, Color, Area

TS
Behavior: Open door, close door

So if I had to write a class based on states and behaviours of House. We can do it like this: States
can be represented as instance variables and behaviours as methods of the class.

class House {
String address;
String color;
double are;
void openDoor() {
//body of the method
}

}
CI
void closeDoor() {

}
...
// body of the method

PROCEDURAL PROGRAMMING LANGUAGE AND OBJECT ORIENTED LANGUAGE

Procedure Oriented Programming Object Oriented Programming


In POP, program is divided into small In OOP, program is divided into parts
BV
Divided Into
parts called functions. called objects.
In POP, Importance is not given to data In OOP, Importance is given to the data
Importance but to functions as well as sequence of rather than procedures or functions
actions to be done. because it works as a real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access OOP has access specifiers named Public,
POP does not have any access specifier.
Specifiers Private, Protected, etc.
In OOP, objects can move and
In POP, Data can move freely from
Data Moving communicate with each other through
function to function in the system.
member functions.
To add new data and function in POP is OOP provides an easy way to add new
Expansion
not so easy. data and function.
In POP, Most function uses Global data In OOP, data cannot move easily from
Data Access for sharing that can be accessed freely function to function, it can be kept public
from function to function in the system. or private so we can control the access of
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
data.
POP does not have any proper way for OOP provides Data Hiding so provides
Data Hiding
hiding data so it is less secure. more security.
In OOP, overloading is possible in the form
Overloading In POP, Overloading is not possible. of Function Overloading and Operator
Overloading.
Examples of POP are: C, VB, FORTRAN, Examples of OOP are : C++, JAVA, VB.NET,
Examples

TS
Pascal. C#.NET.

PRINCIPLES OF OOP
There are four main principles in the area of object-oriented programming:
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
ABSTRACTION:
One of the most fundamental concept of OOPs is Abstraction. Abstraction is a process

CI
where you show only “relevant” data and “hide” unnecessary details of an object from the user.
For example, when you login to your Amazon account online, you enter your user_id and
password and press login, what happens when you press login, how the input data sent to amazon
server, how it gets verified is all abstracted away from the you.
Another example of abstraction: A car in itself is a well-defined object, which is composed of
several other smaller objects like a gearing system, steering mechanism, engine, which are again
have their own subsystems. But for humans car is a one single object, which can be managed by
the help of its subsystems, even if their inner details are unknown.
Abstraction in Java is done by using an interface and abstract class in Java. In order to use
an interface or abstract class we need to explain the methods of an interface or abstract class in a
BV
sub-class.
Main advantage: the user gets data according to their needs but they don't need to use
unnecessary data.
ENCAPSULATION:
Encapsulation is binding the data with the code that manipulates it or Encapsulation means
binding all methods and classes in a single class It keeps the data and the code safe from external
interference.
Encapsulation is the technique of making the fields in a class private and providing access
to the fields via public methods. If a field is declared private then it cannot be accessed by anyone
outside the class, thereby hiding the fields within the class. The main benefit of encapsulation is
the ability to modify our implemented code without breaking the code of others who use our
code.
Encapsulation provides data hiding, maintainability, flexibility and extensibility of our code.
Advantages:
The following are a few advantages of using Encapsulation:
1. Provides the ability to change one part of code without affecting another part of code.
2. Controls the access of the user interface.
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
3. With new requirements it is easy to change encapsulated code.
4. Helps to write immutable classes in Java that are beneficial in multi-threading
environments.
5. Encapsulation in Java makes unit testing easy.
6. Reduces the coupling of modules since all pieces of the same type are encapsulated in one
place.
INHERITANCE:
The process by which one class acquires the properties and functionalities of another class

TS
is called inheritance. Inheritance provides the idea of reusability of code and each sub class
defines only those features that are unique to it, rest of the features can be inherited from the
parent class.
1. Inheritance is a process of defining a new class based on an existing class by extending its
common data members and methods.
2. Inheritance allows us to reuse of code, it improves reusability in your java application.
3. The parent class is called the base class or super class. The child class that extends the
base class is called the derived class or sub class or child class.
Note: The biggest advantage of Inheritance is that the code in base class need not be rewritten in
the child class.
The variables and methods of the base class can be used in the child class as well.
Syntax: Inheritance in Java:

}
CI
To inherit a class we use extends keyword. Here class B is child class and class A is parent class.
class B extends A
{

POLYMORPHISM:
In Core Java, Polymorphism is an easy concept to understand. Polymorphism in Greek is a
combination of poly, which means many and morphism which means forms. It refers to the
object's ability to be Polymorphic depending on its type.
There are two types of Polymorphism available in Java.
BV
1) Static Polymorphism
2) Dynamic Polymorphism
1. Static Polymorphism:
Overloading methods demonstrate the concept of polymorphism. For this reason Method
overloading is also known as Static Polymorphism.
Method Overloading: In Java method overloading we define two or more methods with the same
name but different parameters (type signatures). The methods are said to be overloaded, and the
process is referred to as method overloading.
Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding
where binding of method call to its definition happens at Compile time.
When java encounters a call to an overloaded method, it simply executes the version of
the method whose parameters match the arguments used in the call.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
EX :
class MethodOver
{
int n1;
int n2;
MethodOver()
{
n1 = 10;

TS
n2 = 20;
}
void square()
{
System.out.println("The Square is " + n1 * n2);
}
void square(int p1)
{
n1 = p1;
System.out.println("The Square is " + n1 * n2);
}
void square(int p1, int p2)

CI {

{
n1 = p1;
n2 = p2;
System.out.println("The Square is " + n1 * n2);

public static void main(String args[])

MethodOver obj1 = new MethodOver();


obj1.square(); //call non parameterized method
obj1.square(4); //call method which has 1 argument
BV
obj1.square(7,8); //call method which has 2 argument
}
}

Output :
The Square is 200
The Square is 80
The Square is 56
You can see that here we have 3 square methods with different argument. It is called method
overloading.
2. Dynamic Polymorphism: Dynamic polymorphism is also called as runtime polymorphism. We
can also call it as Method Overriding.
Method Overriding:
In a class hierarchy, when a method in a sub class has the same name and type signature as
a method in its superclass, then the method in the subclass is said to override the method in the
superclass. This feature is called method overriding.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
Points to Note:
1. Dynamic Polymorphism is also known as run time binding or late binding.
2. Dynamic binding happens at run time. Method overriding is an example of dynamic binding
where binding of method call to its definition happens at runtime.
Ex:
class Human{
//Overridden method
public void eat()

TS
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()

}
}CI
obj.eat();

Output: Boy is eating


Difference Between Method Overloading and Method Overriding:
Method Overloading
In Method Overloading, Methods of the
Method Overriding
In Method Overriding, sub class has
same class shares the same name but the same method with same name
Definition each method must have different and exactly the same number and
BV
number of parameters or parameters type of parameters and same return
having different types and order. type as a super class.
Method Overloading means more than Method Overriding means method of
Meaning one method shares the same name in the base class is re-defined in the derived
class but having different signature. class having same signature.
Method Overloading is to “add” or Method Overriding is to “Change”
Behavior
“extend” more to method’s behavior. existing behavior of method.
Polymorphism It is a compile time polymorphism. It is a run time polymorphism.
It may or may not need inheritance in It always requires inheritance in
Inheritance
Method Overloading. Method Overriding.
In Method Overloading, methods must In Method Overriding, methods must
Signature
have different signature. have same signature.
In Method Overriding, relationship is
Relationship of In Method Overloading, relationship is
there between methods of super class
Methods there between methods of same class.
and sub class.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
In Method Overloading, methods have In Method Overriding, methods have
Criteria same name different signatures but in same name and same signature but in
the same class. the different class.
Method Overloading does not require Method Overriding requires at least
No. of Classes
more than one class for overloading. two classes for overriding.
APPLICATIONS OF OOP
OOP Provides Many Applications:

TS
Real time Systems : - A real time system is a system that give output at given instant and its
parameters changes at every time. A real time system is nothing but a dynamic system. Dynamic
means the system that changes every moment based on input to the system. OOP approach is
very useful for Real time system because code changing is very easy in OOP system and it leads
toward dynamic behavior of OOP codes thus more suitable to real time system.
Simulation and Modeling: - System modeling is another area where criteria for OOP approach is
countable. Representing a system is very easy in OOP approach because OOP codes are very easy
to understand and thus is preferred to represent a system in simpler form.
Hypertext And Hypermedia : - Hypertext and hypermedia is another area where OOP approach is
spreading its legs. Its ease of using OOP codes that makes it suitable for various media
approaches.
Decision support system : - Decision support system is an example of Real time system that too

CI
very advance and complex system. More details is explained in real time system.
CAM/CAE/CAD System : - Computer has wide use of OOP approach. This is due to time saving in
writing OOP codes and

it
dynamic behavior

easy to use OOP for


of OOP
Office Automation System : - Automation system is just a part or type of real time system.
Embedded systems make
codes.

automated system.
AI and expert system : - It is mixed system having both hypermedia and real time system.
Advantages of Object Oriented Programming:
Object Oriented Programming (OOP) offers several advantages to both the program
designer and the user. The important advantages are given below:
Reusability: Elimination of redundant code and use of existing classes through inheritance. Thus
BV
provides economy of expression.
Modularity: Programs can be the built from standard working modules.
Security: Principle of information hiding helps programmers to build secure programs.
Easy Mapping: Object in the problem domain can be directly mapped to the objects in the
program.
Scalability: Can be easily upgraded from small programs to large programs. Object oriented
systems are also resilient to change and evolves over time in a better way.
Easy Management: Easy management of software complexity.
• OOP provides a clear modular structure for programs which makes it good for defining
abstract datatypes where implementation details are hidden and the unit has a clearly
defined interface.
• OOP makes it easy to maintain and modify existing code as new objects can be created
with small differences to existing ones.
• OOP provides a good framework for code libraries where supplied software components
can be easily adapted and modified by the programmer. This is particularly useful for
developing graphical user interfaces

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
• Provides a way to interact with real-world data more effectively.
• OOP allows development of solutions for real-world problems.
• Provides hiding of codes but in a procedure-oriented language the data can be accessed
from anywhere.
HISTORY OF JAVA
Java was developed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems, in the year 1991. It took 18 months to develop the first working
version. This language was initially called “Oak,” but was renamed “Java” in June, 1995. Java is an

TS
object-oriented programming language; it was originally designed for the development of
software for consumer electronic devices like TVs, VCRs, set-up boxes and other electronic
devices. Currently, Java is used in internet programming, mobile devices, games, e-business
solutions etc. The goal had a strong impact on the development team to make the language
simple, portable and high reliable. The java team which included Patrick Naughton discovered that
the existing languages like C and C++ had limitations in terms of both reliability and portability.
However, they modeled their new language Java on C and C++ but removed a number of features
of C and C++ that were considered as sources of problems and thus made Java a really simple,
reliable, portable, and powerful language.
➢ The following table shows some important milestones in the development of Java

CI
BV

2006 J2SE 6.0 was released


2011 J2SE 7.0 was released
2014 J2SE 8.0 was released
2017 J2SE 8.0 was released

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
JAVA BUZZWORDS or JAVA FEATURES
There are many features of java. They are also known as java buzzwords. The key
considerations were summed up by the Java team in the following list of buzzwords:

1. Simple 7. Portable
2. Object-Oriented 8. Dynamic
3. Platform independent 9. Interpreted

TS
4. Secured 10. High Performance
5. Robust 11. Multithreaded
6. Architecture neutral 12. Distributed

Simple : Java was designed to be easy for the professional programmer to learn and use
effectively. 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/C++ programmer, moving to Java
will require very little effort. Because Java inherits the C/C++ syntax.
Object-Oriented: Object-oriented means we organize our software as a combination of different
types of objects that incorporates both data and behavior. Object-oriented programming (OOPs) is
a methodology that simplifies software development and maintenance by providing some rules.
Platform independent: A platform is the hardware or software environment in which a program

CI
runs. There are two types of platforms software-based and hardware-based. Java provides
software-based platform. Java code can be run on multiple platforms e.g.Windows,Linux,Sun
Solaris,Mac/OS etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform independent code because it can be run on multiple platforms i.e. Write
Once and Run Anywhere(WORA).
Secured: 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.
Robust : Robust simply means strong. Java uses strong memory management. There are lack of
BV
pointers that avoids security problem. There is automatic garbage collection in java. There is
exception handling and type checking mechanism in java. All these points makes java robust.
Architecture neutral: One of the main problems facing programmers is that no guarantee exists
that if you write a program today, it will 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, anytime, forever.”
Portable: Portability is a major aspect of the Internet because there are many different types of
computers and operating systems connected to it. If a Java program were to be run on virtually
any computer connected to the Internet, there needed to be some way to enable that program to
execute on different systems. So we can carry the java byte code to any platform.
Dynamic: 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.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
Interpreted: Java is both compiled and interpreted language. Because, Java compiler translates
source code into bytecode instructions. Then java interpreter generates machine code that can be
directly executed by any machines.
High Performance: The Java bytecode was carefully designed so that it would be easy to translate
directly into native machine code for very high performance by using a just-in-time compiler(JIT).
So compared to C and C++, Java programs are executed with high performance.
Multithreaded: A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main advantage of

TS
multi-threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.
Distributed: Java is designed as a distributed language for creating applications on networks. It
has the ability to share both data and programs. Java applications can open and access remote
objects on Internet as easily as they can do in a local system. This enables multiple programmers
at multiple remote locations to collaborate and work together on a single project. Java also
supports Remote Method Invocation (RMI). This feature enables a program to invoke methods
across a network.
JAVA VIRTUAL MACHINE
JVM is an abstract computing machine. It is a specification that provides runtime
environment in which java bytecode can be executed. The output of a Java compiler is not
executable code. Rather, it is bytecode. Bytecode is a highly optimized set of instructions designed

CI
to be executed by the Java run-time system,which is called the Java Virtual Machine. In essence,
the original JVM was designed as an interpreter for bytecode.The JVM plays a central role in
making Java portable. It provides a layer of abstraction between the compiled Java program and
the underlying hardware platform and operating system. The JVM is central to Java's portability
because compiled Java programs run on the JVM. Java program execution uses a combination of
compilation and interpretation. Programs written in Java are compiled into machine language, but
it is a machine language for a computer that is, virtual and doesn't really exist. This so-called
"virtual" computer is known as the Java virtual machine (JVM). The machine language for the Java
virtual machine is called Java bytecode.
BV
Java Virtual Machine is a program that runs pre compiled Java programs, which mean JVM
executes .class files (byte-code) and produces output. The JVM is written for each platform
supported by Java included in the Java Runtime Environment (JRE). JDK is an acronym for Java
Development Kit. It physically exists. It contains JRE + development tools.
What is JVM?
It is:
1. A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment) that
means Sun’s implementations of the Java virtual machine (JVM) is itself called as JRE
3. Runtime Instance Whenever you write java command on the command prompt to run the
java class, and instance of JVM is created.
What it does?
The JVM performs following operation:
• Loads code
• Verifies code

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
• Executes code
• Provides runtime environment

Difference between JRE, JDK and JVM


In short here are few differences between JRE, JDK and JVM:
1) JRE and JDK come as installer while JVM are bundled with them.
2) JRE only contain environment to execute java program but doesn’t contain other tool for
compiling java program.

TS
3) JVM comes along with both JDK and JRE and created when you execute Java program by giving
“java” command.

CI Fig: Diagram to show the relations between JVM JRE JDK


Just-in-time Compiler (JIT):
The Just-In-Time (JIT) compiler is a component of the Java Runtime Environment (JRE). It improves
BV
the performance of Java applications by compiling bytecode to native machine code at run time.JIT
is the part of the Java Virtual Machine (JVM) that is used to speed up the execution time. JIT
compiles parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here the term “compiler” refers to a
translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a
specific CPU.
JAVA PROGRAM STRUCTURE
Let us see now how the simple java program structure will look like. You can use any editor like
notepad or any Java IDE(eclipse or NetBeans) for writing java programs.
/*This is a sample java program.
Save this file as Welcome.java
*/
class Welcome
{
// A java program will start from here.
public static void main(String args[])
{
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
System.out.println(" Welcome to Java ");
}
}
Suppose if you are entering your program in notepad, then save this file as Welcome.java
Compiling the program: After we have written our program we need to compile and run the
program. For that we need to use the compiler called javac which is provided by java. Go to the
command prompt and type the file name as shown here.
c:\>javac Welcome.java

TS
The javac compiler will create a class file called Welcome.class that contains only bytecodes. These
bytecodes have to be interpreted by a Java Virtual Machine(JVM) that will convert the bytecodes
into machine codes. Once we successfully compiled the program, we need to run the program in
order to get the output. So this can be done by the java interpreter called java. In the command
line type as shown here.
c:\>java Welcome
So the output will be displayed as
Welcome to Java
As we had seen above, when the source code has been compiled , it creates a class file with a
extension of .class. Since this class file contains the bytecodes that can be interpreted by the JVM
which can be resided at any platform. Remember that while running the program we are using
only .class file but not the .java file. So once you got the class file you can run the same java

CI
program at any platform instead of writing the program again and again. This is the very special
feature about java that 'Write once and Run anywhere'
Looking into the program line by line
Let us closely examine each part of the program.
/*
This is a sample java program
Save this file as Welcome.java
*/
This is called comment. This is for us to enter the comments about the program for our own
convenience. The contents of a comment will be ignored by the compiler. Actually java supports
BV
three styles of comments. The above one is called multi-line comment which may contain several
lines. This type of comment must begin with /* and end with */.
The next line of the code in a program is
class Welcome
{
The word class is a keyword to define a new class and Welcome is a name of the class. The class
definition must begins with opening curly brace ({) and ends with closing curly brace (}). The rest
of the things defined inside these braces are called member of the class. And note that all the
program activities are defined inside the class.
// A java program will start from here.
This is another type of comment. This is called single line comment starts with // and ends with
end of the line. Generally we use it for brief comments.
The next line of the code in a program is
public static void main(String args[])
This line begins with main method as like functions or subroutines in other languages. The
program will start execute by calling this main method. Let us see briefly about the other
attributes declared in main method. However we are going to discuss in detail about this in later
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
chapters. The keyword public is an access specifier. The keyword static is a kind of modifier. The
keyword void means that the method main() does not return any value. As we had seen before
the entire java program will start execute by calling the main method. If we want to pass any
information to a method will be received by the variables declared within the parenthesis is called
parameters. In a main() method there is only one parameter ,String args[] . args[] is a name of the
parameter that is an array of the objects of data type String. String store sequences of characters
and args will receive the command line arguments.
All the methods in java must be start with opening curly brace ({) and ends with closing curly brace

TS
(}).
The next line of the program is
System.out.println(" Welcome to Java");
System.out.println helps to display the output in the command line. As you have probably noticed,
the System.out.println statement ends with ;. All statements in java must end with semicolon. And
remember that java is case sensitive. So we should be very careful about cases while coding the
program. Otherwise it will lead to the serious problems.
In short, we can illustrate as follows:
public: It indicates that main() can be called outside the class.
static: It is an access specifier, which indicates that main() can be called directly without creating
an object to the class.
void: It indicates that the method main() doesn’t return a value.

CI
main(): It is a method which is an entry point into the java program. When you run a java
program, main() is called first.
String args [ ]: String is a class, which belongs to java.lang package. It can be used as a string data
type in java.
args[]: It is an array of string type. It is used to store command line args.
System: It is a class, which belongs to java.lang package.
out: It is an output stream object, which is a member of System class.
println(): It is a method supported by the output stream object “out”. It is used to display any kind
of output on the screen. It gives a new line after printing the output.
print(): It is similar to println(). But doesn’t give a new line after printing the output.
BV
VARIABLES
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime.
You must declare all variables before they can be used. The basic form of a variable declaration is
shown here:
datatype variable [ = value][, variable [= value] ...] ;
Here data type is one of Java's datatypes and variable is the name of the variable. To declare more
than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java:
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
➢ The names of variables in the Java language are referred to as identifiers.
Rules for naming variables:

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
➢ All variable names must begin with a letter of the alphabet, an underscore, or ( _ ), or a
dollar sign ($). The convention is to always use a letter of the alphabet. The dollar sign
and the underscore are discouraged.
➢ After the first initial letter, variable names may also contain letters and the digits 0 to 9.
No spaces or special characters are allowed.
➢ The name can be of any length, but don't get carried away. Remember that you will have
to type this name.
➢ Uppercase characters are distinct from lowercase characters. Remember that variable

TS
names are case-sensitive.
➢ You cannot use a java keyword (reserved word) for a variable name.
➢ Variable name should be meaningful.
Examples:
String i=”Raj”; //valid but not meaningful
String name=”Raj”; //valid and meaningful
int abc=7; (valid)
int _abc=8; (valid)
int abc8=9; (valid)
int 8abc=10 (invalid)
int $_abc=12; (valid)
int $_abc*=15; (invalid)

CI
Note: Some programmers use underscore in variable names to separate parts of the name, such
as shipping_weight. Others prefer a "capital style" notation, such as shippingWeight to separate
parts of the name. NEVER use uppercase for every letter in a variable name, because uppercase
names are reserved for final (constant) variables.
Types of Variable: There are three types of variables in java
➢ local variable
➢ instance variable
➢ static variable
Local Variable: A variable that is declared inside the methods, constructors or blocks is called
BV
local variable.
Instance Variable: A variable that is declared inside the class but outside the method is called
instance variable. It is not declared as static.
Static variable: A variable that is declared using static keyword is called static variable. It
cannot be local.
Example program:
class A
{
int x=12; //instance variable
static int y=13; //static variable
public static void main(String args[])
{
int z=30; //local variable
System.out.println(x);
System.out.println(y);
System.out.println(z);

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
}
}

SCOPE AND LIFETIME OF VARIABLES


Java allows variables to be declared within any block. a block is begun with an opening curly
brace and ended by a closing curly brace. A block defines a scope. Thus, each time you start a
new block, you are creating a new scope. Ascope determines what objects are visible to other
parts of your program. It also determines the lifetime of those objects. In Java, the two major

TS
scopes are those defined by a class and those defined by a method. 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.
Example program:
// Demonstrate block scope.
class Scope {
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)

CI
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
BV
}
}
As the comments indicate, the variable x is declared at the start of main( )’s scope
and is accessible to all subsequent code within main( ). Within the if block, y is declared. Since
a block defines a scope, y is only visible to other code within its block. This is why outside of its
block, the line y = 100; is commented out. If you remove the leading comment symbol, a
compile-time error will occur, because y is not visible outside of its block. Within the if block, x
can be used because code within a block (that is, a nested scope) has access to variables
declared by an enclosing scope.
Lifetime refers to the amount of time a variable exists. Variables are created when
their scope is entered, and destroyed when their scope is left. This means that a variable will
not hold its value once it has gone out of scope. Therefore, variables declared within a method
will not hold their values between calls to that method. Also, a variable declared within a block
will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope.
If a variable declaration includes an initializer, then that variable will be reinitialized each time
the block in which it is declared is entered. For example, consider the next program.
// Demonstrate lifetime of a variable.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
class LifeTime {
public static void main(String args[])
{
int x;
for(x = 0; x < 3; x++)
{
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1

TS
y = 100;
System.out.println("y is now: " + y);
}}}
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
As you can see, y is reinitialized to –1 each time the inner for loop is entered. Even though it is
subsequently assigned the value 100, this value is lost.

CI DATATYPES
The term data type refers to the type of data that can be stored in a variable. Java is
called a “strongly typed language” because when you declare a variable, you must specify the
variable’s type. Then the compiler ensures that you don’t try to assign data of the wrong type
to the variable. Java defines eight primitive types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
• Integers: This group includes byte, short, int, and long, which are for whole-valued signed
numbers.
• Floating-point numbers: This group includes float and double, which represent numbers
BV
with fractional precision.
• Characters: This group includes char, which represents symbols in a character set, like letters
and numbers.
• Boolean: This group includes boolean, which is a special type for representing true/false
values.
Data Type Default Value Default size
boolean False 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
boolean: This is used as a result of conditional statements. It represents one bit of
information. Here there are only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.
Eg. boolean a =true;
char: The char data type is used to represent the characters. It is a single 16-bit Unicode
character. Minimum value is '\u0000' (or 0). Maximum value is '\uFFFF' (or 65,535 inclusive).
So the range of char is 0 to 65535. It is important to note that Java does not support unsigned
types. All int variants are signed. But char is an exception; it is unsigned and consumes 2 bytes

TS
in memory.
Why char uses 2 bytes in java and what is \u0000 ?
Because java uses unicode system rather than ASCII code system. \u0000 is the lowest range
of unicode system. In unicode, character holds 2 bytes, so java also uses 2 bytes for characters.
Eg. char b ='z';
Here is a program that demonstrates char variables:
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';

}
CI
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}

This program displays the following output:


ch1 and ch2: X Y
Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
corresponds to the letter X.
byte: The smallest integer type is byte. This is a signed 8-bit type that has a range from –128
BV
to 127. This data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an int. Byte variables are declared by use of the byte keyword.
For example, the following declares two byte variables called b and c:
eg. byte b, c;
short: It is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-
used data type. Here are some examples of short variable declarations:
short s;
short t;
int: The most commonly used data type is int. It is a signed 32-bit type that has a range from –
2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly
employed to control loops and to index arrays. When byte and short values are used in an
expression they are promoted to int when the expression is evaluated.
Eg: int a = 10000;
long: It is a signed 64-bit type and is useful for those occasions where an int type is not large
enough to hold the desired value. The range of a long is quite large. This makes it useful when
big, whole numbers are needed. Minimum value is -9,223,372,036,854,775,808 (-2^63) and
Maximum value is 9,223,372,036,854,775,807 (2^63 -1).

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
Eg: long a = 100000L;
float : Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. For example, calculations such as square root,
division etc. The type float specifies a single-precision value that uses 32 bits of storage. Single
precision is faster on some processors and takes half as much space as double precision. float
can be useful when representing dollars and cents. The range of float is 1.4e–045 to 3.4e+038
approximately.
Example: float f1 = 234.5f;

TS
double: Double precision, as denoted by the double keyword, uses 64 bits to store a value.
Double
precision is actually faster than single precision on some modern processors. All math
functions, such
as sin( ), cos( ), and sqrt( ), return double values. Double data type should never be used for
precise values such as currency. The range of double is 4.9e–324 to 1.8e+308 approximately.
Example: double d1 = 123.4
Here is a short program that uses double variables to compute the area of a circle:
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;

CI
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
LITERALS
Java literals are fixed or constant values in a program's source code. You can use any primitive
type value as a literal e.g. Boolean,int, char and float. However, string is not a primitive type in
BV
Java yet we can use strings as literals.
For example, Here are some literals :
integer literal value : 100
floating-point literal value : 98.6
character literal value : ‘X’
string literal value : “This is a test”
A literal can be used anywhere a value of its type is allowed.
Integer Literals :
Integer literals are the primary literals used in Java programming. They come in a few different
formats: decimal, hexadecimal, and octal. These formats correspond to the base of the
number system used by the literal. Decimal (base 10) literals appear as ordinary numbers with
no special notation. Hexadecimal numbers (base 16) appear with a leading 0x or 0X. Octal
(base 8) numbers appear with a leading 0 in front of the digits.
For example, an integer literal for the decimal number 12 is represented in Java as 12 in
decimal, 0xC in hexadecimal, and 014 in octal.
Integer literals default to being stored in the int type, which is a signed 32-bit value. If you are
working with very large numbers, you can force an integer literal to be stored in the long type

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
by appending an l or L to the end of the number, as in 79L. The long type is a signed 64-bit
value.
Floating-Point Literals :
Floating-point literals in Java default to double precision. To specify a float literal, you must
append an F or f to the constant. You can also explicitly specify a double literal by appending a
D or d.
Example:
float f = 89.0; // Type mismatch: cannot convert from double to float

TS
float ff = 89.0f; //OK
double dou = 89.0D; //OK
double doub = 89.0d; //OK
double doubl = 89.0;
Boolean Literals :
Boolean literals are certainly welcome if you are coming from the world of C/C++. In C, there is
no boolean type, and therefore no boolean literals. The boolean values true and false are
represented by the integer values 1 and 0.
Java fixes this problem by providing a boolean type with two possible states: true and false.
Not surprisingly, these states are represented in the Java language by the keywords true and
false.
Boolean literals are used in Java programming about as often as integer literals because they

CI
are present in almost every type of control structure. Any time you need to represent a
condition or state with two possible values, a boolean is what you need. The two boolean
literal values: true and false.
Character Literals :
Character literals represent a single Unicode character and appear within a pair of single
quotation marks. Special characters (control characters and characters that cannot be printed)
are represented by a backslash (\) followed by the character code.
A good example of a special character is \n, which forces the output to a new line when
printed. Table shows the special characters supported by Java.
BV
Description Representation
Backslash \\
Continuation \
Backspace \b
Carriage return \r
Form feed \f
Horizontal tab \t
Newline \n
Single quote \'
Double quote \"
Unicode character \udddd
Octal character \ddd
An example of a Unicode character literal is \u0048, which is a hexadecimal representation of
the character H. This same character is represented in octal as \110.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
String Literals :
String literals represent multiple characters and appear within a pair of double quotation
marks. Unlike all the other literals discussed in this chapter, string literals are implemented in
Java by the String class. This arrangement is very different from the C/C++ representation of
strings as an array of characters.
When Java encounters a string literal, it creates an instance of the String class and sets its state
to the characters appearing within the double quotes.
Ex:”bvcits” , “1”, “kumar”

TS
OPERATORS
JAVA supports a rich set of operators. An operator is a symbol that tells the computer to
perform certain mathematical operations or logical manipulations. Operators are used in
programs to manipulate data and variables. Operators act upon data items called as operands.
JAVA operators can be classified into a number of categories. They include
1. Arithmetic operators 5. Increment and decrement operators
2. Relational operators 6. Conditional operator
3. Logical operators 7. Bitwise operators
4. Assignment operator
1. Arithmetic Operators:
JAVA provides all the basic arithmetic operators. They are listed in below table. These can
operate on any built-in data type allowed in Java.
CI Operator
+
-
*
/
%
Table : Arithmetic Operators
Meaning
Addition or unary plus
Subtraction or unary minus
Multiplication
Division
Module Division

Integer division truncates any fractional part. The modulo division produces the remainder of
an integer division.
BV
Examples of arithmetic operators are:
a+b a-b a*b a/b a%b -a*b
Here a and b are variables and are known as operands. The module division operator % can
also be used on floating point datatype in Java, whereas in C, % can’t be applied on floating
point datatype.
Arithmetic operations are classified as:
1. Integer arithmetic 2. Real arithmetic 3. Mixed mode arithmetic
Integer arithmetic: When both the operands in a single arithmetic expression such as a+b are
integers, the expression is called an “integer expression”, and the operation is called integer
arithmetic. Integer arithmetic always yields an integer value. The largest integer value
depends on the machine. In the above examples, if a and b are integers, then for a=14 and b=4
we have the following results:
a-b=10 a+b=18
a*b=56 a/b=3 (decimal part truncated)
a%b=2 (remainder of division)
During integer division, if both the operands are of the same sign, the result is truncated
towards zero. If one of them is negative, the direction of truncation is implementation
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
dependent. That is,
6/7=0 and -6/-7=0
But-6/7 may be 0 or -1 (machine dependent)
Similarly, during module division, the sign of the result is always the sign of the first operand of
the dividend. This is,
-14 % 3= -2 -14 % -3 = -2 14 % -3 = 2
Real arithmetic: An arithmetic operation involving real operands is called as “real arithmetic”.
A real operand may assume values either in decimal or exponential notation. If x, y and z are

TS
floats, then we will have
X= 6.0/7.0 = 0.857143 Y= 1.0/3.0 = 0.333333 Z= -2.0/3.0= -0.666667
The operator % can also be used with real operands in java.
Example: float a= 20.0, b= 3.0:
a+b= 23.000000 a-b= 17.000000 a*b= 60.000000 a/b= 6.666666666666667 a%b
=2.0
iii. Mixed mode arithmetic: When one of the operand is real and the other is integer, the
expression is called a “mixed mode arithmetic” expression. If either operand is of the real
type, then only the real operation is performed and the result is always a real number.
Thus 15/10.0=1.5 whereas, 15/10=1
Example: int a=3;
float b=2.0;

CI
a+b=5.0 a-b=1.0 a*b=6.0 a/b=1.50
2. RELATIONAL OPERATORS(Comparative Operators):
a % b = 1.0

We often compare two quantities, and depending on their relation, take certain decisions. For
example, we may compare the age of two persons or the price of two items and so on. These
comparisons can be done with the help of relational operators.
An expression such as, a<b or 1<20 containing a relational operators is termed as a
“relational expression”. The value of a relational expression is either 0 or 1. It is 1 if the
specified relation is true and 0 if the relation is false. For example, 10 < 20 is true so it returns
1. But 20<10 is false so it returns 0.
BV
Java supports 6 relational operators. These operators & their meanings are shown in table
below:
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
Fig : Relational Operators

A simple relational expression contains expression contains only one relational operator and
takes the following form.
ae1 relational operator ae2

Ae1 and ae2 are arithmetic expressions, which may be simple constants variables or
combinations of them. Given below are some examples of simple relational expressions and
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
their values:
4.5 <=10 TRUE 4.5 < -10 FALSE
-3.5 > =0 FALSE 10 < 7+5 TRUE
a+b==c+d TRUE only if the sum of values of a and b is equal to the sum of values of c and d.
When arithmetic expressions are used on either side a relational operator, the arithmetic
expressions will be evaluated first and then the results compared. That is, arithmetic operators
have a higher priority over relational operators. Relational expressions are used in decision
statements such as, if and while to decide the course of action of a running program.

TS
3.LOGICAL OPERATORS:
In addition to the relational operators, Java has the following 3 logical operators.
Logical Operators Meaning
&& Logical AND
Logical OR
! Logical NOT
The logical operators && and are used when we want to test more than one condition and
make decisions.
An example is : a>b && x==10
An expression of this kind which combines two or more relational expressions is termed as a
logical expression or a compound relational expression.
Like simple relational expressions, logical expression also yields a value of 1 or 0, according to
CI
the truth table shown in below table. The logical expression given above is true only if a>b is
true and x==0 is true. If either (or both) of them are false, the expression is false.
Truth table:
op1 op2 op1&&op2 op1 op2
0
0
1
0
1
0
0
0
0
0
1
1
1 1 1 1
Logical AND: The result of the logical AND expression will be true only when both the
BV
relational expressions are true.
Syntax: op1 && op2
Eg: 1) if a=9, b=4, c=14
i = (a>b) && (b<c):
The value of i in this expression will be 1.
2) i=(a<b) && (b<c)
The value of i is 0.
Logical OR: The result of logical or expression will be false only when both relational
expressions are false.
Syntax: op1 op2
Ex: i=(a<b) (b<c)
Here the value of i is 1.
i=(a<b) (b>c) Here the value of i is 0
Logical Not: The result of the expression will be true, if the expression is false & viceversa.
Syntax: !0p1
Eg: x=20
i=!(x==20)
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
The value of i = 0. This is because x==20 is true (value 1), !true(!1=0) is false(i.e, 0)
4.ASSIGNMENT OPERATORS:
Assignment operators are used to assign the result of an expression to a variable. The
assignment operator is ‘=’. In addition ‘Java’ has a set of ‘shorthand’ assignment operators of
the form
v o p = e x p;
Where v is a variable, exp is an expression and op is a c binary arithmetic operator. The
operator op= is known as the shorthand assignment operator.

TS
Assignment statement,
vop= exp; is equivalent to v=vopexp;
With v evaluated only once. Consider an example, x+=y+1;
This is same as the statement x=x+(y+1);
The shorthand operator + = means ‘add y + 1 to x ‘ or ‘increment x by y+1’. For y=2, the above
statement becomes
x+=3;
And when this statement is executed, 3 is added to x. if the old value of d is, say 5, then the
new value of x is 8.
Eg: a+=5; or a=a+5;
Some of the commonly used shorthand assignment operators are illustrated in below table
Statement with simple assignment Statement with shorthand operator
CI
operator
a=a+1
a=a-1
a=a*(n+1)
a=a/(n+1)
a=a%b
The use of shorthand assignment operators has three advantages
a+=1
a-=1
a*=n+1
a/=n+1
a%=b

1. What appears on the left hand side need not be repeated and therefore it becomes
easier to write.
BV
2. The statement is more concise and easier to read.
3. The statement is more efficient.
5.INCREMENT AND DECREMENT OPERATORS :
C has two very useful operators , these are increment (++) and decrement (--) operators ++
add 1 o the operand while subtracts 1. These are unary operators and take the following
form.
Operator Action
a++ post – increment
++a pre-increment
a-- post decrement
--a pre decrement
Suppose, if we take a=5,
y= a++,
Then, the value of y would be 5 and a would be 6.
A prefix operator first adds 1 to the operand and then the result is assigned to the variable in
left. On the other hand, a postfix operator first assigns the value to the variable on left then

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
increments the operand.
Similar is the case, when we use ++ (or--) in subscripted variables. That is, the statement,
a[i++]=10
is equivalent to
a [i ] =10,
i = i+1
Examples:
1. int a = 8;

TS
y=++a;
The value of y will be 9, and a is also 9
2. int a=8;
y=a++;
The value of y will be 8, and a is also 9.
3. int a=5;
y=--a;
the value of y will be 4, and a is also 4.
4. int a=5;
y=a--;
The value of y will be 5, and the value of a is 4
6.Conditional Operator: It is also called as ternary operator (?:)

CI
Syntax: exp1?exp2:exp3;
Where exp1, exp2 and exp3 are expressions.
The operator ? : works as follows:
Exp1 is evaluated first. If it is non zero (True) , then the expression exp2 is evaluated and
becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes
the value of the expression. Note that only one of the expressions (either exp2 or exp3) is
evaluated. For example consider the following statements.
int a=10,b=15;
x=(a>b)?a:b;
BV
Here, x will be assigned the value of b. because the condition (a>b) is false. So, exp3 is
evaluated.
This can be achieved using the if…. else statements as follows..
if(a>b)
x=a;
else
x=b;
Example: int a=5, b=10, c=15;
y=(a>b)?b:c;
In the above statement, the expression a>b is evaluated since,, it is false, so value of c will be
assigned to y. so value of y will be 15.
y = (a<b) ? b:c; Here a<b is true, so value of b is assigned to y. so value of y will be 10.
7.BITWISE OPERATORS:
These operators are used for manipulation of data at bit level. When bitwise operators are
used with variables they are internally converted to binary numbers and then bitwise
operators are applied on individual bits. These operators work with char and int data types.
They can’t be used with float or double. These operators & their meanings are shown in

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
below;
Operator Meaning
& Bitwise AND
Bitwise OR
^ Bitwise exclusive OR
<< Left Shift
>> Right Shift
~ One’s complement

TS
>>> Right Shift filled with 0’s
Table: Bitwise Operators
Bitwise AND: If two bits are set to 1, then the result is 1 otherwise the result is 0.
Truth Table
A B a&b
0 0 0
0 1 0
1 0 0
1 1 1
Ex: If a=4 (0100), b=6 (0110) Then c=a&b (0100)
Bitwise OR: If either of the bit is 1, then the result is set to 1, otherwise the result is 0.

Ex:
CI A
0
0
1
1
If a=4 (0100) b=6 (0110) Then

A
B
0
1
0
1

B
c=a b = 0110
ab
0
1
1
1

Bitwise XOR: If one bit is 0 and other is 1, then the result is set to 1, otherwise 0.
a^b
0 0 0
BV
0 1 1
1 0 1
1 1 0
Ex: If a=4 (0100) b=6 (0110) then c=a^b = 0010
Left Shift Operator (<<) :
This operator is useful when we want to multiply an integer by a power of 2.
a<<b
The above expression returns the value of a multiplied by 2 to the power of b.
Ex.
5<<1=10 /*5*21=10*/
5<<2=20 /*5*22=20*/
5<<3=40 /*5*23=40*/
10<<2=40 /*10*22=40*/
4<<2=16 /*4*22=16*/
Consider the example 4<<2 by using binary values.
The equivalent binary value of 4 is 00000100. So 4<<2 means, it shifts the binary bits twice. So
we get 00010000. The decimal value of 00010000 is 16.

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
Right shift operator (>>)
This operator does the opposite to the left shift operator, and takes way bits on the right.
a>>b
This expression returns the value of a divided by 2 to the power of b.
8>>2 /*8/22*/
4>>1 /*4/22*/
5>>2 /*5/22*/
Consider the example 5>>2 by using binary values, the equivalent binary value of 5 is 0101. So,

TS
5>>2 means we want to remove last two bits then the binary number is 0001, it is equivalent
to decimal number 1.
One’s Complement :
The operator is represents as ~ and operates on one operand. For a binary number if we take
one’s complement all zero’s become 1 and one’s become 0’s.
Example: x=0001
~x=1110
Right Shift filled with 0’s: Zero fill shift right is represented by the symbol >>>. This operator
fills the leftmost bits by zeros. So the result of applying the operator >>> is always positive. (In
two's complement representation the leftmost bit is the sign bit. If sign bit is zero, the number
is positive, negative otherwise.) The example below illustrates applying the operator >>> on a
number.
int
CI b = 13; // 00000000

of applying the operator >>> on a negative number.


int b = -11; //11111111
00000000
b = b >>> 2; // b is now 00000000 00000000 00000000 0000 0011

11111111
b = b >>> 2; // b now becomes 00111111 11111111 11111111 1111 1101
00000000

11111111
0000

1111

So the result of applying zero fill right shift operator with operand two on -11 is 1073741821.
1101

So the result of doing a zero fill right shift by 2 on 13 is 3. The next example explains the effect

0101

Note: For positive numbers the signed right shift operator and the zero fill right shift operator
both give the same results. For negative numbers, their results are different.
BV
EXPRESSIONS
An expression is a combination of variables, constants and operators arranged as per the
syntax of the language. Java can handle any complex mathematical expressions. Some of the
examples of Java expressions are shown in the below table.
Algebraic Expressions Java Expressions
axb-c a*b-c
(m+n)(x+y) (m+n)*(x+y)
a*b/c
3x2+2x+1 3*x*x+2*x+1
x/y+c
Table : Expressions
Evaluations of Expressions:
Expressions are evaluated using as assignment statement of the form
variable = expression;
variable is any valid Java variable name. When the statement is encountered, the expression is

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
evaluated first and the result then replaces the previous value of the variable on the left-hand
side. All the variables used in the expression must be assigned values before evaluation is
attempt. Examples of evaluation statements are
x=a*b-c;
y=b/c*a;
z=a-b/c+d;
the blank space around an operator is optional and adds only to improve readability. When
these statements are used in a program, the variables a,b,c and d must be defined before they

TS
are used in the expressions.
Rules for evaluation of expression:
➢ First parenthesized sub expressions from left to right are evaluated.
➢ If parenthesis are nested, the evaluation begins with the innermost sub expression.
➢ The “precedence” rule is applied when two or more operators of the same precedence
level appear in a sub expression.
➢ Arithmetic expressions are evaluated from left to right using the rules of precedence.
➢ When the parenthesis are used, the expressions within the parenthesis assume highest
priority.
Precedence of Arithmetic operators:
An arithmetic expression without parenthesis will be evaluated from left to right using the
rules of precedence of operators. These are two distinct priority levels of arithmetic operators

CI
in Java.
High Priority *, /, % Low Priority +, -
The basic evaluation procedure includes two left – to – right passes through the expression.
During the first pass, the high priority operators (if any) are applied as they are encountered.
During the second pass, the low priority operators (if any) are applied as they are
encountered.
/* Program evaluation of expressions*/
class Example
{
BV
public static void main(String args[])
{
float a=9,b=12,c=3,x,y,z;
x=a-b/3+c*2-1;
y=a-b/(3+c)*(2-1);
z=a-(b/(3+c)*2)-1;
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
}
OUTPUT: x=10.000000
y=7.000000
z=4.000000
when a=9,b=12,c=3, the statement becomes
And is evaluated as follows
First pass : Step 1 :

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
Step 2 :
Second Pass: Step 3 :
Step 4:
Step 5 :
However , the order of evaluation can be changed by introducing parenthesis into an
expression. Consider the same expression with parenthesis as shown below.

Whenever parentheses are used, the expressions within the parenthesis assume highest

TS
priority. If two or more sets of parenthesis appear one after another as shown above, the
expression contained in the left most set is evaluated first and the right most in the in the last.
Given below are the new steps:
First Pass: Step 1 :
Step 2 :
Second Pass: Step 3 :
Step 4:
Third Pass: Step 5 :
This time the procedure consists of three left to right passes. However the number of
evaluation steps remain the same as 5. (i.e. equal to the number of arithmetic operators).
Parenthesis may be nested, and in such cases, evaluation of expression will proceed outward

CI
from the inner most set of parenthesis, just make sure that every opening parenthesis has a
matching closing one. For example

Whereas
While parenthesis allows us to change the order of priority, we may also use them to improve
understandability of the program.

PRECEDENCE RULES AND ASSOCIATIVITY


Java has well-defined rules for specifying the order in which the operators in an
BV
expression are evaluated when the expression has several operators. For example,
multiplication and division have a higher precedence than addition and subtraction.
Precedence rules can be overridden by explicit parentheses.
Precedence order:
When two operators share an operand the operator with the higher precedence goes first. For
example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since
multiplication has a higher precedence than addition.
Associativity:
When an expression has two operators with the same precedence, the expression is evaluated
according to its associativity. For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving
all three variables with the value 17, since the = operator has right-to-left associativity (and an
assignment statement evaluates to the value on the right hand side). On the other hand, 72 / 2
/ 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity.
Precedence and associativity of Java operators:
The table below shows all Java operators from highest to lowest precedence, along with their
associativity. Most programmers do not memorize them all, and even those that do still use
parentheses for clarity.
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
Operator Description Level Associativity
[] access array element
. access object member
() invoke a method 1 left to right
++ post-increment
-- post-decrement

TS
++ pre-increment
-- pre-decrement
+ unary plus
2 right to left
- unary minus
! logical NOT
~ bitwise NOT
() cast
3 right to left
new object creation
*
/ multiplicative 4 left to right
%
+
+
<<
CI
>>>
< <=
>>
- additive
string concatenation

shift
5

6
left to right

left to right

relational
> >= 7 left to right
type comparison
BV
instanceof
==
equality 8 left to right
!=
& bitwise AND 9 left to right
^ bitwise XOR 10 left to right
| bitwise OR 11 left to right
&& conditional AND 12 left to right
|| conditional OR 13 left to right
?: conditional 14 right to left
= += -=
*= /= assignment 15 right to left
%=

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
&= ^=
|=
<<= >>=
>>>=
PRIMITIVE TYPECONVERSION AND CASTING
If you have previous programming experience, then you already know that it is fairly common
to assign a value of one type to a variable of another type. If the two types are compatible,

TS
then Java will perform the conversion automatically. For example, it is always possible to
assign an int value to a long variable. However, not all types are compatible, and thus, not all
type conversions are implicitly allowed. For instance, there is no automatic conversion defined
from double to byte. Fortunately, it is still possible to obtain a conversion between
incompatible types. To do so, you must use a cast, which performs an explicit conversion
between incompatible types. Let’s look at both automatic type conversions and casting.
Java’s Automatic Conversions:When one type of data is assigned to another type of variable,
an automatic type conversion will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. That means the data
type of smaller size is converted into higher size then implicit casting is done. It will done by

CI
compiler itself. This process is also called as widening. For example, the int type is always large
enough to hold all valid byte values, so no explicit cast statement is required.
Ex:
class Example {
public static void main(String[] args) {
byte b = 120;
int i ;
i = b;
System.out.println("b is " + b);
BV
System.out.println("i is " + i);
}
}
Output: b is 120
i is 120
Casting Incompatible Types:Although the automatic type conversions are helpful, they will
not fulfill all needs. For example, what if you want to assign an int value to a byte variable?
This conversion will not be performed automatically, because a byte is smaller than an int.
This kind of conversion is sometimes called a narrowing conversion, since you are explicitly
making the value narrower so that it will fit into the target type. To create a conversion
between two incompatible types, you must use a cast. A cast is simply an explicit type
conversion. It has this general form:
(target-type) value;
Here, target-type specifies the desired type to convert the specified value to. For example, the
following fragment casts an int to a byte. If the integer’s value is larger than the range of a
byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range.
int a;

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
byte b;
// ...
b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to an integer
type: truncation. As you know, integers do not have fractional components. Thus, when a
floating-point value is assigned to an integer type, the fractional component is lost. For
example, if the value 1.23 is assigned to an integer, the resulting value will simply be 1. The
0.23 will have been truncated. Of course, if the size of the whole number component is too

TS
large to fit into the target integer type, then that value will be reduced modulo the target
type’s range.
The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Example{
public static void main(String[] argc) {
byte b;
int i =257;
b = (byte)i;
System.out.println("b is " + b);
System.out.println("i is " + i);
}
}
CI
Output: b is 1
i is 257
When the value 257 is cast into a byte variable, the result is the remainder of the division of
257 by 256 (the range of a byte), which is 1 in this case. So the value of b is 1.
Some examples of casts and their actions are shown in below table :
Example
x=int(7.5)
Action
7.5 is converted to integer by truncation.
a=(int)21.3/(int)4.5 Evaluated as 21/4 & the result would be 5.
BV
b=(double)sum/n Division is done in floating point mode.
y=(int)(a+b) The result of a+b is converted to integer.
z=(int)a+b a is converted to integer and then added to b.
p=cos((double)x) Converts x to double before using it.
Explicit casting means when the higher type of data is converted into lower type data, then
some value may be truncated. This process is called narrowing.

FLOW OF CONTROL OR CONTROL STATEMENTS


In Java, control statements can be divided into the following three categories:
• Selection Statements
• Iteration Statements
• Jump Statements
Selection Statements
Selection statements allow you to control the flow of program execution on the basis of the
outcome of an expression or state of a variable known during runtime. Selection statements
can be divided into the following categories:

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
• The if statement
• The if-else statement
• The nested if statement
• The if-else-if statement
• The switch statement
The if statement
The first contained statement (that can be a block) of an if statement only executes when the
specified condition is true. If the condition is false and there is not else keyword then the first

TS
contained statement will be skipped and execution continues with the rest of the program.
The condition is an expression that returns a boolean value.
Syntax :
if (condition)
{
statement1;
}
When the condition is true the Statement within the if is executed. After that execution
continues with the next statement after the if statement.
If the condition is false then the statement within the if is not executed and the execution
continues with the statement after the if statement.
Ex: if(a>=0)

CI{

}
System.out.println(“ a is positive”);

System.out.println(“ a is negative”);
Here if we give a value is -5 then it will be executed the statement a is negative but when we
give a value is 5 then it will be executed both the print statements because there is no else in
simple if statements. That’s the reason simple if is also called as null else statement.
if-else statement:
If-else statement is used for test condition to check whether the statement is true or false.
BV
Depending upon the condition, the control statement exists. The syntax for if-else statement
is
Syntax :
if (condition)
{
statement1;
}
else
{
statement2;
}
The if else work like this: If the condition is true, then statement1 is executed. Otherwise,
statement2 is executed. In no case will both statements be executed.
Ex: if(a>=0)
{
System.out.println(“ a is positive”);
}

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
else
{
System.out.println(“ a is negative”);
}
Here if we give a value is -5 then it will be executed the statement a is negative and when we
give a value is 5 then it will be executed the statement a is positive.
Nested if : A nested if is an if statement that is the target of another if or else.
Syntax :

TS
if(condition)
{
if(condition)
statements....
else
statements....
}
else
{
if(condition)
statements....
else

}
Ex.
CI statements....

import java.util.Scanner;
class MaxValue
{
public static void main(String args[])
{
int a,b,c;
BV
int max=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter value for a : ");
a=s.nextInt();
System.out.println("Enter value for b : ");
b=s.nextInt();
System.out.println("Enter value for c : ");
c=s.nextInt();
if (a>b)
{
if(a>c)
max=a;
else //This else is associate with this if(a>c)
max=c;
}
else //This else is associate with this if(a>b)
{

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
if(b>c)
max=b;
else //This else is associate with this if(b>c)
max=c;
}
System.out.println("\n max value = " +max);
}
}

TS
Output: max value=15
if-else-if Ladder :
Syntax :
if(condition)
statements;
else if(condition)
statements;
else if(condition)
statements;
...
...
else

CI
statements;
The if statements are executed from the top down. 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.
Ex:
BV
import java.util.Scanner;
class example
{
public static void main( String[] args )
{
int age;
Scanner s = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = s.nextInt();
if ( age >= 18 && age <=35 )
System.out.println( "between 18-35 " );
else if(age >35 && age <=60)
System.out.println("between 36-60");
else
System.out.println( "your age is above 60" );
}
}

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
switch statement:
The switch statement is Java’s multiway branch statement. It provides an 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. Here is the general
form
of a switch statement:
switch (expression) {
case value1:

TS
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}

CI
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. However, the default statement is optional. If no case
matches and no default is present, then no further action is taken. The break statement is
used inside the switch to terminate a statement sequence. When a 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 the switch.
Here is a simple example that uses a switch statement:
BV
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
default:
System.out.println("i is greater than 3.");
}
}
}
The output produced by this program is shown here:
i is zero.
i is one.

TS
i is two.
i is three.
i is greater than 3.
i is greater than 3.
Iteration Statements: Repeating the same code fragment several times until a specified
condition is satisfied is called iteration. Iteration statements execute the same set of
instructions until a termination condition is met.
Java provides the following loop for iteration statements:
• The for loop
• The while loop
• The do-while loop
for loop :

CI • The for loop repeats a set of statements a certain number of times until a condition is

Syntax :
matched.
• It is commonly used for simple iteration. The for loop appears as shown below.

for (initialization; condition; increment/decrement)


{

}
Set of statements;

• In the first part a variable is initialized to a value.


BV
• The second part consists of a test condition that returns only a Boolean value. The last
part is an updation; it can be evaluated every time the loop is executed.
• The following example depicts the usage of the for loop.

class Example
{
public static void main(String args[])
{
int i;
for (i=1;i<=5;i++)
{
System.out.println(i);
}
}
}
Output: 1
2

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
3
4
5
while loop:
• The while loop executes a set of code repeatedly until the condition returns false.
• The syntax for the while loop is given below:
Syntax :
while (condition)

TS
{
body(statements) of the loop
}
• Where <condition> is the condition to be tested. If the condition returns true then the
statements inside the <body of the loop> are executed.
• Else, the loop is not executed.
class Example
{
public static void main(String args[])
{
int i=1;
while(i<=5)

}
CI}

do-while:
{

}
System.out.println(i);
i++;

• The do while loop is similar to the while loop except that the condition to be evaluated
is given at the end.
BV
• Hence the loop is executed at least once even when the condition is false.
• The syntax for the do while loop is as follows:

Syntax :
do
{
body of the loop
} while (condition);

In do while loop semicolon(;) is compulsory after while.

NOTE : for and while loops are entry control loop because here conditions are checked at
entry time of loop but do while loop is exit control loop because the condition is checked at
exit time.
class Example
{
public static void main(String args[])

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
{
int i = 1;
int sum = 0;
do
{
sum = sum + i;
i++;
}while (i<=10);

TS
System.out.println("\n\n\tThe sum of 1 to 10 is .. " + sum);
}
}
Output :
The sum of 1 to 10 is .. 55
Jump statements: These are used to unconditionally transfer the program control to another
part of the program. Java provides the following jump statements:
• break statement
• continue statement
• return statement
break statement : The break statement immediately quits the current iteration and goes to
the first statement following the loop. Another form of break is used in the switch statement.

CI
The break statement has the following two forms:
• Labeled break Statement
• Unlabeled break Statement
Unlabeled break Statement: This is used to jump program control out of the specific loop on
the specific condition.
Ex: class Example
{
public static void main( String[] args )
{
BV
for ( int var = 0; var < 5; var++ )
{
System.out.println( "Var is : " + var );
if ( var == 3 )
break;
}
}
}
Output:
Var is 0
Var is 1
Var is 2
Var is 3
Labeled break Statement: This is used for when we want to jump the program control out of
nested loops or multiple loops.
Ex:
class Example

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
{
public static void main( String[] args )
{
Outer: for ( int var1 = 0; var1 < 5; var1++ )
{
for ( int var2 = 1; var2 < 5; var2++ )
{
System.out.println( "var1:" + var1 + ", var2:" + var2 );

TS
if ( var1 == 3 )
break Outer;
}
} } }
Output:

CI
continue statement:
• This statement is used only within looping statements.
• When the continue statement is encountered, the next iteration starts.
• The remaining statements in the loop are skipped. The execution starts from the top
of loop again.
The program below shows the use of continue statement.
BV
class Example
{
public static void main(String args[])
{
for (int i=1; i<=10; i++)
{
if (i%2 == 0)
continue;
System.out.println( i);
}
}
}
Output :
1
3

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
5
7
9
return statement : This is used to immediately quit the current method and return to the
calling method. It is mandatory to use a return statement for non-void methods to return a
value.
class ReturnDemo
{

TS
public static void main( String[] args )
{
ReturnDemo r = new ReturnDemo();
System.out.println( "No : " + r.returnCall() );
}
int returnCall()
{
return 5;
}
}
Output: No: 5

CI
BV

BVCITS –BATLAPALEM Prepared By,


A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer

You might also like