[Go to site: main page, start]

0% found this document useful (0 votes)
12 views71 pages

Java Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts, particularly in Java, highlighting its features such as encapsulation, inheritance, and polymorphism. It explains the structure of Java programs, including classes and objects, and discusses the benefits and applications of OOP. Additionally, it covers the history and milestones of Java's development, emphasizing its platform independence and various features that make it suitable for modern programming needs.

Uploaded by

thenvithi
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)
12 views71 pages

Java Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts, particularly in Java, highlighting its features such as encapsulation, inheritance, and polymorphism. It explains the structure of Java programs, including classes and objects, and discusses the benefits and applications of OOP. Additionally, it covers the history and milestones of Java's development, emphasizing its platform independence and various features that make it suitable for modern programming needs.

Uploaded by

thenvithi
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

Course Content

FUNDAMENTALSOFOBJECTORIENTED-PROGRAMMING
INTRODUCTION:

​ Object-oriented programming is an approach to development and an organization that attempts to


eliminate some of the flaws of conventional programming.
​ It involves new ways of organizing and developing programs and does not concern using a particular
language.
​ C++is a procedural language with object oriented extension.

​ Java, a pure object oriented language.


Languages supporting OOP features include Smalltalk, Objective C, C++, Ada, Pascal, and Java.

Definition of OOPS Concepts in Java


“Object-oriented programming is an approach that modularizes programs by creating a partitioned memory
area for both functions and data that can be used as templates for creating copies of such modules on demand.”

OOPS Paradigm
​ The primary objective of the object-oriented approach is to eliminate some of the pitfalls that exist in the
procedural approach.
​ OOPS allows decomposing a problem into several entities called Objects and then builds data and
functions from these entities. The combination of the data makes up an object.

Object=Method+ Data

​ The data of an object is accessed by the methods associated with that object. However, the methods of
an object can access methods of other objects.

Features of OOPS

Java is a robust and scalable object-oriented programming language that is based on the concept of objects and
classes.
Some features of object-oriented programming in java are:

●​ Emphasis is on data than procedures


●​ Programs are divided into objects
●​ Data Structures are designed to characterize objects.
●​ Methods operating on the data of an object are tied together in the data structure.
●​ Data is hidden, and external functions cannot access it.
●​ Objects communicate with each other through methods
●​ New methods and data can be easily added whenever necessary
●​ Follows the bottom-up approach in program design
General OOPS concepts in Java:

Objects and Classes

​ Objects are runtime entities in an object-oriented system.

​ An object can represent a person, a bank account, a place, a table of data.

​ Any programming problem is analyzed based on objects and how they communicate amongst
themselves. The objects interact with each other by sending messages to one another when a program is
executed.

​ For Example, ‘customer’ and ‘account’ are two objects that may send a message to the account object
requesting for the balance. Each object contains code and data to manipulate the data. Objects can even
interact without knowing the details of each other’s code or data.

​ The entire set of code and data of an object can be made user-defined data type using the concept of the
class. A class is a ‘data-type’ and an object as a ‘variable’ of that type. Any number of objects can be
created after a class is created.

​ The collection of objects of similar types is termed as a class. For Example, apple, orange, and mango
are the objects of the class Fruit. Classes behave like built-in data types of a programming language but
are user-defined data types.

Representation of an Object

Data Abstraction and Encapsulation


The wrapping up of the data and methods into the single unit is known as Encapsulation. The data is accessible
only to those methods, which are wrapped in the class, and not to the outside world.
This insulation of data from the direct access of the program is called Datahiding.
Encapsulation-Objects as “black-boxes”
Abstraction is the act of reducing programming complexity by representing essential features without including
the background explanations or details. Classes wrap or encapsulate all the essential properties of the objects that
are to be created.

Inheritance

​ Inheritance is the process by which objects of one class acquire some properties of objects of another
class. Inheritance supports the concept of hierarchical classification.

​ In OOP, the idea of inheritance provides the concept of reusability. It means that we can add additional
features to the parent class without modification; this is possible by deriving a new class from the parent
class.

​ The new class consists of the combined features from both the classes. In Java, the derived class is also
known as the subclass.

​ For Example, a bird Robin is part of the class, not a mammal, which is again a part of the class Animal.
The principle behind this division is that each subclass shares common characteristics from the class
from its parent class.

Properties of Inheritance

​ Types of Inheritance

●​ Single
●​ Multiple
●​ Multilevel
●​ Hybrid

Polymorphism

▪​ Polymorphism means the ability to take many forms. For Example, an operation exhibits different behavior
in different situations.
▪​ Example: A single function name can be used to handle the different numbers and different types of
arguments.
o​ In polymorphism, objects having different internal structures can share the same external interface

o​ Inheritance extensively uses the concept of polymorphism.

o​ Polymorphism can be achieved in two ways:

●​ Method Overloading
●​ Method Overriding

​ Binding is the process of linking a procedure call to the code to be executed in response to the call.

​ It means that the code associated with the given procedure call is not known until the time of the call at
runtime.

​ It is associated with inheritance and polymorphism.

Message Communication

​ Objects communicate with each other in OOPs. The process of programming in case of OOP consists of the
following:

●​ Creating classes defining objects and their behavior.


●​ Creating objects
●​ Establishing communication between objects.

The network of Objects Communicating with Each Other


​ Specifying the object name, the method name, and the information to be sent is involved in message
passing.

​ Objects can be created or destroyed as they have a life cycle. It allows communication between the
objects until the objects are alive.

Benefits of OOPs

●​ Inheritance eliminates redundant code and enables reusability.


●​ As Message passing allows communication with objects, this presents writing code from scratch every
time. It is thus saving development time and higher productivity.
●​ The principle of data hiding helps the programmer to build secure programs that cannot be invaded by a
code in other parts of the program.
●​ It is possible to have multiple objects to coexist without any interference.
●​ It is easy to partition work in a project based on classes and objects.
●​ System up-gradation is easy from small to larger systems.
●​ Software complexity can be easily managed.

Applications of OOPs
●​ Real-time systems
●​ Simulation and modeling
●​ Object-oriented databases
●​ Hyper text and Hypermedia
●​ AI and expert systems
●​ Neural networks and parallel programming
●​ Decision support and office Automation systems
●​ CIM/CAD/CAD System.
​ Java is the general purpose, true object oriented programming language and is highly
suitable for modeling the real world and solving the real world problems.

