0% found this document useful (0 votes)
10 views

Unit-1 java

Uploaded by

shahmeet644
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit-1 java

Uploaded by

shahmeet644
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Java Programming Notes

CO4I

Chapter-1

1. Basic concepts of object oriented programming


The concepts of object oriented programming are as follows:

1. Classes

 A class consist of data and methods.


 A class is a collection of objects of similar type of objects.
 Classes are user defined data.
 Once class has been defined,we can create any number of object belonging to that class.
 Eg.
class Person
{
String name;
int age;
void accept( String n,int a)
{
name=n;
age=a;

}
void display()
{
System.out.println(“Name=”+name);
System.out.println(“Age=”+age);
}

2. Objects

 Objects are basic run time entities in object oriented system. They may represent a place, a bank
account, a table of data or any item that the program must handle.
 Objects are variables of class.
 Objects are generally used to access members (data and methods) of class.
 Eg. Person p =new Person()
Here p is an object of Person class

3. Data abstraction

 Data abstraction refers to act of representing essential features without including background
details or explanations.
 Classes use the concept of abstraction and are defined as the list abstraction attribute such as size,
weight and cost and function to operate on this attribute. They encapsulate all essential properties
of objects that they are to be created since the class used the concept of data abstraction they are

1
Java Programming Notes
CO4I
known as abstract data types(ADT).

4. Data encapsulation

 Data encapsulation means wrapping of data and functions into a single unit. It is most striking
feature of class. The data is not accessible to the outside world and only functions which are
wrapped in the class can access it.
 Thus insulation of data from direct access from program is called data hiding.

5. Inheritence

 Inheritence is the process by which object of one class can acquire the properties of the objects of
other classes. Inheritence means one class of object inherits the data and behavoiur(methods)
from another class .
 The old is refered as a base class and new one is called as derived class. The new class has
combined features of both the classes.

6. Polymorphism

 Polymorphism is the ability to take more than one form.


 For eg: an operation may demonstrate different behaviour in different instance. The behavior
depends upon the type of data used in the operation. As addition of two integer numbers gives
addition while addition of two strings gives concatenation.

7. Dynamic binding

 Binding refers to the linking of a procedure call to the Procedure definition (code) to be executed
in response to the call.
 Binding is classified as static binding and dynamic binding.
 Static binding means that the code associated with given procedure call is known at compile time.
 Dynamic binding means that the code associated with given procedure call is not known until the
time of the call at run time.
 Dynamic binding associated with polymorphism and inheritance.

8. Message Passing

 Message passing involves specifying the name of object, the name of the method and the
information to be sent.
 Example:.
p.accept(“abc”,18);

Here p is an object of Person class.


Accept is message
Arguments is information
1.1 Benefits of OOP

2
Java Programming Notes
CO4I
 OOP emphasis on data rather than procedure.
 Programs are divided into objects.
 Objects are characterized by functions or data structure that operates on data.
 Functions that operates on the data of an object are tied together in the data structure.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 Follows bottom-up approach in program design.

2. Java Features:
1. Compiler/Interpreter
 Java Source Code (.java file) is compiled to byte codes(.class file) that are interpreted by a Java
virtual machines (JVM) .
 This provides portability to any machine for which a virtual machine has been written.
 The two steps of compilation and interpretation allow for extensive code checking and improved
security.

Java source code Java Compiler Byte code Interpreter Machine code
(.java file) (javac) (.class file) (java)

2. Platform Independence
 Java byte code achieves the Write-Once-Run-Anywhere approach so running on different
platforms is possible. As we know java is both compiler & interpreter based language. Once the
java code also known as source code is compiled, it gets converted to Byte Code which is
portable & can be easily executed on all operating systems. Byte code generated is basically
represented in hexa decimal format in .class file. This .class file contains bytecode which is
executed JVM(Java virtual machine) which is a runtime environment for java. Now this .class file
can be run in any environment with the help of JVM and JVM convert bytecode into native
code.

Java Virtual Machine like its real counter part, executes the program and generate output. To
execute any code, JVM utilizes different components. JVM is divided into several components
like the stack, the garbage-collected heap, the registers and the method area.

3
Java Programming Notes
CO4I

Above fig. shows that JVM for different operating system is different.The JVM must translate the
bytecode into machine language, and since the machine language depends on the operating
system being used, it is clear that the JVM is platform (operating system) dependent – in other
words, the JVM is not platform independent.

3. Object Oriented
 Supports all the concepts of object oriented programming language like object classes,
polymorphism etc.
 Java is pure object oriented Language – Each and every code in java comes under a class,
including main().
 Following is the example shows that even main function is comes under a class:

class Demo
{
public static void main(String args[])
{
System.out.println(“hello”);

}
}

4. Robust and Secure


 Exception handling built-in, strong type checking (that is, all data must be declared an explicit
type), local variables must be initialized.
 Automatic Memory Management
o Automatic garbage collection - memory management handled by JVM.

