Page 1
1 Unit I
1
INTRODUCTION TO JAVA
PROGRAMMING
Unit Structure
1.0 Objectives
1.1 Introduction
1.2 History
1.3 Java Architecture and its components
1.3.1 The Java Virtual Machine
1.3.1.1 JVM Components
1.3.2 Java Runtime Environment
1.3.3 Java Development Kit
1.4 The Java API
1.5 Java Platform
1.6 Lambda Expressions
1.7 Methods References
1.8 Type Annotations
1.9 Method Parameter Reflection
1.10 Setting the path environment variable
1.11 Java Compiler and Interpreter
1.12 Java class file
1.13 Java Programs
1.14 Java Applications
1.15 Whitespace and case sensitivity
1.16 Identifiers and keywords
1.17 Comments
1.18 Braces and code block
1.19 Variables and variable name
1.20 Summary
1.21 List of References
1.22 Bibliography
1.23 Model Questions
munotes.in
Page 2
2 1.0 OBJECTIVES
In this chapter, you will be going to learn following topics:
Introduction to java programming and its various features
Java architecture
JVM Components
Different Java platforms
How to write and execute a java program?
Different terms used in java language like variables, keywords,
identifiers
1.1 INTRODUCTION
What is Java?
Java is a programming language and platform. Java is High -level,
object -oriented programming language developed by sun microsystems. It
is simple programming language. Java Language is used to developed
Standalone Applications, Web Applications, Enterprise Applications and
Mobile Applications. Java Provides a runtime En vironment (JRE) and
Java API, that’s why it is called as a platform.
Features of Java language:
1) Simple: Java was designed to be a very easy to learn and understand
and use effectively. If you understand the basic concepts of object -
oriented programming, learning java will be easier.
2) Object - Oriented: Java is purely an object -oriented programming
language. In Java, everything is an object which has some data and its
own behavior.
Following are some basic concepts of OOPs:
Class: Class is col lection of objects. You can create multiple objects
of a class. It represents properties and methods that are common to all
objects of one type.
Object: Any entity that has state and behaviors is called as an object.
Object can be defined as instance of a class.
Inheritance: Inheritance is a mechanism in java which allows one
class to inherit properties and behavior of another class (parent class).
Polymorphism: If one task is performed in many different ways, it is
called as polymorphism. In java method o verloading and method
overriding is used to implement polymorphism.
Abstraction: Hiding internal details and showing only functionality
is known as abstraction. For example, we don’t know the internal
processing of car, when it is moving. munotes.in
Page 3
3 Encapsulation: B inding or wrapping code and data together into a
single unit are known as encapsulation. For example, capsule
wrapped it with so many medicines.
3) Robust: Java is robust because it provides strong memory management
and automatic garbage collection. Java Virt ual machine is responsible
to manage allocation and deal location of memory for objects. It will
automatically free the memory for such objects which have not been
used in java application. It also provides compile time and run -time
error checking mechanis m.
4) Platform Independent: Java code is not complied into platform
specific machines. Java Code can be executed on multiple platforms
like Windows, Linux, Mac/OS etc.
5) Secured: We can develop secured and virus free applications. Java is
secured because java programs always get executed inside java virtual
machine which has no interaction with OS.
6) Architecture -Neutral: Java has no implementation dependent features.
In java size of the primitive data type is fixed. Once byte code is
generated it can be execut ed on 32 -bit architecture as well as 64 -bit
architecture.
7) Portable: Java is writing once and run anywhere language. Java byte
code generated after compilation can be executed on any machine.
8) High - Performance: Java is an interpreted language. It faster tha n other
traditional interpreted languages.
9) Distributed: Java is distributed because it supports creating distributed
applications. Using RMI and EJB you can create distributed
applications in java.
10) Multi -Threaded: Java multi -threading allows you to creat e multiple
threads to executed simultaneously. With this feature we can divide
program in multiple threads that will execute different tasks at once.
11) Dynamic: Java support dynamic loading of classes.
1.2 HISTORY
Java language was Initially developed by James Gosling, Patrick,
Chris Wart hand Mike Sheridan at Sun Microsystems in 1991.This
language was initially called “Oak” but was renamed “Java” in 1995.
Initially it was developed to create software to be embedde d in various
electronic devices like microwave ovens, remote controls, set -top boxes
etc. munotes.in
Page 4
4 Sun micro system releases first version JDK 1.0 in Jan 1996. It
provides Write once and run anywhere functionality. After first release
they have added various new f eatures in each new release version. Second
version JDK 1.1 was released in Feb 1997.
On 13 November 2006 Sun Micro system released some part of
Java Virtual Machine(JVM) as free and open source software, under the
General Public License. On May 8, 2007 , Sun finished the process of
making all of its JVM Code available under free and open source
distribution term, except small portion of the code to which sun did not
have copyright. In 2010 java was acquired by Oracle Corporation. Later
on, Oracle Corpora tion keeps on releasing new versions by adding many
new features in each version. Oracle released current version JDK SE 16
on 16 march, 2021.
1.3 JAVA ARCHITECTURE AND ITS COMPONENTS
Java Architecture includes components JVM, JRE and JDK. It
combines the pr ocess of compilation and Interpretation. It defines all the
processes involves in creating a java program. Architecture explains all
steps like creating program, how program is compiled and how it is
executed.
Java architecture performs following steps:
1) In Java, Program execution is a two -step process which include
Compilation and Interpretation.
2) In first Step, Java compiler converts the source code into byte code.
3) In second step, JVM converts byte code into machine code.
4) Then machine code is executed by O perating System.
Fig. Java Architecture
munotes.in
Page 5
5 Components of Java Architecture
Java Architecture includes three main components:
1) Java Virtual Machine (JVM)
2) Java Runtime Environment (JRE)
3) Java Development Kit (JDK)
1.3.1 The Java Virtual Machine
Java virtual machine is a part of Java Runtime Environment. The
primary function of JVM is to execute the java bytecode. It is a
specification that provides java runtime environment in which java
bytecode is executed. JVM is respon sible to load java code in memory and
calls main method present in java code and then execute that method.
Java language provides a feature of Write Once Run Anywhere.
Which means we can write code once and execute it anywhere and on any
operating system. Java program executes on any platform only because of
Java Virtual Machine.
1.3.1.1 JavaVirtual Machine Components
JVM performs following operations:
Loads java byte code, verifies code, execute code, provides
runtime Environment
Fig. JVM Architecture
1) Class Loader: Class Loader is used to loads the .class files into
memory. Whenever we execute the java program, class loader loads it
first.
There are three built in class loader are available in Java.
1) Bootstrap Class Loader: Bootstrap class loader is super class of
Extension Class Loader. It loads all the packages included in Java
Standard Edition like java.lang package, java.io package, java.util
package, java.net package and so on.
2) Extension Cla ss Loader: Extension classloader is subclass of
bootstrap classloader and superclass of application classloader. It munotes.in
Page 6
6 loads all jar files present in the $JAVA_HOME/jre/lib/ext
directory.
3) Application Class Loader: Application Classloader is subclass of
the Extension Classloader. It loads files from classpath. By default,
classpath is set to a current working directory. You can able to
modify classpathby using -cp or -classpath command.
2) Method Area: Method Area stores the all the class level data such as
runtime constant pool, fields, method data and code for methods. There
is only one method area par JVM.
3) Heap: Heap memory created when JVM Start up. It stores all the
objects created during program execution and their corresponding
instance variable. It is the run -time data area from which memory for
all class instances and array is allocated. There is only one heap area
par JVM.
4) Stack: Java Stack memory stores Stack frames, local variable, method
calls, partial results. Whenever a new thread is created in the JVM, a
separate JVM stack is also created at the same time for that thread. A
new frame is created whenever a method is invoked and it is deleted
when method invocation process is completed.
5) Program Counter (PC) Registers: Program Counter Register stores
address of the currently executing JVM Instruction. JVM Support
Multiple threads, so each thread has it own PC register. Once the
instruction is executed PC register is updated with new instru ction.
6) Native Method Stack: It contains all the native methods used in
application. These methods are written any other language than java
like c, c++ etc. For each thread separate native Method Stack is created.
7) Execution Engine: Once the bytecode has b een loaded into memory,
next step is to execute the program. Execution engine is responsible to
execute the program. Before executing program, bytecode need to be
converted into machine language instructions. The JVM uses
interpreter or JIT Compiler to co nverts byte code into machine
language instructions.
8) Execution engine includes:
Interpreter: The interpreter read and executes byte code instructions
line by line.
Just-In-Time Compiler: it is used to improved performance. JIT
complies the parts of the bytecode that have similar functionality at the
same time. It reduces amount of time needed for compilation.
Garbage Collector: The Garbage Collector collects and remove
unused objects from th e heap area. It is the process of automatically munotes.in
Page 7
7 destroying unused objects and making runtime memory available to use
for some other objects.
9) Java Native Interface: Java Native Interface(JNI) provides an
interface to communicate with another application wr itten in another
language like c, c++ etc. Java provides execution of native code
through JNI.
10) Native Libraries: Java Native Libraries provides a collection of
libraries which are written in other programming languages needed by
execution engine.
1.3.2 Java Ru ntime Environment (JRE)
Java Runtime Environment is a set of software tools which are
used for developing Java applications. It is used to provide a runtime
environment where we can execute our java program. JRE is part of JDK
means it get install automati cally along with JDK. JRE includes JVM, set
of libraries, plugins and applet support. JRE initiates JVM for its
execution.
1.3.3 Java Development Kit (JDK)
We need JDK for execution of java programs and for developing
java applications. Java Development Kit is a software development
environment which is used to developed Java applications. It includes
JRE, a compiler, an interpreter, aa debugger and other tools like document
generator etc.
1.4 THE JAVA API
Java API (Application Programming Interface) provides a large
collection of packages. Each package includes a large collection of classes
and interfaces along with their methods.
Java API Packages:
java.io Provides Classes for system input and output through data
streams and the file system.
java.net Provides classes for implementing networking application.
java.util It contains date and time facilities and collection
framework and classes.
java.awt Provides a large list of classes for creating user interfaces
and for painting graphics and images.
java.sql Provides classes and interface required for accessing and
processing data stored in data based
javax.swing Provides a set of lightweight components required for
creating graphical user interface. munotes.in
Page 8
8 Java.math Provides classes and interfaces for performing arbitrary -
precision integer arithmetic and arbitrary -precision decimal
arithmetic..
1.5 JAVA PLATFORM
Java platforms is a collection of programs that helps programmer
to develop and run java programs written in java programming language.
It is hardware and software environment in which programs runs. Java
platform includes an JVM, a compiler and set of libraries called as API.
Java Platforms:
1) Java SE (Standa rd Edition): It is a java programming platform.
It includes java programming APIs like java.io, java.net,
java.util,java.math, etc.
2) Java EE (Enterprise Edition): It is an enterprise platform which
is usedto developed web applications and enterprise applications.it
includes java technologies like Servlet, JSP, Web Services, EJB
etc.
3) Java ME (Micro Edition): Java micro edition used to develop
mobile applications.
1.6 LAMBDA EXPRESSIONS
Lambda Expression is an anonymous method (unnamed method).
Lambda expression is used to implement a method defined by functional
interface. Lambda expression is treated as function.
Lambda expression provides an implementation of fun ctional
interface. Functional interface is an interface which has only one abstract
method. A method which includes only declaration not any
implementation is called as abstract method. Functional interface is also
known as Single Abstract Method (SAM) int erface.
Syntax for creating functional interface:
interface interface_name
{
Return_typemethod_name(); //abstract method
}
Example:
1) interface Draw
{
void circle();
} munotes.in
Page 9
9 2) interface Addition
{
add(int a, int b);
}
Lambda Expression Syntax:
(argument list) ->{ body }
-> This operator is called as lambda operator or arrow operator. This
operator divides lambda expression in two parts, left side includes
parameters required by lambda expression and right side include body,
which specifies actions of the lambda expression. Body part includes
expressions or statements for lambda expression.
Examples:1) () -> 123.14
This lambda expression returns constant value 123.14.
2) () -> 12*6
Program:
interface Area
{
void findArea();
}
public class LambdaEx pressionDemo1
{
public static void main(String arg[])
{
Area obj1;
int r = 3;
//Lambda Expression without any argument
obj1 = () ->System.out.println("Circle Area:" + (3.14*r*r));
obj1.findArea();
int side = 5;
obj1 = () ->System.out.prin tln("Square Area: " +( side*side));
obj1.findArea();
}
}
Output:
Circle Area:28.259999999999998
Square Area: 25
Lambda expression with parameter:
1) (n) -> n*n
2) (r) -> 3.14*r*r
munotes.in
Page 10
10 Program:
interface Calculate
{
int display(int p, int q);
}
public class LambdaExpressionDemo2
{
public static void main(String arg[])
{
Calculate obj1;
obj1 = (a,b) -> (a+b); //lambda expression with argument
System.out.println("Addition: " + obj1.display(10,20));
obj1 = (h,w) -> (h*w);
System.ou t.print("Rectangle Area:" + obj1.display(5,4));
}
}
Output:
Addition: 30
Rectangle Area:20
1.7 METHOD REFERENCES
Lambda Expression is used to create anonymous methods. Method
references is similar to lambda expression. Sometimes, a lambda
expression only calls an existing method. When you want to refer existing
method by name then you can use method references. Method reference
provides a way to refer to a method without executing. Whenever you are
using a lambda expression just to refer a method, you can replace that
lambda expression with method reference.
Types of method references:
1) Method reference to a static method:
You can refer a static method created in class.
To create static method reference use following syntax:
Class_name :: m ethodName
Program:
interface Calculate //functional interface
{
void cube(int a); //abstract method munotes.in
Page 11
11 }
class StaticReference
{
public static void display(int b)
{
System.out.println("Cube: " + (b*b*b));
}
public static void main(String arg[])
{
Calculate c = StaticReference :: display;
c.cube(5);
}
}
Output:
Cube: 125
2) Method Reference to anInstance Method
To create instance method reference use following syntax:
Object_reference :: methodName
This syntax is similar to static method r eference, except it uses a
object reference instead of class name.
Program:
interface Calculate
{
void square(int a);
}
class InstanceReference
{
public void display(int b)
{
System.out.println("Square: " + (b*b));
}
public static void main(String arg[])
{
InstanceReference instance =new InstanceReference();
Calculate c = instance :: display;
c.square(15);
}
}
Output:
Square: 225
munotes.in
Page 12
12 3) Method Reference to a constructor
Constructor: Constructor is a one kind of function in java which has
same name as the class name. It does not have any return type.
Constructor will get called automatically after creating an object (instance)
of a class. Constructor is mostly used to initialized object of class. Every
time you will create object of a class, th e constructor will get executed.
Syntax: class_name() {}
Example of creating constructor:
Class Demo
{
Demo() //constructor
{
//Statements
}
}
Similarly, you are creating references to a method, you can also
create a reference to a constructor.
Syntax for creating reference to a constructor:
Class_name :: new
Program:
interface Calculate
{
void display();
}
public class MyConstructor
{
MyConstructor()
{
System.out.println("Creating reference to a constructor");
}
public static void main(String arg[])
{
Calculate c = MyConstructor :: new;
c.display();
}
}
Output:
Creating reference to a constructor
munotes.in
Page 13
13 1.8 TYPE ANNOTATIONS
Java Annotations are used to provide supplementary information
about your program. Java Annotat ions represents a metadate or
information attached with class, interface, methods, instance variables and
constructor etc. Annotations can be used by compiler to detect errors or
suppress warnings. Annotations can be applied while declaring methods,
fields , classes, constructor and other program elements.
All the annotations in java start with ‘@’ symbol. Annotations do
not change action or execution of a compiled program. Annotations are
not considered as comments as they change the way the compiler treat s a
program.
Types of Java Annotations:
1) Marker Annotation: The purpose of market annotation is to mark a
declaration . Marker annotation do not contain any members or do not
consist of any data. Marker interface in java does not consists of any
method, for declaring this interface we can use marker annotation.
@Override and @Deprecated are the examples of Marker Annotati on
Example of declaring marker Annotation:
@TestAnnotation()
@interface MyAnnotation{}
2) Single Value Annotation:
Single Value Annotation contain only one value. They allow
shorthand form of specifying the value to of the member. While using this
annotat ion, we only need to specify the value for that member and also do
not need to specify the name of the member.
Example:
@TestAnotation(name = “amit”)
@MyAnnotation(value= 10)
3) Multi Value Annotation:
Multi value Annotation consists of multiple data memb ers, values and
pairs.
Example of declaring Multi value annotation:
1) @interfaceMyAnnotation
{
int id();
String name();
String class();
}
2) // you can also provide default value to each member
@interface MyAnnotation2
{
int id() default 101; munotes.in
Page 14
14 String name() “Pranali”;
}
3) @TestAnnotaion(id = 1, name= “shruti”, class = “SYIT”)
4) @Author(name= “balguru swami” , date = “28/8/2021”)
Predefined Java Annotations used in java code:
1) @Deprecated: The @Deprecated Annotation is marker annotation
that indicat es the element is deprecated and should no longer be
used. The compiler generated a warning whenever program uses a
method, class and field with @Deprecated annotation.
2) @Override: the @override annotation informs the compiler that
element is meant to override an element declared in a superclass.
3) @SuppressWarnings: The @SuppressWarnings annotation
instruct the compiler to suppress warning that are generated while
program executes. The java langua ge specification lists two
categories of warnings: Deprecation and Unchecked.
Example: To suppress particular category of warning, we use
@SupressWarning(“Deprecation”)
To suppress multiple category of warnings, we use
@SupressWarning({“Deprecation”, “ Unchecked”})
4) @Safevarargs: This annotation asserts that the annotated method
or constructor does not perform unsafe operations on its varargs
(variable number of argument).
5) @Functional Interface: This annotation is introduced in JDK SE
8, indicates that the type declaration is intended to be a functional
interface.
Predefined Java annotation applied to other Annotation:
1) @Retention: Retention annotation specifies how the marked
annotation is stored:
@RetentionPolicy.SOURCE : The marked annotation is
retained only in the source level and is ignored by the
compiler.
@RetentionPolicy.CLASS : The marked annotation is
retained by the compiler at compile time, but it is ignored
by JVM.
@RetentionPolicy.RUNTIME : The marked annotation is
retained by the JVM so that it can be used by the runtime
environment.
2) @Documented: Documented annotation indicated that whenever
the specified annotation is used those elements should be
documented using the Javadoc tool. munotes.in
Page 15
15 3) @Terget: Target annotation marks another annotation to restrict
what kind of java elements the annotation can be applied to. It
specifies one of the following element types as its value:
@ElementType.ANNOTATION_TYPE
@ElementType.CONSTRUCTOR
@ElementType.FIELD
@ElementType.LOCAL_VARIABLE
@ElementType.METHOD
@ElementType.PACKAGE
@ElementType.PARAMETER
@ElementType.TYPE
4) @Inherited: This annotation indicates that the annotation type can
be inherited from the super class
5) @Repeatable: repeatable annotation indicates that the marked
annotation can be applied more than once to the same declaration
or type use.
1.9 METHOD PARAMETER REFLECTION
Method contains executable code which may be invoked, once you
called method. By default, .class file generated after compilation does not
store formal parameter names of any method or constructor. Method
Parameter Reflection provides you feature in which you can able to store
names of formal parameters. The java.lang.reflect package provides you
all classes required for method parameter reflection. Method and
Parameter class are main ly used to store and read formal parameter.
Method class:
The java.lang.reflect.Method class provides APIs to access
information about a method’s modifiers, return type, parameter,
annotations and thrown exception. It is also used to invoked methods.
Reflected method can be a class method or instance method.
Method Class Methods
Method Description
int getModifiers() Returns java language modifiers for the
executable represented by objects.
String getName() Return the name of the method
represented by this method object.
Annotation[][]
getParameterAnnotations() It returns array of array of annotations
that represents the annotations of the
formal parameter, in declaration order,
of the executable represented by object.
Class>getReturnType() It returns a class object that represents
the formal return type of the method
represented by this Method Object munotes.in
Page 16
16 int getParameterCount() Returns a number of formal parameters
for the executable represented by this
object.
Class>[]
getParameterTypes() Returns an array of Class objects that
represents the formal parameter types, in
declaration order, of the executable
represented by object.
Parameter Class:
It is used to obtain information about method parameters, including
its name, and modifier. To store formal parameter names in a particular
.class file, and thus enable the reflection API to retrieve formal parameter
names, compile the source file with the -parameters option to the javac
compiler.
Parameter Class Methods:
Method Description
int getModifiers() Get the modifier flags for the parameter
represented by this parameter object.
String getName() Return the name of the parameter.
Type
getParameterizedType() Return a type object that identifies the
parameterized type for the parameter
represented by this parameter object.
Class>getType() Return a class object that identifies the
declared type for the parameter represented
by this parameter object.
booleanisNamePresent() Return true if the parameter has a name
according to class file.
booleanisImplicit() Return true if this parameter is implicitly
declared in source code.
booleanisSynthetic() Return true is this parameter is neither
implicitly nor explicitly declared in source
code.
Program:
Calculate.java
public class Calculate
{
int add(int a, int b, int c)
{
return (a+b+c);
}
int sub(int a, int b)
{ munotes.in
Page 17
17 return (a -b);
}
}
Compile this class with following command:
javac -parameters Calculate.java
MethodReflection.java
import java.lang.reflect.*;
public class MethodReflection
{
public static void main(String arg[])
{
Calculate c = new Calculate();
Class obj1 = c.getClass(); //creating instance of Class
// returns array of methods from calculate class
Method[] m1 = obj1.getDeclaredMethods();
for(Method m2 :m1)
{
System.out.print(m2.getName()); //returns name of method
Parameter p[] = m2.getParameters(); // returns parameter
od each method
for(Parameter p2: p)
{
System.out.print(" " + p2.getParameterizedType());
System.ou t.print(" " +p2.getName());
}
System.out.println();
System.out.println(" no of parameter : " +
m2.getParameterCount());
System.out.println(" Return Type : " +
m2.getReturnType());
}
}
}
Command to compile and execute the program
Compile: javac MethodReflection.java
Execute: java MethodReflection
munotes.in
Page 18
18 1.10 SETTING THE PATH ENVIRONMENT VARIABLE
The Path is the system variable that your operating system uses to
locate needed executables from the command line. If you have saved your
java file in JDK/bin directory, the path is not required to be set. If you
save your java files in other directory then you need to set path of JDK.
There are two ways to set the JDK path:
1) Temporary: It will be valid till your command prompt is open.
Steps to s et temporary path of JDK:
Open the command prompt.
Copy the path of JDK/bin Directory
Write the command in command prompt: set path = copied_path
Example: Set path=” C: \Program Files \Java \jdk1.8.0_261 \bin”
2) Permanent:
Steps to set Permanent path of JDK in Windows 10 and Windows 8:
1) Open My Computer properties.
2) Click on Advanced System Setting
3) Click on Environment Variable options.
4) In system variable section, click on new option.
5) Specify variable name as Path and in place of variable value specify
path of java bin folder, then click OK.
1.11 JAVA COMPILER AND INTERPRETER
Java program execution is a two -step process i.e., Compilation and
interpretation.
Java Compiler: Compiler Translate the source code written by
programmer into byte code. The bytecode generated after compilationis
save with .class file extension. File name is same as a class name.
Compiler also responsible to check source code for errors. It cannot f ix
errors if present in program; it generates error message and programmer
have to solve that all errors. If your program is having no errors then
compiler convert it into byte code.
Java Interpreter:
Java Interpreter is a computer program, which impleme nts the
JVM specification and helps to actually execute the java bytecode. After
compilation compiler generates bytecode (.class file), interpreter takes this munotes.in
Page 19
19 byte code and translate it into machine code. Then interpreter executes
instruction available in machine code line by line.
1.12 JAVA CLASS FILE
Java class file contains bytecode. It is saved with .class extension.
This file automatically gets generated after successful compilation of the
program. It has a same name as the class name. This file is execu ted on
Java Virtual Machine. If your java program contains more than one class,
then in such cases after compilation we get same number of .class files as
the number of classes present in java program. It is saved in same
directory where your java file is stored.
1.13 JAVA PROGRAMS
Structure of java program:
Java source code file saved with .java extension. Source code
includes one class definition. We can also include multiple classes t single
source code file. Class includes one or more methods. All the me thods
need to be defined inside the class. Within the curly braces of the method,
you can write instructions that method should be performed. Method
includes collection of statements. Every Java program must have at least
one class and one main method in e ach program.
class Example
{
public static void main(String arg[])
{
System.out.print("we are learning java programming");
}
}
Program should be saved with Example.java file name.
Parameters use in above java program:
class: class is inbuild keyword use to declare class in java. Class keyword
followed with class_name.
public: It is a access specifier which represents the visibility of main
method. Public means accessible everywhere.
static: It is defined keyword in java. If you declared any method as a static
in java, then this method should be called without creating any object of
the class. Main method is executed by JVM, so there is no need to create
any class object to called main method.
void: It is one return type. Void means not returning any value.
munotes.in
Page 20
20 main(): main is starting point of program execution. Java program
execution starts from main method.
String arg[]: It is argument to the method. Main method must be array of
string. This will be use to read command line argument.
System.out.print(): It is used to print statement on output screen. System
is a class, out is an object. Print method is used to print statement.
Java program will be executed on command prompt.
Command used to compile java program:
C:\>javac classname.java
example: javacExample.java
This javac compiler create a file with name Example.class stored
in save location where you have saved java file. It is the byte code version
of original program. This byte code is latter on executed by Java Virtual
Machine.
command use to execute the java program:
c:\>java classname
example: java Example
when you run this program, following output is displayed.
Output:
we are learning java programming
1.14 JAVA APPLICATIONS
There ar e four different types of applications we can developed using
java language.
1) Standalone Application: Standalone Application also called as
desktop application or windows -based application. This kind of
software we need to install on every system where you w ant to use
that software. Examples of standalone applications are office suite,
media player and all other programming software like turbo++
compiler, python etc. AWT and SWING in java used to developed
standalone applications.
2) Web Application: Like standalone applications which need to be
install on machine, Web Applications we can be access through
internet. It is installed on the server and users can used it through
internet. Currently, Servlet, JSP, Struts Framework, Spring
Framework, Hibern ate Framework etc.
3) Enterprise Application: An Application that is distributed in
nature are called as enterprise application. Examples of enterprise
applications are banking application, Skype, call center and
customer support application, Health Informat ion Management
system etc. Technologies used to develop Enterprise Application munotes.in
Page 21
21 include Java Persistence API, Java Transaction API, Java
Enterprise Bean, Java Mail etc.
4) Mobile Application: An Applications which is created for mobile
devices are called as Mo bile Application. It will work only on
smart phones.
1.15 WHITESPACE AND CASE SENSITIVITY
Whitespace: Java is free form language. There is no need to follow any
special indentation while writing program like you are doing in python
programming language. This means you can write entire java program in
one line. Whitespace in java includes a space, tab and new line.
Case Sensitivity: Java is case sensitive language. In java program add
variable will be different from ADD variable. If you are using some
inbuild methods in program then it needs to use in same defined format.
Example: int add;
int ADD;
Both will be considered as completely different variables.
1.16 IDENTIFIERS AND KEYWORDS
Identifiers: Identifier is a sequence of one or more characters. Identifiers
are used to name things, like variables, methods and classes. An Identifier
is descriptive sequence of uppercase and lowercase letters, numbers, and
underscore sign and dollar -sign.
Rules for defining Identifiers:
You can use combination uppercase and lower -case letters, numbers,
dollar -sign and underscore sign for creating variable name. No other
special characters are allowed to use while creating identifiers.
Identifier name must not be sta rt with digit. Example “111add” will
not be consider as valid identifier.
Identifiers are case sensitive.
Identifier name should be start with either alphabet, underscore sign or
dollar -sign.
Inbuild keywords in java cannot be used as an identifiers.
Exam ple: varaible1, $add, _test2;
This allare the valid identifiers in java language.
Example: 1test, lower -case, ok/cancel;
This all are invalid identifiers in java. Wecannot able to use dash
or any other special character while creating identifiers. munotes.in
Page 22
22 Keywords: Keywords are the reserved words in java. Keywords cannot be
used as identifiers, means you cannot use it as variable name, method
name and class name. The keywords const and goto are reserved but
currently not in use. The keyword strictfp is adde d in JDK 1.2 version.
The keyword assert is added in JDK 1.4 version. Enum keyword is added
in JDK 5.0.
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
Java reserved other four names like null, true, false and var. you may not
use these words as variable, class and method name.
Example: class Example2
{
public static void main(String arg[])
{
int x=10;
int y=20;
int z= x+y;
System.out.print("Addition:" + z);
}
}
Output:
Addition: 30
In this example, Example2, arg, x,y and z are called as identifiers
which are user defined.
Class, public, static, void, main, String is called as keywords which
are predefined in java.
1.17 COMMENTS
Comments are statements in java which are not executed by java
compiler and interpreter. Comments are used to make the program more
readable by adding details of the code. You can add small description
about your program in comments section. You can use comments to
provide description about variab le, methods, class and any other
statement. munotes.in
Page 23
23 There are three types of comments in java:
1) Single Line Comment: Single Line comment is use to add single
line description for your code. It is easy to use. Single Line comment start
with two forwordslashes (//). Any statement written in front of this slash is
not executed by compiler.
Syntax: // this is single line comment
2) Multi Line Comment: Multi Line comment is use to comment
multiple lines of code. It is mostly used to provide explanation about
particular m ethod or your program. Multi line comments start with /* and
ends with */. The statements written inside these comments are ignore by
the compiler and interpreter.
Syntax: /* This is multiline comment
This part is not executed.
This will be used to provide description about the program.
*/
Example: class Comment Example
{
public static void main(String arg[])
{
/* In this example, we will learn how to create variables and
How to display value of variable on output screen. */
double a =4.6755; // we have created variable here
System.out.print("Variable a:" + a);
}
}
3) Documentation Comment: This type of comment is used
produced an HTML file that documents your program. These comments
are usually used to write a code for project or software application, since it
helps to generate documentation page for reference, which can be used for
getting information about present methods, classes and arguments etc.
Documentation comments start with /** and ends with */.
Syntax:
/** Comment start
*You can used various tag to specify a parameters or method or heading
*we can use various HTML tags here.
*
*/ munotes.in
Page 24
24
1.18 BRACES AND CODE BLOCK
Curly Braces {}: Used to defined values of during array initialization. It is
also used to defined block of code for classes, interface. Method and
constructor bodies also enclosed in curly braces. Braces are used to group
statements in an if statement, a loop and other c ontrol statements.
Example: class Example3
{
//statements
}
Brackets []: It is used to declare array type. It is also used to access
individual elements from array list. And dereferencing array values.
Parentheses (): It is used to declare method an d constructor. It is used to
provide parameters in method definition and invocation. It is also used to
defined order of operation in expression.
1.19 VARIABLES AND VARIABLE NAME
Variable is the basic unit of storage in java program. It is like a
container which holds value while java program is executed. A variable is
the name given to a memory location. A variable is assigned with data
type. A value stored in variable can be changed during program execution.
A variable can be defined b y the combination of an identifier, a type and
an option initializer. All the variables have a scope, which defines their
visibility and the lifetime.
Syntax for Variable Declaration:
Type identifier; // variable declaration only
Type identifier = valu e; // variable with initialization
Here, type defines what type of data is stored in this variable. It defines
data type of variable. Identifier is the name of the variable. You can
initialize variable by assigning equal sign after name of variable.
Few Examples of variable declaration:
int a, b, c; // declaring three int variables
int d=3, e; // declaring two int variable and initializing one int variable d
double d=3.14; // declaring and initializing double variable
char c=’a’; //declaring and initia lizing char variable
There are three types of variables you can create in java.
1) Local variable: The variable declare inside the body of method or
constructor is called local variable. Scope of local variable exists only
within the block where it is decla red. We can access variable only munotes.in
Page 25
25 within same block. You cannot able to use local variable outside of
that method.
2) Instance Variable: Variable which is declare inside the class and
outside the method is called as instance variable. Instance variables are
created when an object of class is created and destroyed when object
get destroyed. Value of instance variable is instance specific. You can
use access specifier to defined scope of instance variable. According to
defined access specifier visibility and lifet ime of this variable get
changed.
3) Static Variable: A variable that is declared with static keyword is
called static variable. This variable is also declared inside the class.
For static variable, memory allocated only once when class is loaded
in the me mory. Like instance variable static variable is not instance
specific. Static variable is created when you want to share same value
among all objects of the class. Means Value of static variable is similar
for all objects of class.
Programs:
1) Write a java program to find out area of triangle.
class Triangle
{
public static void main(String arg[])
{
Double pi= 3.14, r = 3, area;
area = 3.14*r*r;
System.out.print("Area of Triangle" + area);
}
}
Output:
Area of Triangle: 28.26
2) Program to calculate simple Interest
public class SimpleInterest
{
public static void main(String args[])
{
float p =2000, r = 6, t =3, sinterest;
//simple interest formula (principal* rate of interest * time
period)/100
sinterest = (p * r * t) / 100;
System.out.print("Simple Interest is: " +sinterest);
}
} munotes.in
Page 26
26 Output:
Simple Interest is: 360.0
1.20 SUMMARY
In this chapter, we learn introduction to java language, features of
java, Java virtual machine, Java Runtime Environment, Java Development
Kit, Lambda Expression, Method References, Writing and executing java
programs, identifiers, keywords, java API and variables with examples.
1.21 LIST OF REFERENCES
Java, A Beginner’s Guide, Eighth Edition, Herbert Schildt, McGraw Hill
Publisher
Java: The Complete Refe rence, Eleventh Edition, Herbert Schildt,
McGraw Hill Publisher
1.22 BIBLIOGRAPHY
https://www.javatpoint.com/java -tutorial
https://www.geeksforgeeks.org/java
https://www.beginnersbook.com/java -tutorial -for-beginners -with-
examples/
http://www.programiz.com/java -programmi ng/
https://docs.oracle.com/javase/tutorial/
1.23 MODEL QUESTIONS
1) Which component is used to compile, debug and execute java program?
a) JVM
b) JRE
c) JDK
d) JIT
2) Which component is responsible for converting bytecode into machine
specific code?
a) JVM
b) JRE
c) JDK
d) JIT
3) What is extension of java byte code?
a) .txt
b) .class
c) .java
d) .js munotes.in
Page 27
27
4) JRE stand for?
a) Java Runnable Environment
b) Java Runtime Environment
c) Java Runtime Extension
d) None of the above
5) ____ are the reserved words in java?
a) Keywords
b) Variables
c) Identifiers
d) All of the above
6) _____ is a sequence of one and more characters?
a) Identifiers
b) Keywords
c) Variables
d) Literals
munotes.in
Page 28
28
2
DATA TYPES
Unit Structure
2.0 Objective
2.1 Introduction
2.2 Primitive Data Types
2.3 Object Reference Types
2.4 Strings
2.5 Auto Boxing and Unboxing
2.6 Operators and Properties of Operators
2.6.1 Arithmetic Operators
2.6.2 Assignment Operators
2.6.3 Increment and Decrement Operators
2.6.4 Relational Operators
2.6.5 Logical Operators
2.6.6 Bitwise Operators
2.6.7 Conditional Operator
2.7 Summary
2.8 List of References
2.9 Bibliography
2.10 Model Questions
2.0 OBJECTIVE
In this chapter, you will be going to learn following topics:
Primitive data types supported in java.
Creating string in java using String class and diffe rent methods of
string class.
How to convert primitive type to object type.
Use of different types operators available in java.
2.1 INTRODUCTION
Data types and Operator are the main fundamental elements of java
Programming. In this chapter we will learn different data types supported munotes.in
Page 29
29 in java language. Java is strongly type language, which means that you
must need to declare variable before they can be used. This declaration
includes variable’s type and name. Data types defines type of value stored
in variable.
Another concept we will going to learn in this chapter is operators
and types of operators supported in java. Java provide a rich set of
operators. Java supports all basic operators and some additional operators
for handing special condition.
2.2 PRIMITIVE DATA TYPES
Data Types: When you define a variable in java, you must need to defined
what kind of value that variable will stored. This wi ll be defined with the
help of data types. Based on this information compiler will decide how
much space to allocate in the memory for the variable.
Java programming language defines eight primitive data types: byte,
short. int, float, double, char, bool ean. A primitive type is predefined in
java language. Primitive types are the most basic data types available in
java. Size of these primitive data type is fixed; it does change from one
operating system to another. This primitive type can be placed into f our
group.
Integers: This group includes byte, short, int and long, which represents
whole numbers. All these integers support signed, positive and negative
values.
Floating - point numbers: This group include float and double data type,
which represents numbers with fractional value. Floating point numbers
are used when evaluating expression that require fractional precision.
Character: this group include char data type.
Boolean: This group include Boolean data type, which includes binary
value like true/false.
Data Type Size Default value
byte 1 byte 0
short 2 byte 0
int 4 byte 0
long 8 byte 0
float 4 byte 0.0f
double 8 byte 0.0d
char 2 byte \u0000 munotes.in
Page 30
30 boolean 1 bit false
Fig. Primitive Data Types
byte:
It is a smallest integer type. The Byte data type is 8 bits (1 byte)
signed two’s complement integer. It has value range lies between -128 to
127. Its default value is zero.
Syntax of declaring byte variable:
byte variable1 ;
short:
It is a signed 16 bits (2 byte) two’s complement integer. It has value
range lies between -32,768 to 32,767. Its default value is zero.
Syntax:
short t, s;
int:
The int data type is 32 bits (4 bytes) signed two’s complement
integer. It has the value range lies between - (2 31)to (231 -1). Its default
value is zero. It is most commonly used data type.
Syntax:
int a, b;
int c=2;
long:
The long data type is 64 bits (8 byte) signed two’s complement
integer. It has value range lies between – (263) to (263-1). Its default value
is zero.
Example:
class DataTypesExample1
{
public static void main(String arg[])
{
byte b = -100;
short num = 150;
int a = 1;
long l = 4562455555555L;
System.out.println("Byte Value :" + b);
System.out.prin tln("Integer Value:" + a );
System.out.println(" Int value: " + a );
System.out.println("Long value: " + l );
}
}
Output:
Byte Value : -100
Integer Value:1
Int value: 1 munotes.in
Page 31
31 Long value: 4562455555555
float:
The float data type is single precision 32 bits (4 byte) floating point.
It is useful for storing smaller precision but not suited for large degree of
precision. Its default value is 0.0f.
Syntax:
Float f = 3.14f, a;
double :
The double data type is double precision 64 bits (8 byte) floating
point. I t is useful for storing floating point values with large precision. Its
default value is 0.0d.
Syntax:
double d = 45.78521457;
char:
The char is 16 bits (2 byte) Unicode character. It has the value range
lie between 0 to 65,535. This data type is used to stored characters.
Unicode defines a fully international character set that can represents
all of the characters that are available in all human languages. Its default
value is ‘ \u0000’.
Syntax:
char c = ‘g’;
Boolean:
The Boolean data type is used to stored logical value. It stores only
two possible values: true and false. It represents only one bit of
information. Values of Boolean variable can not be converted into any
other type. Its default value is false.
Example:
class Da taTypesExample2
{
public static void main(String arg[])
{
float f = 22.14f;
double d = 12.11122452;
char c='g';
boolean flag = true;
System.out.println("float value:" + f);
System.out.println("double value:" +d);
System.out.println("Char value:"+ c);
System.out.println("boolean value:"+ flag);
} munotes.in
Page 32
32 }
Output:
float value:22.14
double value:12.11122452
Char value:g
booleanvalue:true
2.3 OBJECT REFERENCE TYPES
In java, not - primitive data type is also known as object reference
type. Java object refer ence type holds the references of dynamically
created class objects and provide a means to access those objects stored in
memory. For example, if you have created class Example and you have
created its object d, then d is called as object reference type. All the
reference types are subclass of type java.lang.Object. Object reference
type includes class, Annotation, Array, Enumeration and Interface. Like
primitive data type it is not predefined.
Reference
Type Description
Class Class is a collection of objects. You can create multiple
objects of class.
Annotation It provides a way to associate metadate with program
elements.
Array It provides a data structure that stores the elements of
similar type.
Enumeration A reference to a set of objects that re presents a related
set of choices.
Interface It is implemented by java classes. interface provides you
collection of abstract methods.
Fig. Object Reference Types
2.4 STRINGS
Java String is an object that represents a sequence of characters.
String class is used to create string object in java. It is defined in java.lang
package. Java string is immutable. Once string is created, you cannot able
to change its value.
There are two ways to create string in java:
1) Using String Literal
Examples: String name = “Amit”;
String address = “thane”;
munotes.in
Page 33
33 2) Using new keyword
Examples: String s1 = new String(“Welcome”);
String s2 = new String(“we are learning java programming”);
Program:
class StringExample
{
public static void main(String arg[])
{
//creating string using string literal
String name = "Kunal";
System.out.println("Name: " + name);
//creating string using new keyword
String s = new String("java is easy to learn ");
System.out.println(s);
}
}
Output:
Name: Kunal
Java is easy to learn
String class also provides you lots of methods to perform different
operations on string.
List of Methods:
Method Description
toUpperCase(String str) Convert the given string in uppercase.
toLowerCase(String str) Convert the given string in lowercase.
startWith(String prefix) Test if given string starts with specified
prefix. True or false result.
endsWith(String Suffix) Test if given string ends with specified
suffix . Return true or false result.
charAt(int index) Return the character value for specified
index number.
length() Return the length of this string.
substring(int beginindex) Return new string that is substring of the
given string.
replace() Used to replace all the occurrences of old
char in this string with new char.
contains(CharSequence s) Return true or false after matching specified munotes.in
Page 34
34 character sequence in given string.
indexOf(int ch) Return the index value of specified char.
equals(String str) Compares the given string with this
specified string. Return true or false result.
trim() Use to remove leading and trailing
whitespaces in this string.
valueOf(int value)
valueOf(float value)
valueOf(double value)
valueOf(long value) Used to convert gi ven type to string.
concat(String str) Concatenates specified string at the end of
this string.
Example:
class StringMethods
{
public static void main(String arg[])
{
String s="java programming";
String s1= " PYTHON";
System.out.pr intln("Upper Case : " + s.toUpperCase());
System.out.println("Lowercase : " +s1.toLowerCase());
System.out.println("Trim : " + s.trim());
System.out.println( "Start With : " + s.startsWith("Sa"));
System.out.println("Ends with: " + s.endsWith("g "));
System.out.println("Char at: " + s.charAt(3));
System.out.println( "length: " + s.length());
System.out.println("substring : " +s.substring(2,4));
String r=s.replace("java","python");
System.out.println(r);
System.out.println("Contains: " + r.contains("java"));
int index1=s.indexOf("a");
System.out.println("Index OF : " + index1);
int index2=s.lastIndexOf('g');
System.out.println("last Index of: " + index1);
String str1 = "Hello";
String str2 = "Javatpoint";
// Concatenating one string munotes.in
Page 35
35 String str4 = str1.concat("javatpoint");
System.out.println(str4);
}
}
Output:
Upper Case : JAVA PROGRAMMING
Lowercase : python
Trim : java programming
Start With : false
Ends with: true
Char at: a
length: 16
substring :va
python programming
Contains: false
Index OF : 1
last Index of: 1
Hellojavatpoint
2.5 AUTOBOXING AND UNBOXING
Autoboxing:
The Automatic conversion of primitive type into its corresponding
wrapper class type is called Autoboxing. For example, converting an int to
an Integer. Converting an float to Float type.
Unboxing:
The automatic conversion of object of wrapper type into its
corresponding primitive type is called as unboxing. For example,
converting Integer object into int type, Double object into double type.
List of primitive type and their corresponding wrapper type:
Primitive Type (Data Types) Wrapper Type (Classes)
byte Byte
short Short
int Int
long Long
float Float
double Double
char Char
boolean Boolean
munotes.in
Page 36
36
Example:
class AutoboxingEx
{
public static void main(String arg[])
{
int a=20;
Integer n1 = new Integer(a); // autoboxing
Integer n2 = a; //autoboxing
System.out.println("n1 : " +n1);
System.out.println( "n2: " + n2);
Integer n3 = new Integer(50); //unboxing
int b = n3;
System.out.print("b: " +b);
}
}
Output:
n1 : 20
n2: 20
b: 50
2.6 OPERATORS AND PROPERTIES OF OPERATORS
Operators are used to performed some mathematical and logical
operations. Java provides a rich set of operators. All basic operators are
classified into four types; relational, arithmetic, logical and bitwise. It also
provides you some additional operators like conditional operator,
assignment operator and increment and decrement operator.
2.6.1 Arithmetic Operators
Arithmetic operators are used to perform operations like addition,
subtraction, multiplication and division. These are the basic mathematical
operator.
List of arithmetic operators:
Operators Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus division
munotes.in
Page 37
37
Example:
class ArithmeticOperator
{
public static void main(String arg[])
{
double a=20, b=4;
System.out.println("Addition: " + (a+b));
System.out.println("Subtraction: " + (a -b));
System.out.println("Multiplication: " + (a*b));
System.out.println("Division: " + (a/b));
System.out.println("Modulus: " + (a%b));
}
}
Output:
Addition: 24.0
Subtraction: 16.0
Multiplication: 80.0
Division: 5.0
Modulus: 0.0
2.6.2 Assignment Operators
Assignment operator is one of the most common operators; you are
using in java program. It is used to assign value on its right to the operand
(variable) on its left.
Symbol: =
Example: int a = 4;
double d = 3.2;
Compound Assignment Operators:
Operat or Description
+= Addition Assignment: It work by adding the current value
of the variable on left to the value on the right and then
assign result to the operand on the left.
-= Subtraction Assignment: It work by subtracting the
current value of the variable on left to the value on the right
and then assign result to the operand on the left. munotes.in
Page 38
38 /= Division Assignment: It work by dividing the current value
of the variable on left to the value on the right and then
assign result to the operand on the left.
*= Multiplication Assignment: It work by multiplying the
current value of the variable on left to the value on the r ight
and then assign result to the operand on the left.
%= Modulus Assignment: It work by dividing the current
value of the variable on left to the value on the right and
then assign remainder to the operand on the left.
Program:
class AssignmentOperator
{
public static void main(String arg[])
{
int num = 60; // simple asignment operator
double a=20, b=30;
a += 10; // it is similar to the expression a= a+10
b -= 5; // it is similar to b= b -5;
System.out.println(" As signment operator: " + num);
System.out.println("Addition Assignment: " + a);
System.out.println("Subtraction Assignment: " + b);
}
}
Output:
Assignment operator: 60
Addition Assignment: 30.0
Subtraction Assignment: 25.0
2.6.3 Increment and Decrement Operators
Increment operator is used to increase value of operand by one.
Decrement operator is used to decrease value of operand by one. Both
operators required only one operand.These operators can be used in either
prefix and pos tfix form. In prefix form, the operand is incremented and
decremented before the value is obtain for used in the expression. In
postfix form, the operand is incremented and decremented after the value
is obtain for used in the expression.
Operator Descrip tion
++ Increment Operator
-- Decrement Operator
munotes.in
Page 39
39 Program:
class Operator
{
public static void main(String arg[])
{
int num1 = 20, num2 = 10;
System.out.println(num1++); // num1++ is post -increment
System.out.println(++num1); // ++num1is pri -increment
System.out.println(num2 --); //it is post -decrement
System.out.println( --num2); // it is pri -decrement
}
}
Output:
20
22
10
18
Relational Operators
Relational operators are used to determine relationship between two
variables, like value of one operand is greater then, equal to or less than
another operand. The relational operator generates true and false result.
Operator Description
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than and equal to
<= Less than and equal to
Fig. Relational Operators
Program:
class Relationaloperator
{
public static void main(String arg[])
{
int a=10, b=30, c=20;
System.out.println("a System.out.println("a>b :" + (a>b));
System.out.println("a==b :" +(a==b));
System.out.println(" a!=b : " + (a!=b));
}
} munotes.in
Page 40
40 Output:
aa>b :false
a==b :false
a!=b : true
2.6.4 Logical Operators
Logical operators are used to perform logical AND, OR and NOT
operation. Its function is similar to AND gate, OR gate and NOT gate in
digital electronics. Logical AND gate return true result if both the
expressions are true. Logical OR gate return true result if either one
expression is true. Logical Not r eturn true if expression is false and vice
versa.
Operator Description
&& Logical AND
|| Logical OR
! Logical NOT
Fig. Logical Operators
Program:
class LogicalOperator
{
public static void main(String arg[])
{
int a=10, b=30, c=20;
System.out.println("Logical AND: " + (a System.out.println("Logical OR: " + (a>c || a System.out.println("Logical OR: " + (a>c && a System.out.print("Logical NOT:" + !(a>b));
}
}
Output:
Logical AND: true
Logical OR: true
Logical OR: false
Logical NOT:true
munotes.in
Page 41
41 2.6.5 Bitwise Operators
Bitwise operators operate on binary value. It returns result by
performing manipulation on individual bit of a number. In Bitwise OR
operation, it performs bit by bit OR operation of input value and it return 1
if either of the bits is 1 otherwise it returns 0.
In bitwise AND operation, it performs bit by bit AND operation of
input value and it return 0 if either of the bits is 0 otherwise it returns 1.
In bitwise XOR operation, it performs bit by bit XOR operation of
input value and it return 1 if corresponding bits different, else it gives zero
if bits are same. Bitwise Complement operator returns one’s complement
of input value.
Operator Description
& Bitwise AND
| Bitwise inclusive OR
^ Bitwise Exclusive OR
~ Bitwise Complement
Program:
class BitwiseOperator
{
public static void main(String arg[])
{
int a=5, b=12;
System.out.println("Bitwise AND: " + (a&b) );
System.out.println("Bitwise Inclusive OR: " + (a|b) );
System.out.println(" Bitwise Exclusive OR: " + (a^b));
System.out.print("Bitwise Complement:" + (~a));
}
}
Output:
Bitwise AND: 4
Bitwise Inclusive OR: 13
Bitwise Exclusive OR: 9
Bitwise Complement: -6
munotes.in
Page 42
42 2.6.6 Conditional Operator
Operator Description
&& Logical or Conditional AND
|| Logical or Conditional OR
?: Ternary operator
Ternary operator is similar to If -then-else statement in java. A
ternary operator evaluates the test condition and execute the block of code
based on result of the condition.
Syntax: condition ? expression1 : expression2
It first checks the test condition and execute expression1 if
condition is true, else it execute expression2.
Program:
class TernaryOperator
{
public static void main(String args[])
{
int marks=40;
String result = (marks>40) ? "PASS" : "FAIL";
System.out.print(result);
}
}
Output:
FAIL
2.7 SUMMARY
In this chapter, we learn primitive data types, object reference types,
creating string in java and different methods of string clas s, converting
primitive date type to object type and vice -versa, operators and their
different types.
2.8 LIST OF REFERENCES
Java, A Beginner’s Guide, Eighth Edition, Herbert Schildt, McGraw Hill
Publisher
Java: The Complete Reference, Eleventh Edition, Herbert Schildt,
McGraw Hill Publisher munotes.in
Page 43
43 2.9 BIBLIOGRAPHY
https://www.javatpoint.com/java -tutorial
https://www.geeksforgeeks.org/java
https://www.beginnersbook.com/java -tutorial -for-beginners -with-
examples/
http://www.programiz.com/java -programming/
https://docs.oracle.com/javase/tutorial/
2.10 MODEL QUESTIONS
1) How many primitive types are there in java?
a) 5
b) 6
c) 7
d) 8
2) Size of int type in java?
a) 8 bit
b) b) 4 bit
c) 16 bit
d) d) 32 bit
3) The smallest integer type is ___ and its size is ___ bits.
a) short, 16
b) byte, 16
c) short, 8
d) byte, 8
4) which of the following is a symbol of assignment operator?
a) ==
b) =
c) !
d) ~
5) Size of double data type in java?
a) 4 byte
b) 8 byte
c) 2 byte
d) 1 byte
6) What is the range of byte data type in java?
a) - 128 to 127
b) -128 to 128
c) -127 to 128
d) -127 to 127
munotes.in
Page 44
44 7) Increment operator increases value of operand by which value?
a) 2
b) 3
c) 1
d) 4
8) Which of the following is not conditional operator?
a) &&
b) ||
c) ?:
d) ~
9) What is the size of short data type in java?
a) -128 to 127
b) -32768 to 32767
c) – (231) to (231-1)
d) None of this
10) In java, byte, short, int and long all of these are ____ integers.
a) Signed
b) Unsigned
c) Both of the above
d) None of the above
munotes.in
Page 45
45Unit II
3
CONTROL STATEMENTS
Unit Structure
3.1 Introduction
3.2 Java Control Statements
3.2.1. Decision -Making statements
3.2.2. If Statement
3.2.3. if -else statement
3.2.4.if -else-if ladder
3.2.5. Nested if -statement
3.3. Switch Statement
3.4.Jump Statements
3.4.1. Java for loop
3.4.2. Java for -each loop
3.4.3. Java while loop
3.4.4. Java do -while loop
3.4.5. Jump Statements
3.4.5.1. Java break statement
3.4.5.2. Java continue statement
3.5. Summary
3.6. List of References
3.7. Questions
3.1. INTRODUCTION
Java compiler executes the code through and through. The
assertions in the code are executed by the request where they show up.
Nonetheless, Java gives proclamations that can be utilized to control the
progression of Java code. Such proc lamations are called control stream
explanations. It is one of the crucial components of Java, which gives a
smooth progression of program.
3.2. JAVA CONTROL STATEMENTS
In Java, program is a bunch of articulations and which are executed
consecutively all together in which they show up. In that assertions, somemunotes.in
Page 46
46estimation have need of executing for certain conditions and for that we
need to give control to that assertions. All in all, Control explanations are
utilized to furnish the progression of execu tion with condition. In this unit,
we will gain proficiency with the control structure exhaustively. Java
provides three types of control flow statements.
Decision Making statements
if statements
switch statement
Loop statements
do while loop
while loop
for loop
for-each loop
Jump statements
break statement
continue statement
3.2.1. Decision -Making statements:
As the name recommends, dynamic proclamations choose which
articulation to execute and when. Dynamic articulations assess the
Boolean articulation and control the program stream contingent on the
consequence of the condition gave. There are two sorts of dynamic
explanations in Java, i.e., If articulation and switch proclamation.
3.2.2. If Statement
In Java, the "if" articulation is util ized to assess a condition. The
control of the program is redirected relying on the particular condition.
The state of the If articulation gives a Boolean worth, either obvious or
bogus. In Java, there are four kinds of if -proclamations given underneath.
Simple if statement
if-else statement
if-else-if ladder
Nested if -statement
Let's understand the if -statements one by one.
Simple if statement:
It is the most basic statement among all control flow statements in
Java. It evaluates a Boolean expression and enables the program to enter a
block of code if the expression evaluates to true.munotes.in
Page 47
47
Syntax of if statement is given below.
if(condition) {
statement 1;//executes when condition istrue
}
Statement -a;
In proclamation block, there might be single explanation or various
articulations. Assuming the condition is valid, articulation square will be
executed. Assuming the condition is bogus, proclamation square will
preclude and articulation a will be executed. Consider the accompanying
model wher ein we have utilized the if articulation in the java code.
1)Student.java
public class Student {
public static void main(String[] args) {
intx=10;
inty=12;
if(x+y >20)
{
System.out.println( "x+yisgreater than 20");
}
}
}
Output:
x + y is greater than 20munotes.in
Page 48
483.2.3. if -else statement
Theif-else statement is an extension to the if -statement, which
uses another block of code, i.e., else block. The else block is executed if
the condition of the if -block is evaluated as false.
Following figure shows the flow of statement.
Syntax:
if(condition) {
statement 1;//executes when condition istrue
}
else{
statement 2;//executes when condition isfalse
}
Statement -a;
If the condition is true then True -statement block will be
executed. If the condition is false then False -statement block will
beexecuted. In both cases the statement -a will always executed.
Consider the following example.
1)Student .java
public class Student {
public static void main(String[] args) {
intx=10;
inty=12;
if(x+y <10)munotes.in
Page 49
49{
System.out.println( "x+yislessthan 10");
}
else{
System.out.println( "x+yisgreater than 20");
}
}
}
Output:
x+ y is greater than 20
2) write a program to check whether the number is divisible by 2 or
not.
import java.io.*;
classdivisorDemo
{
public static void main(String[ ] args)
{
int a =11;
if(a%2==0)
{
System.out.println(a +" is divisible by 2");
}
else
{
System.out.println(a+" is not divisible by 2");
}
}
}
Output:
11 is not divisible by 2
3.2.4. if-else-if ladder
The if -else-if explanation contains the if -articulation followed by
different else -if proclamations. At the end of the day, we can say that it is
the chain of if -else articulations that make a choice tree where the program
might enter in the square of code where the condition is valid. We can
likewise characterize an else explanation toward the finish of the chain.
Syntax of if -else-if statement is given below.
if(condition 1)
{munotes.in
Page 50
50statement 1;//executes when condition 1istrue
}
elseif(condition 2)
{
statement 2;//executes when condition 2istrue
}
else{
statement 2;//executes when alltheconditions arefalse
}
Consider the following example.
1)Student.java
public class Student {
public static void main(String[] args) {
String city="Delhi";
if(city =="Meerut")
{
System.out.println("city ismeerut");
}
elseif(city =="Noida")
{
System.out.println( "city isnoida");
}
elseif(city =="Agra")
{
System.out.println("city isagra");
}
else
{
System.out.println(city);
}
}
}
Output:
Delhi
3.2.5. Nested if -statement
In nested if -statements, the if statement can contain a iforif-
elsestatement inside another if or else -if statement.munotes.in
Page 51
51
Syntax of Nested if -statement is given below.
if(condition 1){
statement 1;//executes when condition 1istrue
if(condition 2){
statement 2;//executes when condition 2istrue
}
else{
statement 2;//executes when condition 2isfalse
}
}
statement 4;
If the condition1 is true then it will be goes for condition2. If the
condition2 is true then statement block1 will be executed otherwise
statement2 will be executed. If the condition1 is false then statement
block3 will be executed. In both cases the statement4 will always
executed.
Consider the following example.
1)Student.java
public class Student {
public static void main(String[] args) {
String address ="Delhi, India" ;
if(address.endsWith( "India" ))
{munotes.in
Page 52
52if(address.contains( "Meerut" ))
{
System.out.println( "Your cityisMeerut" );
}
elseif(address.contains( "Noida" ))
{
System.out.println( "Your cityisNoida" );
}
else
{
System.out.println(address.split( ",")[0]);
}
}
Else
{
System.out.println( "You arenotliving inIndia" );
}
}
}
Output:
Delhi
3.3. SWITCH STATEMENT:
In Java, Switch articulations are like if -else-if explanations. The
switch explanation contains various squares of code called cases and a
solitary case is executed dependent on the variable which is being
exchanged. The switch proclamation is simpler to u se rather than if -else-if
explanations. It likewise improves the intelligibility of the program.
Focuses to be noted with regards to switch proclamation:
The case factors can be int, short, byte, roast, or list. String type is
likewise upheld since rend ition 7 of Java
Cases can't be copy
Default explanation is executed when any of the case doesn't
coordinate with the worth of articulation. It is discretionary.
Break explanation ends the switch block when the condition is fulfilled.
It is discretionary, if not utilized, next case is executed.
While utilizing switch proclamations, we should see that the case
articulation will be of a similar kind as the variable. Nonetheless, it will
likewise be a consistent worth.munotes.in
Page 53
53The syntax to use t he switch statement is given below.
switch (expression){
casevalue1:
statement block1;
break ;
casevalue 2:
statement block 2;
break ;
casevalue 3:
statement block 3;
break ;
.
.
.
casevalueN:
statementN;
break ;
default :
default statement;
}
The condition is byte, short, character or a number. value1,value -
2,value -3,… are steady and is called as marks. Every one of these qualities
be inimitable or special with the assertion. Proclamation block1,
Articulation block2, Explanation block3,..are rundown of explanations
which contain one articulation or more than one proclamations. Case mark
is consistently end with ":" (colon).
Consider the following example t o understand the flow of the
switch statement.
1)Student.java
public class Student implements Cloneable
{
public static void main(String[] args)
{
intnum =2;
switch (num)
{
case0:
System.out.println( "number is0");
break ;munotes.in
Page 54
54case1:
System.out.println( "number is1");
break ;
default :
System.out.println(num);
}
}
}
Output:
2
While utilizing switch articulations, we should see that the case
articulation will be of a similar kind as the variable. Be that as it may, it
will likewise be a steady worth. The switch allows just int, string, and
Enum type factors to be utilized.
Program: write a program for bank account to perform following
operations.
-Check balance
-withdraw amount
-deposit amount
1)For example:
import java.io.*;
classbankac
{
public static void main(String args[]) throws Exception
{
intbal=20000;
intch=Integer.parseInt(args[0]);
System.out.println("Menu");
System.out.println("1:check balance");
System.out.println("2:withdraw amount... plz enter choiceand amount");
System.out.println("3:deposit amount... plz enter choiceand amount");
System.out.println("4:exit");
switch(ch)
{
case 1:
System.out.println("Balance is:"+bal);
break;
case 2:
int w=Integer.parseInt(args[1]);
if(w>bal)munotes.in
Page 55
55{
System.out.println("Not su fficient balance");
}
bal=bal -w;
System.out.println("Balance is"+bal);
break;
case 3:
int d=Integer.parseInt(args[1]);
bal=bal+d;
System.out.println("Balance is"+bal);
break;
default:
break;
}
}
}
Output:
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is:20000
3.4. LOOP STATEMENTS
In programming, now and again we need to execute the square of
code more than once while some condition assesses to valid. Be that as it
may, circle explanations are utilized to execute the arrangement of
guidelines in a rehashed request. The execution of the arrangement of
directions relies on a specific condition.
In Java, we have three kinds of circles that execute also.
Notwithstanding, there are contrasts in their grammar and condition really
looking at time.
for loop
while loop
do-while loop
Let's u nderstand the loop statements one by one.munotes.in
Page 56
563.4.1. Java for loop
In Java, for circle is like C and C++. It empowers us to introduce
the circle variable, actually look at the condition, and addition/decrement
in a solitary line of code. We utilize the for circle just when we precisely
know the occasions, we need to execute the square of code.
for(initialization, condition, increment/decrement)
{
//block ofstatements
}
The flow chart for the for -loop is given below.
Consider the following ex ample to understand the proper
functioning of the for loop in java.
1)Calculation.java
public class Calculattion
{
public static void main(String[] args)
{
//TODO Auto -generated method stub
intsum=0;
for(intj=1;j<=10;j++)
{
sum=sum+j;
}
System.out.println( "The sumoffirst10natural numbers is"+sum);
}
}
Output:
The sum of first 10 natural numbers is 55
3.4.2. Java for -each loop
Java gives an improved to circle to navigate the information
structures like exhibit or assortment. In the for -each circle, we don't havemunotes.in
Page 57
57to refresh the circle variable. The linguistic structure to utilize the for -each
circle in java is given beneath.
for(data_type var:array_name/collection_name)
{
//statements
}
Consider the following example to understand the functioning of the for -
each loop in Java.
1)Calculation.java
public class Calculation
{
public static void main(String[] args)
{
//TODO Auto -generated method stub
String[] names ={"Java" ,"C","C++" ,"Python" ,"JavaScript" };
System.out.println( "Printing thecontent ofthearray names: \n");
for(String name:names)
{
System.out.println(name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
3.4.3. Java while loop
The while circle is likewise used to emphasize over the quantity of
explanations on numerous occasions. Notwithstanding, in the event that
we don't have the foggiest idea about the quantity of emphasess ahead of
time, it is prescribed to utilize some time circle. Not at all like for circle,
the instatement and addition/decrement doesn't occur inside the circle
proclamation in while circle.
It is otherwise called the passage controlled circle since the
condition is checked toward the beginning of the circl e. On the off chance
that the condition is valid, the circle body will be executed; any other way,
the assertions after the circle will be executed.munotes.in
Page 58
58The grammar of the while circle is given underneath.
while (condition)
{
//looping statements
}
The flow chart for the while loop is given in the following image.
Consider the following example.
Calculation .java
public class Calculation {
public static void main(String[] args) {
//TODO Auto -generated method stub
inti=0;
System.out.println( "Printing thelistoffirst10even numbers \n");
while (i<=10)
{
System.out.println(i);
i=i+2;
}
}
}munotes.in
Page 59
59Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
3.4.4. Java do -while loop
The do -while circle really takes a look at the condition toward the
finish of the circle subsequent to executing the circle explanations. At the
point when the quantity of cycle isn't known and we need to execute the
circle once, we can utilize do -while ci rcle.
It is otherwise called the exit -controlled circle since the condition
isn't checked ahead of time. The sentence structure of the do -while circle
is given beneath.
do
{
//statements
}while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of
the do -while loop in Java.munotes.in
Page 60
601)Calculation.java
public class Calculation
{
public static void main(String[] args)
{
//TODO Auto -generated method stub
inti=0;
System.out.println("Printing thelistoffirst10even numbers \n");
do
{
System.out.println(i);
i=i+2;
}while (i<=10);
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
3.4.5. Jump Statements
Hop articulations are utilized to move the control of the program to
the particular assertions. At the end of the day, bounce articulations move
the execution control to the next piece of the program. There are two kinds
of hop proclamations in Java, i.e., break and proceed.
3.4.5.1. Java break statement
As the name recommends, the break proclamation is utilized to
break the current progression of the program and move the con trol to the
following assertion outside a circle or switch explanation. Be that as it
may, it breaks just the inward circle on account of the settled circle.
The break articulation can't be utilized autonomously in the Java
program, i.e., it must be comp osed inside the circle or switch explanation.
The break statement example with for loop
Consider the following example in which we have used the break
statement with the for loop.
1)BreakExample.java
public class Break Example
{munotes.in
Page 61
61public static void main(String[] args)
{
//TODO Auto -generated method stub
for(inti=0;i<=10;i++)
{
System.out.println(i);
if(i==6){
break ;
}
}
}
}
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
1)Calculation.java
public class Calculation {
public static void main(String[] args)
{
//TODO Auto -generated method stub
a:
for(inti=0;i<=10;i++) {
b:
for(intj=0;j<=15;j++) {
c:
for(intk=0;k<=20;k++) {
System.out.println(k);
if(k== 5){
break a;
}
}
}
}
}
}munotes.in
Page 62
62Output:
0
1
2
3
4
5
3.4.5.2. Java continue statement
Unlike break statement, the continue statement doesn't break the
loop, whereas, it skips the specific part of the loop and jumps to the next
iteration of the loop immediately.
Consider the following example to understand the functioning of
the continue statement in Java.
public class Continue Example
{
public static void main(String[] args)
{
//TODO Auto -generated method stub
for(inti=0;i<=2;i++) {
for(intj=i;j<=5;j++) {
if(j==4)
{
continue ;
}
System.out.println(j);
}
}
}
}
Output:
0
1
2
3munotes.in
Page 63
635
1
2
3
5
2
3
5
3.5. SUMMARY:
In this Chapter, we covered control flow statement
InDecision -Making statements, we learned if, if -else,if -else-if ladder,
Nested if -statement, Switch Statement
In this chapter we study about Looping statement like for loop, for -
each loop, while loop, do -while loop, also jump statement break
statement, continue statement.
3.6. LIST OF REFERENCES
1. Java 2: The Complete Reference, Fifth Edition, Herbert Schildt, Tata
McGraw Hill.
2. An Introduction to Object oriented Programming with JAVA, C
THOMAS WU3. www.javatpoint.com
3.7. QUESTION
1)What mean by Decision control statement?
2)Explain If Else statement with suitable example.
3)Explain Nested if statement with suitable example.
4)Explain loop control statement
5) What is mean by switch control statement with example.
6) Explain loop control statement with example.
munotes.in
Page 64
64 4
CLASSES
Unit Structure
4.1 Objective
4.2 C lass
4.2.1 Creating “main” in a separate class
4.2.2 Methods with parameters
4.2.3 Methods with a Return Type
4.2.4 Method Overloading
4.2.5 Passing Objects as Parameters
4.2.6 Passing Values to methods and Constructor:
4.2.7 Abstract Classes
4.2.8 Extending the class:
4.3 Summary
4.4 List of reference s
4.5 Questions
4.1 OBJECTIVE
In this lesson of Java Tutorial, you will learn...
How to create class
How to create method
How to create constructor
4.2 CLASS
Definition: A class is a collection of objects of similar type. Once a class
is defined, any number of objects can be produced which belong to that
class.
Class Declaration
classclassname
{
…
ClassBody
…
}
Objects are instances of the Class. Classes and Objects are v ery much
related to each other. Without objects you can't use a class. munotes.in
Page 65
65 A general class declaration:
class name1
{
//public variable declaration
voidmethodname()
{
//body of method…
//Anything
}
}
Now following example shows the use of method.
class Demo
{
privateintx,y,z;
public void input()
{
x=10;
y=15;
}
public void sum()
{
z=x+y;
}
public void print_data()
{
System.out.println(“Answer is =” +z);
}
public static void main(String args[])
{
Demo object=new Demo();
object.input();
object.sum();
object.print_data();
}
}
In program,
Demo object=new Demo();
object.input();
object.sum();
object.print_data();
In the first line we created an object. munotes.in
Page 66
66 The three methods are called by using the dot operator. When we call a
method the code inside its block is executed.
The dot operator is used to call methods or access them.
4.2.1 Creating “main” in a separate class
We can create the main method in a separate class, but during compilation
you need to make sure that you compile the class with the “main”
method.
class Demo
{
privateintx,y,z;
public void input() {
x=10;
y=15;
}
public void sum()
{
z=x+y;
}
public void print_data()
{
System.out.println(“Answer is =” +z);
}
}
classSumDemo
{
public static void main(String args[])
{
Demo object=new Demo();
object.input();
object.sum();
object.print_data();
}
}
Use of dot operator
We can access the variables by using dot operator.
Following program shows the use of dot operator.
classDotDemo
{
intx,y,z; munotes.in
Page 67
67 public void sum(){
z=x+y;
}
public void show(){
System.out.println("The Answer is "+z);
}
}
class Demo1
{
public static void main(String args[]){
DotDemo object=new DotDemo();
DotDemo object2=new DotDemo();
object.x=10;
object.y=15;
object2.x=5;
object2.y=10;
object.sum();
object.show();
object2.sum();
object2.show();
}}
output :
C:\cc>javac Demo1.java
C:\cc>java Demo1
The Answer is 25
The Answer is 15
Instance Variable
All variables are also known as instance variable. This is because
of the fact that each instance or object has its own copy of values for the
variables. Hence other use of the “dot” operator is to initialize the value of
variable for that instance.
4.2.2 Methods with parameters
Following program shows the method with passing parameter.
classprg
{
int n,n2,sum;
public void take(intx,int y)
{
n=x;
n2=y; munotes.in
Page 68
68 }
public void sum()
{
sum=n+n2;
}
public void print()
{
System.out.println("The Sum is"+sum);
}
}
class prg1
{
public static void main(String args[])
{
prgobj=new prg();
obj.take(10,15);
obj.sum();
obj.print();
}
}
4.2.3 Methods with a Return Type
At the point when technique return some worth that is the sort of
that strategy. For Instance: a few techniques are with boundary yet that
strategy didn't return any worth that implies kind of technique is void.
Furthermore, in the event that s trategy return whole number worth, the
sort of technique is a whole number.
Following program shows the method with their return type.
class Demo1
{
int n,n2;
public void take( intx,int y)
{
n=x;
n=y;
}
publicintprocess()
{
return (n+n2);
}
} munotes.in
Page 69
69 Class prg
{
public static void main(String args[])
{
int sum;
Demo1 obj=new Demo1();
obj.take(15,25);
sum=obj.process();
System.out.println("The sum is"+sum);
}
}
Output:
The sum is25
4.2.4 Method Overloading
Method overloading means method name will be same but each
method should be different parameter list.
class prg1
{
int x=5,y=5,z=0;
public void sum()
{
z=x+y;
System.out.println("Sum is "+z);
}
public void sum(inta,int b)
{
x=a;
y=b;
z=x+y;
System.out.println("Sum is "+z);
}
Public intsum(int a)
{
x=a;
z=x+y;
return z;
}
}
class Demo
{ munotes.in
Page 70
70 public static void main(String args[])
{
prg1obj=new prg1();
obj.sum();
obj.sum(10,12);
System.out.println(+obj.sum(15));
}
}
Output:
sum is 10
sum is 22
27
4.2.5 Passing Objects as Parameters
Objects can even be passed as parameters.
class para123
{
int n,n2,sum,mul;
public void take(intx,int y)
{
n=x;
n2=y;
}
public void sum()
{
sum=n+n2;
System.out.println("The Sum is"+sum);
}
public void take2(para123 obj)
{
n=obj.n;
n2=obj.n2;
}
public void multi()
{
mul=n*n2;
System.out.println("Product is"+mul);
}
}
classDemoPara
{ munotes.in
Page 71
71 public static void main(String args[])
{
para123ob=new para123();
ob.take(3,7);
ob.sum();
ob.take2(ob);
ob.multi();
}
}
Output:
C:\cc>javac DemoPara.java
C:\cc>java DemoPara
The Sum is10
Product is21
We have defined a method “take2” that declares an object named
obj as parameter. We have passed ob to our method. The method “take2”
automatically gets 3,7 as values for n and n2.
4.2.6 Passing Values to methods and Constructor:
These are two differ ent ways of supplying values to methods.
Classified under these two titles -
1.Pass by Value
2.Pass by Address or Reference