Chapter 1-jpr Full
Chapter 1-jpr Full
OOP allows us to decompose a problem into a number of entities called Objects and then build data and
functions (known as methods in Java) around these entities. The combination of data and methods make up an
object (see Fig.). The data of an object can be accessed only by the methods associated with that object.
However, methods of one object can access the methods of other objects.
Some of the features of object-oriented paradigm are:
Class: A class in java is the building block, that leads to Object-Oriented programming. It is a user-defined data
type, which holds its own data members and member functions, which can be accessed and used by creating an
instance of that class. A java class is like a blueprint for an object.
For Example:
Consider the Class of Cars. There may be many cars with different names and brand but all of them will share
some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is
the class and wheels, speed limits, mileage are their properties.
A Class is a user defined data-type which has data members and member functions.
Data members are the data variables and member functions are the functions used to manipulate these
variables and together these data members and member functions defines the properties and behavior of
the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage etc and member functions
can be apply brakes, increase speed etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated
(i.e. an object is created) memory is allocated.
Abstraction in Java
Data abstraction refers to providing only essential information to the outside world and hiding their
background details, i.e., to represent the needed information in program without presenting the details.
Data abstraction is a programming (and design) technique that relies on the separation of interface and
implementation.
Hiding of data is known as data abstraction. In object oriented programming language this is implemented
automatically while writing the code in the form of class and object.
Real Life Example of Abstraction in Java
Abstraction shows only important things to the user and hides the internal details, for example, when we ride
a bike, we only know about how to ride bikes but can not know about how it work? And also we do not
know the internal functionality of a bike.
Another real life example of Abstraction is ATM Machine; All are performing operations on the ATM
machine like cash withdrawal, money transfer, retrieve mini-statement…etc. but we can't know internal
details about ATM.
Encapsulation in Java
Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation.
Encapsulation is achieved in java language by class concept.
Combining of state and behavior in a single container is known as encapsulation. In java language
encapsulation can be achieve using class keyword, state represents declaration of variables on attributes and
behavior represents operations in terms of method.
Advantage of Encapsulation
The main advantage of using of encapsulation is to secure the data from other methods, when we make a data
private then these data only use within the class, but these data not accessible outside the class.
Real life example of Encapsulation in Java
The common example of encapsulation is capsule. In capsule all medicine are encapsulated in side capsule.
Benefits of encapsulation
Provides abstraction between an object and its clients.
Protects an object from unwanted access by clients.
Example: A bank application forbids (restrict) a client to change an Account's balance.
Polymorphism in Java
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to take
more than on form..
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
Polymorphism is not a programming concept but it is one of the principal of OOPs. For many objects
oriented programming language polymorphism principle is common but whose implementations are varying
from one objects oriented programming language to another object oriented programming language.
Real life example of polymorphism in Java
Suppose if you are in class room that time you behave like a student, when you are in market at that time you
behave like a customer, when you at your home at that time you behave like a son or daughter, Here one
person present in different-different behaviors.
The process of obtaining the data members and methods from one class to another class is known
as inheritance. It is one of the fundamental features of object-oriented programming.
Important points
In the inheritance the class which is give data members and methods is known as base or super or parent
class.
The class which is taking the data members and methods is known as sub or derived or child class.
The real life example of inheritance is child and parents, all the properties of father are inherited by his son.
Diagram
In the above diagram data members and methods are represented in broken line are inherited from faculty
class and they are visible in student class logically.
Advantage of inheritance
If we develop any application using this concept than that application have following advantages,
Redundancy (repetition) of the code is reduced or minimized so that we get consistence results and
less storage cost.
Differences between C, C++ and Java
History of Java
Java language developed by company Sun Microsystems and the creator is James Gosling.
Story behind development of Java
Sun Microsystems Started by a group of the students who are studing in Standard University. These people
found the problem in their room with electronic consumable remote. That means one electronic consumable
control doesn't work on another electronics consumable. These people want to develop a common remote
control which is controlling all the electronic consumables so they contact James Gosling and requested for
the projects. Sun Microsystems started by a group of students out of them one person also Indian whose
name Vinode Khosla.
James Gosling and his team members given the project name as Green started in the year 1990 and common
remote control completed in the year 1992.
The James Gosling team develops a new language called as OAK But this name is already selected by any
other company renamed as Java, but Java has no meaning representation of Island in Indonesia. The
unofficial abbreviation of Java is Just Another Virtual Analyzer (JAVA).
Java Version History
Now a day 8 versions of java are released, which is listed below with realizing date.
JDK Alpha and Beta (1995)
JDK 1.0 (23rd Jan, 1996)
JDK 1.1 (19th Feb, 1997)
J2SE 1.2 (8th Dec, 1998)
J2SE 1.3 (8th May, 2000)
J2SE 1.4 (6th Feb, 2002)
J2SE 5.0 (30th Sep, 2004)
Java SE 6 (11th Dec, 2006)
Java SE 7 (28th July, 2011)
Java SE 8 (18th March, 2014)
Overview of Java
Java is one of the programming language or technology used for developing web applications. Java language
developed at SUN Micro Systems in the year 1995 under the guidance of James Gosling and there team.
Originally SUN Micro Systems is one of the Academic university (Standford University Network)
Whatever the software developed in the year 1990, SUN Micro Systems has released on the name of oak,
which is original name of java (scientifically oak is one of the tree name). The OAK has taken 18 months to
develop.
The oak is unable to fulfill all requirements of the industry. So James Gosling again reviews this oak and
released with the name of java in the year 1995. Scientifically java is one of the coffee seed name.
JAVA FEATURES
As we know that the Java is an object oriented programming language developed by Sun Microsystems of USA in
1991. Java is first programming language which is not attached with any particular hardware or operating system.
Program developed in Java can be executed anywhere and on any system.
Features of Java are as follows:
1. Compiled and Interpreted
2. Platform Independent and portable
3. Object- oriented
4. Robust and secure
5. Distributed
6. Familiar, simple and small
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible
Java is familiar because: It has a base of Native languages like C and C++ and contains many features of
these languages. It removes the drawbacks, complexities and confusing elements of C/C++. So if you
have good knowledge of C/C++, you will find Java familiar and easy to understand.
2. Object Oriented
Java is truly object-oriented language. Java supports major Object-Oriented programming features like
Encapsulation, Abstraction, and Inheritance. In Java, almost everything is an Object. All program code and
data exist in objects and classes. Java comes with an extensive set of classes; organize in packages that can be
used in program by Inheritance.
For example, we cannot develop an executable program in Java without making use of the class. This indicates
that Java very strictly applies the principle of Encapsulation.
Java Interpreter generate machine code that can be directly executed by machine that is running the Java
program..
4. Platform Independent
A programming language or technology is said to be platform independent if and only if which can run on all
available operating systems with respect to its development and compilation(Platform represents O.S)..
Java is a platform independent programming language, because when you install jdk software on your system
then automatically JVM are installed on your system. For every operating system separate JVM is available
which is capable to read the .class file or byte code. When we compile your Java code then .class file is
generated by compiler(Javac) these codes are readable by JVM and every operating system have its own JVM
so JVM is platform dependent but due to JVM java language is become platform independent.
Java Virtual Machine (JVM), which is usually a software-based interpreter.
5. Portable
Portability means java programs can be easily moved from one computer system to another and anywhere.
That is WORE means “Write once run anywhere”.
If any language supports platform independent feature known as portable.
Changes and upgrades in operating systems, processors and system resources will not force any alteration in
Java programs and make the language portable.
This is reason why Java has become a trendy language for programming on Internet which interconnects
different kind of systems worldwide.
The languages like C, CPP, Pascal are treated as non-portable language. It is a portable language.
According to SUN microsystem. Java supports the feature portability..
In Java, we can split a program into many parts and store these parts on different computers. A Java
programmer sitting on a machine can access another program running on the other machine.
This feature in Java gives the advantage of distributed programming, which is very helpful when we develop
large projects. Java helps us to achieve this by providing the concept of RMI (Remote Method
Invocation) and EJB (Enterprise JavaBeans).
Java is dynamic and extensible means with the help of OOPs, we can add classes and add new methods to
classes, creating new classes through subclasses. This makes it easier for us to expand our own classes and
even modify them.
Java gives the facility of dynamically linking new class libraries, methods, and objects. It is highly dynamic
as it can adapt to its evolving environment.
Java even supports functions written in other languages such as C and C++ to be written in Java
programs. These functions are called “native methods”. These methods are dynamically linked at runtime.
10. High performance
It have high performance because of following reasons;
This language uses Bytecode which is faster than ordinary pointer code so Performance of this language
is high.
Garbage collector, collect the unused memory space and improve the performance of the application.
It has no pointers so that using this language we can develop an application very easily.
It support multithreading, because of this time consuming process can be reduced to executing
the program.
Java Environment:
Java environment includes a number of development tools, classes and methods. The development tools
are p art of the system known as Java Development Kit (JDK) and the classes and methods are part of
the Java Standard Library (JSL), also known as the Application Programming Interface (API). Java
Development kit (JDK) –
The JDK comes with a set of tools that are used for developing and running Java program. It includes:
1. Appletviewer( It is used for viewing the applet)
2. Javac(It is a Java Compiler)
3. Java(It is a java interpreter)
4. Javap(Java diassembler,which convert byte code into program description)
5. Javah(It is for java C header files)
6. Javadoc(It is for creating HTML document)
7. Jdb(It is Java debugger)
Create First program
Step 1:-Open the Notepad and write the code
Example
class First
{
public static void main(String[] args)
{
System.out.println("Hello Java");
System.out.println("My First Java Program");
}
}
o oSyntax:
o o o o o
o Filename.java
Path where u save u r file[Different for everyone]
First.java
o Note: Here Javac and Java are called tools or application programs or exe files developed by sun
micro system and supply as a part of jdk 1.5/1.6/1.7 in bin folder. Javac is used for compile the java
program and java is used for run the java program.
Step 3:
If the path is set u will get the following
Step 4:
Compile the code with javac
Step 5:
Interpret the code with java
Components of JDK
java: The loader for Java applications. This tool is an interpreter and
can interpret
the class files generated by the javac compiler. Now a single
launcher is used for
both development and deployment. The old deployment
launcher, jre, no longer
comes with Sun JDK, and instead it has been replaced by this new
java loader.
javah: the C header and stub generator, used to write native methods.
Class: Class is a blue print which is containing only list of variables and method
and no memory is allocated for them. A class is a group of objects that has
common properties.
A class in java contains:
Data Member
Method
Constructor
Block
Class and Interface
Object: Object is a instance of class, object has state and behaviors. Object is the
physical as well as logical entity where as class is the only logical entity.
sleeping.
Vehicle class
Car, bike, truck these all are belongs to vehicle class. These Objects have also
different different states and behaviors. For Example car has state - color, name,
model, speed, Mileage. as well as behaviors - distance travel
Difference between Class and Object in Java
Class Object
OR
Output
Employee ID: 101
Name: Hitesh
Java Tokens
Java Tokens are the smallest individual building block or smallest unit of a Java program. The
Java compiler uses it for constructing expressions and statements. Java program is a
collection of different types of tokens, comments, and white spaces.
When we write a program, we need different important things. We require language tokens,
white spaces, and formats
There are various tokens used in Java:
Reserved Keywords
Identifiers
Literals
Operators
Separators
White space is also considered as a token.
Java Keywords
Keywords are words that have already been defined for Java compiler. They have special
meaning for the compiler. Java Keywords must be in your information because you can not use
them as a variable, class or a method name.
You can't use keyword as identifier in your Java programs, its reserved words in Java library
and used to perform an internal operation.
Note:
true, falseand nu are not reserved words but cannot be used as identifiers, because it is literals
of built-in types.
Java operators
Java operators are symbols that are used to perform mathematical or logical manipulations.
Java is rich with built-in operators.
Operators are tokens that perform some calculations when they are applied to variables.
There are many types of operators available in Java such as:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Conditional Operator
Increment and decrement operator
instanceof Operator
Member Selection or Dot Operator
Identifier:
Identifiers are used to name a variable, constant, function, class, and array. It usually defined
by the user. It uses letters, underscores, or a dollar sign as the first character. The label is also
known as a special kind of identifier that is used in the goto statement. Remember that the
identifier name must be different from the reserved keywords. There are some rules to declare
identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
For example: _hi123,$a,I etc
o The whitespace cannot be included in the identifier.
For example :
Literals:
In programming literal is a notation that represents a fixed value (constant) in the source code.
It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the
programmer. Once it has been defined cannot be changed. Java provides five types of literals
are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean
Literal Type
23 Int
9.86 Double
Separator in java:
Let's discuss what is a separator in java and what are all the types of separators available in
java. let's get started. A separator is a symbol that is used to separate a group of code from one
another is called as separators in java. In java, there are few characters that are used as a
separator. The most commonly used separator is a semicolon. As we have seen it is used to
terminate the statement.
For example, items in the list are separated by commas in a sentence like lists of items in a
sentence. In Java language, it has six types of separators. They are:
1. Integer
Integer types can hold whole numbers such as 123 and −96. The size of the values that can be
stored depends on the integer type that we choose.
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
Data Type Default Value Default size
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
The byte data type is an example of primitive data type. It is an 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
Example: byte a = 10, byte b = -20
9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,755,807
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is
0.0d.
Example: double d1 = 12.3
Type Size Range of values that can be stored
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or
0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example: char letterA = 'A'
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable
is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
There are two types of data types in Java: primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only within
that method and the other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
Example:
int a;
void add(int b)(here variable b is a local variable)
{
a=b;
}
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable. It is not
declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
Example:
int c=20;
[Here c is an instance variable]
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of
static variable and share among all the instances of the class. Memory allocation for static variable happens
only once when the class is loaded in the memory.
Type casting
Convert a value from one data type to another data type is known as type casting.
Types of Type Casting
There are two types of type casting:
o Widening Type Casting
o Narrowing Type
Casting Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known as implicit
conversion or casting down. It is done automatically. It is safe because there is no chance to lose data. It takes
place when:
o Both data types must be compatible with each other.
o The target type must be larger than the source type.
1. byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done automatically. Also, the
char and Boolean data types are not compatible with each other. Let's see an example.
WideningTypeCastingExample.java
1. public class WideningTypeCastingExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 7;
6. //automatically converts the integer type into long type
7. long y = x;
8. //automatically converts the long type into float type
9. float z = y;
10. System.out.println("Before conversion, int value "+x);
11. System.out.println("After conversion, long value "+y);
12. System.out.println("After conversion, float value "+z);
13. }
14. }
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is:
7.0
In the above example, we have taken a variable x and converted it into a long type. After that, the long type is
converted into the float type.
Converting a higher data type into a lower one is called narrowing type casting. It is also known as explicit
conversion or casting up. It is done manually by the programmer. If we do not perform casting then the
compiler reports a compile-time error. There is loss of data in this type.
Syntax
dataType variableName = (dataType) variableToConvert;
Example
double calculatedMark = 87.6;
int finalGrade = (int)calculatedMark; //will return 87
1. double -> float -> long -> int -> char -> short -> byte
Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation.
Java supports following lists of operators.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Ternary or Conditional Operators
Arithmetic Operators
Given table shows all the Arithmetic operator supported by Java Language. Lets suppose variable A hold 8
and B hold 3.
Java arithmetic operator takes numerical values as operands, operates on them, and returns a single numerical
value. Java Arithmetic operators are used for simple mathematic operations, they are
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
Relational Operators
Which can be used to check the Condition, it always return true or false. Lets suppose variable A hold 8
and B hold 3.
Operators Example (int A=8, B=3) Result
< A<B False
== A== B False
!= A!=(-4) True
Logical Operator
Which can be used to combine more than one Condition?. Suppose you want to combined two
conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is
Logical Operator.
Example (int A=8, B=3, C=-
Operator Result
10)
! !(B<=-A) True
Truth table of Logical Operator
C1 C2 C1 && C2 C1 || C2 !C1 !C2
T T T T F F
T F F T F T
F T F T T F
F F F F T T
Assignment operators
Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
Ternary operator
If any operator is used on three operands or variable is known as ternary operator. It can be represented with "
?: "
Ternary Operator in java
If any operator is used on three operands or variable is known as Ternary Operator. It can be represented
with ? : . It is also called as conditional operator
The ternary operator is an operator that takes three arguments. The first argument is a comparison argument,
the second is the result upon a true comparison, and the third is the result upon a false comparison. Ternary
operator is shortened way of writing an if-else statement.
Ternary operator is a?b:c it say that the condition a is true b will be executed else c will be executed.
In the above symbol expression-1 is condition and expression-2 and expression-3 will be either value or
variable or statement or any mathematical expression. If condition will be true expression-2 will be execute
otherwise expression-3 will be executed.
Bitwise Operator in Java
In Java, an operator is a symbol that performs the specified operations. In this section, we will discuss only
the bitwise operator and its types with proper examples.
Types of Bitwise Operator
There are six types of the bitwise operator in Java:
o Bitwise AND
o Bitwise exclusive OR
o Bitwise inclusive OR
o Bitwise Compliment
o Bit Shift Operators
Bitwise Compliment ~ ~ op
Note: When we apply right shift operator on a positive number, we get the positive number in the result also.
Similarly, when we apply right shift operator on a negative number, we get the negative number in the result
also.
Example: Apply the signed right shift operator with specified positions 4 if x = 256 and x = -256.
If x = 256
256 >> 4
256/24 = 16
If x = -256
-256 >> 4
-256/24 = -16
In the above example, we have observed that after shifting the operator 256 converted into 16 and -256
converted into -16.
Let's create a Java program and implement the left shift operator.
SignedRightShiftOperatorExample.java
1. public class SignedRightShiftOperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x = 50;
6. System.out.println("x>>2 = " + (x >>2));
7. }
8. }
Output
x>>2 = 12
Signed Left Shift Operator (<<)
The signed left shift operator (<<) shifts a bit pattern to the left. It is represented by the symbol <<. It also
preserves the leftmost bit (sign bit). It does not preserve the sign bit.
In general, if we write a<<n, it means to shift the bits of a number toward the left with specified position (n). In
the terms of mathematics, we can represent the signed right shift operator as follows:
Example 1: What will be the result after shifting a<<3. The value of a is 20.
Representation of 20 in binary is = 00010100
After performing the left shift operator, we get:
a << 3 = 10100000 (last three bits are the filled bits)
a << 3 = 160
Let's check the result by using the formula.
20 << 3
20*23 = 20*8 = 160
Example 2: What will be the result after shifting a<<2. The value of a is -10.
Representation of -10 in binary is = 11110110
a<<2 = 11011000 = -40
Let's check the result by using the formula.
-10 << 3
-10*22 = -10*4 = -40
Let's create a Java program and implement the signed left shift operator.
SignedLeftShiftOperatorExample.java
1. public class SignedLeftShiftOperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x = 12;
6. System.out.println("x<<1 = " + (x << 1));
7. }
8. }
Output
x<<1 = 24
Unsigned Right Shift Operator (>>>)
It shifts a zero at the leftmost position and fills 0. It is denoted by the symbol >>>. Note that the leftmost
position after >> depends on the sign bit. It does not preserve the sign bit.
Example: If a=11110000 and b=2, find a>>>b?
a >>> b = 11110000 >>> 2 = 00111100
The left operand value is moved right by the number of bits specified by the right operand and the shifted bits
are filled up with zeros. Excess bits shifted off to the right are discarded.
Therefore, before shifting the bits the decimal value of a is 240, and after shifting the bits the decimal value of a
is 60.
Let's create a Java program and use the unsigned right shift operator.
UnsignedRightShiftOperatorExample.java
1. public class UnsignedRightShiftOperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x = 20;
6. System.out.println("x>>>2 = " + (x >>>2));
7. }
8. }
Output
x>>>2 = 5
Java Operator Precedence
Operator Type Category Precedence
additive +-
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
Java instanceof
The java instanceof operator is used to test whether the object is an instance of the specified type (class or
subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the instance with type. It
returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns
false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple1);//true
5. }
6. }
Output:true
Method Description
Example 1
1. public class JavaMathExample1
2. {
3. public static void main(String[] args)
4. {
5. double x = 28;
6. double y = 4;
long y = -1876487618764l;
7. // return the maximum of two numbers
8. System.out.println("Maximum number of x and y is: " +Math.max(x, y));
9. System.out.println(“Minimum number of x and y is:” +Math.min(x,y));
10. // return the square root of y
11. System.out.println("Square root of y is: " + Math.sqrt(y));
12. //returns 28 power of 4 i.e. 28*28*28*28
13. System.out.println("Power of x and y is: " + Math.pow(x, y));
14.
15. // return the logarithm of given
value 16.
17.
18. // return a power of 2
19. System.out.println("exp of a is: " +Math.exp(x));
System.out.println("Math.abs(" + y + ")=" + Math.abs(y));
20.20.
21. }
22. }
Output:
Maximum number of x and y is: 28.0 Minimum number of x and y is: 4.0 Square root of y is: 2.0
Power of x and y is: 614656.0
exp of a is: 1.446257064291475E12
Math.abs(-1876487618764)=1876487618764
Decision Making Statement in Java
Decision making statement statements is also called selection statement. That is depending on the condition
block need to be executed or not which is decided by condition. If the condition is "true" statement block
will be executed, if condition is "false" then statement block will not be executed. In java there are three
types of decision making statement.
if
if-else
switch
if-then Statement
if-then is most basic statement of Decision making statement. It tells to program to execute a certain part of
code only if particular condition is true.
Syntax
if(condition)
{
Statement(s)
}
Example if statement
class Hello
{
int a=10;
public static void main(String[] args)
{
if(a<15)
{
System.out.println("Hello good morning!");
}
}
}
Output
Hello good morning
if-else statement
In general it can be used to execute one block of statement among two blocks, in java language if and else are
the keyword in java.
Syntax
if(condition)
{
Statement(s)
}
else
{
Statement(s)
}
........
In the above syntax whenever condition is true all the if block statement are executed, remaining statement
of the program by neglecting. If the condition is false else block statement executed and neglecting if block
statements.
Example if else
import java.util.Scanner;
class Oddeven
{
public static void main(String[] args)
{
int no;
Scanner s=new Scanner(System.in);
System.out.println("Enter any number :");
no=s.nextInt();
if(no%2==0)
{
System.out.println("Even number");
}
else
{
System.out.println("Odd number");
}
}
}
Output
Enter any number :
10
Even number
Switch Statement
The switch statement in java language is used to execute the code from multiple conditions or case. It is same
like if else-if ladder statement.
A switch statement work with byte, short, char and int primitive data type, it also works with enumerated
types and string.
Syntax
switch(expression/variable)
{
case value:
//statements
// any number of case
statements break; //optional
default: //optional
//statements
}
import java.util.*;
class switchCase
{
public static void main(String arg[])
{
int ch;
System.out.println("Enter any number (1 to 7) :");
Scanner s=new Scanner(System.in);
ch=s.nextInt();
switch(ch)
{
case 1:
System.out.println("Today is Monday");
break;
case 2:
System.out.println("Today is Tuesday");
break;
case 3:
System.out.println("Today is Wednesday");
break;
case 4:
System.out.println("Today is Thursday");
break;
case 5:
System.out.println("Today is Friday");
break;
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
default:
System.out.println("Only enter value 1 to 7");
}
}
}
Output
Enter any number (1 to 7) :
5
Today is Friday
class whileDemo
{
public static void main(String args[])
{
int i=0;
while(i<5)
{
System.out.println(+i); i++;
}
Output
0
2
3
4
Initialization: This step is execute first and this is execute only once when we are entering into the
loop first time. This step is allow to declare and initialize any loop control variables.
Condition: This is next step after initialization step, if it is true, the body of the loop is executed, if it
is false then the body of the loop does not execute and flow of control goes outside of the for loop.
Increment or Decrements: After completion of Initialization and Condition steps loop body code
is executed and then Increment or Decrements steps is execute. This statement allows to update any
loop control variables.
Flow Diagram
Control flow of for loop
class Hello
{
public static void main(String args[])
{
int i;
for (i=0: i<5; i++)
{
System.out.println("Hello Friends !");
}
}
}
Output
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
n below example you can see in this program i=20 and we check condition i is less than 10, that means
condition is false but do..while loop execute onec and print Hello world ! at one time.
Example do..while loop
class dowhileDemo
{
public static void main(String args[])
{
int i=20;
do
{
System.out.println("Hello world !");
i++;
}
while(i<10);
}
}
Output
Hello world !
class dowhileDemo
{
public static void main(String args[])
{
int i=0;
do
{
System.out.println(+i);
i++;
}
while(i<5);
}
}
Output
1
2
3
4
5
Using break, we can force immediate termination of a loop, bypassing the conditional expression and any
remaining code in the body of the loop. When we use break inside the nested loops, it will only break out of the
innermost loop.
Example:
Java
Output
i: 0
i: 1
i: 2
i: 3
i: 4
Out of Loop
Using break as a Form of Goto
Java does not have a goto statement because it provides a way to branch in an arbitrary and unstructured
manner. Java uses a label. A Label is used to identify a block of code.
Syntax:
label:
{
statement1;
statement2;
statement3;
.
.
}
Now, the break statements can be used to jump out of the target block. We cannot break to any label which is
not defined for an enclosing block.
Syntax:
break label;
Example:
Java
Output
00
01
02
10
Using break to terminate a sequence in a switch statement.
The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different
parts of code based on the value of the expression. The break statement is used inside the switch to terminate a
statement sequence. The break statement is optional. If omitted, execution will continue on into the next case.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example:
Java
Output
i is two.
Continue:
The continue statement in Java is used to skip the current iteration of a loop. We can use continue statement
inside any types of loops such as for, while, and do-while loop. Basically continue statements are used in the
situations when we want to continue the loop but do not want the remaining statement after the continue
statement.
Syntax:
continue;
Using continue to continue a loop
Using continue, we can skip the current iteration of a loop and jumps to the next iteration of the loop
immediately.
Example:
Java
Output
013456789
Using continue as a labelled continue statement
The unlabeled continue statement is used to continue the innermost loop. However, since JDK 1.5 java
introduces another feature known as labelled continue statement. We can use a labelled continue statement to
continue the outermost loop.
Example:
Java
Output
00
01
02
10
20
21
22
Difference between break and continue:
Break Continue
The break statement is used to terminate the loop The continue statement is used to skip the current
immediately. iteration of the loop.
break keyword is used to indicate break statements continue keyword is used to indicate continue
in java programming. statement in java programming.
We can use a break with the switch statement. We can not use a continue with the switch statement.
It stops the execution of the loop. It does not stop the execution of the loop.