 Java is secure as several dangerous features of C & C++ eliminated


o No memory pointers
o No preprocessor
o Array index limit checking

5.Dynamic Binding

4
Java Programming Notes
CO4I
o The linking of data and methods to where they are located, is done at run-time.New
classes can be loaded while a program is running. Linking is done on the fly.
o Even if libraries are recompiled, there is no need to recompile code that uses classes in
those libraries.

6. Good Performance
o Interpretation of bytecodes slowed performance in early versions, but advanced virtual
machines with adaptive and just-in-time compilation and other techniques now typically
provide performance up to 50% to 100% the speed of C++ programs.

7. Threading
o Lightweight processes, called threads, can easily be added to perform multiprocessing.
o Can take advantage of multiprocessors where available
o Good for multimedia displays.

8. Built-in Networking
o Java was designed with networking in mind and comes with many classes to develop
sophisticated Internet communications.

3. History of Java
Java language developed by SUN MICROSYSTEM. Its initial purpose was o handle consumer electronic
devices. The team which was working on java is named as “Green team” which headed by James
Gosling.

1991-: In 1991 they developed a new language and gave the name of "oak".
1992-: In 1992 they demonstrate the application of new language to handle consumer electronic devices.
1993-: WWW came into existence to handle computer on internet.
1994-: Developed web browser to support web applets.
1995-: Name "OaK" is replaced by java.
1996-:onwards it is knows as object oriented language.

4. Difference between Java and C++

Sr. No. Java C++


1 Java is a true object oriented language. C++ is basically C with object oriented
extension
2 Java is platform independent C++ is not platform independent
3 Java uses two stage execution i.e. C++ uses one stage execution i.r.
Java source code->compiler->bytecode-> Source code->compiler->machine code
interpreter->machine code
4 Java does not support operator overloading C++ supports operator overloading
5 Java does not support multiple inheritances C++ supports multiple inheritances of classes.
of classes. This is accomplished using a
new feature called “interface”
6 Java does not support global variables. C++ supports global variable

5
Java Programming Notes
CO4I
Every variable and method is declared
within a class and forms part of that class
7 Java does not have template classes C++ has template classes
8 Java has replaced the destructor function C++ has the destructor function
with a finalize( )function
9 There are no header files in Java C++ includes header files in program

5. Java Program Structure


Following fig. is showing the typical java program structure. Explanation of each section is as follows:

Documentation section:
This section is not compiled by java compiler. In this section only title of program is written for
understanding of programmer.Title of program can be single line or multiline.

Single line comment wriiten by //……………….


Multi line comment written by using /* ……….*/

Package /statement:
This statement is used by programmer whenever they want to create a package. Package is collection of
classes and interface. Statement is written as
package Packagename;

Import Statement:
This statement is used to include java packages or user defined packages in to your program. For example
to include java input output package user can use following statement.

import java.io.*;

Interface Statement:
Interface statement is added to program when we want to achieve multiple inheritance. Statement is
written as

6
Java Programming Notes
CO4I
interface interfacename;

Class Definition:
As java is pure object oriented so each and every code will comes under a class .which consist of main
method. The syntax of main method is as follows:

Public static void main (String args[])

Meaning of this line is as follows:

public: main() method access specifier is public so it is accessible by all.


static: main() method is not related with any of the object of class.
void: main() method does not returns anything
String args[]: All command line arguments will be stored in args[] array.

6. Java and Internet


The evolution of internet helped to make a java as leading programming language .Over the network
there are two categories of objects that are transmitted between the server and client computers:

(1) Active objects


A self executing program is dynamic data. This data is called as active agent on the client
computer.
(2) Passive objects
These objects are in the form of information and active programs. A downloaded program until is
executed is called as passive data.

These dynamic networked programs create problems in terms of security and portability. Java
effectively handles these problems. Introducing a new form of program known as Applet does
this.

Java Applets

 Java communicates with Web page through a special tag called <APPLET>. An applet as a
special program that is transmitted over the network or Internet. It automatically get executed by
Java – compatible Web Browser.
 An applet is said to an “Intelligent Program” because the applet tends to react to the user input
and changes its status dynamically.
 Java takes care of major issues related with security and portability of any program code over
Internet.

7
Java Programming Notes
CO4I

Security and Portability

 Security becomes an important issue for a language which is used for programming on Internet.
Java system not only verifies all memory access but also ensure that no viruses are communicated
with an applet and also ensure that programs cannot gain access to memory locations without
proper authorization.
 Java supports the feature portability. Java programs can be easily moved from one computer
system to another ,anywhere and any time. This is the reason why Java has become a popular
language for programming on Internet which interconnects different kind of systems worldwide.
Java ensures portability in two ways.
1. Java compiler generates byte-code instructions that can be implemented on any machine.
2. The size of the primitive data types is machine independent.

7. Constants
In java constants, refer to fixed values that do not change during the execution of a program. Java
supports several types of constants listed below and shown below:

Integer constants
An integer constants means the sequence of digits. There are three types of integers,
1. Decimal Integer: Decimal integers consists of a set of digits,0 through 9,preceded by an
optional minus sign.
Ex:325,-978,45673

Embedded spaces, commas, and non-digits characters are not allowed between digits.
Ex:15 78,$657-,#47 is illegal number.

2. Octal Integer: An octal integer constant consists of any combination of digits from the set 0
through 7, with al leading 0.
Ex:027, 0, 0231, 0341

8
Java Programming Notes
CO4I
3. Hexadecimal Integer: A sequence of digits preceded by 0x or ox is considered a hexadecimal
integer(hex integer).They may also include alphabet A through F or a through f.A letter A
through F represents the number 1 through 15. Ex:0X4 ,0X15, 0xabed.
Real Constant:
Integers numbers are insufficient to represents quantities that vary continuously, such as distance
Heights, temperature, prices, and so on. Numbers having fractional parts like 17.548 represents
these quantities. Such numbers are called real(or floating point) constants.
Examples: 1.9783, 0 0047
The real number constant can comprise of four parts:
 A whole number.
 A decimal point.
 A fractional part.
 An exponent part.
These numbers are shown in decimal notation, having a whole number followed by a decimal
point and the fractional part, which is an integer. For example: 0.035, 111.98
A real number may also be expressed as in exponential (or scientific) notation. For example, the
value 215.65 may be written as 2.1565e2 in exponential notation. E2 means multiply by 10^2.
The general form is: mantissa e exponent.
Example: 0.65e4, 15e-5, 2.6e+6 56.E4

Character constant:

A single character constant or character constant contains a single character enclosed within a pair of
single quote marks. Examples are ‘7’, ‘A’,’*’,’’. The character constant ‘7’ is not the same as the number
7. The last constant is blank space.

String constant:

A string constant is a sequence of character enclosed between double quotes in which the character may
be alphabets, digits, special characters and blank spaces.

Examples: “WELCOME”,”@june”,”abhishek”,”!NIDHI!”

Backslash:

The backslash character constant are used with output statements for getting more effects like tab, new
line, single quote etc. Java support some special backslash character constants. A list of such backslash
character constant is given following table. Each one of them represents one character, although they
consist of two character. These characters combinations are known as escape sequences.

Table for Backslash Character Constants

Constant Meaning
‘\b’ Back space
‘\f’ Form feed
‘\n’ New line
‘\r’ Carriage return

9
Java Programming Notes
CO4I
‘\t’ Horizontal tab
‘\” Single quote
‘\ “” Double quote
‘\ \’ Backslash

8. Symbolic Constants
Symbolic constants refer to the variable name having value which cannot be modified. For example
pi=3.14 now the pi can be used instead of 3.14.For the convention symbolic names are written in
CAPITALS to distinguish from other variable names. After declaration of symbolic constants, they
should not be reassigned any other value. Symbolic constants cannot be declared inside a method. They
should be used only as class data members in the beginning of the class.

Syntax:
Final datatype symbolic_name=value;
Example
class Circle
{
final double PI=3.14f; //Symbolic constant
int radius;
void accept(int r)
{
radius=r;
}
void display()
{
double area=PI*radius*radius;
System.out.println("Radius is :"+radius);
System.out.println("Area of circle is :"+area);
}
public static void main(String args[])
{
Circle c=new Circle();
c.accept(5);
c.display();
}
}
Output:
Radius is : 5
Area of circle is :78.50000262260437
9.Variable its rules and naming conventions

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

10
Java Programming Notes
CO4I

A variable name can be chosen by the programmer in a meaningful way so as to reflect data stored in it.
For example: radius, squ, total_height, classStreangth. A variable names may consist of alphabates, digits,
the underscore (-) and dollar ($) characters.

Following are the rules for naming variables:

 They must not begin with a digit


 Upper case and lower case must be distinct this means that the variable Abc is not the same as
abc or ABC.
 (White space is not allowed.
 It should not be a keyword.
 Variable names can be of any length. Variable must be declared before it is used in the program.
Variables must be declared to the compiler.

Declaration does following three things:


 It tells variable name to the compiler
 It specifies the data type of the data hold by variable.
 The place of declaration in the program decided the scope of the variable.

Naming conventions for variables in java:


 Name all public methods ands instance variables start with lower case letter.(eg. accept(),)
 When more than one word are used in name, the second and subsequent words should start with
uppercase letter (eg. paresInt())
 All private and local variables use only lower case (eg. int age)
 All classes and interface start with uppercase letter.( eg. class Person)
 All variable represent constants values use all uppercase letter(eg. PI=3.14)

10.Dynamic Initialization
Java allows its programmers to initialize a variable at run time also. Initializing a variable at run time is
called dynamic initialization.

class DynamicInit
{
public static void main(String args[])
{
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.print("C=" + c);
}
}
Output:

11
Java Programming Notes
CO4I
C=5.0
11.Date types and its storage
In java every variable has a data type. Datatypes specifies the size and types of data that can be stored.

Data types

Primitive Non-Primitive

Numeric Non-Numeric Array Class

Integer Non-Integer boolean

int long double char String

byte short float

The eight primitive data types supported by the java programming language are:

1. byte: The byte data type is an 8-bit signed two’s complement integer. It has a maximum value of
-128 and a maximum value of 127(inclusive).
2. short: The short data type is 16-bit singed two’s complement integer. It has a maximum value of
-32,768 and a maximum value of 32,767(inclusive).
3. int: The int data type is 32-bit singed two’s complement integer. It has a maximum value of -
2,147,483,648 and a maximum value of 2,147,483,647(inclusive).
4. long: The long data type is 64-bit singed two’s complement integer. It has a maximum value of -
9,223,372,036,854,775,808 anda maximum value of 9,223,372,036,854,775,808
(inclusive).Use this data type when you need a range of values wider than those provided
by int.
5. float: The float data type is a single-precision 32-byte IEEE 754 Floating point.
6. double: The float data type is a double-precision 64-byte IEEE 754 Floating point.
7. boolean: The Boolean data type has only two possible values. true and false.Use this data type
for simple flags that track true/false conditions.
8. char: The char data type is single 16-bit Unicode character. It has a maximum value of ‘\
u0000’(or 0) and a maximum value of ‘\uffff’(or 65,535 inclusive).

Following table is showing data types with their size in bytes

Sr. no. Data Type Size in bytes


1 Byte 1
2 Short 2
3 Int 4
4 Long 8
5 Float 4

12
Java Programming Notes
CO4I
6 Double 8
7 char 2

12. Scope of Variables


Scope of the variables is nothing but life of a variable. It depends upon the where in the program that
variable are declared. The area of the program where the variable is accessible is called its scope.

Java variables are actually classified into three categories and their scope is defined according their
category. The types of Java Variables are as follows:

(i) Instance Variables (Non-Static Fields)

Instances are declared inside the class. Instance variables are created when the objects are instantiated
(created) and those are associated with the objects .They take different values for each object.

(ii) Class variables(Static Fields)

Class variables are declared inside the class and global to the class and belong to the entire set of
object and that class creates. Only one memory location is created for each class variable.

(iii) Local variables

Local variables declared and used inside the methods. They are not available outside of the method
definition. Local variables can be declared inside the program blocks that are defined between the
opening ({) and closing braces (}). These variables are visible to the program only. When the
program control leaves block, all the variables in the block will cease to exit.

Characteristic Local variable Instance variable Class variable


Where In a method, constructor, In a class, but outside a method. In a class, but outside a
declared or block. method. Must be declared
static.
Use Local variables hold Instance variables hold values Class variables are mostly
values used in that must be referenced by more used for constants,
computations in a than one method variables that never
method. change from their initial
value.
Lifetime Created when method or Created when instance of class Created when the
constructor is entered. is created with new. program starts.
Destroyed when there are no Destroyed when the
Destroyed on exit.
more references to enclosing program stops.
object (made available for
garbage collection).
Scope/ Local variables (including Instance (field) variables can Same as instance variable,
Visibility formal parameters) are been seen by all methods in the but are often
visible only in the class. declared public to make

13
Java Programming Notes
CO4I

method, constructor, or constants available to


block in which they are users of the class.
declared.

Example:

public class Sample


{

String name; //instance variable


int age;
static int count; //class variable
void accept( String n,int a) // n,a are local varaibles
{
name=n;
age=a;

}
void show()
{
count++;
System.out.println("count="+count);
}
void display()
{
System.out.println("Name="+name);
System.out.println("Age="+age);
}
public static void main(String args[])
{
Sample s1=new Sample();
Sample s2=new Sample();
s1.accept("abc",10);
s1.display();
s1.show();
s2.accept("xyz",20);
s2.display();
s2.show();
}

}
Output:
Name=abc
Age=10
count=1
Name=xyz
Age=20
count=2

14
Java Programming Notes
CO4I

13.Type Conversion

In some cases we might want to assign value of one type to variable of another type. If both the source
and destination types are compatible, then java performs the conversion implicitly(automatically).
Examples of compatible types are int, long, short and byte. Also float and double are compatible with
each other while char and boolean are not compatible with each other.

Implicit conversion (Automatic conversion)

Implicit conversion is also called as coercion. Java automatically converts from one type to another only
when the following two conditions are satisfied:

1) Both types are compatible with each other.


2) The size of destination type is more than the source type.