​ In the company Sun Microsystem, James Goslings(an employee there), started a project
named „GREEN‟.

​ So James Goslings started to develop a new language known as“OAK”.Inmay1995,Sun


officially announced this language at Sunworld [Link] to some reasons, the name was
changed to “JAVA”.

​ The prime motive of Java was the need for a platform independent language.

​ The second motive was to design a language which is “Internet Enable”. To run the
programs on the internet, the Green project team came up with the idea of developing
“Web Applet”. The team developed a web browser called “Hot Java” to locate and run
applet programs on the internet.

​ The most striking feature of Java is “Platform neutralness”. Java is the first language
that is not tied to any particular hardware or O.S.

JAVA MILESTONES

YEAR DEVELOPMENT
1990 Sun Microsystem started to develop special software for electronic devices.
1991 James Goslings developed a new language “OAK”.
1992 The new language Oak was demonstrated in handheld devices.
1993 WorldWideWeb(WWW) appeared on the internet and transformed the text based
internet to a graphical environment. Sun developed Applets.
1994 The Green project team developed a web browser “Hot Java” to run applets on the
internet.
1995 Oak was renamed to JAVA.
1996 Java established itself as the leader of internet programming. Sun released Java
development kit 1.0.
1997 Sun released Java development kit1.1 (JDK1.1).
1998 Sun released Java2 with version1.2 (SDK1.2).
1999 Sun released Java2 standard edition (J2SE) and Enterprise Edition(J2EE).
2000 J2SE with SDK1.3 was released.
2002 J2SE with SDK1.4 was released.
2004 J2SE with JDK5.0 was released.
Features of Java

Some following Features of Java are given below:


1.​Simple and Small
2.​Compiled and Interpreted
3.​Platform-Independent and Portable
4.​Object-Oriented
5.​Distributed
6.​Multithreaded
7.​Dynamic and Extensible
8.​High performance
9.​Ease of Development
10.​Scalability
11.​Monitoring and Manageability
12.​Desktop Client

1.​ Simple and Small: Java is a small and simple language, Many features of C and C++ that are either
redundant or sources of unreliable code are not part of Java. Such as Java does not use pointers, preprocess or
header files, goto statements and many others. It also eliminates operator overloading and multiple inheritances.

2.​ Compiled and Interpreted: Generally a computer language is either compiled or interpreted. Java
combines both these approaches thus making java a two-stage system. First, the Java compiler translates source
code into byte code instruction. Byte code instructions are not machine instructions. In the second stage, Java
interpreter generates machine code that can be directly executed by the machine that is running the java
program. So,we can say that Java is both a Compiled and Interpreted Language.
3.​ Platform-Independent and Portable : Java ensures portability in two ways, first, Java compiler
generates byte code instructions that can be implemented on any machine. Second, the size of the primitive data
types is Machine-Independent. The most significant contribution of Java over other languages is its portability.
Java programs can be easily moved from one computer system to another.
4.​ Object-Oriented: Java is a true object-oriented language. Almost everything in Java is an object. All
program code and data reside within objects and classes. Java comes with an extensive set of classes, arranged
in packages.
5.​ Distributed : Java is designed as a distributed language for creating applications on networks. It can
share both data and programs. Java applications can open and access remote objects on the Internet as easily as
they can do in a local system. This enables multiple programs at multiple remote locations to collaborate and
work together on a single project.
6.​ Multithreaded : Multithreaded means handling multiple tasks simultaneously. Java supports
multithreaded programs. This means that we need not wait for the application to finish one task before
beginning another.
7.​ Dynamic and Extensible : Java is a dynamic language, Java is also capable of dynamically linking in
new class libraries, methods, and objects. Java can also determine the type of class through a query, making it
possible to either dynamically link or abort the program depending on the response.
8.​ High performance : Java performance is impressive for an interpreted language, mainly due to the use
of intermediate bytecode. According to Sun, Java speed is comparable to the native C/C++. Java architecture is
also designed to reduce overheads during run-time.
9.​ Ease of Development : Java2 Standard Edition(J2SE) 5.0 supports features –Generics, Enhanced for
Loop, Autoboxing or Unboxing, Typesafe Enums, Static import and Annotation. These features reduce the
work of a programmer by shifting the responsibility of creating the reusable code to the compiler. The resulting
source code is free from bugs because the errors made by the compiler are less when compared to those made
by programmers.
10.​ Scalability: J2SE5.0 assures a significant increase in scalability by improving the startup time and
reducing the amount of memory used in the Java 2 runtime environment.
11.​ Monitoring and Manageability : Java supports several APIs, such as JVM Monitoring and
Management API, Sun Management Platform Extension, Logging, Monitoring, and Management Interface, and
Java Management Extension (JMX) to monitor and manage Java applications.
12.​ Desktop Client : J2SE 5.0 provides enhanced features to meet the requirements and challenges of the
Java desktop client users. It provides an improved Swing look and feels called Ocean. This feature is mainly
used for developing graphics applications that require OpenGL hardware accelerator

Overview of Java Language

Java is a general purpose object oriented programming language. We can develop two types
of java programs:

​ Stand–alone applications

​ Web applets
Stand–alone applications:-

Stand–alone applications are programs written in java to carry out certain tasks on a stand –
alone local computer. Executing a stand –alone java program involves two steps:

1.​ Compiling source code into bytecode using javac compiler.


2.​ Executing the bytecode program using java interpreter.

classSimple
{
Public static void main(Stringargs[])

{
}
[Link]("Hello Java");

}
1.​ Class keyword is used to declare a class in java.
2.​ Public key word is an access modifier which represents visibility. It means it is visible to all.
3.​ static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main method is executed by theJVM,so it doesn't require to create an object to invoke
the main method. So it saves memory.
4.​ Void is their turn type of the [Link] means it doesn't return any value.
5.​ Main represents the starting point of the program.
6.​ String[]args is used for commandline [Link] will learn it later.
7.​ [Link]() is used to print [Link],System is a class,out is the object of PrintStream
class, println() is the method of PrintStream class. We will learn about the internal working of
[Link] statements later.

