Java Notes
Java Notes
Java Notes
Subject Incharge:
Unit I: N.Baby Kala, Guest Lecturer in Computer Science.
Unit II: K.Sharmila, Guest Lecturer in Computer Science.
Unit III: N.Anuradha, Guest Lecturer in Computer Science.
Course Content
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 build data and functions
from these entities. The combination of the data makes up an object.
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:
Representation of an Object
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 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.
In polymorphism, objects having different internal structures can share the same external interface.
Method Overloading
Method Overriding
Dynamic Binding
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.
Message Communication
Objects communicate with each other in OOPs. The process of programming in case of OOP consists of
the following:
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
Applications of OOPs
Real-time systems
Simulation and modeling
Object-oriented databases
Hypertext and Hypermedia
AI and expert systems
Neural networks and parallel programming
Decision support and office Automation systems
CIM/CAD/CAD System.
HISTORY
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”. In may 1995, Sun
officially announced this language at Sunworld 95.Due 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 internet, Green project team come up with the idea of developing “Web
Applet”. The team developed a web browser called “Hot Java” to locate and run applet
programs on 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 New language Oak was demonstrated in hand held devices.
1993 World Wide Web(WWW)appeared on internet and transformed the text based internet
to graphical environment. Sun developed Applets.
1994 Green project team developed a web browser “Hot Java” to run applets on 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 kit 1.1(JDK 1.1).
1998 Sun released Java2 with version 1.2(SDK 1.2).
1999 Sun released Java2 standard edition (J2SE) and Enterprise Edition (J2EE).
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE with JDK 5.0 was released.
Features of Java
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, preprocessor header
files, goto statement 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 is a two-stage system. First, Java compiler translates source code into
bytecode instruction. Bytecode 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 Compiled and Interpreted Language.
3. Platform-Independent and Portable : Java ensures portability in two ways, first, Java compiler generates
bytecode 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 that 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, it 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 : Java 2 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 : J2SE 5.0 assures a significant increase in scalability by improving the startup time and reducing
the amount of memory used in 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 accelera
Java is a general purpose object oriented programming language. We can develop two types
of java programs:
Stand – alone application 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:
class Simple
{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
1. class keyword is used to declare a class in java.
2. public keyword 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 the JVM, so it doesn't require to create an object to invoke the main
method. So it saves memory.
4. void is the return type of the method. It means it doesn't return any value.
5. main represents the starting point of the program.
6. String[] args is used for command line argument. We will learn it later.
7. System.out.println() is used to print statement. Here, 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
System.out.println statement later.
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Test it Now
Output:
55
45
A Java program may contain many classes of which only one class defines the main method. Classes
contain data members and methods that operate on the data members of the class. Methods may contain data
type declaration 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 at a 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 allowed in a Java file is a package statement. This statement declares a 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 classes do not have to be part of a package.
Import Statement :-
The next thing after a package statement (but before any class definition) may be a number of import
statements. This is similar to the #include statement in C. Example,
import student.test;
This statement instructs the interpreter to load the test class contained in the package student. Using 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 starting point, this class is the essential part
of 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.
Java Tokens
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified as
follows:
1. Keywords
2. Identifiers
3. Constants
4. Special Symbols
5. Operators
Keyword: Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to
perform a specific function in a program.
Identifiers: Identifiers are used as the general terminology for naming of variables, functions and arrays.
Constants/Literals: Constants are also like normal variables. But, the only difference is, their values can not be
modified by the program once they are defined. Constants refer to fixed values. They are also called as literals.
Special Symbols: The following special symbols are used in Java having some special meaning and thus,
cannot be used for some other purpose. The Special symbols are [] () {}, ; * =.
Operators: Java provides many types of operators which can be used according to the need. They are classified
based on the functionality they provide. Some of the types are-
Arithmetic Operators, Unary Operators, Assignment Operator, Relational Operators, Logical Operators
Ternary Operator, Bitwise Operators, Shift Operators, instance of operator, Precedence and Associativity
Period (.): It separates the package name form the sub-packages and class. It also separates a variable or
method from a reference variable.
Comments: Comments allow us to specify information about the program inside our Java code. Java 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:
JAVA STATEMENT:
class Javaapp
{
public static void main(String[] args)
{ System.out.println("Wlcome to Java"); }
}
We must save this program in a file called Javaapp.java ensuring that the file name contains the class name
properly. This file is called the source file. Note that all Java source files will have the extension java.
The JVM which in turn acts as the intermediary the Operating System and Java Object Frame Work.
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.
class Test
{
public static void main(String args[])
{
int count, i=0;
String string;
count=arg.length;
System.out.println("Number of arguments ="+count);
while(i<count)
{
string=args[i];
i=i+1;
System.out.println(i+" : "+"Java is"+string+"!");
}
}
} // The output of the program would be :
Number of arguments=3
Output:
Java Simple Programming Language!
Java Object-Oriented Programming Language!
Constants:
Constants in java refer to fixed values that do not change during the execution of a program.
Java supports several types of constants.
JAVA CONSTANTS
Integer Constants
An Integer constant refers to a sequence of digits. There are three types of Integers , namely
decimal Integer, Octal Integer and Hexadecimal Integer.
➢ Decimal Integer consists of set of digits, 0 through 9, preceded by optional minus sign.
Valid examples of decimal Integer constants are:
Embedded spaces, commas, and non-digit characters are not permitted between digits.
For example, 15 750 20.000 $1000 are illegal numbers
➢ An Octal Integer consists of any combination of digits from the set 0 through 7, with a
leading 0. Some examples of Octal integer are 037 0 0435 0551
0X2 0X9F 0Xbcd 0X We rarely use octal and hexadecimal numbers in programming.
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
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 -.71 are all valid real
numbers.
A real number may also expressed in exponential(or scientific)notation. For example, the value 215.65
may be written as 2.1565e2in exponential notation. E2 means multiply by 102.
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 lower case or upper case. Since the exponent causes the decimal point to “float”, this
notation is said to represent a real number in floating point form.
Examples are: 0.65e4 12e-2 1.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
A single character constant contains a single character enclosed 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 character enclosed between double quotes. The characters may
be alphabets, digits, special characters and blank spaces.
Examples are:
“Hello Java” “2021” “WELL DONE” “?..!” “5+5” “X”
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
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.
Constant Meaning
‘\b’ Back space
‘\f’ Form feed
‘\n’ New line
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\’’ Single quote
‘\”’ Double quote
‘\\’ 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.
Variable names may consist of alphabets, digits, the underscore( _)and dollar characters, subject to the
following conditions:
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
DATA TYPES
Every variable in java has a data type. Data types specify the size and type of values that can
be stored. Java language is rich in its data types.
classes Arrays
Numeric Non-numeric
Interface
Integer
Integer Types Floating point Characte Boolean
rs
Integer types can holt whole numbers such as 123, -96, 5639 . the size of the values that can be stored
depends on the integer data type. Java supports four types of integer
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
Float Double
Character Type
To store character constant in memory, java provides a character data type called char. The 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 false . Boolean 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 of any data
type.the general form of declaration of variable is
Variables are separated by commas. A declaration statement must end with semicolon. Some valid
declarations are:
int count;
float x,y;
double pi;
byte b;
char c1,c2,c3;
variableName = value
For example:
initialvalue = 0;
finalvalue = 100;
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
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 declaration. This takes the form:
Examples:
int finalvalue = 100;
char yes = `x`;
double total = 75.36
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.
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
Variables declared and used inside the methods are called local variables. They 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.
{
int x = 0 Block 1
{
:
Block 2
:
int n =5;
:
:
}
{
: Block 3
:
int m = 0
:
:
}
UNIT II
} K.SHARMILA
18K4MACS3 Programming with Java
We can have program blocks within other blocks (called nesting). Each block can contain its
own set of local variable declarations. We 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 available only in block2, because it goes out of the scope
at the end of the block2. 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 analysis program”The number
of students say 50, may be used for calculating the class total, 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 to 100 to process the test result of another class. In both 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 places. Example, 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 problems. Example, 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
From To
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float double
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 automatically . this is known as automatic type conversion.
Example: byte b= 75;
int a= 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.
The print() sends the information into the buffer. This buffer is not flushed until a
newline character is sent. As a result, the print() method prints output on one line until a
newline character is encountered.
Example:
System.out.print(“Hello”);
System.out.print(“Java”);
Will display the words Hello Java on one line and waits for displaying further information on the same
line. The next line by printing a newline character as shown below:
System.out.print(“\n”);
Example: System.out.print(“Hello”);
System.out.print(“\n”);
System.out.print(“Java”);
Will display the output in two lines as follows
Hello
Java
The println() method by contrast, takes the information provided and displays it on a line followed by
a line feed.
System.out.println(“Hello”);
System.out.println(“Java”);
Will display the output in two lines as follows
Hello
Java
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
Arithmetic operators
Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra. Java provides all the basic arithmetic operations.The 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 expression. And the operation is called integer arithmetic. Integer arithmetic
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
always yields an integer value.if 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 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
class FloatPoint
{
public static void main(String args[])
{
float a = 20.5f, b=6.4f;
System.out.println(“a=” +a);
System.out.println(“b=” +b);
System.out.println(“a+b=” +(a+b));
System.out.println(“a-b=” + (a-b));
System.out.println(“a*b=” +(a*b));
System.out.println(“a/b=” +(a/b));
System.out.println(“a%b=” +(a%b));
}
}
Mixed-mode Arithmetic
When one of the operand is real and the other is integer, the expression is called mixed-mode arithmetic
expression. If either operand is of the real type, then the other operand is converted into real and the real
arithmetic is performed. The result will be a 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:
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
Logical Operators
Java has three logical operators. The 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
Operator Meaning
&& logical AND
|| logical OR
! logical NOT
Truth table
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
V op = exp
Where v is a variable, exp is an expression and op is a java binary operator. The operator op=is known
as the shorthand assignment operator.
The assignment statement
v op=exp; is equivalent to v=v op (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 languages. These are the
increment and decrement operators:
++ and –
The operator ++ adds 1 to the operand while – subtracts 1. Both are unary operators and are used in the
following form:
++m; or m++;
--m; or m--;
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
class incrementoperator
{
public static void main(String args[])
{
int m=10, n=20;
System.out.println(“m=” +m);
System.out.println(“n” +n);
System.out.println(“++m=”+ +m);
System.out.println(“n++=” +n++);
System.out.println(“m=” +m);
System.out.println(“m=” +m);
}
}
Output will be
m=10
n=20
++m=11
n++=10
m=11
n=21
conditional operator
The character pair ?: is a ternary operator available in java. This operator is used to construct
conditional expression of the form
b=15;
x= (a>b) ? a : b ; in this example, x will be assigned the value of b. this can be achieved using the
if…else statement as follows:
if(a>b)
x=a;
else
x=b;
Bitwies operators
This operators are used for testing the bits, or shifting them to the right or left. This operator
may not be applied to float or double.
Operator Result
Dot operator
The dot operator(.) is used to acess the instance variable and methods of class objects.
Example:
person1.age//reference to the variable age
person1.salary()//reference to the method salary()
Arithematic expressions
An arithematic expression is a combination of variables, constants, and operators arranged as per
the syntax of the language.
Expressions
Algebric 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
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
Evaluation of expressions
Expressions are evaluated using an assignment statement of the form
variable=expression
Variable is any valid java name. when the statement is encountered, the expression is evaluated first and
the result then replaces the variable on the left-hand side. All 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 */%
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 operator(if any) are applied as they are encountered. Consider
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 passes. However, the number of evaluation steps remain the
same as 5.
Parenthesis may be nested, and in such cases, evaluation of expression will proceed outward from the
innermost set of parenthesis. Make sure that every opening parentheses has a matching closing one. For
example
9-(12/(3+3)*2)-1=4
Whereas 9-((12/3)+3*2)-1= -2
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
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 it. However , the following changes are introduced during the final
assignment.
1. Float to int causes truncation of the fractional part.
2. Double to float causes rounding of digits.
3. Long to int causes dropping of the excess higher order bits.
Casting a value
Java performs type conversion automatically. However, 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 ratio of female to males in a town.
The operator (float) converts the female _ number to floating points for the purpose of evaluation of
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
the expression. Then using the rule of automatic conversion, the division is performed in foalting
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 result.
Note that in no way dose the operator (float) affect the value of the variable female _ number. And
also, the type of female _ number remains as int in theother parts program.
The process of such a local conversion is known as casting value. The general form of a cast is;
Where type- name is one of the standard data types. The expression may be a constant, variable or
an expression.
Examples:
x= (int) 7.5 7.5 is 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 integer . consider the following statement;
x = (int) (y + 0.5) ;
If y is 27.6, y + 0.5 is 28.1 and casting, the results becomes 28, the value that is assigned to x. Of
course, the expression being is not changed.
When combining two different types of variables in an expression, never assume the rules of
automatic conversion. It is always a good practice to explicitly force the conversion. It 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;
Mathematical Functions
Mathematical functions such as cos, sqrt, log, etc., are frequently used in analysis of real-life problems.
Java supports these basic math functions through math class defined in the java.lang package. These
functions should be used as Math.function_name()
Example:
Double y=Math.sqrt(x);
UNIT II
K.SHARMILA
18K4MACS3 Programming with Java
Math functions
sin(x) Returns the sine of angle x in radians
cos(x) Returns the cosine of angle x in radians
tan(x) Returns the tangent of angle x in radians
asin(y) Returns the angle whose sine is y
acos(y) Returns the angle whose cosine is y
atan(y) Returns the angle whose tangent is y
UNIT II
K.SHARMILA
18K4MACS3 Programming with java
Branching:
When a Program breaks the sequential flow and jumps to
another part of the code ,it is called branching.There 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.
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
Syntax:
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
Flow diagram of Java nested if statement:
Syntax:
if
{
//code to be executed
}
else if(condition)
{
//code to be executed
}
else if(condition)
{
//code to be executed
}
else
{
//code to be executed
}
• for loop
• while loop
• do...while loop
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)
{
// body of the loop
}
Here,
class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println("Java is fun");
}
}
}
Output
Java is fun
Java is fun
Java is fun
Java is fun
Java is fun
While Loop
Java while loop is used to run a specific code until a certain condition
is met. The syntax of the while loop is:
while (testExpression) {
// body of loop
}
Here,
class Main {
public static void main(String[] args) {
// declare variables
int i = 1, n = 5;
System.out.println(i);
i++;
}
}
}
Output
1
2
3
4
5
class Main {
public static void main(String[] args) {
int i = 1, n = 5;
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 statements.
• jump: Java supports three jump statement: break, continue and return. These three
statements transfer control to other part of the program. Break: In Java, break is
majorly used for: Terminate a sequence in a switch statement.
The break cannot be used outside the loops and switch statement
Labeled Loops
We can give a label to a block of statements.A label is any valid java variable
name.To give a label to a loop,place it before the loop with a colon at the end.
For ex.
Outer:for(int m=1;m<11;m++)
For(int n=1;n<11;n++)
System.out.print(“”+m*n );
If (n==m)
Continue outer;