When the above two conditions are satisfied, java performs an implicit conversion. This is also known as
“Widening Conversion”.

int x=60;
long n= x;

here int can be auto converted to long since the size of long is 64, where as size of int is 32. Similarly a
byte can be auto converted or implicitly converted to int.int can also be implicitly converted to float and
double. 19 specific conversions on primitive types are called the widening primitive conversions:

 byte to short, int, long, float, or double


 short to int, long, float, or double
 char to int, long, float, or double
 int to long, float, or double
 long to float or double
 float to double

In widening primitive conversion there is no losing of information about the magnitude of a numeric
value.

Explicit Conversion ( Type Casting)

Explicit conversion also called as casting. Type casting occurs when there is a need to store a value of one
data type into a variable of another type. Casting is necessary when a method returns a type different than
one require. Type casting refers to changing an entity of one datat ype into another. This is important for
the type conversion in developing any application. If you will store a int value into a byte variable
directly, this will be illegal operation. For storing your calculated int value in a byte variable you will
have to change the type of resultant data which has to be stored .It is possible to cast a value to be stored
by proceeding it with the type name in paranthesis.

15
Java Programming Notes
CO4I

The syntax is
DataType variable1=(DataType)variable2;
Examples are:

int x=60;
byte n=(byte)x;

This is also known as “narrowing conversion” ,which may result in loss of information.22
specific conversions on primitive types are called the narrowing primitive conversions:

 short to byte or char

 char to byte or short

 int to byte, short, or char

 long to byte, short, char, or int

 float to byte, short, char, int, or long

 double to byte, short, char, int, long, or float

14. Standard Default Values:


Initialization is the process of providing value to a variable at declaration time. A variable is initialized
once in its life time. Any attempt of setting a variable's value after its declaration is called assignment. To
use a local variable you have to either initialize or assign it before the variable is first used. But for class
members, the compulsion is not so strict. If you don't initialize them then compiler takes care of the
initialization process and set class members to default values as shown in following table:

Type of Variable Default value

Byte Zero(byte 0)

Short Zero(short 0)

Int Zero:0

Long Zero:0L

Float 0.0f

Double 0.0d

Char Null character

16
Java Programming Notes
CO4I
Boolean False

Reference Null

15. Operators in java


Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following
groups:
 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators

The 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: Assume integer variable A holds 10 and variable B holds 20, then:

Operator Description Example

+ Addition - Adds values on either side of the operator A + B will give 30

- Subtraction - Subtracts right hand operand from left hand operand A - B will give -10

* Multiplication - Multiplies values on either side of the operator A * B will give 200

/ Division - Divides left hand operand by right hand operand B / A will give 2

Modulus - Divides left hand operand by right hand operand and returns
% B % A will give 0
remainder

++ Increment - Increases the value of operand by 1 B++ gives 21

-- Decrement - Decreases the value of operand by 1 B-- gives 19

The following simple example program demonstrates the arithmetic operators. Write following Java program in
Test.java file and compile and run this program:

public class Test


{
public static void main(String args[])
{
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );

17
Java Programming Notes
CO4I

System.out.println("a++ = " + (a++) );


System.out.println("b-- = " + (a--) );
// Check the difference in d++ and ++d
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
}

This would produce the following result:

a + b = 30
a - b = -10
a * b = 200
b/a=2
b%a=0
c%a=5
a++ = 10
b-- = 11
d++ = 25
++d = 27

The Relational Operators:


There are following relational operators supported by Java language. Assume variable A holds 10 and
variable B holds 20, then:

Operato
Description Example
r
Checks if the values of two operands are equal or not, if yes then (A == B) is
==
condition becomes true. not true.
Checks if the values of two operands are equal or not, if values are not (A != B) is
!=
equal then condition becomes true. true.
Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value of right (A < B) is
<
operand, if yes then condition becomes true. true.
Checks if the value of left operand is greater than or equal to the value (A >= B) is
>=
of right operand, if yes then condition becomes true. not true.
Checks if the value of left operand is less than or equal to the value of (A <= B) is
<=
right operand, if yes then condition becomes true. true.

18
Java Programming Notes
CO4I

Example:
public class Sample
{

public static void main(String args[])


{
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a < b = " + (a < b) );
System.out.println("c > b = " + (c > b) );
System.out.println("c <= d = " + (c <= d) );
System.out.println("c >= d = " + (c >= d) );
System.out.println("c == d = " + (c == d) );

}
}
Output:

a < b = true
c > b = true
c <= d = true
c >= d = true
c == d = true

The Bitwise Operators:


Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and
byte. Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now
in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

The following table lists the bitwise operators: Assume integer variable A holds 60 and variable B holds
13 then:
Operato
Description Example
r
Binary AND Operator copies a bit to the result if (A & B) will give 12 which is 0000
&
it exists in both operands. 1100
| Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is 0011

19
Java Programming Notes
CO4I

either operand. 1101


Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49 which is 0011
^
one operand but not both. 0001
(~A ) will give -61 which is 1100
Binary Ones Complement Operator is unary and
~ 0011 in 2's complement form due to a
has the effect of 'flipping' bits.
signed binary number.
Binary Left Shift Operator. The left operands
A << 2 will give 240 which is 1111
<< value is moved left by the number of bits
0000
specified by the right operand.
Binary Right Shift Operator. The left operands
>> value is moved right by the number of bits A >> 2 will give 15 which is 1111
specified by the right operand.
Shift right zero fill operator. The left operands
value is moved right by the number of bits A >>>2 will give 15 which is 0000
>>>
specified by the right operand and shifted values 1111
are filled up with zeros.

Example:

public class Sample


{

public static void main(String args[])


{
int a = 60;
int b = 20;

System.out.println("a & b = " + (a & b) );


System.out.println("a | b = " + (a | b) );
System.out.println("a << 2 = " + (a << 2) );
System.out.println("a >> 2 = " + (a >> 2) );
System.out.println("a >>> 2 = " + (a >>> 2) );

}
}
Output:

a & b = 20
a | b = 60
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15

20
Java Programming Notes
CO4I
The Logical Operators:
The following table lists the logical operators: Assume Boolean variables A holds true and variable B
holds false, then:
Operato
Description Example
r
Called Logical AND operator. If both the operands are non-zero, then
&& (A && B) is false.
the condition becomes true.
Called Logical OR Operator. If any of the two operands are non-zero,
|| (A || B) is true.
then the condition becomes true.
Called Logical NOT Operator. Use to reverses the logical state of its
! operand. If a condition is true then Logical NOT operator will make !(A && B) is true.
false.

Example:

public class Sample


{

public static void main(String args[])


{
int a = 60;
int b = 20;
int c = 25;
int d = 25;

System.out.println("(a > b && c == d) = " + (a > b && c == d) );


System.out.println("(a < b && c == d) = " + (a < b && c == d));
System.out.println("(a < b || c == d) " + (a < b || c == d) );
System.out.println(" !(a < b) = " + !(a < b ) );

}
}
Output:

(a > b && c == d) = true


(a < b && c == d) = false
(a < b || c == d) true
!(a < b) = true

The Assignment Operators:


There are following assignment operators supported by Java language:

Operato
Description Example
r
= Simple assignment operator, Assigns values from right C = A + B will assign value of A +

21
Java Programming Notes
CO4I

side operands to left side operand B into C


Add AND assignment operator, It adds right operand to
+= C += A is equivalent to C = C + A
the left operand and assign the result to left operand
Subtract AND assignment operator, It subtracts right
-= operand from the left operand and assign the result to C -= A is equivalent to C = C - A
left operand
Multiply AND assignment operator, It multiplies right
*= operand with the left operand and assign the result to C *= A is equivalent to C = C * A
left operand
Divide AND assignment operator, It divides left
/= operand with the right operand and assign the result to C /= A is equivalent to C = C / A
left operand
Modulus AND assignment operator, It takes modulus C %= A is equivalent to C = C %
%=
using two operands and assign the result to left operand A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Misc Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands and is
used to evaluate Boolean expressions. The goal of the operator is to decide which value should be
assigned to the variable. The operator is written as:

variable x = (expression) ? value if true : value if false

Following is the example:

public class Test


{
public static void main(String args[])
{
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );

22
Java Programming Notes
CO4I
}
}
This would produce the following result:

Value of b is : 30
Value of b is : 20

instanceof Operator:
This operator is used only for object reference variables. The operator checks whether the object is of a
particular type(class type or interface type). instanceof operator is wriiten as:

( Object reference variable ) instanceof (class/interface type)

If the object on the left side of the operator is an object of right side, then the result will be true.
Following is the example:

public class Test


{
public static void main(String args[])
{
String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
System.out.println( result );
}
}

This would produce the following result:


true

Dot operator:
Dot operator is used to access class members i.e. methods and data.

class Person
{
String name;
int age;
void display()
{
System.out.println(“Name=”+name);
System.out.println(“Age=”+age);
}
public static void main(String args[])
{
Person p=new Person()
p.name=”abc”;
p.age=”10”;
p.display();

23
Java Programming Notes
CO4I
}
}
This would produce the following result:

Name=abc
Age=10

16.Operator Precedence in Java


Java has well-defined rules for specifying the order in which the operators in an expression are evaluated
when the expression has several operators. For example, multiplication and division have a higher
precedence than addition and subtraction. Precedence rules can be overridden by explicit parentheses.

Precedence Order

When two operators share an operand the operator with the higher precedence goes first. For example, 1 +
2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher
precedence than addition.

Associativity