//JavaProgram to illustrate the use of Rectangleclass which


//has length and width data members
classRectangle{
intlength;
intwidth;
voidinsert(intl,intw){ length=l;
width=w;
}
voidcalculateArea(){[Link](length*width);}
}
classTestRectangle2{
publicstaticvoidmain(String args[]){
Rectangler1=newRectangle(),r2=newRectangle();//creatingtwoobjects [Link](11,5);
[Link](3,15);
[Link]();
[Link]();
}
}
Test itNow

Output:

contain data members and methods that operate on the data members of the class. Methods may contain data type
declarations and executable statements. To write a java program, we first define classes and then put them together.
A Java program may contain one or more section are shown as following in Fig:
Documentation Section:-
The documentation section comprises a set of comment lines giving the name of the program, the author and
other details, which the programmer would like to refer to ata later stage. Comments must explain why and what
Of classes and how of algorithms. This would greatly help in maintaining the program. In addition to the two
styles of comment like “single line comment”and “double line comment”, Java also uses a third style comment
/**…..*/ known as documentation comment. This form of comment is used for generating documentation
automatically.
Package Statement:-
The first statement allows in a Java file is a package [Link] statement declares the package name and
informs the compiler that the classes defined here belong to this package.
Example:
package student;
The package statement is optional. That is,our classesdonothavetobepartofa package.
Import Statement:-
The next thing after a package statement (but before any class definition) maybe a number of import
statements. This
is similar to the #include statement in C. Example,
[Link];
This statement instructs the interpreter to load the test class contained in the package [Link] import
statement, we can have access to classes that are part of other named packages.
Interface Statement:-
An interface is like a class but includes a group of method declarations. This is also an optional section and is
used only when we wish to implement the multiple inheritance feature in the program.

Class Definitions:-
A Java program may contain multiple class definitions. Classes are the primary and essential elements of a
Java program. These classes are used to map the objects of real-world problems. The number of classes used
depends on the complexity of the problem.
Main Method Class:-
Since every Java stand-alone program requires a main method as its startingpoint,thisclass istheessentialpart of
a Java program. A simple Java program may contain only this part. The main method creates objects of various
classes and establishes communications between them. On reaching the end of main, the program terminates
and the control passes back to the operating system.
Constants/Literals:Constantsarealso like [Link],theonlydifference is,their valuescannotbe
modified bythe programonce theyare defined. Constants refer to fixed values. Theyare also called as literals.

SpecialSymbols: The followingspecialsymbolsareused inJavahavingsomespecialmeaningand thus, cannot be


used for some other purpose. The Special symbols are [] () {}, ; * =.

Operators: Javaprovides manytypesofoperatorswhichcanbeusedaccordingtotheneed. Theyare classified based


on the functionality they provide. Some of the types are-

ArithmeticOperators,UnaryOperators, Assignment
Operator,RelationalOperators,LogicalOperatorsTernary Operator, Bitwise Operators, Shift Operators, instance
of operator, Precedence and Associativity

Period(.):Itseparatesthepackagename formthesub-packagesandclass. It also separatesavariableor method from


a reference variable.

Comments: Comments allow us to specify information about the program inside our Java [Link] compiler
recognizes these comments as tokens but excludes it form further processing. The Java compiler treats
comments as whitespaces. Java provides the following two types of comments:

o​ LineOriented:It begins with a pair of forwarding slashes(//).


o​ Block-Oriented: It begins with/* */.
JAVA STATEMENT:

Implementing Java Program

Implementation of a Java application program involves a series of [Link] include :

●​ Creating the program


●​ Compiling the program
●​ Running the program

Creating the program


We can create a program using any text editor. Assume that we have entered the following program:

class Java app

{
Public static void main(String[] args)
{​ [Link]("Wlcometo Java");​ }
}
We must save this program in a file called Java [Link] ensuring that the file name contains the classname
properly. This file is called the source file. Note that allJava source files will have the extension java.

Compiling the program


To compile the program, we must run the Java Compiler javac, with the name of the source file on the
command line the javac compiler creates a file called Java [Link] containing the bytecodes of the program.
Notethat the compiler automatically names the bytecode file as <classname>.class. To compile the Program,

Syntax:[Link]
Running the program
To run the program, we must run the Java interpreter java, with the name of the class file on the command line
Syntax: Java Filename

All language compilers translate Source code into machine code for a specific computer. The Java
compilerproduceanintermediatecodeknownasbytecodeas Bytecodeforamachinethat doesnotexist. The machine is
called the Java VirtualMachine (JVM) and its only exist only inside the computer memory.

TheJVMwhich inturnactsastheintermediarytheOperating Systemand JavaObjectFrameWork.


Command-line arguments are parameters that are supplied to the application program at the time of invoking it
for execution. It may be recalled that the program was invoked for execution.

classTest

publicstaticvoidmain(Stringargs[])

intcount,i=0;

count=[Link];

while(i<count)

string=args[i];

[Link](i+":"+"Javais"+string+"!");

Number of arguments=3

Output:
JavaSimpleProgrammingLanguage!
JavaObject-OrientedProgrammingLanguage!​
Introduction:
Constants,Variables,and Data types
A Programming Language is designed to process
certain kinds of data consisting of
numbers, characters and strings and to provide useful output known as information. The task of
processing data is accomplished by executing a sequence of instructions constituting a program.
These instructions are formed using certain symbols and words according to some rigid rules known
as syntax rules.

Constants:
Constants in java refer to fixed values that do not change during the execution of a program.
Java supports several types of constants.
JAVACONSTANTS
Numeric constants​ Character constants

Integerconstants​ Real constants​ Character​ String constants


Constants

Integer Constants
An Integer constant refers to a sequence of [Link] are three types of Integers,namely
decimal Integer, Octal Integer and Hexadecimal Integer.

​ Decimal Integer consists of a set of digits,0 through 9,preceded by an optional


minus sign. Valid examples of decimal Integer constants are:

123​ -321​ 0​ 654321

Embedded spaces,commas,and non-digit characters are not permitted between digits.


For example, 15750​ 20.000​ $1000 are illegal numbers

​ An Octal Integer consists of any combination of digits from these t0 through7,with


a leading 0. Some examples of Octal integer are​ 037​ 0​ 0435​ 0551

​ A sequence of digits preceded by 0X considered as Hexadecimal [Link]


may also include Alphabets Athrough For a through f. A letter A through F
represents the numbers 10 through 15. Following are the examples of valid hex
integers.

0X2​ 0X9F0 X bcd0 X We rarely use octal and hexadecimal numbers in


programming.
Real Constants

Integer numbers are inadequate to represents quantities that vary continuously,such as


distances, heights, temperatures and prices and so on. These quantities are represented by numbers
containing fractional parts like 17.548. Such numbers are called real or floating point constants.
Example:0.0083​ -0.75​ 435.36

These numbers are shown in decimal notation, having a whole number followed by a decimal
point and the fractional part, which is an integer. It is possible that the number may not have digits
before the decimal points or digits after the decimal point. That is​215.​ .95​ -.71are all valid
real numbers.

A real number may also expressed in exponential(or scientific)[Link] example,the


value215.65 may be written as 2.1565e2in exponential notation. E2 means multiply by 102.

The general form is

The mantissa is either real number expressed in decimal notation or an integer. The exponent is
an integer with an optional plus or minus sign. The letter e separating the mantissa and the
exponent can be written in either lowercase or [Link] the exponent causes the decimal
point to"float",this notation is said to represent a real number in floating point form.
Examples are: 0.65e412e-21.5e+5​ 3.18E3​ -1.2E-1
Embedded white(blank)space is not allowed,in any numeric
constant.

Exponential notation is useful for representing numbers that are either very large or very small in
magnitude. For example, 7500000000 may be written as 7.5E9 or 75E8.
A floating point constant may comprise four parts:
●​ A whole number
●​ A decimal number
●​ A fractional part
●​ An exponent

Single character constants

A single character constant contains a single charactere n closed within a pair of single quote
marks.
Example:‘5’​ ‘X’​ ‘;’​ ‘’
Note that the character constant ‘5’is not the same as the number 5. The last constant is a blank space.
String constants

A string constant is a sequence of characters n closed between double [Link] characters


may be alphabets, digits, special characters and blank spaces.
Examples are:
“Hello Java”​ “2021”​ “WELL DONE”​ “?..!”​ “5+5”“X”
Backslash character constants

Java supports some special backslash character constants that are used in output methods. For
example, the symbol `\n’ stands for newline character. Each of them represents one character,
although they consists of two characters. These characters combination is known as escape
sequences.

Backslash character constants

Constant Meaning
‘\b’ Backspace
‘\f’ Form feed
‘\n’ Newline
‘\r’ Carriage return
‘\t’ Horizontaltab
‘\’’ Singlequote
‘\”’ Doublequote
‘\\’ backslash
VARIABLES

A variable is an identifier that denotes a storage location used to store a data value. Unlike
constants that remain unchanged during the execution of a program,a variable may take different
values at different times during the execution of the program.

Some examples of variable names are:


●​ Average
●​ Height
●​ Total-height
●​ Class Strength

Variable names may consist of alphabets,digits,the under score(_)and dollar characters,subject to the
following conditions:

[Link] must not begin with a digit.


Upper case and lower case are [Link] means that the variable Total is not the same as total
or TOTAL.
2.​It should not be a keyword.
3.​Whitespace is not allowed.
4.​Variable names can be of any length.
DATA TYPES
Every variable in java has a [Link] specify the size and type of values that
can be stored. Java language is rich in its data types.

Integer types can hold whole numbers such as123, -96,[Link] size of the values that can be stored
depends on the integer data type. Java supports four types of integer

Size and range of integer types


Type Size Minimum value Maximum value
byte Onebyte -128 127
short Twobytes -32,768 32, 767
int Four bytes -2,147, 483, 648 2,147, 483, 647
long Eight bytes -9,223, 372, 036, 854, 775, 808 9, 223, 372, 036, 854, 775, 807

Floating point types


Floating point types contain fractional parts such as27.59, -[Link] are two kinds of
floating point storage. The float type values are single-precision numbers while the double
type represents double-precision numbers.
Size and range of Floating point types
Type Size Minimum value Maximum value
Float 4 bytes 3.4e-038 1.7e+0.38
double 8 bytes 3.4e-038 1.7e+308
Floatingpoint datatypes

Character Type
To store character constant in memory,java provides a character datatype called [Link]
char type assumes the size of two bytes, basically, it can hold only a single character.
Boolean Type
We want to test a particular condition during the execution of a program. There are only two values
that a Boolean type can take:true or [Link] type is denoted by the keyword Boolean and uses only
one bit of storage.

Declaration of Variables

Variables are name of the storage location variables can be used to store a value
Variables are separated by commas.A declaration statement must end with s of any data [Link]
general form of declaration of variable is
[Link] valid declarations are:
intcount;
float x,y;
double p i;
byte b;
charc1,c2,c3;

Giving value to variables


A variable must be given a value after it has been declared but before it is used in an
expression.
This can be achieved in two ways:
1.​ By using an assignment statement
2.​ By using a read statement.
Assignment statement
A simple method of giving value to a variable is through the assignment statement as follows:

For example:
initialvalue=0;
finalvalue=100;
yes=’x’
String assignment expression is shown
below: x=y=z=0;
It is also possible to assign a value to a variable at the time of its [Link] takes the form:

Examples:
intfinalvalue=10
0; char yes = `x`;
doubletotal=75.3
6
The process of giving initial values to a variable is known as
initialization. float x, y, z;​ //declares three float
variables.
int m= 5, n=10;​ //declares and initializes two int
variables. int m,n=10;​ //declares m and n and initializes n
Read statement
We may also give values to variables interactively through the keyboard using the readLine()
Method as illustrated in program.

Reading data from the


keyboard
Import
[Link];
class Reading
{
Publicstaticvoidmain(String args[])
{
DatInputStreamin=newDataInputStream([Link]);
Int intnumber =0;
Floatfloatnumber=0.0f
; try
{
[Link](“Enter an Integer: “);
Intnumber=[Link]([Link]());
[Link](“Enter a float number:”);
floatnumber=[Link]([Link]()).floatvalue()
;
}
Catch(Exceptions)
{}
[Link](“intnumber=”+intnumber);
[Link](“floatnumber=”+floatnumber);
}
}
The input and output of the
program Enter an integer:
123
Enter a float number:
123.45
Int number=123
Float
number=123.45

Scope of the variable

Java variables are actually classified into three kinds


1.​ Instancevariables
2.​ Class variables
3.​ Local variables
Instance and class variables are declared inside the class. Instance variables are created when the
objects are instantiated and therefore they are associated with the objects. They take different values
for each object. On the other hand, class variables are global to the class and belong to the entire set
of objects that the class creates. Only one memory location is created for each class variable.

Variables declared and used inside the methods are called local [Link] are not available for
use outside the method definition. Local variables can also be declared inside the program blocks
that are defined between an opening brace{ and a closing brace }. These variables are visible to the
program only from the beginning of its program block to the end of the program block. When the
program control leaves a block, all the variables in the block will cease to exist. The area of the
program where the variable is accessible(ie Usable)is called its scope.

Nested program blocks

Block 1

UNITII
We can have program blocks within other blocks (called nesting). Each block can contain its
own set of local variable [Link] cannot however,declare a variable to have the same name
as one in an outer block. The variable declared x declared in Block1 is available in all the three
blocks.
However the variable n declared in block2 is a vailable only in block2,because it goes out of the
scope at the end of the block 2. Similarly , m is accessible only in block3.

Symbolic constants
These constants may appear repeatedly in a number of places in the program. One example
of such a constant is 3.142, representing the value of the mathematical constant “pi” . Another
example is the total number of students whose mark-sheets are analysed by the “test analys is
program”The number of students say 50,maybe used for Calculating the classtotal,class
average,standard deviation etc. we face two problems in the subsequent use of such programs. They
are:
1.​ Problem in modification of the program
2.​ Problem in understanding the problem.
Modifiability
We may like to change the value of “pi” from 3.142 to 3.14159 to improve the accuracy of
calculations or the number 50 to100 to process the test result of another class. Inboth the cases,we
will have to search throughout the program and explicitly change the value of the constant wherever
it has been used. If any value is left unchanged , the program may produce disastrous outputs.
Understandability
When a numeric values appeared in a program, its use is not always clear, especially when
the same value means different things in different [Link],the number 50 may mean the
number of students at one place and the ‘pass marks` at another place of the same program. We may
forget what a certain number meant, when we read the program some days later.
Assignment of a symbolic name to such constants frees us from these [Link],we may
use the name STRENGTH to denote the number of students and PASS-MARK to denote the pass
marks required in a subject. Constant values are assigned to these names at the beginning of the
program.
Subsequent use of the names STRENGTH and PASS-MARK in the program has the effect of
causing their defined values to be automatically substituted at the appropriate points.A constants is
declared as follows

Valid examples of constant declaration are:


Final int STRENGTH=100;
finalintPASS-MARK=50;
finalfloat PI = 3.14159;
TypeCasting
There is a need to store a value of one type in to a variable of another [Link] must cast
the value to be stored by proceeding it with the type name in parentheses. The syntax is:

The process of converting one data type to another is called


[Link]: int m=50;
byte n=(byte)m;
long count =(long)m;

Automatic conversion
It is possible to assign a value of one type to a variable of a different type without a cast. Java
does the conversion of the assigned value [Link] is known as automatic type conversion.
Example: byte b= 75;
inta=b;
Getting values of variable
A computer program is written to manipulate a given set of data and to display or print the
results. Java supports two output methods that can be used to send the result to the screen.
●​ print()method​ //print and wait
●​ println() method​ //print a line and move to the next line.
Theprint() sends the information into the buffer. This buffer is not flushed until a new
line character is [Link] a result,the print()method prints output on oneline until a new
line character is en countered.

Example:
[Link](“Hello”);
[Link](“Java”);
Will display the words Hello Java on oneline and waits for displaying further in formation on the
same line. The next line by printing a newline character as shown below:
[Link](“\n”);
Example:​ [Link](“Hello”);
[Link](“\n”);
[Link](“Java”);
Will display the output in two lines as
follows Hello
Java
The println()method by contrast,takes the in formation provided and displays it on a line followed
by a line feed.
[Link](“Hello”);
[Link](“Java”);
Will display the output in two lines as
follow Hello Java
The statement [Link](); will print a blank line.

Getting the result to the screen


Class Displaying
{
publicstatic void main(String args[])
{
[Link](“ScreenDispla
y”); for(int i=1; i<=9; i++)
{
for(intj=1;j<=n;j++)
{
[Link](“”);
[Link](“i”);
}
[Link](“\n”);
}
[Link](“ScreenDisplayDone”);
}
}

The output will be


Screen Display
1
2​ 2
3​ 3 3
4​ 4 4 4
5​ 5 5 5 5
6​ 6 6 6 6 6
7​ 7 7 7 7 7 7
8​ 8 8 8 8 8 8 8
9​ 9 9 9 9 9 9 9 9
Screen Display Done

Standard Default Values


Every variable has a default [Link] we don’t initialize a variable when it is first created,java
provides default value to that variable type automatically.
Default values for various types
Types of variable​ Default value
byte​ Zero:(byte)0
short​ Zero:(short)0
int​ Zero:0
long​ Zero:0L
float​ 0.0f
double​ 0.0d
char​ null character
boolean​ false
reference​ null

Operators and Expressions


Java supports rich set of operators. we have already used several of them such as = , +, -, and * . an
operator is a symbol that tells a computer to perform certain mathematical or logical manipulations.
Operators are used in programs to manipulate data and [Link] operators can be classified
into
1.​ Arithmetic operators
2.​ RelationalOperators
3.​ Logical Operators
4.​ Assignment Operators
5.​ Increment and Decrement operators
6.​ Conditional Operators
7.​ Bitwise operators
8.​ Special operators.

Arithmetic operators
Arithmetic operators are used in mathematical expressions in the same way that
they are used in [Link] provides all the basic arithmetic [Link]
following table lists the arithmetic operators:

Operator​ Result

+​ Addition
–​ Subtraction(also unary minus)
*​ Multiplication
/​ Division
%​ Modulus
++​ Increment
+=​ Addition assignment
–=​ Subtraction assignment
*=​ Multiplication assignment
/=​ Division assignment
%=​ Modulus assignment
––​ Decrement
Arithmetic operators are used as shown
below
a+b​
a-b
a*b​
a/b
a%b-a
*b
Here a and b may be variables or constants and are known as operands
Integer Arithmetic
When both the operands in a single arithmetic expression such as a+b are integers. The
expression is called integer [Link] the operation is called integer [Link]
arithmetic
Always yields an integer [Link]=14andb=4we have the following
results:
a-b=10
a+b
=18
a*b
=56
a/b=3(decimal part truncated)
a%b=2(remainder of integer
division)
Real arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real
operand may assume values either in decimal or exponential notation.
Floating point arithmetic
classFloatPoint
{
publicstatic void main(String args[])
{
float a = 20.5f, b=6.4f;
[Link](“a=” +a);
[Link](“b=” +b);
[Link](“a+b=”
+(a+b));
[Link](“a-b=” +
(a-b)); [Link](“a*b=”
+(a*b));
[Link](“a/b=”
+(a/b));
[Link](“a%b=”+(a%
b));
}
}

The output is given


below a=20.5
b=6.4
a+b=
26.9
a-b=1
4.1
a*b=131.
2
a/b=3.203
13
a%b=1.3

Mixed-mode Arithmetic
When one of the operands is real and the other is integer,the expression is called mixed-mode
arithmetic [Link] either operand is of there al type,then the other operand is converted in to
real and the real arithmetic is performed. The result will be real.
15/10.0 produces the result
1.5 15/10 produces the
result 1

Relational operators
The relational operators determine the relationship that one operand has to the
other. The relational operators are shown here:
Operator​ Result

==​ Equal to
!=​ Not equal to
>​ Greater than
<​ Less than
>=​ Greater than or equal to
<=​ Less than or equalto

The general form is:

Implementation of relational operators


Class Relational Operators
{
publicstatic void main(string args[])
{
float a=15.0f, b=20.75f, c=15.0f;
[Link](“a=” +a);
[Link](“b=” +b);
[Link](“c=” +c);
[Link](“a<b is ” +(a<b));
[Link](“a>b is” +(a>b));
[Link](“a==c is” +(a==c));
[Link](“a<=c is” + (a<=c));
[Link](“a>=b is” +(a>=b));
[Link](“b!=c” +(b!=c));
[Link](“b==a+cis”+(b==a+c))
;
The output of the
program a=15
b=2
0.75
c=1
5
a<b is true
a>b is
false a==c
is true
a<=c is
true
a>=bisfals
e a!=c is
true
b==a+cisfalse
Logical Operators
Java has three logical [Link] logical operators && and||are used when we want to form
compound condition by combining two or more relations.
An example is: a>b&&x==10
An expression of this kind which combines two or more relational expressions is termed as logical
expression or a compound relational expression.A logical expression also yields a value of true or
false according to the truth table.
Logical operators

Truthtable
Op-1 Op-2 Op- Op-1||op-
1&&op- 2
2
True True True true
True False False true
False True False true
False False False false

The Assignment Operator


Assignment operators are used to assign the value of an expression to [Link] have
seen the usual assignment operator”=”.Java has a set of shorthand assignment operators which are
used in the form

Where v is a variable,expisan expression and op is a java binary [Link] operator op=is


known as the shorthand assignment operator.
The assignment statement
vop=exp;is equivalent tov=vop(exp);with v accessed only once.
Example : x + = y+1;
This is same as the statement
x=x+ (y+1);
Increment and decrement operator
Java has two very useful operators not generally found in many other [Link] are the
increment and decrement operators:
++and–
The operator++adds 1 to the operand while–[Link] are unary operators and are used in the
following form:
++m;orm++;
--m;orm--;
++m;is equivalent tom=m+1;(or m+=1)
--m;is equivalent to m =m-1; (orm-=1)
We operators extensively in for and while loops.
While++mandm++mean the same thing when they form statements independently,they behave
differently when they are used in expressions on the right-hand side of an assignment statement.
Consider the following
m=5;
y=++m;
In this case,the value of y and m would be [Link],ifwere write the above n statementnas
m=5;
y=m++;
Then, the value of y would be 5 and m would be 6.A prefix operator first adds1to the operand and
then the result is assigned to the variable on left. On the other hand, a postfix operator first assigns
the value to the variable on the left and then increments the operand.
Increment operator illustrated

Class increment operator


{
Public static void main(String args[])
{
int m=10, n=20;
[Link](“m=” +m);
[Link](“n” +n);
[Link](“++m=”++
m);
[Link](“n++=”+n+
+); [Link](“m=”
+m); [Link](“m=”
+m);
}
}
Output will
be m=10
n=20
++m
=11
n++
=10
m=1
1
n=21
conditional operator
The character pair?:is a ternary operator available in [Link] operator is used to construct
conditional expression of the form

Where exp1,exp2 and exp3 are expressions.


Exp1 is evaluated [Link] it is non zero(true),then the expression one x p2 is evaluated and becomes
the value of conditional expression. Note that only one of the expressions is evaluated first.
Example:a=10;
b=15;
x=(a>b)?a:b;in this example,x will be assigned the value of [Link] can be achieved using the
if…else statement as follows:
if(a
>b)
x=
a;
els
e
x=
b;
Bitwise operators
This operators are used for testing the bits,or shifting them to the right or [Link] operator
may not be applied to float or double.

Operator​ Result

& Bitwise AND


|​ Bitwise OR
^​ Bitwise exclusive OR
>>​ Shift right
>>>​ Shift right zero fill
<< Shift left
Special Operators
Java supports some special operators of interest such as instance of operator and member
selection operator(.)
Instance of operator
The instance of is an object reference and returns true if the object on the left-handside is an
instance of the class given on the right-hand side. This operator allows us to determine whether
the object belongs to a particular class or not.
Example:
Person instance of​ student
Is true if the object person belongs to the class student;otherwise it is false.

Dot operator
The dot operator(.)is used to access the instance variable and methods of class objects.
Example:
[Link]//reference to the variable age
[Link]()//referencetothemethodsalary()

Arithmetic expressions
An arithmetic expression is a combination of variables,constants,and operators arranged as per
the syntax of the language.
Expressions
Algebraic expression​ java expression

ab-1​ a*b-1
(m+n)(x+y)​ (m+n)*(x+y)
ab/c​ a*b/c
3x2+2x+1​ 3*x*x+2*x+1
Evaluation of expressions
Expressions are evaluated using an assignment statement of the form

Variable is any valid java [Link] the statement is encountered,the expression is evaluated first
and the result then replaces the variable on the left-hand [Link] the variable used in the expression
must be assigned values before evaluation is attempted. Examples of evaluation statements are
x=a*b
-c
y=b/c*
a;
z=a-b/
c+d;
Precedence and arithmetic operators
An arithmetic expression without any parenthesis will be evaluated from left to right using the rules
of precedence of operators. There are two distinct priority levels of arithmetic operators in java:
High priority​ */%
Lowpriority​ +-
The basic evaluation procedure includes two left-to-right passes through the [Link] the
first pass, the high priority operators(if any) are applied as they are encountered.
Duringthesecondpass,thelowpriorityoperator(if any)are applied as they are [Link] the
following evaluation statement:
x=a-b/3+c*2-1
When a=9,b=12,and c=3,the statement
becomes x=9-12/3+3*2-1 and is evaluated as
follows:
second pass
step3:x=5+6-
1 step4:
x=11-1 step5:
x=10
The order of evaluation can be changed by introducing parenthesis into an
expression first pass:
step1:9-12/6*(2
-1) step2:
9-12/6*1
second pass
step3:9-
2*1
step4:
9-2 third
pass
step5: 7
The procedure consists of three left to right [Link],the number of evaluation steps remains
the same as 5.
Parenthesis may be nested, and in such cases, evaluation of expression will proceed outward from
the inner most set of [Link] sure that every opening parentheses has a matching closing
one. For example
9-(12/(3+3)*2)-1=4
Where as 9-((12/3)+3*2)-1=-2
Type Conversion in
Expressions Automatic Type
Conversion
Java permits mixing of constants and variables of different types in an expression, but during
evaluation it [Link] know that the computer,considers one
operator at time, involving two operands are of different type, the ‘lower’ type is automatically
converted to the ‘higher’ type before the operation proceeds. The results are of the higher type.
If byteshort and int variables are used in an expression,the results is always promoted to int,to avoid
overflow. If a single long is used in the expression, the whole expression is promoted to long.
Remember that all integer values are considered to bein tun less they have their L appended to them.
If an expression contains a float operand, the entire expression is promoted to float. If any operand is
double, result is double.

Automatic Type conversion


char byte short int long float double
char int int int int long double double
byte int int int int long double double
short int int int int long double double
int int int Int int long double double
long long long long long long double double
float float float float float float double double
double double double double double double double double

The final result of an expression is converted to the type of the variable on the left of the
assignment sign before assigning the value to [Link],the following changes are introduced
during the final assignment.
1.​ Float to int causes truncation of the fractional part.
2.​ Doubleto float causes rounding of digits.
3.​ Longto int causes dropping of the excess higher order bits.

Casting a value
Java performs type conversion [Link],there are instances when we want to force
a type conversion in a way that is different from the automatic conversion. Consider, for example,
the calculation of the ratio of females to males in a town.

ratio=female_ number/male_ number

Since female_number and male_number are declared as integers in the program,the decimal part of
the result of the division would be lost ratio would not represent a correct figure. This problem can
be solved by converting locally one of the variables to the floating points​ as shown below;

ratio=(float)female_number/ male_ number

The operator (float) converts the female number to floating points for the purpose of evaluation of
The [Link] using the rule of automatic conversion,the division is per for median
floating point mode, thus retaining the factional part of result.
Note that (float) converts the female_number to floating point for the purpose of evaluation of
the expression. Then using the rule of automatic conversion, the division is performed in
floating point mode, thus retaining the fractional part of the result.
Note that no way does the operator(float)affect the value of the variable female_number.And
also, the type of female _ number remains as int in the other parts program.
The process of such a local conversion is known as casting value. The general form of a cast is;

(Type_number)expression

Where type- name​ is one of the standard [Link] expression may be a constant,variable or
an expression.
Examples:
x=(int) 7.5​ 7.5is converted to integer by truncation.
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.

Casting can be used to round–off a given value to an [Link] the following statement;
x = (int)(y + 0.5) ;
If y is 27.6,y+0.5 is 28.1and casting,the result becomes28,the value that is assigned to [Link] course,
the expression being is not changed.
When combining two different types of variables in an expression, never assume the rules of
automatic [Link] is a good practice to explicitly force the [Link] is more safer. For
example, when y and p are double and m is int,the following two statements are equivalent.
Y=p+m;
Y=p+(double)m;

Operator precedence and associativity


This precedence is used to determine how an expression involving more than one operator is
evaluated. There are distinct levels of precedence and an operator may belong to one of the
[Link] operators at the higher level of precedence are evaluated first. The operators of the same
precedence are evaluated either from right to left, depending on the [Link] is known as the
associativity property of an operator.

Mathematical Functions
Mathematical functions such as cos,sqrt,log,etc.,are frequently usedinanalysisofreal-lifeproblems.
Java supports these basic math functions through math classes defined in the [Link] package.
These functions should be used as Math.function_name()
Example:
Doubley=[Link](x);
Mathfunctions
sin(x)​ Returns the sine of angles in radians
cos(x)​ Returns the cosine of angle x in radians
tan(x)​ Returns the tangent of angles in radians
asin(y)​ Returns the angle whose sine is y
acos(y)​ Returnstheanglewhose cosineis y
atan(y)​ Returnstheanglewhose tangent is y
Decision Making and Branching:
Decision making statements in Java:

Decision making structures have one or more conditions to be


evaluated or tested by the program ,along with a statement or
statements that are to be executed if the condition is determined to be
true, and optionally, other statements to be executed if the condition is
determined to be false.

Branching:
When a Program breaks the sequential flow and jumps to
another part of the code ,it is called [Link] are Two types of
Branching .

1.​Conditional Branching
When a program breaks the sequential flow and jumps to
another part of the code,it is called conditional Branching.

2.​Unconditional Branching
If Branching takes place without any decision,it is known as
unconditional Branching.

There are the 5 ways of exercising decision making in java:


1.​if
2.​if-else
3.​nested-if
4.​else-if-Ladder
5.​switch-case

1.​If Statement in Java


Java if statement is the simplest decision making statement. It
encompasses a boolean condition followed by a scope of code which
is executed only when the condition evaluates to true. However if
There are no curly braces to limit the scope of sentences to be executed
if the condition evaluates to true, then only the first line is executed.
Syntax:
if(condition)
{
//codetobeexecuted
}
2.​If else statement in Java
This pair of keywords is used to divide a program to be executed into
two parts,one being the code to be executed if the condition evaluates
to true and the other one to be executed if the value is false.
However if no curly braces are given the first statement after the if
else keyword is executed.
if(condition)
{
//code to be executed if the condition is true
}
else
{
//code to be executed if the condition is false
}
3.​Nested if Statements in Java
●​ The nested if is similar to the nested loops we learnt about in the
previous chapters. If the condition of the outer if statement
evaluates to true then the inner if statement is evaluated.
●​ Nested if’s are important if we have to declare
extended conditions to a previous condition
Syntax:
if(condition)
{
//codetobeexecuted
if(condition)
{
//codetobeexecuted
}
}
Flow diagram of Java nested if statement:

4.​Else-if Ladder Statements in Java


These statements are similar to the if else statements . The only
difference lies in the fact that each of these statements can be paired
with a different if condition statement. This renders the ladder as a
multiple choice option for the [Link] soon as one of the if conditions
evaluates to true the equivalent code is executed and the rest of the
ladder is ignored.
Syntax:
if
{
//codetobeexecuted
}
elseif(condition)
{
//codetobeexecuted
}
elseif(condition)
{
//codetobeexecuted
}
else
{
//codetobeexecuted
}

Flow Diagram of Java else ifLadder statements:


5.​Switch Statement in Java
Java switch statementisadifferentformoftheif elseifladder statements.
●​ It branches the flow of the program to multiple points as and
when required or specified by the conditions.
●​ As soon as the expression is evaluated, the result is matched with
each and every case listed in the [Link] the output matches with
any of the cases mentioned, then the particular block is executed.
●​ A break statement is written after every end of the case block so
that the remaining statements are not executed.
●​ The default case is written which is executed if none of the cases
are the result of the [Link] is generally the block where
error statements are written.
Syntax:
switch(expression)
{
case<value1>:
//codetobeexecuted break;
case<value2>:
//codetobeexecuted break;
default:
//codetobedefaultlyexecuted
}
Flow Diagram of Java switch statement:

The Conditional Operator(?:Operator)


Java Conditional Operator or ternary operate the if else statement. It
consists of a condition followed by a question mark(?). It contains
two expressions separated by a colon(:). If the condition evaluates to
true, then the first expression is executed, else the second expression
is executed.
Syntax:
(Condition)?(expression1):(expression2);
Forexample,thesegment
If(x<0)
Flag=0;
else
Flag=1;
Canbewrittenasflag=(x<0)?0:1;
Decision making and Looping

In computer programming,loops are used to repeat a block of code.


For example, if you want to show a message 100 times, then rather
than typing the same code 100 times, you can use a loop.

In Java,there are three types of loops.

●​ forloop
●​ whileloop
●​ do...whileloop
For Loop
Java for loop is used to run a block of code for a certain number of
times. The syntax of for loop is:
for(initialExpression;testExpression;updateExpression)
{
​ //bodyoftheloop
}
Here,

1.​ The initial Expression initializes and/or declares variables


and executes only once.
2.​ The condition is [Link] the condition is true,the body of
the​ loop is executed.
3.​ The update Expression updates the value of initial Expression.
4.​ The condition is evaluated [Link] process continues until
the condition is false.
Example1:DisplayaTextFiveTimes

Output
JavaisfunJa
vaisfunJava
isfunJavais
funJavaisfu
n

While Loop

Java​ loop is used to run a specific code until a certain condition


[Link] syntax of the while loopis:
(testExpression) {
​ //bodyof loop
}

Here,

1.​ A loope valuates the textExpression inside the parenthesis().


2.​ Ifthe textExpression evaluates to 4.​ This process continues until the
true,the code inside is executed. textExpression is false.
3.​ The textExpression is evaluated 5.​ WhenthetextExpressionevaluatesto
false,theloopstops.
again.
loop
Flow chart of while loop

Example1:DisplayNumbersfrom1to5
Output
1
2
3
4
5

Java do...while loop


The of Loop is similar
to while
[Link],the
body loop i s
executed once
before the
testexpression is
[Link], do
{
​ //bodyof loop
}while(textExpression)He
re,

1.​ The body of the loop is executed at [Link] the textExpression is


evaluated.
2.​ If the textExpression evaluates to true,the body of the loop inside
The statement is executed again.
3.​ The textExpression is evaluated once again.
4.​ If the textExpression evaluates to true,the body of the loop inside
the do statement is executed again.
5.​ This process continues until the textExpression evaluates to false.
Then the loop stops.
Flow chart of do...while loop

Example3:DisplayNumbersfrom1to5
Output
1
2
3
4
5
Jumps in Loop
●​ The jumping statements are the control statements which transfer the program
execution control to a specific statement.
●​ jump:Java supports three jump statements:break,continue and [Link] three
statements transfer control to other parts of the program. Break: In Java, break is
majorly used for: Terminate a sequence in a switch statement.

Java Break Statement

●​ We can use the break statement in the following cases.


●​ Inside the switch case to come out of the switch block.
●​ Within the loops to break the loop executionbasedonsome condition.
●​ Inside labelled blocks to break that block execution based on some condition.

​ The break cannot be used outside the loops and switch statement​

Java Continue Jumping Statement

●​ This statement is used only within looping statements.


●​ When the continue statement is encountered, then it skips the current iteration
and the next iteration starts.
●​ The remaining statements in the loop are skipped. The execution starts from
the top of the loop again.
●​ We can use the continue statement to skip the current iteration and continue
the next iteration inside loops.

Labeled Loops

We can give a label to a block of statements.A label is any valid java variable
[Link] give a label to a loop,place it before the loop with a colon at the end.
Forex.

Outer:for(intm=1;m<11;m++)

For(intn=1;n<11;n++)

[Link](“”+m*n);

If (n==m)

Continueouter;

You might also like