Download as pdf or txt
Download as pdf or txt
You are on page 1of 81

Mr. Atul Bondre (M.Sc.

Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1


Java Features:
1. Compiled and Interpreted:
 Usually computer language is compiled or interpreted. But Java combines both these approaches
thus making Java a two-stage system.
 First, Java compiler translates source code into bytecode. Bytecode is intermediate code and it
is not machine code.
 In Second stage, Java interpreter generates machine code that can be directly executed by the
machine that is running the Java program.
 We can thus say that Java is compiled and interpreted language.
2. Platform-Independent and Portable:
 Portability is most significant feature of Java over other languages.
 Java programs can be easily moved from one computer system to another, anywhere and
anytime.
 Changes and upgrades in operating systems, processors and system resources will not force any
changes in Java programs.
 Due to above reasons Java is popular language for programming on Internet which interconnects
different types of systems worldwide.
 We can download a Java applet from a remote computer onto our local system via Internet and
execute it locally. This makes the Internet an extension of the user’s basic system providing
practically unlimited number of accessible applets and applications.
 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.
3. Object Oriented:
 Java is a true object-oriented language. Almost everything in Java is an object. All program code
and data reside within objects and classes.
 Java comes with an extensive set of classes, arranged in packages that we can use in our
programs by inheritance.
 The object model in Java is simple and easy to extend.
4. Robust and Secure:
 Java is a robust language.
 It provides many safeguards to ensure reliable code.
 It has strict compile time and run time checking for data types.
 It is garbage-collected language, which relieves the programmer from memory management
problems.
 It incorporates exception handling, which captures run time errors and eliminates any risk of
crashing the system.
 Security is very important for a language that is used for programming on Internet.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 1
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
 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.
5. Distributed:
 Java is designed as a distributed language for creating applications on networks. It has ability to
share both data and programs.
 Java applications can open and access remote objects on Internet as easily as they can do in a
local system.
 This enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.
6. Simple, Small and Familiar:
 Java is a small and simple language. Many features of C and C++ that are either redundant or
sources of unreliable code are not part of Java. For example, java does not use pointers, pre-
processor header files, goto statement and many others.
 Java also eliminates operator overloading and multiple inheritance.
 To make the language look familiar to the existing programmers, it was modelled on C and
C++ and therefore, Java code ―looks like a C++ code. In fact, Java is a simplified version of
C++.\
7. Multithreaded and Interactive:
 Multithreaded means handling multiple tasks simultaneously.
 Java supports multithreaded programs. This means that we need not wait for the application to
finish one task before beginning another.
 For example we can listen to an audio clip while scrolling a page and at the same time download
an applet from distant computer. This feature greatly improves the interactive performance of
graphical application.
 The Java runtime comes with tools that support multiprocessor synchronization and construct
smoothly running interactive system.
8. High Performance:
 Java performance is impressive though it is an interpreted language. This is mainly due to
bytecode.
 According to Sun, Java speed is comparable to the native C / C++. Java architecture is also
designed to reduce overheads during runtime.
 Incorporation of multithreading enhances the overall execution speed of Java programs.
9. Dynamic and Extensible:
 Java is dynamic language.
 Java is capable of dynamically linking in new class libraries, methods and objects.
 Java can also determine the type of class through a query, making it possible to either
dynamically link or abort the program, depending on the response.

© 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.

Fig: Downloading of Applet via Internet

© 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

Fig: Java’s Interaction with Web


 The output produced by the Java compiler is not executable code, it is intermediate code called
as byte code.
 Byte code is highly optimized set of instructions executed by Java run time system (JVM).
 Byte code is machine independent.
Java Components (What is Java Virtual Machine – JVM?):
 Java compiler produces an intermediate code known as bytecode for a machine that does not
exist. This machine is called the Java Virtual Machine and it exists only inside the computer
memory.
 It is a simulated computer within the computer and does all major functions of a real computer.
 Following figure illustrate the process of compiling a Java program into bytecode which is also
referred to as Virtual Machine Code.

Java Program Java Compiler Virtual Machine


Source Code Byte Code
 The Virtual Machine Code is not machine specific.

© 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.

Bytecode Java Interpreter Machine Code


Virtual Machine Real Machine
 The JVM performs following operation:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
Java Environment:

Fig: Process of building and running Java application program


 Java environment includes many development tools and hundreds of classes and methods.

© 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.

Java Standard Library (JSL) or Application Programing Interface (API):


 The JSL or API includes hundreds of classes and methods group into several packages.
 Most commonly used packages are as follows:
Packages Description
lang A collection of classes required for implementing basic features of Java.
Ex: String, StringBuffer, Integer, Float, Exception, Math, Thread, etc.
io A collection of classes required for input / output operations.
Ex: InputStreamreader, BufferedReader, IOException, etc.
util A collection of classes required for utility functions such as date and time.
Ex: Date, Vector, Scanner, ArrayVector, etc.
awt A collection of classes required for platform independent GUI.
Ex: Button, Menu, TextField, List, Choice, Scrollbar, etc.
net A collection of classes required for communication with other computer via Internet.
Ex: InetAddress, Socket, ServerSocket, etc.
applet A collection of classes required for creation of java applets.
Ex: Applet

© 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.

Assigning Object Reference Variables:


 One object reference can be assigned to another object reference variable, then the copy of the
object is not created but copy of the reference is made.
 Rectangle r1 = new Rectangle();
 Rectangle r2 = r1;
 Here,r1 and r2 refer to same objects and no separate copy will be created. It simply makes r2
refer to the same object as r1.
 Thus, any changesmade to the object through r2 will affect the object to which r1 is referring,
since they are thesame object.

 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:

Fig: Two Ways of Using Java


Application Program:
public class SimpleProgram
{
public static void main(String args[])
{
System.out.println("Hello this is my first program");
}
}
Class Declaration:
First line of program declares a class which is an Object Oriented construct. As we know java is
true Object Oriented Language, so everything must be placed inside class. class is a keyword for
define a class. Class body must be enclosed between { and }. It does not end with semi colon (;) as
in C++.
Main Line:
It defines main() method. Every java application program must have main() method. This is starting
point for interpreter to begin the execution of program. A Java application can have any number of
classes but only one of them must include a main() methid to initiate the execution.

© 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

MindSpace Institute of Computer Technology, Yavatmal


Where The Future Begins…
Mobile No: 7020499143, 7798967460

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.

Floating Point Types:


It contains numbers with decimal point and with or without sign. There are two types of floating
point storage, namely float (single-precision) and double (double-precision). In java floating point
numbers are treated as double-precision quantities. To force them to be single-precision, we must
append f or F to the numbers, like 3.14f or 3.14F.
Ex: 15.7, 56.7, +30.5, -5.7, 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.

 Casting float to integer will result in loss of fractional part.


 Following cast will result in loss of information:
byte -> short, int, long, float, double
short -> int, long, float, double
char -> int, long, float, double
int -> long, float, double

© 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.

Getting Values of Variables:


 The print("aString") method prints just the string "aString", but does not move the cursor to a
new line. Hence, subsequent printing instructions will print on the same line.
 The println("aString") method prints the string "aString" and moves the cursor to a new line.
Standard Default Values:

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: atulrbondre@gmail.com 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

Operators and Expressions:


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.
Arithmetic Operators:
Arithmetic Operators are used to do arithmetic operations in a program. Expression containing
Arithmetic Operator is called as Arithmetic Expression.
Suppose, a= 7 and b = 3
Operators Meaning Examples
+ Addition or unary plus a + b = 10
- Subtraction or unary minus a–b=4
* Multiplication a * b = 21
/ Division a/b=2
% Modulo division a%b=1
Categories of Arithmetic Expressions:
i. Integer Arithmetic:
When both the operands in a single arithmetic expression such as a + b are integers, the expression
is called as integer expression, and operation is called integer arithmetic. Integer arithmetic always
results in an integer value.
Ex: 2 + 3 = 5
ii. Real Arithmetic:
When both the operands in a single arithmetic expression such as a + b are real, the expression is
called as real expression, and operation is called real arithmetic. Real arithmetic always results in a
real value.
Ex: 2.5 + 3.2 = 5.7
iii. Mixed-mode Arithmetic:
When one of the operand is real and other is integer, the expression is called as mixed-mode
arithmetic expression and operation is called as mixed-mode arithmetic.
Ex: 5 / 2.0 = 2.5
Program:
// WAP to demonstrate Arithmetic Operators.
import java.lang.*;
class Arithmetic
{
public static void main(String args[ ])
{

© 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

Operators Meaning Examples Result


7 > 6 && 7 < 10 True
&& Logical AND 7 < 6 && 7 < 10 False
7 < 6 && 7 > 10 False
|| Logical OR 7 > 6 || 7 < 10 True
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 36
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
7 < 6 || 7 < 10 True
7 < 6 || 7 > 10 False
! Logical NOT It negates the result.
Program:
// WAP to demonstrate Logical Operators.
import java.lang.*;
class Logical
{
public static void main(String args[ ])
{
System.out.println(―Result 1 = ― + (7> 6 && 7 < 10));
System.out.println(―Result 2 = ― + (7 < 6 && 7 < 10));
System.out.println(―Result 3 = ― + (7 < 6 || 7 < 10));
System.out.println(―Result 4 = ― + (7 < 6 || 7 > 10));
System.out.println(―Result 5 = ― + !(7>6));
}
}
Output: C:\> javac Logical.java
C:\> java Logical
Result 1 = true
Result 2 = false
Result 3 = true
Result 4 = false
Result 5 = false
Assignment Operators:
It is used to assign (store) the value on the right to the variable on left of ’=’ sign.
Syntax: variable = expression;
Ex: c = a + b, here result of a + b will be assigned to c.
Shorthand assignment operators:
C also has shorthand assignment operators as follows:
Syntax: variable op= expression;

© 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

Left Shift Operator:


The left shift operator is represented by <<. It shifts each bit to the left by specified number of
position. Left shift by 1 is having the effect of multiplication by 2; left shift by 2 is having the effect
of multiplication by 4, and so on.
Ex: If variable a= 00010101, then, a<< 1 results in 00101010 and a>> 2 results in 01010100.
Right Shift Operator:
The right shift operator is represented by >>. It shifts each bit to the right by specified number of
position. Right shift by 1 is having the effect of integer division by 2, right shift by 2 is having the
effect of integer division by 4, and so on.
Ex: If variable a = 11010111, then, a>> 1 results in 01101011 and a>> 2 results in00110101.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 41
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
Right Shift with Zero Fill:
The >> operator preserves the leftmost bits. The leftmost bits are filled with the previous content.
This is to do with sign extension. In this case there is a 1 at the left and it is preserved. If you do not
want to keep the 1 to the left, use >>> operator which shifts 0’s into the leftmost bits.
Program:
// WAP to demonstrate Bitwise Operators.
class Bitwise
{
public static void main(String args[])
{
int a = 60; // 60 = 0011 1100
int b = 13; // 13 = 0000 1101
int c;
c = ~a; // -61 = 1100 0011
System.out.println("~a=" + c);
c = a & b; // 12 = 0000 1100
System.out.println("a&b=" + c);
c = a | b; // 61 = 0011 1101
System.out.println("a|b=" + c);
c = a ^ b; // 49 = 0011 0001
System.out.println("a^b=" + c);
c = a << 2; // 240 = 1111 0000
System.out.println("a<<2=" + c);
c = a >> 2; // 15 = 1111
System.out.println("a>>2=" + c);
c = a >>> 2; // 15 = 0000 1111
System.out.println("a>>>2=" + c);
}
}
Output: C:\> javac Bitwise.java
C:\> java Bitwise
~a = -61
a&b=12
a|b=61
a^b=49
a<<2=240
a>>2=15
a>>>2=15
Special Operators:
Instanceof of Operator:

© 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

Operator Precedence And Associativity Table


Operator Description Precedence Associativity
() Function Expression
[] Array Expression
1 Left To Right
 Structure Operator
. Structure Operator
- Unary Minus
++ -- Increment / Decrement
~ One’s Compliment
! Negation
2 Right To Left
& Address of
* Value of Address
(type) Type Cast
sizeof Size in bytes
* Multiplication
/ Division 3 Left To Right
% Modulo Division
+ Addition
4 Left To Right
- Subtraction
<< Left Shift
5 Left To Right
>> Right Shift
< Less Than
<= Less Than or Equal To
6 Left To Right
> Greater Than
>= Greater Than or Equal To
== Equal Equals To
7 Left To Right
!= Not Equal To
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 44
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
& Bitwise AND 8 Left To Right
| Bitwise OR 9 Left To Right
^ Bitwise XOR 10 Left To Right
&& Logical AND 11 Left To Right
|| Logical OR 12 Left To Right
?: Conditional Operator 13 Right To Left
=
*= /= %= += -= Assignment Operators 14 Right To Left
&== |= ^= <<= >>==
, Comma 15 Right To Left
Decision Making and Branching:
 When a program breaks the sequential flow and jumps to another part of the code, it is called
branching.
 When the branching is based on a particular condition, it is known as conditional branching. If
branching takes place without any decision, it is known as unconditional branching.
 Java supports the following statement known as control or decision making statements.
o If statement
 Simple if
 If—else
 Nested if—else
 Else if ladder
o Switch statement
o Conditional operator statement
Decision Making With If Statement:
Simple If:
Description: In simple if statement, if the condition is true, true block executes. It does not include
false block.
Syntax: if (condition)
{
true block;
}
Flowchart:

© 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

// WAP to decide if number is even.


class Number
{
public static void main(String args[])
{
int n = Integer.parseInt(args[0]);
if(n % 2 == 0)
{
System.out.println(―Even‖);
}
}
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 46
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
}
Output: C:\>javac Number.java
C:\>java Number 8
Even
C:\>java Number 7
If---Else:
Description: In if---else statement, if the condition is true, true block executes, otherwise false
block executes.
Syntax: if (condition)
{
true block;
}
else
{
false block;
}
Flowchart:

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:

// WAP to print week days.


class Weekdays
{
public static void main(String args[])
{
int d=Integer.parseInt(args[0]);
switch(d)
{
case 1:
System.out.print("Monday");
break;
case 2:
System.out.print("Tuesday");
break;
case 3:
System.out.print("Wednesday");
break;
case 4:
System.out.print("Thursday");

© 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.

Exit Controlled Loops:


 In this type of loops condition is tested after body of the loop.
 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 body of the loop executes at least once even if the condition is false at very
first time.
 Example: do---while 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)
{
----
----
}
---
}

Nested do--while loop: do


{
----
do
{
----
----
} while(condition);
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 71
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java Unit-1
---
} (while);
Flowchart:

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

Enhanced For Loop / For Each Loop:


 Enhanced for loop / for each loop is extended language feature introduced in Java J2SE 5.0.
 This feature is useful to retrieve the array elements efficiently rather than using array indexes.
 We can also use this feature to eliminate the iterators in for loop and to retrieve the elements
from collection.
 So, it is use to track the elements of an array efficiently.
 Syntax: for (Type Identifier : Expression)
{
// Statements;
}
// Program For Enhanced For Loop / For Each Loop
class ForDemoEnh
{
public static void main(String args[])
{
int ary[ ]={30,10,60,70,40};
for(int i : ary) /* for(int i=0;i<=4;i++) */

© 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.

// Program on labelled loops, breaks and continue.


class ContinueBreak
{
public static void main(String args[])
{

© 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: *
**
***
****
*****

Space for Extra Work:


________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________

© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 81

You might also like