When two operators with the same precedence the expression is evaluated according to its associativity.
For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value 17,
since the = operator has right-to-left associativity (and an assignment statement evaluates to the value on
the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-
right associativity.

Following table is showing the associativity and precedence order of java operators.

Operators Associativity Precedence Rank


(),[] Left to right 1
-,++,--,! Right to left 2
*,/,% Left to right 3
+,- Left to right 4
<<,>> Left to right 5
<,<=,>,>= Left to right 6

==,!= Left to right 7


& Left to right 8
^ Left to right 9
| Left to right 10
&& Left to right 11
|| Left to right 12
?: Right to left 13
= Right to left 14

17. Evaluation of Expressions:


24
Java Programming Notes
CO4I

More complex expressions can be built up by using operators to combine simpler expressions. Operators
include + for adding two numbers, > for comparing two values, and so on. When several operators appear
in an expression, there is a question of precedence, which determines how the operators are grouped for
evaluation. For example, in the expression "A + B * C", B*C is computed first and then the result is
added to A. We say that multiplication (*) has higher precedence than addition (+). If the default
precedence is not what you want, you can use parentheses to explicitly specify the grouping you want.
For example, you could use "(A + B) * C" if you want to add A to B first and then multiply the result by
C.

In general, the type of the expression on the right-hand side of an assignment statement must be the same
as the type of the variable on the left-hand side. However, in some cases, the computer will automatically
convert the value computed by the expression to match the type of the variable. Consider the list of
numeric types: byte, short, int, long, float, double. A value of a type that occurs earlier in this list can be
converted automatically to a value that occurs later. For example:

int A;
double X;
short B;
A = 17;
X = A; // OK; A is converted to a double
B = A; // illegal; no automatic conversion from int to short

In some cases, you might want to force a conversion that wouldn't be done automatically. For this, you
can use what is called a type cast. A type cast is indicated by putting a type name, in parentheses, in front
of the value you want to convert. For example,

int A;
short B;
A = 17;
B = (short)A; // OK; A is explicitly type cast to a value of type short

18. Mathematical Functions


The java.lang.Math class contains methods for performing basic numeric operations such as the
elementary exponential, logarithm, square root, and trigonometric functions. Following table is showing
some of the methods of Math class.

S.N Description
Method & Description
.
1 static double abs(datatype a) This method returns the absolute value of a mentioned data.
2 static double ceil(double a) This method returns the smallest (closest to negative infinity)

25
Java Programming Notes
CO4I
double value that is greater than or equal to the argument and
is equal to a mathematical integer.
This method returns Euler's number e raised to the power of
3 static double exp(double a)
a double value
This method returns the largest (closest to positive infinity)
4 static double floor(double a) double value that is less than or equal to the argument and is
equal to a mathematical integer
static double log(double a) This method returns the natural logarithm (base e) of a
5
double value.
static double max(double a, This method returns the greater of two double values
6
double b)
7 static float max(float a, float b) This method returns the greater of two float values
static int max(int a, int b) This method returns the greater of two int values.
8
static long max(long a, long b) This method returns the greater of two long values.
9
static double min(double a, This method returns the smaller of two double values.
10 double b)

static float min(float a, float b) This method returns the smaller of two float values.
11
static int min(int a, int b) This method returns the smaller of two int values.
12
static long min(long a, long b) This method returns the smaller of two long values.
13
static double pow(double a, This method returns the value of the first argument raised to
14 double b) the power of the second argument.

static long round(double/float a) This method returns the closest long to the argument.
15
This method returns the correctly rounded positive square
16 static double sqrt(double a) .
root of a double value
Example:

public class Sample


{
public static void main(String args[])
{
double x = 10;
double y = 16;
double z = 1.34;
double s= -2.03;
System.out.println("Ceil =" + Math.ceil(z));
System.out.println("Floor =" + Math.floor(z));
System.out.println("Ceil =" + Math.ceil(s));
System.out.println("Floor =" + Math.floor(s));
System.out.println("Power =" + Math.pow(x,2));
System.out.println("Sqrt =" + Math.sqrt(y));
System.out.println("Minimum=" + Math.min(x, y));

26
Java Programming Notes
CO4I
System.out.println("Maximum=" + Math.max(x, y));
}
}
This would produce the following result:

Ceil =2.0
Floor =1.0
Ceil =-2.0
Floor =-3.0
Power =100.0
Sqrt =4.0
Minimum=10.0
Maximum=16.0

19. Java Statements


STATEMENT DESCRIPTION
Empty Statement These do nothing and are used during program development as a place holder.

Any statement may begin with a label. Such labels may noy be keywords, already
Labeled
declared as local variables or previously used labels in this module. Labels in java
Statement
are used as arguments of jump statements, which are later described in this list.

Most statements are expression statements.java has seven types of expression


Expression
statements: assignment.pre-increment, pre-decrement, post-increment, post-
Statement
decrement, method call and allocation expression.
Selection These select one of several control flows. There are three types of selection
Statement statements in java: if,if-else and switch .

These specify how and when looping will take place. There are three types of
Iteration Statement
iteration statements: while do and for.

Jump statements pass control to the beginning or end of the current block,or at a
labelled statement.such labels must be in the same block,and continue labels must
Jump Statement
be in the iteration statement.the four types of jump statements are:
break,continue,return and throw.
Synchronization
These are used for handling issues with multi-threading.
Statement

Gaurding Guarding statements are used for safe handling of code that may cause exceptions
Statement (such as division by zero) these statements use keywords try, catch and finally.

27
Java Programming Notes
CO4I

JAVA STATEMENTS

EXPRESSION LABELLED SYNCHRONIZATIO GAURDING


STATEMENT STATEMENT N STATEMENT STATEMEN
T

CONTROL
STATEMENT

ITERATION STATEMENT

SELECTION STATEMENT JUMP STATEMENT

IF IF-ELSE SWITC BREAK CONTINUE RETUR


H N

WHILE FOR

DO

20. Java Environment

28
Java Programming Notes
CO4I
Java environment includes a number of development tools, classes and methods. The development tools
are part 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 Java Development Kit comes with a collection of tools that are used for developing and running java
programs. They include:
1. appletviewer (for viewing Java applets):
A pre-created applet can be viewed using applet viewer. Enables us to run Java applets (without
actually using a Java-compatible browser). it has syntax:
c:\ appletviewer<URL of the .html file>
2. javac (java compiler):
A java program can be created by using any text editor and save file with extension .java. Java
compiler, which translates Java sourcecode to bytecode files that the interpreter can understand.
Or it converts the "java" file to a "class" file. it has following syntax:
c:\>javac filename.java
3. java (java interpreter):
The Java interpreter is used to execute a compiled java application (.class). Java interpreter,
which runs applets and applications by reading and interpreting bytecode files. The bytecode
created as a result of compilation is interpreted.
The syntax is (file extension is not needed);
c:\> java filename
4. javap (Java disassembler:
Java disassembler, which enables us to convert bytecode files into a program, description.
5. javah (for C header files):
Produces header files for uses with native methods.
6. javadoc (for creating HTML documents):
Creates HTML-format documentation from Java source code files.
7. jdb (java debugger):
Java debugger, which helps us to find errors in our programs.

These tools are applied to build and run application programs is illustrated in fig. The steps are listed
below
1. To create a Java program, we need to create a source code file using a text editor.

29
Java Programming Notes
CO4I
2. The source code is then compiled using the Java compiler Javac.
3. Then it is executed using the java interpreter java.
4. The Java debugger jdb is used to find errors, if any, in the source code.
5. A compiled Java program can be converted into a source code with the help of Java disassembler
javap.

Process of building and running Java application programs

Application Programming Interface (API)/Java standard Library(JSL)

Java API provides a large number of classes which are grouped into different packages according to
functionality. Following table shows the built in packages of java.

Sr. no. Package name Contents


1 java.lang Language support classes. They are used by java compiler itself and
thus automatically imported. They include classes for primitive
types, strings, math, tread and exceptions.
2 java.io Input/output support classes. They provide support for input and
output.
3 java.util Language utility classes such as Vector, Date ,hash tables, random
numbers etc.
4 java.awt Set of classes for implementing graphical user interface. They include
classes for windows, buttons, lists, menus and so on.

30
Java Programming Notes
CO4I
5 java.applet Classes for creating and implementing applets.
6 java.net Classes for networking. They include classes for communication with
local computers as well as with internet servers.

21. Decision making and Control Flow statements:


For decision making java uses if and switch statement which are explained as follows:

IF STATEMENTS:-

The if statement is a powerful decision makeing statement and is useful to control the flow of execution
of statement the if is the simplest one in decision statement. it is basically a two way decision statement
and is used in conjunction with an expression.

java provides different if statements are as follows


1) simple if statement.
2) if else statement.
3) nested if.
4) else if ladder.

1) Simple if statement (i.e. If statement)


