Java Notes
Java Notes
FUNDAMENTALSOFOBJECTORIENTED-PROGRAMMING
INTRODUCTION:
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:
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
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.
● 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.
Message Communication
Objects communicate with each other in OOPs. The process of programming in case of OOP consists of the
following:
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
● 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‟.
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
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
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:
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.
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.
ArithmeticOperators,UnaryOperators, Assignment
Operator,RelationalOperators,LogicalOperatorsTernary Operator, Bitwise Operators, Shift Operators, instance
of operator, Precedence and Associativity
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:
{
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.
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.
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
Integer Constants
An Integer constant refers to a sequence of [Link] are three types of Integers,namely
decimal Integer, Octal Integer and Hexadecimal Integer.
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 is215. .95 -.71are all valid
real numbers.
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
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
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’ 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.
Variable names may consist of alphabets,digits,the under score(_)and dollar characters,subject to the
following conditions:
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
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;
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.
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.
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
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.
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));
}
}
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
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
Operator Result
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.
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.
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;
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;
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:
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.
● 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,
Output
JavaisfunJa
vaisfunJava
isfunJavais
funJavaisfu
n
While Loop
Here,
Example1:DisplayNumbersfrom1to5
Output
1
2
3
4
5
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.
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
[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;