Core Java U - 1-2019
Core Java U - 1-2019
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 2
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Java programs support functions written in other languages such as C and C++. These functions
are known as native methods. This facility enables the programmers to use the efficient
functions available in these languages. Native methods are linked dynamically at runtime.
Benefits / Advantages of Object Oriented Programming:
Inheritance eliminates redundant (repeated) code. We can derive new class from existing class.
It gives reusability, hence saves development time.
Due to data hiding programs becomes more secure.
It is possible to have multiple instances of an object to co-exist without any interference.
It models real-world problems very well.
It is easy to partition the work in a project based on objects.
Object oriented systems can be easily upgraded from small to large systems.
Software complexity can be easily managed.
Message passing technique for communication between objects makes the interface description
with external systems much simpler.
The data cantered design approach is used.
Applications of Object Oriented Programming:
Real-Time Systems
Simulation and Modelling
Object-Oriented Databases
Hypertext, Hypermedia and Expertext
Artificial Intelligence and Expert Systems
Neural Networks and Parallel Programming
Decision Support and Office Automation Systems
CIM / CAM / CAD Systems
Difference between Java and C:
Java C
Java is an Object-Oriented Programming C is Procedure Oriented Programming Language.
Language.
Java does not include sizeof and typedef C includes sizeof and typedef keywords.
keywords.
Java does not contain struct and union user C contains struct and union user defined data
defined data types. types.
Java does not include type modifiers keywords C includes type modifiers keywords auto, extern,
auto, extern, register, signed and unsigned. register, signed and unsigned.
Java does not support explicit pointer type C supports explicit pointer type statement.
statement.
Java does not have pre-processor directives C have pre-processor directives #define, #include
#define, #include and #ifdef. and #ifdef.
Java requires that the function with no arguments C requires that the function with no arguments
must be declared with empty parenthesis. must be declared with empty parenthesis or void.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 3
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Java add new operator known as instanceof. C does not support instance of operator.
Java adds labelled break and continue. C supports only simple break and continue.
Java adds many features require for OOP such as C never supports OOP features.
classes and objects.
Difference between Java and C++:
Java C++
Java is an Object-Oriented Programming C++ is basically C with Object Oriented
Language. extensions.
Java does not support Operator Overloading. C++ supports Operator Overloading.
Java does not have template classes. C++ has template classes.
Java does not support multiple inheritance C++ supports multiple inheritance.
directly. This is accomplished using a new
feature called interface.
Java does not support global variables. Every C++ support global variables.
variable and method is declared within a class
and forms part of that class.
Java has replaced the destructor function with a C++ has the destructor function to destroy the
Garbage Collection System. So Java objects get objects.
cleaned up automatically when they are no longer
required.
Java does not have pre-processor directives C++ have pre-processor directives #define,
#define, #include and #ifdef. #include and #ifdef.
Java requires that the function with no arguments C++ requires that the function with no arguments
must be declared with empty parenthesis. must be declared with empty parenthesis or void.
Java add new operator known as instanceof. C++ does not support instance of operator.
Java adds labelled break and continue. C++ supports only simple break and continue.
Java does not use pointers. C++ uses pointers.
Java does not include sizeof and typedef C++ includes sizeof and typedef keywords.
keywords.
Java does not contain struct and union user C++ contains struct and union user defined data
defined data types. types.
Java does not include type modifiers keywords C++ includes type modifiers keywords auto,
auto, extern, register, signed and unsigned. extern, register, signed and unsigned.
Java and Internet (Why Java is popular on Internet?):
Applet:
Java is strongly associated with Internet. Java is used to create applet or we can download the
remote applet and run them on local machine using java enabled web browser such as HotJava.
Applets have made the Internet a true extension of the storage system of the local computer.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 4
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Internet users can setup their websites containing Java applets that could be used by other
remote users of Internet. This ability of Java to hitch a ride on Information Superhighway has
made Java a unique programming language for Internet. Hench Java is popularly known as
Internet Language.
Security:
Security is very important for a language that is used for programming on Internet.
Java verifies all memory access and ensures that no viruses are communicated with an Applet.
The absence of pointers in Java ensures that programs cannot gain access to memory locations
without proper authorization.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 5
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Portability:
Java ensures portability in two ways. First, Java compiler generates bytecode that can be
implemented on any machine. Secondly, the sizes of the primitive data types are machine-
independent.
As the java support applet, portability and security features which are the very important features
related to internet hence Java is popular on Internet.
Java Components (What is Byte Code?):
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 6
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 7
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
The machine specific code (known as machine code) is generated by the Java Interpreter by
acting as an intermediary between the virtual machine and the real machine as shown in
following.
Interpreter is different for different machines.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 8
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
The development tools are the part of Java Development Kit (JDK) and the classes and methods
are part of the Java Standard Library (JSL), also known as Application Programming Interface
(API).
Java Development Kit (JDK):
The JDK comes with a collection of tools that are used for developing and running Java
programs.
The tools are as follows:
Tools Description
appletviewer Use to run Java Applets.
javac Java Interpreter, which runs applet and applications by reading and interpreting
bytecode files.
java Java Compiler, which translates java source code to bytecode that the interpreter
can understand.
javadoc Creates HTML format documentation from Java source code files.
javah Produce header files for use with native methods.
javap Java Disassembler, which converts bytecode to source code.
jdb Java Debugger, which helps to find errors in programs.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 9
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Defining / Creating a Class:
What is a Class?
Class contains variables (data members) and functions (member functions / methods).
A class is a template for an object, and an object is an instance of a class.
Class is a collection of objects of similar types.
Class is a user defined data type.
Syntax: class ClassName
{
datatype instance-variable1;
datatype instance-variable2;
:
datatype instance-variableN;
return_datatype methodName1(parameter-list)
{
// body of method
}
return_datatype methodName2(parameter-list)
{
// body of method
}
:
return_datatype methodNameN(parameter-list)
{
// body of method
}
}
Description of Syntax:
Class is defined using class keyword.ClassName is any valid java identifiers.
Data or variables defined within a class are called instance variables because each instance of
the class (that is, each object of the class) contains its own copy of these variables. Thus, the
data for one object is separate and unique from the data for another. The variables and functions
defined inside the class are called members of the class.
Class declaration only creates a template; it does not create an actual object.
Class body written inside curly braces { and }. It does not terminate with semicolon.
Example: class Rectangle
{
int len, bre;
void getData(int l, int b)
{
len = l;
bre = b;
}
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 10
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
void putData()
{
System.out.print(―Area = ― + len*bre);
}
}
classRectArea
{
public static void main(String args[ ])
{
Rectangle r = new Rectangle();
r.getData(20,15);
r.putData();
}
}
Output: Area = 300
Creating / Declaring Objects:
What is an Object?
Object is an instance of a class. Creating an object is called as instantiating an object.
An object is a block of memory that contains space to store instance variables and methods.
Once the class is defined we can create any number of objects of that class.
Objects are created by using new operator (dynamic memory allocation operator).
Steps for Creating Object:
Creating objects of a class is a two-step process.
Step 1: Declare a variable of the class type. This variable does not define an object. Instead, it is
simply a variable that can refer to an object.
Syntax: ClassName reference_variable;
Example: Rectangle r; // declare reference to object.
After this line executes rcontains the value null, which indicates that it does not yet point to an
actual object. Any attempt to use object rat this point will result in a compile-time error.
Step 2: Acquire an actual, physical copy of the object and assign it to that variable. We can do this
using the new operator. The new operator dynamically allocates (that is, allocates at run time)
memory for an object and returns a reference to it. This reference is the address of memory of the
objectallocated by new. This reference is then stored in the variable. Thus, in Java, all class
objectsmust be dynamically allocated.
Syntax: reference_variable = new ClassName();
Here, reference_variable is a variable (object) of the class type being created. The ClassName is the
name of the class that is being instantiated. The class name followed by parentheses specifies the
constructor for the class.
Example: r = new Rectangle(); // allocate a Rectangle object
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 11
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Above line allocates an actual object and assigns a reference of it to r. After this line executes, we
can useras a Rectangleobject. But in reality, rsimply holds the memoryaddress of the actual
Rectangleobject. The effect of these two steps of code is shown in Figure.
Above both statements can be combined into a single statement as follows:
ClassName object_name = new ClassName();
Rectangle r = new Rectangle();
Here Rectangle() is default constructor.
Although r1 and r2 both refer to the same object, they are not linked in any other way.For
example, a subsequent assignment to r1 will simply unhook r1 from the original objectwithout
affecting the object or affecting r2.
For example:
Rectangle r1 = new Rectangle ();
Rectangle r2 = r1;
// ...
r1 = null;
Here, r1 has been set to null, but r2 still points to the original object.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 12
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Creating / Defining Methods:
Classes consist of two things: instance variables and methods.
Syntax: return_type function_name (parameter_list)
{
// body of method
}
Example: void calculate(int l, int b)
{
len = l;
bre = b;
System.out.print(―Area = ― + len*bre);
}
Here, return_type specifies the type of data returned by the method. This can be any valid
type,including class type.If the method does not return a value, its return typemust be void.
Methods that have a return type other than void return a value to the calling routine using the
following form of the return statement:
returnvalue;
The function_name of the method is any legal identifierother than those already used by other
items within the current scope.
The parameter_list is asequence of type and identifier pairs separated by commas.If the
methodhas no parameters, then the parameter list will be empty.
Declaring Instance Variable:
Data or variables defined within a class are called instance variables because each instance of
the class (that is, each object of the class) contains its own copy of these variables.
Thus, the data for one object is separate and unique from the data for another.
Syntax : datatype instance-variable1, instance-variable2, instance-variableN;
Example : int a, b, c;
Accessing Class Members:
Object contains data members (instance variables) and member functions (methods). Each
object has its own memory space for data members.
Object name and dot (.) operator is used to access variables and methods from outside the class.
Variables and methods can be access directly from within the class.
Syntax: object_name . Variable_name = value;
Object_name . method_name(parameter_list);
Example: r1.len = 20; r2.len = 10;
r1.bre = 15; r2.bre = 8;
r1.calculate (20, 15); r2.calculate (10, 8);
r1.len 20 r2.len 10
15 8
r1.bre r2.bre
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 13
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Programs:
// Program to calculate area of rectangle.
class RectangleArea
{
int len,bre;
void getData(int l, int b)
{
len = l;
bre= b;
}
void putData()
{
System.out.println("Area = " + len*bre);
}
public static void main(String args[])
{
RectangleArea r1 = new RectangleArea();
r1.getData(20,15);
r1.putData();
RectangleArea r2 = new RectangleArea();
r2.len=10;
r2.bre=15;
System.out.println("Area = " + r2.len*r2.bre);
}
}
Output: Area = 300
Area = 150
-----------------------------------------------------------------------------------------------------------------------
// Program to calculate area of rectangle.
class Rectangle
{
int len,bre;
voidgetData(int l,int b)
{
len = l;
bre = b;
}
void putData()
{
System.out.println("Area = " + len*bre);
}
}
classRectArea
{
public static void main(String args[])
{
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 14
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Rectangle r1 = new Rectangle();
r1.getData(20,15);
r1.putData();
Rectangle r2 = new Rectangle();
r2.len=10;
r2.bre=15;
System.out.println("Area = " + r2.len*r2.bre);
}
}
Output: Area = 300
Area = 150
-----------------------------------------------------------------------------------------------------------------------
// Program to swap two numbers.
import java.io.*;
class Swap
{
int a,b,temp;
InputStreamReader is=new InputStreamReader(System.in);
BufferedReaderbr=new BufferedReader(is);
void get()
{
try
{
System.out.print("Input two numbers: ");
a = Integer.parseInt(br.readLine());
b = Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("Exception occured: " + e);
}
}
void put()
{
temp = a; // a =a + b;
a = b; // b = a - b;
b = temp; // a = a- b;
System.out.println("Value of a = " + a);
System.out.println("Value of b = " + b);
}
}
class SwapTwo
{
public static void main(String args[])
{
Swap s = new Swap();
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 15
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
s.get();
s.put();
}
}
Output: Input two numbers: 10 20
Value of a = 20
Value of b = 10
-----------------------------------------------------------------------------------------------------------------------
// Program to calculate gross salary of employee.
import java.io.*;
class Salary
{
intbasic,da,ta,hra,gross;
BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));
voidgetSal()
{
try
{
System.out.print("Input basic salary: ");
basic=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("Exception Occurred: " + e);
}
}
voidputSal()
{
da = basic * 50/100;
ta = basic * 25/100;
hra = basic * 10/100;
gross = basic + da + ta + hra;
System.out.println("Gross Salary: " + gross);
}
}
class Emp
{
public static void main(String args[])
{
Salary s = new Salary();
s.getSal();
s.putSal();
}
}
Output: Input basic salary: 10000
Gross Salary: 18500
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 16
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
// Program to input and output student data.
import java.io.*;
class Student
{
String name;
int rollno;
float per;
InputStreamReader is=new InputStreamReader(System.in);
BufferedReaderbr=new BufferedReader(is);
void input()
{
try
{
System.out.println("Input student details: ");
name = br.readLine();
rollno = Integer.parseInt(br.readLine());
per = Float.parseFloat(br.readLine());
}
catch(Exception e)
{
System.out.println("Exception Occurred: ― + e);
}
}
void output()
{
System.out.println("Name = " + name);
System.out.println("Roll No = " + rollno);
System.out.println("Percentage = " + per);
}
}
classStudData
{
public static void main(String args[])
{
Student st = new Student();
st.input();
st.output();
}
}
Output: Input student details: Disha 12 86.92
Name = Disha
Roll No = 12
Percentage = 86.92
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 17
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Simple Java Programs:
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 18
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Public: The keyword public is an access specifier which specifies that main() method is available to
all other classes and everywhere.
Static: It specifies that this method belongs to the entire class and not a part of any objects of that
class. Only one copy of main() method will be craeted and shared by all objects of that class.
Main() method must be declared vas static as it is used by interpreter before creation of any objects.
Void: It specifies that main() method is not returning any value.
All parameters to a method are declared inside a pair of parenthesis. Her String args[] declares a
parameter args, which contains an array of objects of String class type.
Output Line:
The only executable statement in the program is:
System.out.println("Hello this is my first program");
Since Java is true Object Oriented Language, every method must be part of an object. The println
method is a member of out object, which is static data member of System class. This line prints the
String. The method println always append a newline character to the end of string, whereas print
method doesn’t. This means any subsequent output will start on a new line. Every java statement
must end with semicolon ();
Java Program Structure:
Documentation Section
Package Statement
Import Statement
Interface Statement
Class Definition
Main Method Class
{
Main Method Definition
}
Fig: General structure of Java Program
Documentation Section:
It consists of set of comments lines that provides the name of the program, programmer and other
details about the program.
Multiline comment /*------*/ and single line comment //------ both are available in Java. Java uses a
third style of comment /**------*/ known as documentation comment. This form of comment is used
for generating documentation automatically.
Packages Statement:
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 19
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
It is used to declare and create user defined packages. It is not necessary that user defined class
belongs to this package.
Syntax: package package_name;
Ex: package student;
Import Statements:
It is used to import and use readymade classes and interfaces from the packages. It is similar to
#include statement in C.
Ex: import java.lang.*;
This statement will import all the classes and interfaces form the lang package of Java.
Interface Statements:
Interface is like a class, but it contains only abstract methods and final, static variables. It is
generally used to implement multiple inheritance.
Class Definition:
A Java program may contain multiple class definitions. Classes in this section doesn’t have main().
Main Method Class:
Every Java program should have main( ) function. Main method creates objects of various classes
and establishes communication between them. Java programs start their execution from main
method. It is the only essential part of the Java program.
Command Line Arguments:
Command Line Arguments are parameters that are supplied to the application program at the
time of invoking its execution.
They must be supplied at the time of its execution after the file name.
In the main (), the args is declared as an array of strings known as string objects. Any arguments
provided in the command line at the time of program execution, are passes to the array args as
its elements.
Using index or subscripted notation we can access the individual elements of an array.
The number of elements in the array args can be getting with the length parameter, like:
cnt = args.length;
// WAP to find sum and average of three numbers.
import java.lang.*;
import java.io.*;
class CmdDemo
{
public static void main(String args[])
{
int n1,n2,n3,sum,avg;
int n1=Integer.parseInt(args[0]);
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 20
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
int n2=Integer.parseInt(args[1]);
int n3=Integer.parseInt(args[2]);
sum=n1+n2+n3;
avg=sum/3;
System.out.println(―Sum = ― + sum);
System.out.println(―Average = ― + avg);
}
}
Output: C:\>javac CmdDemo.java
C:\> java CmdDemo 10 30 20
Sum =30
Average = 20
// WAP to accept and print student details.
import java.lang.*;
import java.io.*;
class Student
{
public static void main(String args[])
{
String name = args [0];
int rollno=Integer.parseInt(args[1]);
float per=Float.parseFloat(args[2]);
System.out.println(―Name = ― + name);
System.out.println(―Roll Number = ― + rollno);
System.out.println(―Percentage = ― + per);
}
}
Output: C:\>javac Student.java
C:\> java Student Amol 12 86.5
Name = Amol
Roll Number = 12
Percentage = 86.5
Java Tokens:
Tokens are the smallest individual unit of the Java-Program.
Every meaningful entry in a Program is known as Token.
Every Java program is a collection of Tokens.
There are 5 types of tokens.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 21
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Keywords:
Keywords are the words whose meaning is fixed and already known to the Complier.
Keywords are also called as reserved words.
There 50 keywords in Java.
Keywords are case sensitive and always written in lower case letters.
Note: true, false and null are not keywords, but we should not try to use them as user defined names
in Java programs.
Identifiers:
Identifier refers to the names given to variables, class, functions or arrays.
These are user defined names and consist of sequence of letters and digits.
Ex: num1, main, a, b, n1, etc.
Rules for Naming Identifiers:
1. The first character in the identifier name must be an alphabet or underscore.
2. It can be on any length.
3. Identifier should not be a keyword.
4. Uppercase and lowercase are significant.
5. No commas or blank spaces are allowed within an identifier name.
6. Must consist of only letters, digits, underscore or dollar sign.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 22
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Literals:
Literals are sequence of characters (digits, letters and other characters) that represents constant
value to be stored in variable.
Types of Literals:
o Integer literals: Any whole number value is an integer literal. Examples are 1, 2, 3, and
42. It requires 32 bit. Java has four classes of integer, byte, short, int and long.
o Floating point literals: Floating-point numbers represent decimal values with a fractional
component. They can be expressed in either standard or scientific notation. It requires 32
bit. Java has two classes of float, single precision float and double precision double.
o Character literals: Characters in Java are indices into the Unicode character set. They are
16-bit values that can be converted into integers and manipulated with the integer
operators, such as the addition and subtraction operators. A literal character is represented
inside a pair of single quotes.
o String literals: String in Java is a sequence of characters between a pair of double quotes.
Examples of string literals are: ―Hello World‖ and ―2017‖
o Boolean literals: Boolean value can have, true and false. The values of true and false do
not convert into any numerical representation. The true literal in Java does not equal 1, nor
does the false literal equal 0. In Java, they can only be assigned to variables declared as
boolean, or used in expressions with Boolean operators.
Operators:
An operator is a symbol that tells the computer to perform certain mathematical or logical
calculations. Operators are used in programs to manipulate data and variables.
There are 8 types of operators are available in Java (Discussed in same unit).
Separators:
Separators are symbols used to indicate where group of code divided, terminate and arranged.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 23
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Constants:
Constants in Java refer to fixed values that do not change during the execution of a program.
Numeric Constants:
These constants refer to the sequence of digits. It may have decimal point and + or - sign.
1. Integer Constants:
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 24
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
It refers to sequence of digits without decimal point. It is of three types octal, decimal and
hexadecimal.
Ex: 78, -78, 0 etc.
2. Real Constants:
Numbers containing fractional part separated by a decimal point is called real constant. It may also
have + or – sign.
Ex: 1.2, 3.14, -3.24 etc.
Character Constants:
These constants contain letters (alphabets) and any other character from Java character set.
1. Single Character Constants:
It contains any single character from Java character set & enclosed in a single quotation mark.
These are represented by their ASCII values within computer.
Ex: ’A’ ’b’ ’7’ ’+’ ’;’ etc.
2. String Constants:
Set of characters enclosed in double quotation mark is called as string constant.
Ex: ―Disha‖ ―2015‖ etc.
Backslash Character Constants / Escape Sequences:
• These constants are used in output functions.
• These are also called as escape sequences.
• Note that each one represents one character, although they contain two.
Variables:
Variable is a quantity whose value changes continuously throughout the program execution.
Rules for variable names:
1. The first character in the variable name must be an alphabet or underscore.
2. Variable name can be of any length.
3. Variable should not be a keyword.
4. Uppercase and lowercase are significant.
5. No commas or blank spaces are allowed within a variable name.
6. Must consist of only letters, digits, underscore or dollar sign.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 25
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Types of variables:
As variables are used to hold constants they are of constants type:
1. Numeric Variables: These are used to represent numeric constants. Ex. prize, marks, etc.
2. Character Variables: These are used to represent single character value. Ex. gender.
3. String Variables: These are used to represent string values. Ex. city, stud_name, etc.
Declaration of Variables:
After designing suitable variable names, we must declare them to the compiler. Declaration of
variables must be done before they are used in the program.
Declaration does 3 things:
o It specifies what type of data the variable will hold.
o It tells compiler what the variable name is.
o It specifies how many bytes it will require to store.
Syntax: data-type variable1, variable2, ---, variable-n;
Declaration must end with semicolon (;).
Ex: int marks;
char gender;
float percentage;
Initialization of Variables / Giving Value to Variables:
Using Assignment Statement:
It refers to assigning values to variables.
Syntax: variable-name = value;
Ex: marks = 75;
gender = ’M’;
percentage = 73.85f;
It is also possible to assign a value to the variable at the time of declaration.
Syntax: data-type variable-name = value;
Ex: int marks = 75;
It is also possible to assign values to more than one variable in one statement.
Ex: p = q = r =0;
Using Read Statement:
We can give values interactively at run time through keyboard using readline() method.
readLine() reads the input as a String which can be converted to required datatype using
Wrapper classes.
readLine() can generate IOException, so it needs to write in try block; otherwise we need to use
throws IOException.
// Run time i/o using readLine().
import java.io.*;
class Demo
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 26
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
{
public static void main(String args[]) throws IOException
{
String nm;
int rn;
float pr;
BufferedReader b=new BufferedReader(i);
System.out.print("Input name: ");
nm = b.readLine();
System.out.print("Input rollno: ");
rn = Integer.parseInt(b.readLine());
System.out.print("Input percentage: ");
pr = Float.parseFloat(b.readLine());
System.out.println("Name="+nm);
System.out.println("Roll No="+rn);
System.out.print("Percentage="+pr);
}
}
Output: Input name: Disha
Input rollno: 23
Input percentage: 86.4
Name = Disha
Roll No = 23
Percentage = 86.4
Data Types:
Data Type is a term which represents the type of value hold by the variable. Every variable in
Java has the data type. Data type also specifies size of the value that can be stored.
Integer Types:
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 27
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Integers are whole numbers. Java has 4 types of integer storage, namely byte, short, int and long.
Java does not support unsigned types and therefore all Java values are signed.
Ex: 15, 567,-30, 0, etc.
Character Type:
A single character can be defined as a character (char) type data. It requires 2 bytes.
Ex: ’A’, ’a’, ’-’, ’4’, etc.
Boolean Type:
It is used to store true or false values. It is used to test the condition. It is denoted by boolean and
require only 1 bit of storage.
Scope of Variables:
The area of the program where the variable is accessible (usable) is known as scope.
Java variables are classified into three kinds:
Instance Variables:
These are declared inside a class.
These are created when objects are instantiated (created) and therefore they are associated with
the objects.
Separate copy of the variable will be created for every individual object of the class.
They take different values for each object.
Class Variables:
These are declared inside the class.
Class variables are global to a class and belong to the entire set of objects of that class.
Only one memory location is created for each class variable.
Local Variables:
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 28
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
These are declared inside a method / function.
These can be used only inside the method (in which it is declared). It cannot be used outside of
that method.
These can also be declared inside the program blocks between { and }.
These can be used within only that block and cannot be used outside of that block.
{
int x = 0; Block 1
{
Block
int n = 5; 2
}
{
Block
int m = 10; 3
}
}
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 29
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
In above figure; variable x declared in block 1 can be used in all three blocks.
Scope of variable n is only up to block 2 and can be used only in block 2.
Similarly, m can be used only in block 3.
We cannot re-declared x again in block 2 or block 3 (it is possible in C and C++).
Symbolic Constants:
Symbolic constants refer to the variable name having value which cannot be changed.
They are also known as constant identifier or named constants.
For example, PI=3.14, this value cannot be changed so we can declare it as symbolic constant.
Rules:
Symbolic constants names must be in capital letters (convention not a rule).
After declaration of symbolic constants, they should not be reassigned any other value.
Data types of symbolic constants must be specified.
Symbolic constants cannot be declared inside a method.
Syntax: final data-type symbolic-name = value;
Example: final float PI = 3.14f;
Advantages:
Modification of the program becomes easy.
Understanding of the program becomes easy.
Type Casting:
Type casting is used to convert value of one datatype into another datatype.
Syntax: datatype variable1 = (target_datatype) variable2;
Examples: int m = 50;
byte n = (byte) m;
long count = (long) m;
Type casting is often required when a method returns a type different than the one we required.
Casting into smaller type (narrowing) may result in loss of data.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 30
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
long -> float, double
float -> double
Automatic Conversion:
For some types, it is possible to assign a value of one type to a variable of a different type
without a cast. Java does the conversion of assigned value automatically.
Automatic type conversion is possible only if the destination type has enough precision (size) to
store the source value. For example, int is large enough to hold byte value. Therefore,
byte b = 75;
int a = b;
are valid statements.
The process of assigning a smaller type to a larger type is known as widening or promotion and
there is no loss of data in it.
MindSpace Computers
A Division of Disha Computers
Where the future begins…
We Provide Excellent Result Over The Years…
Mr. Atul R. Bondre
(M.Sc. Computer Science, MBA HRM)
Call Us: 7020499143, 7798967460
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation)
E-Mail Us: [email protected] Page 31
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Mathematical Functions:
The java.lang.Math.min(int a, int b) returns the smaller of two int values. If the arguments
have the same value, the result is that same value.
public static int min(int a, int b)
Aobve function can be used for int, long, float, double, etc.
Ex: Math.min(10,23); Ans: 10
The java.lang.Math.max(int a, int b) returns the greater of two int values. If the arguments
have the same value, the result is that same value.
public static int max(int a, int b)
Aobve function can be used for int, long, float, double, etc.
Ex: Math.max(10,23); Ans: 23
The java.lang.Math.sqrt(double a) returns correctly rounded positive sqr root of double value.
public static double sqrt(double a)
Ex: Math.sqrt(25.0); Ans: 5.0
The java.lang.Math.pow(double a, double b) returns the value of the first argument raised to
the power of the second argument.
public static double pow(double a, double b)
Ex: Math.pow(5.0,3.0); Ans: 125.0
The java.lang.Math.exp(double a) returns Euler's number e raised to the power of a double
value.
public static double exp(double a)
Ex: Math.exp(5.0); Ans: 148.4131591025766
The java.lang.Math.abs(int a) returns the absolute value of an int value. If the argument is not
negative, the same argument is returned. If the argument is negative, the positive value of the
argument is returned.
public static int abs(int a)
Ex: Math.abs(-5); Ans: 5
The java.lang.Math.round(double a) returns the closest long to the argument.
public static long round(double a)
Ex: Math.round(1654.9874); Ans: 1655
The java.lang.Math.round(float a) returns the closest int to the argument.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 32
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
public static int round(float a)
Ex: Math.round(1654.9874f); Ans: 1655
The java.lang.Math.ceil(double a) returns the smallest double value that is greater than or
equal to the argument and is equal to a mathematical integer.
public static double ceil(double a)
Ex: Math.ceil(128.2); Ans: 129
The java.lang.Math.floor(double a) returns the greatest double value that is smaller than or
equal to the argument and is equal to a mathematical integer.
public static double floor(double a)
Ex: Math.floor(128.2); Ans: 128
Program on Mathematical Functions:
// Math Function Demo
class MathDemo
{
public static void main(String args[])
{
int n1=5,n2=3;
System.out.println("Max="+Math.max(n1,n2));
System.out.println("Min="+Math.min(n1,n2));
System.out.println("Power="+Math.pow(n1,n2));
System.out.println("Abs="+Math.abs(-75));
System.out.println("Exp="+Math.exp(5.0));
System.out.println("Root="+Math.sqrt(25.0));
System.out.println("Round="+Math.round(37.43));
}
}
Output: Max = 5
Min = 3
Power = 125
Abs = 75
Exp = 148.4131591025766
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 33
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Root = 5.0
Round = 37
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 34
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("Add = " + (a+b));
System.out.println("Sub = " + (a-b));
System.out.println("Mul = " + (a*b));
System.out.println("Div = " + (a/b));
System.out.println("Rem = " + (a%b));
}
}
Output: C:\> javac Arithmetic.java
C:\> java Arithmetic 23 5
Add = 28
Sub = 18
Mul = 115
Div = 4
Rem = 3
Relational Operators:
Relational Operators are used to compare values. It results in true or false. Expression containing
Relation Operator is called as Relational Expression.
Operators Meaning Examples Result
4<9 True
< Is less than 9<4 False
9<9 False
4 <= 9 True
<= Is less than or equal to 9 <= 4 False
9 <= 9 True
9>4 True
> Is greater than 4>9 False
9>9 False
9 >= 4 True
>= Is greater than or equal to 4 >= 9 False
9 >= 9 True
9 = = 7+2 True
== Is equal to
9==8 False
9 != 7+2 False
!= Is not equal to
9 != 8 True
Program:
// WAP to demonstrate Relational Operators.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 35
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
import java.lang.*;
class Relational
{
public static void main(String args[ ])
{
System.out.println(―Result 1 = ― + (4<9));
System.out.println(―Result 2 = ― + (9<=9));
System.out.println(―Result 3 = ― + (4>9));
System.out.println(―Result 4 = ― + (4>=9));
System.out.println(―Result 5 = ― + (9==7+2));
System.out.println(―Result 6 = ― + (9!=8));
}
}
Output: C:\> javac Relational.java
C:\> java Relational
Result 1 = true
Result 2 = true
Result 3 = false
Result 4 = false
Result 5 = true
Result 6 = true
Logical Operators:
Logical Operators are used to combine two or more Relational Expressions. It results in true or
false. Expression containing Logical Operator is called as Logical Expression or Compound
Relational Expression.
Truth Table
a b a && b a || b
True True True True
True False False True
False True False True
False False False False
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 37
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Advantages of Shorthand Assignment Operators:
1. Statement becomes easier to write.
2. Statement becomes more concise and easier to read.
3. Statement becomes more efficient.
Increment and Decrement Operators:
Increment operator ’++’ is use to increase the value of operand by 1 and decrement operator ’- -’ is
used to decrease the value of operand by 1.
Syntax: variable ++ OR ++variable
variable- - OR --variable
Suppose, m=5
m++ = 6 and ++m = 6 m-- = 4 and --m = 4
So, m++ (postfix) and ++m (prefix) results similarly when they form the statements independently.
Difference between postfix and prefix:
Difference 1: Suppose, m=5
y = ++m; Result: y = 6 and m=6
y = m++; Result: y = 5 and m=6
y = --m; Result: y = 4 and m=4
y = m--; Result: y = 5 and m=4
So, a prefix operator first adds 1 to the operand and then the result is assigned to the variable on
left. On the other hand, a postfix operator first assigns the value to the variable on left and then
increments the operand.
Difference 2: Suppose, m=5
System.out.println(++m); Result: 6
System.out.println(m++); Result: 5
Program:
// WAP to demonstrate Increment and Decrement Operators.
import java.lang.*;
class IncrDecr
{
public static void main(String args[ ])
{
int m = 10, n = 20;
System.out.println(―Value of m = ― + ++m);
System.out.println(―Value of n = ― + n++);
System.out.println(―Value of m = ― + m);
System.out.println(―Value of n = ― + n);
}
}
Output: C:\> javac IncrDecr.java
C:\> java IncrDecr
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 38
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Value of m = 11
Value of n = 20
Value of m = 11
Value of n = 21
Write Output:
Write an output of the following expression. If a=1, b=2, c=3. Also give the contents of a, b and c at
the end of every expression.
i. a = d++ + --b
ii. b = b + c-- * --a
class IncrDecr
{
public static void main(String args[ ])
{
int a = 1, b = 2, c=3;
a = b++ + --b
System.out.println(―Value of a = ― + a);
System.out.println(―Value of b = ― + b);
System.out.println(―Value of c = ― + c);
b = b + c-- * --a
System.out.println(―Value of a = ― + a);
System.out.println(―Value of b = ― + b);
System.out.println(―Value of c = ― + c);
}
}
Output: C:\> javac IncrDecr.java
C:\> java IncrDecr
Value of a = 4
Value of b = 2
Value of c = 3
Value of a = 3
Value of b = 11
Value of c = 2
Conditional Operator:
A ternary operator pair ’? :’ in C is called as Conditional Operator. Expression containing
Conditional Operator is called as Conditional Expression. It can be nested.
Syntax: variable = exp1 ? exp2 : exp3;
In above syntax, exp1 is always relational or logical expression. exp1 is calculated first and it
results in true or false. If it is true exp2 is evaluated and that becomes the value of the variable, if
not, exp3 is evaluated and that becomes the value of the variable.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 39
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Ex: a = 10;
b = 15;
x = (a > b) ?a : b;
Here, x = b i.e. x = 15
Note: Same can be achieved by if—else statement:
if(a > b)
x = a;
else
x = b;
Program:
// WAP to find greatest of two numbers using Conditional Operator.
import java.lang.*;
class CO
{
public static void main(String args[ ])
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int max = a>b ? a : b;
System.out.println(―Greatest = ― + max);
}
}
Output: C:\> javac CO.java
C:\> java CO 15 12
Greatest = 15
Program:
// WAP to find greatest of three numbers using Nested Conditional Operator.
import java.lang.*;
class CO
{
public static void main(String args[ ])
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
int max = (a>b) ? (a>c ? a : c) : (b>c ? b : c);
System.out.println(―Greatest = ― + max);
}
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 40
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
}
Output: C:\> javac CO.java
C:\> java CO 15 12 18
Greatest = 18
Bitwise Operators:
Bitwise Operators are used to perform operations on individual bits. Bitwise Operators can operate
upon int and char but not on float and double. Expression containing Bitwise Operator is called as
Bitwise Expression.
Operators Meaning
~ One’s Complement
>> Right Shift
<< Left Shift
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
Truth Table
a b a&b a|b a^b
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0
One’s Complement:
It converts 1 to 0 and 0 to 1.
Ex: If a = 11010111 then ~a = 00101000
Bitwise AND: Bitwise OR: Bitwise XOR:
a 0000 1101 a 0000 1101 a 0000 1101
b 0001 1001 b 0001 1001 b 0001 1001
a & b 0000 1001 a | b 0001 1101 a ^ b 0001 0100
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 42
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
It is an object reference operator and return true if the object on the left hand side is an instance of
the class given on the right hand side. This operator allows us to determine whether the object
belongs to a particular class or not.
Ex: person instanceof student;
It is true if person object belongs to the student class; otherwise it’s false.
Program:
// WAP to demonstrate Instanceof Operator.
class Instance
{
public static void main(String args[])
{
String s1 = ―Hello‖;
String s2 = null;
System.out.println(―Res1 = ― + (s1 instanceof java.lang.String) );
System.out.println(―Res2 = ― + (s2 instanceof java.lang.String) );
}
}
Output: C:\> javac Instance.java
C:\> java Instance
Res1=true
Res2=false
Dot Operator (.):
It is used to access the instance variables and methods of class objects.
Ex: person.age; // Reference to the variable age
person.salary( ); // Reference to the method salary ()
It is also used to access classes and sub-packages from a package.
Operator Precedence & Associatively:
Precedence is used to determine how an expression containing more than one operator is
evaluated. There are distinct levels of precedence.
The operators at the higher level of precedence are evaluated first than lower level.
The operators of the same precedence are evaluated either from left to right or right to left,
depending on the level. This is known as associativity property of an operator.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 43
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 45
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Programs:
// WAP to decide if number is positive.
class Number
{
public static void main(String args[])
{
int n = Integer.parseInt(args[0]);
if(n > 0)
{
System.out.println(―Positive‖);
}
}
}
Output: C:\>javac Number.java
C:\>java Number 7
Positive
C:\>java Number 7
Programs:
// WAP to decide if number is positive or negative.
class Number
{
public static void main(String args[])
{
int n = Integer.parseInt(args[0]);
if(n > 0)
{
System.out.println(―Positive‖);
}
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 47
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
else
{
System.out.println(―Negative‖);
}
}
}
Output: C:\>javac Number.java
C:\>java Number 7
Positive
C:\>java Number 7
Negative
// WAP to decide if number is even or odd.
class Number
{
public static void main(String args[])
{
int n = Integer.parseInt(args[0]);
if(n % 2 == 0)
System.out.println(―Even‖);
else
System.out.println(―Odd‖);
}
}
Output: C:\>javac Number.java
C:\>java Number 8
Even
C:\>java Number 7
Odd
// WAP to find greatest of two numbers.
class Number
{
public static void main(String args[])
{
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
if(n1 > n2)
System.out.println(―Greatest = ‖ + n1);
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 48
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
else
System.out.println(―Greatest = ‖ + n2);
}
}
Output: C:\>javac Number.java
C:\>java Number 8 13
Greatest = 13
Nested If---Else:
Description: When multiple conditions are available, we may use nested if else statements. In this
multiple conditions are tested and depending on its results particular block of statements executes.
Syntax: if(condition1)
{
if(condition2)
block 1;
else
block 2;
}
else
{
if(condition3)
block 3;
else
block 4;
}
Flowchart:
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 49
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Programs:
// WAP to find greatest of three numbers.
class Number
{
public static void main(String args[])
{
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
int n3 = Integer.parseInt(args[2]);
if(n1 > n2)
{
if(n1>n3)
System.out.println(―Greatest = ‖ + n1);
else
System.out.println(―Greatest = ‖ + n3);
}
else
{
if(n2>n3)
System.out.println(―Greatest = ‖ + n2);
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 50
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
else
System.out.println(―Greatest = ‖ + n3);
}
}
}
Output: C:\>javac Number.java
C:\>java Number 8 13 9
Greatest = 13
Home Work: Write a program to find smallest of three numbers.
Else If Ladder:
Description: It is used when multiple conditions are available. It test the conditions from top to
bottom, as soon as true condition is found statements in that block will be executed and control
returns out of else if ladder. If true statement does not found default else block will get execute.
Syntax: if(condition-1)
{
block 1;
}
else if(condition-2)
{
block 2;
}
:
else if(condition-n)
{
block n;
}
else
{
default block;
}
Flowchart:
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 51
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Programs:
// WAP to print weekday as per day number.
class Weekdays
{
public static void main(String args[])
{
int d=Integer.parseInt(args[0]);
if(d==1)
System.out.println(―Monday‖);
else if(d==2)
System.out.println(―Tuesday‖);
else if(d==3)
System.out.println(―Wednesday‖);
else if(d==4)
System.out.println(―Thursday‖);
else if(d==5)
System.out.println(―Friday‖);
else if(d==6)
System.out.println(―Saturday‖);
else if(d==7)
System.out.println(―Sunday‖);
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 52
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
else
System.out.println(―Invalid day‖);
}
}
Output: C:\>javac Weekdays.java
C:\>java Weekdays 4
Thursday
// WAP to print grade of the student.
class Grade
{
public static void main(String args[])
{
int percent=Integer.parseInt(args[0]);
if(percent>=80)
System.out.println(―Grade A‖);
else if(percent>=60)
System.out.println(―Grade B‖);
else if(percent>=50)
System.out.println(―Grade C‖);
else if(percent>=40)
System.out.println(―Grade D‖);
else
System.out.println(―Fail‖);
}
}
Output: C:\>javac Grade.java
C:\>java Grade 67
Grade B
// WAP to perform all arithmetic operations.
class Arithmetic
{
public static void main(String args[])
{
int op=Integer.parseInt(args[0]);
int n1=Integer.parseInt(args[1]);
int n2=Integer.parseInt(args[2]);
if(op==1)
System.out.println(―Add = ‖ + (n1+n2) );
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 53
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
else if(op==2)
System.out.println(―Sub = ‖ + (n1-n2) );
else if(op==3)
System.out.println(―Mul = ‖ + (n1*n2) );
else if(op==4)
System.out.println(―Div = ‖ + (n1/n2) );
else if(op==5)
System.out.println(―Rem = ‖ + (n1%n2) );
else
System.out.println(―Invalid arithmetic operation‖);
}
}
Output: C:\>javac Arithmetic.java
C:\>java Arithmetic 3 25 8
Mul = 200
// WAP to decide if year is leap year or not.
class Leap
{
public static void main(String args[])
{
int yr=Integer.parseInt(args[0]);
if(yr % 400 == 0)
System.out.println("Leap Year");
else if(yr % 100 == 0)
System.out.println("Not Leap Year");
else if(yr % 4 == 0)
System.out.println("Leap Year");
else
System.out.println("Not Leap Year");
}
}
Output: C:\>javac Leap.java
C:\>java Leap 2012
C:\>java Leap 2100
Not Leap Year
// WAP to decide greatest of three numbers.
class Greatest3
{
public static void main(String args[])
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 54
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
{
int n1=Integer.parseInt(args[0]);
int n2=Integer.parseInt(args[1]);
int n3=Integer.parseInt(args[2]);
if(n1>n2 && n1>n3)
System.out.println(―Greatest = ― + n1);
else if(n2>n1 && n2>n3)
System.out.println(―Greatest = ― + n2);
else if(n3>n1 && n3>n2)
System.out.println(―Greatest = ― + n3);
else
System.out.println(―All numbers are equal‖);
}
}
Output: C:\>javac Greatest3.java
C:\>java Greatest3 13 25 8
Greatest = 25
Switch Case Statement:
Description: Switch is used to check multiple conditions. It can be used in place of else if ladder. It
is also known as Multiway Branching Statement. Switch checks the expression against available
multiple cases. If value of expression match with any case value then block of statements associated
with that case get executes. If no match found default block executes. Default block is optional.
Syntax: switch(expression)
{
case value-1:
block 1;
break;
case value-2:
block 2;
break;
:
case value n:
block n;
break;
default:
block default;
break;
}
In above syntax expression can be of integer or character type. In switch break is used to jump
outside of the switch.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 55
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Flowchart:
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 56
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
break;
case 5:
System.out.print("Friday");
break;
case 6:
System.out.print("Saturday");
break;
case 7:
System.out.print("Sunday");
break;
default:
System.out.print("Invalid day");
break;
}
}
}
Output: C:\>javac Weekdays.java
C:\>java Weekdays 4
Thursday
// WAP to print grades.
class Grade
{
public static void main(String args[])
{
int p=Integer.parseInt(args[0]);
switch(p/10)
{
case 10:
case 9:
case 8:
System.out.print("Grade A");
break;
case 7:
case 6:
System.out.print("Grade B");
break;
case 5:
System.out.print("Grade C");
break;
case 4:
System.out.print("Grade D");
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 57
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
break;
default:
System.out.print("Fail");
break;
}
}
}
Output: C:\>javac Grade.java
C:\>java Grade 67
Grade B
// WAP to perform all arithmetic operations.
class Arithmetic
{
public static void main(String args[])
{
int op=Integer.parseInt(args[0]);
int n1=Integer.parseInt(args[1]);
int n2=Integer.parseInt(args[2]);
switch(op)
{
case 1:
System.out.println(―Add = ‖ + (n1+n2) );
break;
case 2:
System.out.println(―Sub = ‖ + (n1-n2) );
break;
case 3:
System.out.println(―Mul = ‖ + (n1*n2) );
break;
case 4:
System.out.println(―Div = ‖ + (n1/n2) );
break;
case 5:
System.out.println(―Rem = ‖ + (n1%n2) );
break;
default:
System.out.println(―Invalid arithmetic operation‖);
break;
}
}
}
Output: C:\>javac Arithmetic.java
C:\>java Arithmetic 3 25 8
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 58
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Mul = 200
Looping / Iteration / Repetition Control Structure:
When some statements need to be repeated we can use looping control structure.
Types of loops:
o Entry Control Loops
o Exit Control Loops
Entry Controlled Loops:
In this type of loops condition is tested before getting entry inside the loop body.
Body of the loop keeps on executing till the condition is true. Once the condition becomes false
loop get stop.
In this type of loop if the condition becomes false at very first time body of the loop does not
executed once also.
Example: while and for loop.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 59
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
While Loop:
Description:
It is entry controlled loop.
Loop gets iterate till the given condition is true. Once the condition becomes false loop gets
stop.
In it if the condition becomes false at very first time body of the loop does not executed once
also.
Syntax:
while(condition)
{
loop body;
}
Flowchart:
Programs:
// WAP to print 1 to 10 using while loop.
class WhileDemo
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 60
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
{
public static void main(String args[])
{
int i = 1;
while(i<=10)
{
System.out.print(i + "\t");
i++;
}
}
}
Output: 1 2 3 4 5 6 7 8 9 10
// WAP to print table of seven in reverse order.
class WhileDemo
{
public static void main(String args[])
{
int i = 70;
while(i>=7)
{
System.out.print(i + "\t");
i = i - 7;
}
}
}
Output: 70 63 56 49 42 35 28 21 14 7
------------------------------------------------------------------------------------------------------------------------
// WAP to calculate sum of all numbers between 1 to n.
import java.util.*;
class SumNum
{
public static void main(String args[])
{
int n,i=1,sum=0;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
n=sc.nextInt();
while(i<=n)
{
sum = sum + i;
i++;
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 61
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
}
System.out.print("Result = " + sum);
}
}
Output: Input number: 10
Result = 55
------------------------------------------------------------------------------------------------------------------------
// WAP to calculate Factorial of a number.
import java.util.*;
class SumNum
{
public static void main(String args[])
{
int n,i=1,fact=1;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
n=sc.nextInt();
while(i<=n)
{
fact = fact * i;
i++;
}
System.out.print("Factorial = " + fact);
}
}
Output: Input number: 5
Factorial = 120
------------------------------------------------------------------------------------------------------------------------
// WAP to print Fibonacci series.
import java.util.*;
class SumNum
{
public static void main(String args[])
{
int fno=0, sno=1, tno, terms,i=1;
Scanner sc=new Scanner(System.in);
System.out.print("Input number of terms: ");
terms=sc.nextInt();
System.out.print(fno + " " + sno) ;
while (i<=terms-2)
{
tno=fno+sno;
System.out.print(" " + tno);
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 62
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
fno=sno;
sno=tno;
i++;
}
}
}
Output: Input number of terms: 8
0 1 1 2 3 5 8 13
------------------------------------------------------------------------------------------------------------------------
// WAP to decide if number is Prime or not.
import java.lang.*;
import java.util.*;
class Prime
{
public static void main(String args[]) throws IOException
{
int n,flag=0,i=2;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
n=sc.nextInt();
while(i<=n-1)
{
if(n%i == 0)
{
flag=1;
break;
}
i++;
}
if(flag==0)
System.out.println(n + " is prime");
else
System.out.println(n + " is not prime");
}
}
Output: Input number: 13
13 is prime
Input number: 8
8 is not prime
------------------------------------------------------------------------------------------------------------------------
// WAP to print sum of all digits of a number.
import java.util.*;
class SumAll
{
public static void main(String args[])
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 63
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
{
int num,sum=0,rem=0;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
num=sc.nextInt();
while(num>0)
{
rem = num%10;
sum = sum+rem;
num = num/10;
}
System.out.print("Addition = "+sum);
}
}
Output: Input number: 786
Addition: 21
// WAP to reverse a given number.
class Reverse
{
public static void main(String args[])
{
int num,rev=0,rem=0;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
num=sc.nextInt();
while(num>0)
{
rem = num%10;
rev = rev*10+rem;
num = num/10;
}
System.out.print("Reverse Number = "+rev);
}
}
Output: Input number: 786
Reverse Number = 687
----------------------------------------------------------------------------------------------------------------------------------
// WAP to decide if number is Palindrome or not.
class Reverse
{
public static void main(String args[])
{
int num,n,rev=0,rem=0;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
num=sc.nextInt();
n=num;
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 64
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
while(num>0)
{
rem = num%10;
rev = rev*10+rem;
num = num/10;
}
if(rev==n)
System.out.print(n + " is Palindrome");
else
System.out.print(n + " is not Palindrome");
}
}
Output: Input number: 717
717 is Palindrome
Input number: 786
786 is not Palindrome
// WAP to decide if number is Armstrong or not.
class Armstrong
{
public static void main(String args[])
{
int num,n,arm=0,rem=0;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
num=sc.nextInt();
n=num;
while(num>0)
{
rem = num%10;
arm = arm+rem*rem*rem;
num = num/10;
}
if(arm==n)
System.out.print(n + " is Armstrong");
else
System.out.print(n + " is not Armstrong");
}
}
Output: Input number: 153
153 is Armstrong
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 65
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Input number: 786
786 is not Armstrong
Do---While Loop:
Description:
It is exit controlled loop.
In it condition is tested while exiting from the loop.
Loop keeps executing till the condition is true. Once the condition becomes false loop stops.
In it body of the loop executes at least once even if the condition becomes false at very first
time.
Syntax:
do
{
loop body;
} while(condition);
Flowchart:
Fals
Programs:
// WAP to print 1 to 10 using do-while loop.
class DoWhileDemo
{
public static void main(String args[])
{
int i = 1;
do
{
System.out.print(i + "\t");
i++;
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 66
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
}while(i<=10);
}
}
Output: 1 2 3 4 5 6 7 8 9 10
------------------------------------------------------------------------------------------------------------------------
// WAP to print table of seven in reverse order.
class DoWhileDemo
{
public static void main(String args[])
{
int i = 70;
do
{
System.out.print(i + "\t");
i = i - 7;
}while(i>=7);
}
}
Output: 70 63 56 49 42 35 28 21 14 7
Difference between while and do---while loop:
While Loop Do---while Loop
It is entry controlled loop in which condition is It is exit controlled loop in which condition is
checked at the beginning of the loop. checked at the end of the loop.
In while loop if condition becomes false at very In do---while loop body will be executed at least once
first time loop body will not be executed once even if the condition becomes false at very first time.
also.
Execution of while loop is more accurate. Execution of do while loop is less accurate.
In while loop semicolon (;) is not used. In do--while loop (;) is used after while condition.
Syntax: Syntax:
While(condition) do
{ {
---- ----
---- ----
} } while(condition);
For Loop:
Description:
It is entry controlled loop.
It is compact version of while loop.
In for loop initialization, test condition and increment / decrement are written on same line.
Execution of for loop is as follows:
i. Initialization of loop control variable.
ii. Test condition.
iii. Body of the loop.
iv. Increment or decrement of loop control variable.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 67
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Here, steps ii to iv keeps on repeating till the condition is true. Once the condition becomes false
loop get stop.
Syntax:
for (initialization; test condition; increment/decrement)
{
loop body;
}
Flowchart:
Programs:
// WAP to print 1 to 10 using for loop.
class ForDemo
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
System.out.print(i + "\t");
}
}
}
Output: 1 2 3 4 5 6 7 8 9 10
------------------------------------------------------------------------------------------------------------------------
// WAP to print table of seven in reverse order.
class ForDemo
{
public static void main(String args[])
{
int i;
for(i=70;i>=7;i=i-7)
{
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 68
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
System.out.print(i + "\t");
}
}
}
Output: 70 63 56 49 42 35 28 21 14 7
------------------------------------------------------------------------------------------------------------------------
// WAP to calculate sum of all numbers between 1 to n.
import java.util.*;
class SumNum
{
public static void main(String args[])
{
int n,i,sum=0;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
sum = sum + i;
}
System.out.print("Result = " + sum);
}
}
Output: Input number: 10
Result = 55
------------------------------------------------------------------------------------------------------------------------
// WAP to calculate Factorial of a number.
import java.util.*;
class Fctorial
{
public static void main(String args[])
{
int n,i,fact=1;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
n=sc.nextInt();
for(i=1;i<=n;i++)
{
fact = fact * i;
}
System.out.print("Factorial = " + fact);
}
}
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 69
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Output: Input number: 5
Factorial = 120
------------------------------------------------------------------------------------------------------------------------
// WAP to print Fibonacci series.
import java.util.*;
class Fibonecci
{
public static void main(String args[])
{
int fno=0, sno=1, tno, terms,i;
Scanner sc=new Scanner(System.in);
System.out.print("Input number of terms: ");
terms=sc.nextInt();
System.out.print(fno + " " + sno) ;
for(i=1;i<=terms-2;i++)
{
tno=fno+sno;
System.out.print(" " + tno);
fno=sno;
sno=tno;
}
}
}
Output: Input number of terms: 8
0 1 1 2 3 5 8 13
------------------------------------------------------------------------------------------------------------------------
// WAP to decide if number is Prime or not.
import java.lang.*;
import java.util.*;
class Prime
{
public static void main(String args[]) throws IOException
{
int n,flag=0,i;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
n=sc.nextInt();
for(i=2;i<=n-1;i++)
{
if(n%i == 0)
{
flag=1;
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 70
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
break;
}
}
if(flag==0)
System.out.println(n + " is prime");
else
System.out.println(n + " is not prime");
}
}
Output: Input number: 13
13 is prime
Input number: 8
8 is not prime
786 is not Armstrong
Nested Loops:
Description:
When one loop is put inside another loop it is called as nested loops.
In nesting inner loop executes entirely for one iteration of outer loop, so inner loop executes
more number of times as compared to outer loop.
Syntax:
Nested for Loop: for(initialization; condition; increment/decrement)
{
----
for(initialization; condition; increment/decrement)
{
----
----
}
---
}
Programs:
// WAP to print the table of numbers from 2 to 12.
class Table
{
public static void main(String args[])
{
int no=1,i=1;
do
{
no++;
do
{
System.out.print("\t " + no*i);
i++;
}while (i<=10);
i=1;
system.out.println();
}while(no<12);
}
}
Output: Table from 2 to 12 will be printed.
-------------------------------------------------------------------------------------------- ----------------------------------------------------------------
// WAP to print the * pattern.
import java.util.*;
class Pattern1
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 72
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
{
public static void main(String args[])
{
int i, j, pos;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
System.out.print("Enter position/ number of rows: ");
pos=sc.nextInt();
for(i=1;i<=pos ; i++)
{
for(j=1;j<=i;j++)
{
System.out.print(" * ");
}
system.out.println();
}
}
}
Output: Enter position/ number of rows: 4
*
* *
* * *
* * * *
// WAP to print the * pattern in reverse order.
import java.util.*;
class Pattern2
{
public static void main(String args[])
{
int i, j, pos;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
System.out.print("Enter position/ number of rows: ");
pos=sc.nextInt();
for(i=pos;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.print(" * ");
}
system.out.println();
}
}
}
Output: Enter position/ number of rows: 4
* * * *
* * *
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 73
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
* *
*
-------------------------------------------------------------------------------------------- ----------------------------------------------------------------
// WAP to print the number pattern.
import java.util.*;
class Pattern3
{
public static void main(String args[])
{
int i, j, pos;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
System.out.print("Enter position/ number of rows: ");
pos=sc.nextInt();
for(i=1;i<=pos ; i++)
{
for(j=1;j<=i;j++)
{
System.out.print(i + "\t");
}
system.out.println();
}
}
}
Output: Enter position/ number of rows: 4
1
2 2
3 3 3
4 4 4 4
-------------------------------------------------------------------------------------------- ----------------------------------------------------------------
// WAP to print the number pattern.
import java.util.*;
class Pattern4
{
public static void main(String args[])
{
int i, j, pos;
Scanner sc=new Scanner(System.in);
System.out.print("Input number: ");
System.out.print("Enter position/ number of rows: ");
pos=sc.nextInt();
for(i=1;i<=pos ; i++)
{
for(j=1;j<=i;j++)
{
System.out.print(j + "\t");
}
system.out.println();
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 74
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
}
}
}
Output: Enter position/ number of rows: 4
1
1 2
1 2 3
1 2 3 4
Home Work:
HW 1: 3 3 3
2 2
1
HW 2: 3 2 1
3 2
3
HW 3: 1 2 3
1 2
1
HW 4: 1
2 3
4 5 6
7 8 9 10
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 75
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
{
if(i<50) /* if(ary[i]<50) */
{
System.out.println(i); /* S.o.p(ary[i]) */
}
}
}
}
Output: 30
10
40
Jumps in Loops:
Sometimes, when executing a loop we may need to exit the loop or to skip a part of the loop as
soon as certain condition occurs.
For example, if we want to search a given name from the list of 100 names. A program loop
should be written to repeat 100 times, but as soon as desired name is found we should terminate
the loop.
To support above things, Java permits a jump from one statement to the end or beginning of a
loop as well as a jump out of a loop using break and continue statement.
Java also support labeled break and continue statement to jump from nested loops.
Break Statement:
Simple break:
The simple break statement is used to early exit from loop, switch or any other block.
It can jump outside of the loop in which it is written.
It cannot jump outside of more than one loop at a time.
Behavior of simple break is shown in figure.
It is generally associated with if statement.
Syntax: break;
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 76
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Labelled break:
The labeled break statement is used to jump outside of the nested loops.
It can jump outside of more than one nested loop at a time.
Behavior of labeled break is shown below.
It is generally associated with if statement.
Syntax: break label;
Program:
class BreakDemo
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
if(i>5) break;
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 77
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
System.out.println(i);
}
}
}
Output: 1
2
3
4
5
Continue Statement:
Simple continue:
The simple continue statement is used to transfer the control to the beginning of the loop.
Whenever continue statement is encountered remaining part of the loop will be skipped and
control immediately transfer to the beginning of the loop.
It can skip / continue only one loop in which it is written.
Behavior of continue is shown in fig.
It is generally associated with if statement.
Syntax: continue;
Labelled continue:
The labeled continue statement is used to transfer the control to the beginning of the nested
loops.
It can skip / continue any specified nested loop.
Behavior of labeled continue is shown below.
It is generally associated with if statement.
Syntax: continue label;
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 78
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Here, continue will take the cursor to the beginning of the outer loop.
Program:
class ContinueDemo
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
if(i>3 && i<8) continue;
System.out.println(i);
}
}
}
Output: 1
2
3
8
9
10
Difference Between Break and Continue Statement:
break continue
break is used to jump / exit outside of the loop.
continue is used to skip / continue part of the
loop.
break sends cursor to the outside of loop or continue sends cursor to the beginning of the
block. loop.
break jump outside of the loop as soon as continue go to the beginning of the loop after
condition satisfies. incrementing / decrementing the value of loop
variable.
break is used in switch statement to jump continue is not used in switch.
outside.
Note: Draw diagram Note: Draw diagram
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 79
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Labelled Loops and Blocks:
In Java, we can give a label to a block of statements.
A label is any valid java identifier.
To give a label to a loop, place it before the loop with colon at the end.
Ex: abc: for (----------)
{
----------
----------
-----------
}
A block of statements can be labeled as shown below:
Ex: block1:{
----------
block2:
{
----------
----------
}
----------
}
Simple break statement causes the control to jump outside the nearest loop and simple continue
statement restart the current loop.
If we want to jump outside a nested loops or to continue a loop that is outside the current one,
then we have to use labeled break and labeled continue statements.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 80
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
loop1: for(int i=1;i<=100;i++)
{
System.out.println();
if(i>5) break loop1;
for(int j=1;j<=100;j++)
{
System.out.print(" * ");
if(j==i) continue loop1;
}
}
}
}
Output: *
**
***
****
*****
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 81