A) Java supports “If statement” whereas, if is a “Keyword” .
B) Working:-
i) if the condition is true then, it executes statement, or statements
Which are present under if statement.
ii) Otherwise (If the condition is false) it goes out of loop or control transfer out of loop.

Syntax:-
if (condition)
{
//Statements ;
}

Example:-

class Abc
{
public static void main (String args[ ] )
{
int a=3, b=2 ;
if (a>b)
{
System.out.println (“a is greater”);
}
}

31
Java Programming Notes
CO4I
Flowchart :-

2) If else statement

To overcome from the drawback of if statement java supports If Else statement also.

Syntax:

if (condition)
{
//Statements 1;
}
else
{
//Statement 2 ;
}

a) If the condition is true then control transfer goes to the statement1 and it executes statement 1.
b) Otherwise (if condition is false) control transfer to the else part and else part executes statement 2.

Example:
class Abc
{
public static void main (String args[ ] )
{
int a=3, b=2 ;
if (a>b)
{
System.out.println (“a is greater”);
}
else
{
System.out.println(“b is greater”);
}
}
}

32
Java Programming Notes
CO4I
Flowchart:

3) Nested if statement

Nested if statement means “one if statement present in another statement”


Syntax

if (condition 1)
{
if (condition 2)
{
//Statement block 1;
}
else
{
//Statement block 2 ;
}
}

If condition 1 is true then control transfer to the inner if statement here, it again checks for condition 2 whether it is
true or false. If condition 2 is true is true then control transfer to the inner part of inner if statement. Otherwise (if
condition 2 is false) control transfer to out of loop of inner if statement. Otherwise (if condition 1 is false) control
transferred out of loop.

4) Else if ladder

When more than one condition arrived then we can use “if else if ladder” is used. Java supports if else if ladder on
the occasion of multiple condition.
Syntax:
if (condition 1)
{
//Statement 1 ;
}
else if (condition 2)
{

33
Java Programming Notes
CO4I
//Statement 2 ;
}
else
{
//Statement n ;
}

Working principle:-

1) In if-else-if ladder 1st of all if checks condition 1,if condition 1 is true then control transfer to the statement 1 and
it executes statement 1.
2) Otherwise (condition 1 id false) then, control transfer to the else part if part.
3) Now, It checks for condition 2 if it is true ctrl transfer to the statement 2 and executes statement 2.
4) Otherwise if(condition 2 is false) then, ctrl, transfer to the next else part.
5) Number of else if condition statements are depends on number of condition used.
6) If none of the condition is true then,ctrl directly transfer to the else part(by default)

Example
class Abc
{
public static void main (String args [])
{
int no=3;
if(no==1)
{
System.out.println(“one”);
}
else if (no==2)
{
System.out.println(“Two”);
}
else if(no==3)
{
System.out.println(“three”);
}
else
{
System.out.println(“Wrong choice”);
}
}
}

2) THE SWITCH STATEMENT

Java has a built-in multi way decision statement known as switch. It can be used instead of if, or nested
if...else. The complexity of the program increases as the number of alternatives increases when it is
designed with if...else for the multi path selection of decisions. This can be overcome with the switch
statement, as switch statement tests the value of a given variable (or expression) against a list of case

34
Java Programming Notes
CO4I
values and when a match is found, a block of statements associated with that case is executed. When the
switch is executed, the value of the expression is successively compared against the values value-1, value-
2. If a case is found whose value matches with the value of expression, then the block of statements that
follow the case are executed. The break statement at the end of each block signal the end of a particular
case and causes an exit from the switch statements & transferring the control to the statement following
switch.

Syntax:

The general form of switch statement is shown below:

switch(expression)
{
case value1:
block 1;
break;
case value2:
block 2;
break;
case value3:
block 3;
break;
.. .....
.......
default:
Default block;
break;
}

Example:

class test
{
public static void main(String args[])
{
int a,b,c;
a=10;
b=20;
char ch;
System.out.println("Enter your choice.a:add,b:sub,c:mul,d:div");
try
{
ch=(char) System.in.read();
switch(ch)
{
case 'a':
c=a+b;
System.out.println("Sum is"+c);

35
Java Programming Notes
CO4I
Break;
case 'b':
c=a-b;
System.out.println("Sub is"+c);
break;
case 'c':
c=a*b;
System.out.println("Mul is"+c);
break;
case 'd':
c=a/b;
System.out.println("Div is"+c);
break;
default:
System.out.println("Invalid choice");
}
catch(Exception e)
{}
}
}

Output:
Enter your choice.a:add,b:sub,c:mul,d:div
a
Sum is 30

It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case
constants of the inner and outer switch contain common values, no conflicts will arise.

public class NestedSwitchDemo


{
public static void main(String args[])
{
int a = 100;
int b = 200;
switch(a)
{
case 100:
System.out.println("This is part of outer switch");
switch(b)
{
case 200:
System.out.println("This is part of inner switch" );
}
}
System.out.println("Exact value of a is : "+ a );
System.out.println("Exact value of b is : "+ b );

36
Java Programming Notes
CO4I
}

When the above code is compiled and executed, it produces the following result:

This is part of outer switch


This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

22. Loops in java


Java supports for loop, while loop and do while loop. Explanations of these loops are as follows:

The for Loop

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it
as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied.
The general form of the for statement can be expressed as follows:

for (initialization; termination condition; increment/decrement)


{
statement(s)
}

When using this version of the for statement, keep in mind that:

 The initialization expression initializes the loop; it's executed once, as the loop begins.
 When the termination expression evaluates to false, the loop terminates.
 The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.

Example:
class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
System.out.print("Count is: " + i +” “);
}
}
}

Output:

1 2 3 4 5 6 7 8 9 10

The For each loop

37
Java Programming Notes
CO4I
The basic for loop was extended in Java 5 to make iteration over arrays and other. This
newer for statement is called the enhanced for or for-each .
The for-each and equivalent for statements have these forms. The two basic equivalent forms are given,
depending one whether it is an array or an Iterable that is being traversed. In both cases an extra variable
is required, an index for the array and an iterator for the collection.
Syntax:

for (type var : arr)


{
body-of-loop
}
Here var represent the element of array. During first iteration var will contain first element of array,
during second iteration it will hold second element of array and so on. The loop will be executed for all
elements of array. If array elements are finished loop will terminate automatically.

