OOPTJ R23 Unit 1
OOPTJ R23 Unit 1
UNIT I
Object Oriented Programming: Basic concepts, Principles
Program Structure in Java: Introduction, Writing Simple Java Programs, Elements or Tokens in
Java Programs, Java Statements, Command Line Arguments, User Input to Programs, Escape
Sequences Comments, Programming Style.
Data Types, Variables, and Operators: Introduction, Data Types in Java, Declaration of
Variables, DataTypes, Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic
Constants, Formatted Output with printf() Method, Static Variables and Methods, Attribute Final,
Introduction to Operators, Precedence and Associativity of Operators, Assignment Operator ( = ),
Basic Arithmetic Operators, Increment (++) and Decrement (- -) Operators, Ternary Operator,
Relational Operators, Boolean Logical Operators, Bitwise Logical Operators.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions,
Ternary Operator ?:,Switch Statement, Iteration Statements, while Expression, do–while Loop, for
Loop, Nested for Loop, For–Each for Loop, Break Statement, Continue Statement.
OOP is programming which deals with building the programs and applications
using the objects. These objects are similar to the real-world objects. Every
object has an identity, attributes and behavior. The features of OOP such as
abstraction, encapsulation, inheritance and polymorphism are closely
related to real-world objects.
In real-world we deal with objects such as car, plane, and bike. Each object has
its own Identity (name), attributes (data) and behavior (functions). The
attributes define data for an object. For example the attributes of student
object are name, roll number, and branch. The behavior defines the functions
that operate on the data. There can be one or more functions.
Encapsulation
Encapsulation is the mechanism that binds data and methods together into a
single unit. It is also known as data hiding. It prevents outside code from
accessing the data. One way to think about encapsulation is as a protective
wrapper that prevents the code and data from being arbitrarily accessed by
other code defined outside the wrapper. Access to the code and data inside the
wrapper is tightly controlled through a well-defined interface. In Java, the basis
of encapsulation is the class. A class is defined as blue print or prototype or
template of an object. The objects are defined as instances of a class. Thus, a
class is a logical construct; an object has physical reality.
When you create a class, you will specify the code and data that
constitute that class. Collectively, these elements are called members of the
class. Specifically, the data defined by the class are referred to as member
variables or instance variables. The code that operates on that data is
referred to as member methods or just methods. The members can be public
or private. When a member is made public any code outside the class can
access them. If the members are declared, then only the members of that class
can access its members.
Inheritance
Note:- The sub class is also known as child class or derived class. The super class is also known
as parent class or base class.
Polymorphism
Objects: Objects are the basic run time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program has
to handle. They may also represent user-defined data such as vectors, distance, time, lists
etc. An object is an instance of a class. It is a variable that represents data and functions
required for operating on the data.
Class: Class is an abstract data type (user defined data type) that contains member variables
and member functions that operate on data. It starts with the keyword class. A class denotes a
group of similar objects.
e.g.: Employee e1, e2;
Abstraction: Abstraction refers to the act of representing essential features without including
the background details or explanation.
There are two types of abstraction
i) Procedural Abstraction
ii) Data Abstraction
Procedural Abstraction: Procedural Abstraction is representing procedure without
internal level details.
Data Abstraction: Data Abstraction is representing data without its information.
Data Hiding: All the data in a class can be restricted from using it by giving some access
levels (visibility modes). The three access levels are private, public, protected.
Private data and functions are available to the public functions only. They
cannot be accessed by the other part of the program. This process of hiding
private data and functions from the other part of the program is called as data
hiding.
Example:
Reusability: Using the already existing code is called as reusability. This is mostly used in
inheritance. The already existing code is inherited to the new class. It saves a lot of time and
effort. It also reduces the size of the program.
Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic binding means that the code associated with a given procedure call is not known
until the time of the call at run time. It is associated with polymorphism and inheritance. A
function call associated with a polymorphic reference depends on the dynamic type of that
reference.
History of JAVA
Java history is interesting to know. The history of java starts from Green Team. Java team
members (also known as Green Team), initiated a revolutionary task to develop a language for
digital devices such as set-top boxes, televisions etc. For the green team members, it was an
advance concept at that time. But, it was suited for internet programming. Later, Java technology
as incorporated by Netscape. Currently, Java is used in internet programming, mobile devices,
games, e-business solutions etc. There are given the major points that describes the history of
java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Why Oak name for java language?
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc. During 1991 to 1995 many people around the world
contributed to the growth of the Oak, by adding the new features. Bill Joy, Arthur van Hoff,
Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the original
prototype.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Why Java name for java language?
7) Why they chose java name for java language? The team gathered to choose a new name.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted
something that reflected the essence of the technology: revolutionary, dynamic, lively, cool,
unique, and easy to spell and fun to say. According to James Gosling "Java was one of the top
choices along with Silk". Since java was so unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
9) Notice that Java is just a name not an acronym.
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996).
There are many java versions that has been released. Current stable release of Java is Java SE 8.
There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
o Simple
o Secure
o Portable
o Object-oriented
o Robust
o Multithreaded
o Architecture-neutral
o Interpreted
o High performance
o Distributed
o Dynamic
Simple
Java was designed to be easy for the professional programmer to learn and use effectively.
According to Sun, Java language is simple because: syntax is based on C++ (so easier for
programmers to learn it after C++). removed many confusing and/or rarely-used features e.g.,
explicit pointers, operator overloading etc. No need to remove unreferenced objects because
there is Automatic Garbage Collection in java.
Secure
Once the byte code generated, the code can be transmitted to other computer in the world with
knowing the internal details of the source code.
Portable
The byte code can be easily carried from one machine to other machine.
Object Oriented
Everything in Java is an Object. The object model in Java is simple and easy to extend, while
primitive types, such as integers, are kept as high-performance non-objects.
Robust
Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows you to
write programs that do many things simultaneously.
Architecture-neutral
The Java designers made several hard decisions in the Java language and the Java Virtual
Machine in an attempt to alter this situation. Their goal was “write once; run anywhere, any time,
forever.” To a great extent, this goal was accomplished.
Distributed
Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols. In fact, accessing a resource using a URL is not much different from accessing a file.
Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke
methods across a network.
Dynamic
Java programs carry with them substantial amounts of run-time type information that is used to
verify and resolve accesses to objects at run time. This makes it possible to dynamically link
code in a safe and expedient manner.
The key that allows Java to solve both the security and
the portability problems is the byte code. The output of Java
Compiler is not directly executable file. Rather, it contains
highly optimized set of instructions. This set of instructions is
called, "byte code". This byte code is designed to be executed
by Java Virtual Machine (JVM). The JVM also called as the
interpreter for byte code. JVM also helps to solve many
problems associated with web-based programs.
Translating a Java program into byte code makes it much
easier to run a program in a wide variety of environments
because only the JVM needs to be implemented for each Figure 2 JVM
platform. Once the run-time package exists for a given system, any Java program can run on it.
Remember, although the details of the JVM will differ from platform to platform, all understand
the same Java byte code. Thus, the execution of byte code by the JVM is the easiest way to
create truly portable programs.
The fact that a Java program is executed by the JVM also helps to make it secure. Because
the JVM is in control, it can contain the program and prevent it from generating side effects
outside of the system.
To give on-the-fly performance, the Sun began to design HotSpot Technology for Compiler,
which is called, Just-In-Time compiler. The JIT, Compiler also produces output immediately
after compilation.
Program Structures
class Example
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
We can use any text editor such as "notepad' or "dos text editor". The source code is typed and is
saved with ".java" as extension. The source code contains one or more class definitions. The
program name will be same as class name in which main function is written. This in not
compulsory, but by convention this is used. The source file is officially called as compilation
unit. We can even uses our choice of interest name for the program. If we use a different name
than the class name, then compilation is done with program name, and running is done with class
file name. To avoid this confusion and organize the programs well, it is suggested to put the
same name for the program and class name, but not compulsory.
To compile the program, first execute the compiler, "javac", specifying the name of the source
file on the command line, as shown bellow:
c:\>javac Example.java
The javac compiler creates the file called "Example.class", that contains the byte code version of
the source code. This byte code is the intermediate representation of the source code that
contains the instructions that the Java Virtual Machine (JVM) will execute. Thus the output of
the javac is not the directly executable code.
To actually run the program, we must use Java interpreter, called "java". This is
interpreter the "Example.class" file given as input.
When the program is run with java interpreter, the following output is produced:
Hello World
The first line contains the keyword class and class name, which actually the basic unit for
encapsulation, in which data and methods are declared.
Second line contains "{" which indicates the beginning of the class.
where “public” is access specifier, when a member of a class is made public it can be accessed
by the outside code also. The “static” is the keyword which is used to call the main function
without instantiation. The “void” is also a keyword which is used to describe the the return type
of the function. The main function is the beginning of from where execution starts. Java is case-
sensitive. "Main" is different from the "main". In main there is one parameter, String args,
which is used to read the command line arguments.
Fourth line contains the "{", which is the beginning of the main function.
System.out.println("Hello World");
Here "System" is the predefined class, that provides access to the system, and out is the output
stream that is used to connect to the console. The println(), is used to display string passed to it.
This can even display other information to.
Identifiers
Identifiers are used for class names, method names, and variable names. An identifier may be
any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and
dollar-sign characters. They must not begin with a number, lest they be confused with a numeric
literal. Again, Java is case-sensitive, so VALUE is a different identifier than Value. Some
examples of valid identifiers are:
Class or Interface- These begin with a capital letter. The first alphabet of every internal
word is capitalized. Ex: class Myclass;
Variable or Method –These start with lower case letters. The first alphabet of every
internal word is capitalized. Ex:- int totalPay;
Constants- These are in upper case. Underscore is used to separate the internal word.
Ex:-final double PI=3.14;
Package – These consist of all lower-case letters. Ex:- import java.io.*;
Literals
A literal is a value that can be passed to a variable or constant in a program. Literals can be
numeric, boolean, character, string notation or null. A constant value can be created using a
literal representation of it.
Separators
In Java, there are a few characters that are used as separators. The most commonly usedseparator
in Java is the semicolon. As you have seen, it is used to terminate statements.The separators are
shown in the following table:
Operators
An operator performs an operation on one or more operands. Java provides a rich
operator environment. An operator that performs an operation on one operand is called unary
operator. An operator that performs an operation on two operands is called binary operator.
Most of its operators can be divided into the following groups: arithmetic operators, relational
operators, logical operators, assignment operators, increment and decrement operators,
bitwise operators and conditional operators. Java also defines some additional operators that
handle certain special situations. In Java under Binary operator we have Arithmetic, relational,
Shift, bitwise and assignment operators. And under Unary operators we have ++, - - , !(
Boolean not), ~(bitwise not) operators.
a) Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
The operands of the arithmetic operations are of numeric type. The Boolean operands are not
allowed to perform arithmetic operations. The basic arithmetic operators are: addition,
subtraction, multiplication, and division.
The modulus operator, %, returns the remainder of a division operation. It can be applied to
floating-point types as well as integer types. The following demonstrates the %
Modulus.java
// Demonstrate the % operator.
class Modulus
{
public static void main(String args[])
{
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
b) Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here:
The outcome of these operations is a boolean value. The relational operators are most
frequently used in the expressions that control the if statement and the various loop statements.
Java provides Logical AND(&&) , Logical OR(||) and Logical NOT(!) operators.
When we use || operator if left hand side expression is true, then the result will be true, no
matter what is the result of right hand side expression. In the case of && if the left hand side
expression results true, then only the right hand side expression is evaluated. In the case of ! if
expression is true, it results false and if expression is false, it results true.
The assignment operator is the single equal sign, =. The assignment operator works in Java
much as it does in any other computer language. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression. The assignment operator
does have one interesting attribute that you may not be familiar with: it allows you to create a
chain of assignments. For example, consider this fragment:
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
As you probably know, statements like the following are quite common in programming:
a = a + 4;
a += 4;
This version uses the += compound assignment operator. Both statements perform the same
action: they increase the value of a by 4.
The ++ and the – – are Java’s increment and decrement operators. The increment operator
increases its operand by one. The decrement operator decreases its operand by one. For example,
this statement:
x = x + 1;
x++;
is equivalent to
x--;
Note: If we write increment/decrement operator after the operand such expression is called post
increment decrement expression, if written before operand such expression is called pre
increment/decrement expression
Java defines several bitwise operators that can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands. They are
summarized in the following table:
These operators are again classified into two categories: Logical operators, and Shift
operators.
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of each
operation. The bitwise operators are applied to each individual bit within each operand.
00101010
becomes
11010101
after the NOT operator is applied.
00001010 10
The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then
the resultant bit is a 1, as shown here:
00101010 42
| 00001111 15
00101111 47
The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1.
Otherwise, the result is zero. The following example shows the effect of the ^.
00101010 (42)
^ 00001111 (15)
00100101 (37)
The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times.
It has this general form:
Here, num specifies the number of positions to left-shift the value in value. That is, the <<moves
all of the bits in the specified value to the left by the number of bit positions specified by num.
The right shift operator, >>, shifts all of the bits in a value to the right a specified number
oftimes. Its general form is shown here:
Here, num specifies the number of positions to left-shift the value in value. That is, the >>moves
all of the bits in the specified value to the right by the number of bit positions specified by num.
ShiftBits.java
class ShiftBits
{
public static void main(String args[])
{
byte b=6;
int c,d;
//left shift
c=b<<2;
//right shift
d=b>>3;
System.out.println("The left shift result is :"+c);
System.out.println("The right shift result is :"+d);
}
}
Difference between >> (shift right) and >>>(shift right zero fill)
There are two types of right shift operator in Java >> and >>>, former is known as right shift
and later is known as right shift with zero fill or simply unsigned right shift operator in Java.
Though both of them are known as bit shift operators and moves bits patterns towards right hand
side of a bit sequence, there is subtle difference between them. When we use right shift operator
i.e. ">>" it keeps sign bit intact i.e. if original number is negative then it will remain negative
even after right shift i.e. first or most significant bit never lost, doesn't matter how many times
you shift.
On the other hand unsigned right shift operator ">>>" doesn't preserve sign of original number
and fills the new place with zero, that's why it's known as unsigned right shift operator or
simply right shift with zero fill.
g) Conditional ?: Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-
else statements. This operator is the ?. It can seem somewhat confusing at first, but the ? can be
used very effectively once mastered. The ? has this general form:
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is
true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?
operation is that of the expression evaluated. Both expression2 and expression3 are required to
return the same type, which can’t be void. Here is an example of the way that the ? is employed:
Test.java
class Test
{
public static void main(String args[])
{
int x=4,y=6;
int res= (x>y)?x:y;
System.out.println("The result is :"+res);
}
}
Note: The operators =,?:, ++, and – are having Right to Left Associativity. The remaining
Operators are having Left to Right Associativity.
Using Parentheses
Parentheses raise the precedence of the operations that are inside them. This is often necessary
to obtain the result you desire. For example, consider the following expression:
a >> b + 3
This expression first adds 3 to b and then shifts a right by that result. That is, this expression
can be rewritten using redundant parentheses like this:
a >> (b + 3)
However, if you want to first shift a right by b positions and then add 3 to that result, you will
need to parenthesize the expression like this:
(a >> b) + 3
Comments in Java
In java we have three types of comments: single line comment, Multiple line comment, and
document type comment.
Single line comment is represented with // (two forward slashes), Multiple comment lines
represented with /*………….*/ (slash and star), and the document comment is represented with
/**……….*/.
Datatypes in java
Data Types
Java is strongly typed language. The safety and robustness of the Java language is in fact
provided by its strict type. There are two reasons for this: First, every variable and expression
must be defined using any one of the type. Second, the parameters to the method also should
have some type and also verified for type compatibility. Java language 8 primitive data types:
The primitive data types are: char, byte, short, int, long, float, double, boolean. These are again
grouped into 4 groups.
1. Integer Group: The integer group contains byte, short, int, long. These data types will
need different sizes of the memory. These are assigned positive and negative values. The
width and ranges of these values are as follow:
byte:
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to
127.Variables of type byte are especially useful when you’re working with a stream of data
from a network or file. They are also useful when you’re working with raw binary data that may
not be directly compatible with Java’s other built-in types. Byte variables are declared by use of
the byte keyword.
For example, the following declares two byte variables called b and c:
short:
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-used
Java type. Here are some examples of short variable declarations:
short s;
short t;
int:
The most commonly used integer type is int. It is a signed 32-bit type that has a range from –
2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly
employed to control loops and to index arrays. We can store byte and short values in an int.
Example
int x=12;
long:
long is a signed 64-bit type and is useful for those occasions where an int type is not large
enough to hold the desired value. The range of a long is quite large. This makes it useful when
big, whole numbers are needed.
Example
long x=123456;
2. Floating-Point Group
Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision. These are used with operations such as square root, cosine, and sine
etc. There are two types of Floating-Point numbers: float and double. The float type represents
single precision and double represents double precision. Their width and ranges are as follows:
float:
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is
faster on some processors and takes half as much space as double precision. Variables of type
float are useful when you need a fractional component, but don’t require a large degree of
precision.
Example:
float height, price;
double:
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double
precision is actually faster than single precision on some modern processors that have been
optimized for high-speed mathematical calculations. All the math functions, such as sin( ), cos( ),
and sqrt( ), return double values.
Example:
double area,pi;
Example program to calculate the area of a circle
import java.io.*;
class Circle
{
public static void main(String args[])
{
double r,area,pi;
r=12.3;
pi=3.14;
area=pi*r*r;
System.out.println("The Area of the Circle is:"+area);
}
}
3. Characters Group
In Java, the data type used to store characters is char. However, C/C++ programmers
beware: char in Java is not the same as char in C or C++. In C/C++, char is 8 bits wide. This is
not the case in Java. Instead, Java uses Unicode to represent characters. Unicode defines a fully
international character set that can represent all of the characters found in all human languages.
Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars.
The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the
extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255.
4. Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two possible
values, true or false. This is the type returned by all relational operators, as in the case of a < b.
There are two types of conversion. They are Implicit Conversion, and Explicit Conversion.
Implicit Conversion
In the case of the implicit conversion type conversion is automatically performed by java when
the types are compatible. For example, the int can be assigned to long. The byte cane assigned to
short. However, all the types are compatible, thus all the type conversions are implicitly
allowed.For example, double is not compatible with byte.
Conditions for automatic conversion
1. The two types must be compatible
2. The destination type must be larger than the source type
When automatic type conversion takes place the widening conversion takes place. For example,
Explicit Conversion
Fortunately, it is still possible obtain the conversion between the incompatible types. This is
called explicit type conversion. Java provides a special keyword "cast" to facilitate explicit
conversion. For example, sometimes we want to assign int to byte, this will not be performed
automatically, because byte is smaller than int. This kind of conversion is sometimes called
"narrowing conversion". Since, you are explicitly making the value narrow. The general form of
the cast will be as follow:
Here the target type specifies the destination type to which the value has to be converted.
Example
int a=1234;
byte b=(byte) a;
The above code converts the int to byte. If the integer value is larger than the byte, then it will be
reduced to modulo byte's range.
casttest.java
import java.io.*;
class casttest
{
public static void main(String args[])
{
int a=258;
byte b;
b=(byte) a;
output:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the range of either of its byte operands.
To handle this kind of problem, Java automatically promotes each byte, short,or char operand
to int when evaluating an expression. This means that the sub expression a * bis performed
using integers—not bytes. Thus, 2,000, the result of the intermediate expression,50 * 40, is legal
even though a and b are both specified as type byte.
As useful as the automatic promotions are, they can cause confusing compile-time errors. For
example, this seemingly correct code causes a problem:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte
variable.However, because the operands were automatically promoted to int when the expression
was evaluated, the result has also been promoted to int. Thus, the result of the expression is now
of type int, which cannot be assigned to a byte without the use of a cast.
In cases where you understand the consequences of overflow, you should use an explicit
cast, such as
byte b = 50;
b = (byte)(b * 2);
Java defines several type promotion rules that apply to expressions. They are as follows:
First,all byte, short, and char values are promoted to int, as just described.
Then, if one operandis a long, the whole expression is promoted to long.
If one operand is a float, the entireexpression is promoted to float.
If any of the operands is double, the result is double.
3. Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
Here the type is any primitive data types, or class name. The identifier is the name of the
variable. We can initialize the variable by specifying the equal sign and value.
Example
The control statements are used to control the flow of execution and branch based on the status
of a program. The control statements in Java are categorized into 3 categories:
if statement: This is the Java's conditional branch statement. This is used to route the execution
through two different paths. The general form of if statement will be as follow:
if (conditional expression)
{
statement1
}
else
{
statement2
}
Here the statements inside the block can be single statement or multiple statements. The
conditional expression is any expression that returns the Boolean value. The else clause is
optional. The if works as follows: if the conditional expression is true, then statement1 will be
executed. Otherwise statement2 will be executed.
Example:
Write a java program to find whether the given number is even or odd?
EvenOdd.java
import java.io.*;
classs EvenOdd
{
public static void main(String args[])
{
int n;
System.out.println("Enter the value of n");
DataInputStream dis=new DataInputStream(System.in);
n=Integer.parseInt(dis.readLine());
if(n%2==0)
{
System.out.println(n+" is the Even Number");
}
else
{
System.out.println(n+"is the ODD Number");
}
}
}
Nested if: The nested if statement is an if statement, that contains another if and else inside it.
The nested if are very common in programming. When we nest ifs, the else always associated
with the nearest if.
The general form of the nested if will be as follow:
if(conditional expresion1)
{
if(conditional expression2)
{
statements1;
}
else
{
satement2;
}
}
else
{
statement3;
}
Example program:
Write a java Program to test whether a given number is positive or negative.
Positive.java
import java.io.*;
class Positive
{
public static void main(String args[]) throws IOException
{
int n;
DataInputStream dis=new DataInputStream(System.in);
n=Integer.parseInt(dis.readLine());
if(n>-1)
{
if(n>0)
System.out.println(n+ " is positive no");
}
else
System.out.println(n+ " is Negative no");
}
}
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the
if-else-if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
The if statements are executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed.
Example Program:
Write a Java Program to test whether a given character is Vowel or Consonant?
Vowel.java
import java.io.*;
class Vowel
{
public static void main(String args[]) throws IOException
{
char ch;
ch=(char)System.in.read();
if(ch=='a')
System.out.println("Vowel");
else if(ch=='e')
System.out.println("Vowel");
else if(ch=='i')
System.out.println("Vowel");
else if(ch=='o')
System.out.println("Vowel");
else if(ch=='u')
System.out.println("Vowel");
else
System.out.println("consonant");
}
}
The switch statement is Java’s multi-way branch statement. It provides an easy way to dispatch
execution to different parts of your code based on the value of an expression. As such, it often
provides a better alternative than a large series of if-else-if statements. Here is the general form
of a switch statement:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char; each of the values specified in thecase
statements must be of a type compatible with the expression. Eachcase value must be a unique
literal (that is, it must be a constant, not a variable). Duplicate casevalues are not allowed.
The switch statement works like this: The value of the expression is compared with eachof the
literal values in the case statements. If a match is found, the code sequence followingthat case
statement is executed. If none of the constants matches the value of the expression,then the
default statement is executed. However, the default statement is optional. If no casematches and
no default is present, then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence. Whena break
statement is encountered, execution branches to the first line of code that follows theentire
switch statement. This has the effect of “jumping out” of the switch.
Write a Java Program to test whether a given character is Vowel or Consonant?( Using
Switch)
SwitchTest.java
import java.io.*;
class SwitchTest
{
public static void main(String args[]) throws IOException
{
char ch;
ch=(char)System.in.read();
switch(ch)
{
//test for small letters
case 'a': System.out.println("vowel");
break;
case 'e': System.out.println("vowel");
break;
case 'i': System.out.println("vowel");
break;
case 'o': System.out.println("vowel");
break;
case 'u': System.out.println("vowel");
break;
//test for capital letters
case 'A': System.out.println("vowel");
break;
default: System.out.println("Consonant");
}
}
}
The break statement is optional. If you omit the break, execution will continue on into thenext
case. It is sometimes desirable to have multiple cases without break statements betweenthem.
For example, consider the following program.
class Switch
{
public static void main(String args[])
{
int month = 4;
String season;
switch (month)
{
case 12:
case 1:
case 2:season = "Winter";
break;
case 3:
case 4:
case 5:season = "Spring";
break;
case 6:
case 7:
case 8:season = "Summer";
break;
case 9:
case 10:
case 11:season = "Autumn";
break;
default:season = "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
}
You can use a switch as part of the statement sequence of an outer switch. This is called anested
switch. Since a switch statement defines its own block, no conflicts arise between thecase
constants in the inner switch and those in the outer switch. For example, the followingfragment
is perfectly valid:
o The switch differs from the if in that switch can only test for equality, whereas if can
evaluate any type of Boolean expression. That is, the switch looks only for a match
between the value of the expression and one of its case constants.
o No two case constants in the same switch can have identical values. Of course, a
switch statement and an enclosing outer switch can have case constants in common.
Java’s iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of
instructions until a termination condition is met.
i. while
The 'while' loops is used to repeatedly execute a block of statements based on a condition. The
condition is evaluated before the iteration starts. A 'for' loop is useful, when we know the
number of iterations to be executed in advance. If we want to execute the loop for indefinite
number of times, a while loop may be better choice. For example, if you execute a query to fetch
data from database, you will not know the exact number of records returned by the query.
Syntax:
while(condition)
{
// body of loop
increment or decrement statement
}
The condition can be any Boolean expression. The body of the loop will be executed as long as
the conditional expression is true. When condition becomes false, control passes to the next line
of code immediately following the loop. The curly braces are unnecessary if only a single
statement is being repeated.
Example program:
Write a java program to add all the number from 1 to 10.
WhileTest.java
import java.io.*;
class WhileTest
{
public static void main(String args[])
{
int i=1,sum=0;
while(i<=10)
{
sum=sum+i;
i++;
}
System.out.println("The sum is :"+sum);
}
}
However, sometimes it is desirable to execute the body of a loop at least once, even if the
conditional expression is false to begin with. In other words, there are times when you would like
to test the termination expression at the end of the loop rather than at the beginning.
Fortunately, Java supplies a loop that does just that: the do-while. The do-while loop always
executes its body at least once, because its conditional expression is at the bottom of the loop. Its
general form is:
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the
conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop
terminates. As with all of Java’s loops, condition must be a Boolean expression.
Example program:
Write a java program to add all the number from 1 to 10. (using do-while)
WhileTest.java
import java.io.*;
SACET, CSE Department, II CSE I SEM ( R23) Page 29
OBJECT ORIENTED PROGRAMMING THROUGH JAVA
class WhileTest
{
public static void main(String args[])
{
int i=1,sum=0;
do
{
sum=sum+i;
i++;
}while(i<=10);
System.out.println("The sum is :"+sum);
}
}
Note 1:Here the final value of the i will be 11. Because the body is executed first, then the
condition is verified at the end.
Note 2: The do-while loop is especially useful when you process a menu selection, because you
will usually want the body of a menu loop to execute at least once.
Example program: Write a Java Program to perform various operations like addition,
subtraction, and multiplication based on the number entered by the user. And Also Display
the Menu.
DoWhile.java
import java.io.*;
class DoWhile
{
public static void main(String args[]) throws IOException
{
int n,sum=0,i=0;
DataInputStream dis=new DataInputStream(System.in);
do
{
System.out.println("Enter your choice");
System.out.println("1 Addition");
System.out.println("2 Subtraction");
System.out.println("3 Multiplicaton");
n=Integer.parseInt(dis.readLine());
System.out.println("Enter two Numbers");
int a=Integer.parseInt(dis.readLine());
int b =Integer.parseInt(dis.readLine());
int c;
switch(n)
{
case 1: c=a+b;
System.out.println("The addition is :"+c);
break;
case 2: c=a-b;
System.out.println("The addition is :"+c);
break;
case 3: c=a*b;
System.out.println("The addition is :"+c);
break;
default:System.out.println("Enter Correct Number");
} while(n<=3);
}
}
for statement
The for loop groups the following three common parts into one statement: Initialization,
condition and Increment/ Decrement.
Syntax:
for(initialization; condition; iteration)
{
// body of the loop
}
ForTest.java
import java.io.*;
class ForTest
{
public static void main(String args[])
{
int i,sum=0;
for(i=1;i<=10;i++)
{
sum=sum+i;
}
System.out.println("The sum is :"+sum);
}
}
There are some important things about the for loop
1. The initialization of the loop controlling variables can be done inside for loop.
Example:
for(int i=1;i<=10;i++)
2. We can write any Boolean expression in the place of the condition for second part of the
loop.
Example: where b is a Boolean data type
boolean b=false;
for(int i=1; !b;i++)
{
//body of the loop
b=true;
}
This loop executes until the b is set to the true;
3. We can also run the loop infinitely, just by leaving all the three parts empty.
Example:
for( ; ;)
{
//body of the loop
}
A for loop also provides another version, which is called Enhanced Version of the for loop. The
general form of the for loop will be as follow:
for(type itr_var:collection)
{
//body of the loop
}
Here, type is the type of the iterative variable of that receives the elements from collection, one
at a time, from beginning to the end. The collection is created sung the array.
Example program:
Write a java program to add all the elements in an array?
ForEach.java
import java.io.*;
class ForEach
{
public static void main(String args[])
{
int i, a[], sum=0;
a=new int[10];
a={12,13,14,15,16};
for(int x:a)
{
sum=sum+x;
}
System.out.println("The sum is :"+sum);
}
}
Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program.
i. break statement
In Java, the break statement has three uses. First, as you have seen, it terminates a statement
sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as
“civilized” form of goto statement.
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<100; i++)
{
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
In addition to its uses with the switch statement and loops, the break statement can also be
employed by itself to provide a “civilized” form of the goto statement. For example, the goto can
be useful when you are exiting from a deeply nested set of loops. To handle such situations, Java
defines an expanded form of the break statement. By using this form of break, you can, for
example, break out of one or more blocks of code.
break label;
Most often, label is the name of a label that identifies a block of code. This can be a
stand-alone block of code but it can also be a block that is the target of another statement. When
this form of break executes, control is transferred out of the named block. The labeled block
must enclose the break statement, but it does not need to be the immediately enclosing bloc.
To name a block, put a label at the start of it. A label is any valid Java identifier
followedby a colon. Once you have labeled a block, you can then use this label as the target of
abreak statement.
Example code:
class Break
{
public static void main(String args[])
{
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
// Demonstrate continue.
class Continue
{
public static void main(String args[])
{
for(int i=1; i<=10; i++)
{
if (i%5 == 0) continue;
System.out.print(i + " ,");}
}
}
Here all the numbers from 1 to 10 except 5 are printed. as 1,2,3,4,6,7,8,9,10.
Example code
class Test
{
public static void main(String args[]) // caller of the method
{
int a=3,b=4;
int x=method(a,b);//function call
System.out.println("The sum is :"+x);
}
int method(int x,int y) // called method
{
return (x+y);
}
}
After computing the result the control is transferred to the caller method, that main in this case.