Example:

For loop Equivalent For each


public class Person public class Person
{ {
public static void main(String [] args) public static void main(String [] args)
{ {
double[] ar = {1.2, 3.0, 0.8}; double[] ar = {1.2, 3.0, 0.8};
int sum = 0; int sum = 0;
for (int i=0;i<ar.length;i++) for (double d : ar)
{ {
System.out.println("elements are"+ ar[i]); System.out.println("Element :"+
} d);
} }
} }
}

Output of both will remain same i.e.


Element: 1.2
Element : 3.0
Element : 0.8

The While Loop

The while statement continually executes a block of statements while a particular condition is true. Its
syntax can be expressed as:

while (expression)
{
statement(s)
}

38
Java Programming Notes
CO4I
The while statement evaluates expression, which must return a boolean value. If the expression evaluates
to true, the while statement executes the statement(s) in the while block. The while statement continues
testing the expression and executing its block until the expression evaluates to false.

Example:

class WhileDemo
{
public static void main(String[] args)
{
int count = 1;
while (count < 11)
{
System.out.print("Count is: " + count +” “);
count++;
}
}
}

Output:

1 2 3 4 5 6 7 8 9 10

Do while Loop

The Java programming language also provides a do-while statement, which can be expressed as follows:

do
{
statement(s)
} while (expression);

The difference between do-while and while is that do-while evaluates its expression at the bottom of the
loop instead of the top. Therefore, the statements within the do block are always executed at least once, as
shown in the following DoWhileDemo program:

class DoWhileDemo
{
public static void main(String[] args)
{
int count = 1;
do
{
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}

39
Java Programming Notes
CO4I
}
Output:
123456789

Nested Loop:
The placing of one loop inside the body of another loop is called nesting. When you "nest" two loops, the
outer loop takes control of the number of complete repetitions of the inner loop. While all types of loops
may be nested, the most commonly nested loops are for loops. Here we will see how nested loops are
used by taking the example of a pattern problem.
public class testFor
{
public static void main(String [] args)
{
for (int i=1; i<=9; i++)
{
for (int j=1; j<=i; j++)
{
System.out.print(j);
}
System.out.println();
}
}
}

Output:
1
12
123
1234
12345
123456
1234567
12345678
123456789

Branching Statements (Jumps in Loops)


Java supports three branching statements. These are break,continue and return statements.

Break statement:
 Early exit from a loop can done by using the break statement.
 The break statement which is used in switch construct, can also be used within while,do or for
loops.
 When the break statement is encountered inside a loop, the loop is immediately exited or
terminated and the program continues with the statement immediately following the loop.
 In while and do loops, the break statement will terminate the control to go directly to next
statement after the loop.

40
Java Programming Notes
CO4I
 In for loops, the break statement will terminate the control to go directly to next statement after
the loop.

The break statement has two forms: labeled and unlabeled. You can also use an unlabeled break to
terminate a for, while, or do-while loop, as shown in the following Break Demo program:

Example1:

public class Sample


{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
if(i==4)
break;
System.out.println("i=" + i);
}
}
}
Output:
i=1
i=2
i=3
Example2: check a number is prime or not
public class Sample
{

public static void main(String args[])


{
int num=7;
int flag=0;
for(int i=2;i< num-1;i++)
{
if(num% i==0)
{
flag=1;
break;
}
else
{
flag=0;
}
}
if(flag==0)
System.out.println(num +"is prime");

41
Java Programming Notes
CO4I
else
System.out.println(num +" is not prime");
}

}
Output:
7 is prime

Example3: Print prime numbers from 1 to 20


public class Sample
{

public static void main(String args[])


{

int flag=0;
for(int num=1;num<=20;num++)
{
for(int i=2;i< num-1;i++)
{
if(num % i==0)
{
flag=1;
break;
}
else
{
flag=0;
}
}
if(flag==0)
System.out.println(num +" is prime");
}
}
}
Output:
1 is prime
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
Continue statement:
 The continue statement causes the loop to be continued with the next iteration after
skipping any statements in between.

42
Java Programming Notes
CO4I
 Continue statement is used when it is necessary to skip a part of the body of the loop
under certain conditions.
 The continue statement tells the compiler "skip or omit the statements mentioned and
continue with the next iteration."
 In while and do loops, using the continue statement, the control to go directly to the test
condition and then continue the iteration process.
 In the case of for loop, the increment section of the loop is executed before the test
condition is evaluated.

 The continue statement skips the current iteration of a for, while , or do-while loop.
 The unlabeled form skips to the end of the innermost loop's body and evaluates
the boolean expression that controls the loop.

Example1:

public class Sample


{

public static void main(String args[])


{
for(int i=1;i<=10;i++)
{
if(i==4)
continue;
System.out.println("i=" + i);
}

}
}
Output:
i=1
i=2
i=3
i=5
i=6
i=7
i=8
i=9
i=10

Labeled break and Continue

In java, It is possible to give label to a block of statements, which is valid java variable name. To give a
label to a loop, place it before the loop with a colon at the end
Example

43
Java Programming Notes
CO4I
LOOP1: for( )
{
...............
...............
}
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a
labeled break terminates an outer statement. The following program, BreakWithLabelDemo, is similar to
the previous program, but uses nested for loops to search for a value in a two-dimensional array. When
the value is found, a labeled break terminates the outer for loop (labeled "search"):

class BreakWithLabelDemo
{
public static void main(String[] args)
{
int a[][] = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 }};
int num = 12;
int i;
int j = 0;
boolean flag = false;

search: for (i = 0; i < a.length; i++)


{
for (j = 0; j < a[i].length; j++)
{
if (a[i][j] == num)
{
flag = true;
break search;
}
}
}
if (flag)
System.out.println("Found " + num + " at " + i + ", " + j);
else
System.out.println(num + " not in the array");
}
}

This is the output of the program.

Found 12 at 1, 0

The return Statement

The last of the branching statements is the return statement. The return statement exits from the current
method, and control flow returns to where the method was invoked. The return statement has two forms:
one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression
that calculates the value) after the return keyword.

44
Java Programming Notes
CO4I
return count;

The data type of the returned value must match the type of the method's declared return value. When a
method is declared void, use the form of return that doesn't return a value.

return;

45

You might also like