Svcet: Introduction To Oop and Java Fundamentals
Svcet: Introduction To Oop and Java Fundamentals
Svcet: Introduction To Oop and Java Fundamentals
C# J# Scala
SV
Abstraction
Abstraction is one of the key concepts of object-oriented programming (OOP) languages.
Its main goal is to handle complexity by hiding unnecessary details from the user. This en-
ables the user to implement more complex logic on top of the provided abstraction without
understanding about all the hidden complexity.
For example, people do not think of a car as a set of tens of thousands of individual parts.
They think of it as a well-defined object with its own unique behavior. This abstraction allows
people to use a car to drive to the desired location without worrying about the complexity of
the parts that form the car. They can ignore the details of how the engine, transmission, and
braking systems work. Instead, they are free to utilize the object as a whole.
If we consider the real-world, we can find many objects around us, cars, dogs, humans,
etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.
If we compare the software object with a real-world object, they have very similar char-
acteristics.
Software objects also have a state and a behavior. A software object’s state is stored in
fields and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the
object-to-object communication is done via methods.
Classes in Java
A class is a blueprint from which individual objects are created.
• Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
SV
A class can have any number of methods to access the value of various kinds of methods.
In the above example, barking(), hungry() and sleeping() are methods.
Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse.
• In Java, the basis of encapsulation is the class. There are mechanisms for hiding the
complexity of the implementation inside the class.
• Each method or variable in a class may be marked private or public.
• The public interface of a class represents everything that external users of the class
need to know, or may know.
• The private methods and data can only be accessed by code that is a member of the
class.
• Therefore, any other code that is not a member of the class cannot access a private
method or variable.
• Since the private members of a class may only be accessed by other parts of program
through the class’ public methods, we can ensure that no improper actions take
place.
Inheritance
Inheritance is the process by which one object acquires the properties of another object.
ET
For example, a Dog is part of the classification Mammal, which in turn is part of the Ani-
mal class. Without the use of hierarchies, each object would need to define all of its charac-
C
teristics explicitly. However, by use of inheritance, an object need only define those qualities
that make it unique within its class. It can inherit its general attributes from its parent. Thus,
inheritance makes it possible for one object to be a specific instance of a more general case.
SV
Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface
to be used for a general class of actions. The specific action is determined by the exact nature
of the situation.
For eg, a dog’s sense of smell is polymorphic. If the dog smells a cat, it will bark and run
after it. If the dog smells its food, it will salivate and run to its bowl. The same sense of smell
is at work in both situations. The difference is what is being smelled, that is, the type of data
being operated upon by the dog’s nose.
Consider a stack (which is a last-in, first-out LIFO list). We might have a program that re-
quires three types of stacks. One stack is used for integer values, one for floating-point values,
and one for characters. The algorithm that implements each stack is the same, even though
the data being stored differs.
1.2 OOP Concepts In Java
OOP concepts in Java are the main ideas behind Java’s Object Oriented Programming.
They are:
Object
Any entity that has state and behavior is known as an object. It can be either physical or
logical.
For example: chair, pen, table, keyboard, bike etc.
Class & Instance
Collection of objects of the same kind is called class. It is a logical entity.
A Class is a 3-Compartment box encapsulating data and operations as shown in figure.
Class Name
Static Attributes
Dynamic Behaviors
ET
Figure: Class Structure
The followings figure shows two classes ‘Student’ and ‘Circle’.
Name (Identifier) Student Circle
C
Variables (Static Attributes) name, gender, dept, marks radius, color
Methods getDetails() getRadius()
SV
Abstraction
Abstraction refers to the quality of dealing with ideas rather than events. It basically deals
with hiding the details and showing the essential things to the user.
We all know how to turn the TV on, but we don’t need to know how it works in order to
enjoy it.
ET
Abstraction means simple things like objects, classes, and variables represent more com-
plex underlying code and data. It avoids repeating the same work multiple times. In java, we
use abstract class and interface to achieve abstraction.
Abstract class:
C
Abstract class in Java contains the ‘abstract’ keyword. If a class is declared abstract, it
cannot be instantiated. So we cannot create an object of an abstract class. Also, an abstract
SV
Single Inheritance
It enables a derived class to inherit the properties and behavior from a single parent
class.
Here, Class A is a parent class and Class B is a child class which inherits the properties
and behavior of the parent class.
Multilevel Inheritance
When a class is derived from a class which is also derived from another class, i.e. a class
having more than one parent class but at different levels, such type of inheritance is called
Multilevel Inheritance.
Here, class B inherits the properties and behavior of class A and class C inherits the prop-
erties of class B. Class A is the parent class for B and class B is the parent class for C. So, class
ET
C implicitly inherits the properties and methods of class A along with Class B.
Hierarchical Inheritance
When a class has more than one child class (sub class), then such kind of inheritance is known
as hierarchical inheritance.
C
SV
Here, classes B and C are the child classes which are inheriting from the parent class A.
Hybrid Inheritance
Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.
Since multiple inheritance is not supported in Java as it leads to ambiguity, this type of inheri-
tance can only be achieved through the use of the interfaces.
Here, class A is a parent class for classes B and C, whereas classes B and C are the parent
classes of D which is the only child class of B and C.
Polymorphism
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means
forms. It is the ability of a variable, function or object to take on multiple forms. In other
words, polymorphism allows us to define one interface or method and have multiple imple-
mentations.
For eg, Bank is a base class that provides a method rate of interest. But, rate of interest
may differ according to banks. For example, SBI, ICICI and AXIS are the child classes that
provide different rates of interest.
ET
Polymorphism in Java is of two types:
• Run time polymorphism
• Compile time polymorphism
C
Secure :
• Java program cannot harm other system thus making it secure.
• Java provides a secure means of creating Internet applications.
• Java provides secure way to access web applications.
Portable :
• Java programs can execute in any environment for which there is a Java run-time
system.
• Java programs can run on any platform (Linux, Window, Mac)
• Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
• Java programming is object-oriented programming language.
• Like C++, java provides most of the object oriented features.
ET
• Java is pure OOP Language. (while C++ is semi object oriented)
Robust :
• Java encourages error-free programming by being strictly typed and performing run-
time checks.
C
Multithreaded :
• Java provides integrated support for multithreaded programming.
SV
Architecture-neutral :
• Java is not tied to a specific machine or operating system architecture.
• Java is machine independent.
Interpreted :
• Java supports cross-platform code through the use of Java bytecode.
• Bytecode can be interpreted on any platform by JVM (Java Virtual Machine).
High performance :
• Bytecodes are highly optimized.
• JVM can execute bytecodes much faster .
Distributed :
• Java is designed with the distributed environment.
• Java can be transmitted over internet.
Dynamic :
• Java programs carry substantial amounts of run-time type information with them that
is used to verify and resolve accesses to objects at run time.
1.4 Java Runtime Environment (JRE)
The Java Runtime Environment (JRE) is a set of software tools for development of Java
applications. It combines the Java Virtual Machine (JVM), platform core classes and support-
ing libraries.
JRE is part of the Java Development Kit (JDK), but can be downloaded separately. JRE
was originally developed by Sun Microsystems Inc., a wholly-owned subsidiary of Oracle
Corporation.
JRE consists of the following components:
Name of the component Elements of the component
Deployment technologies Deployment
Java Web Start
ET
Java Plug-in
User interface toolkits Abstract Window Toolkit (AWT)
Swing
C
Java 2D
Accessibility
SV
Image I/O
Print Service
Sound
Drag and Drop (DnD)
Input methods.
Integration libraries Interface Definition Language (IDL)
Java Database Connectivity (JDBC)
Java Naming and Directory Interface (JNDI)
Remote Method Invocation (RMI)
Remote Method Invocation Over Internet
Inter-Orb Protocol (RMI-IIOP)
Scripting.
Reflection
Collections
Concurrency
Java Archive (JAR)
Logging
Preferences API
Ref Objects
Regular Expressions.
Java Virtual Machine (JVM) Java HotSpot Client
Server Virtual Machines
ET
C
SV
Rules:
• The package statement should be the first line in the source file.
• There can be only one package statement in each source file.
• If a package statement is not used, the class, interfaces, enumerations, and annotation
types will be placed in the current default package.
• It is a good practice to use names of packages with lower case letters to avoid any
conflicts with the names of classes and interfaces.
Following package example contains interface named animals:
Java source program at the time of compilation. The import statement specifies the path for
the compiler to find the specified class.
Syntax of the import statement:
import packagename;
or
import packagename.* ;
as Employee.java.
• If the class is defined inside a package, then the package statement should be the first
statement in the source file.
• If import statements are present, then they must be written between the package
statement and the class declaration. If there are no package statements, then the
import statement should be the first line in the source file.
• Import and package statements will imply to all the classes present in the source file.
It is not possible to declare different import and/or package statements to different
classes in the source file.
1.9 Compilation
In Java, programs are not compiled into executable files. Java source code is compiled
into bytecode using javac compiler. The bytecodes are platform-independent instructions for
the Java VM. They are saved on the disk with the file extension .class. When the program
is to be run, the bytecode is converted into the machine code using the just-in-time (JIT) com-
piler. It is then fed to the memory and executed.
javac ExampleProgram.java
java ExampleProgram
C
1. Open text editor. For example, Notepad or Notepad++ on Windows; Gedit, Kate or
SciTE on Linux; or, XCode on Mac OS, etc.
2. Type the java program in a new text document.
3. Save the file as HelloWorld.java.
4. Next, open any command-line application. For example, Command Prompt on
Windows; and, Terminal on Linux and Mac OS.
5. Compile the Java source file using the command: javac HelloWorld.java
6. Once the compiler returns to the prompt, run the application using the following
command:
java HelloWorld
Syntax Example
/*Comment starts /* This is a
continues comment */
Commnent ends*/
3) Java Documentation Comment
This type of comment is used to produce an HTML file that documents our program. The
documentation comment begins with a /** and ends with a */.
Syntax Example
/**Comment start /**
* This
*comment ends*/
ET
1.11 Data Types
Java is a statically typed and also a strongly typed language. In Java, each type of data
(such as integer, character, hexadecimal, etc. ) is predefined as part of the programming lan-
guage and all constants or variables defined within a given program must be described with
C
iii) Characters - This group includes char, which represents symbols in a character set,
like letters and numbers. char is a 16-bit type. The range of a char is 0 to 65,536.
There are no negative chars.
iv) Boolean - This group includes boolean. It can have only one of two possible values,
true or false.
1.12 Variables
A variable is the holder that can hold the value while the java program is executed. A
variable is assigned with a datatype. It is name of reserved area allocated in memory. In
other words, it is a name of memory location. There are three types of variables in java: local,
instance and static.
A variable provides us with named storage that our programs can manipulate. Each vari-
able in Java has a specific type, which determines the size and layout of the variable’s mem-
ory; the range of values that can be stored within that memory; and the set of operations that
can be applied to the variable.
Before using any variable, it must be declared. The following statement expresses the
basic form of a variable declaration –
datatype variable [ = value][, variable [ = value] ...] ;
Here data type is one of Java’s data types and variable is the name of the variable. To de-
clare more than one variable of the specified type, use a comma-separated list.
Example
int a, b, c; // Declaration of variables a, b, and c.
int a = 20, b = 30; // initialization
byte B = 22; // Declaratrion initializes a byte type variable B.
Types of Variable
There are three types of variables in java:
• local variable
• instance variable
ET
• static variable
C
SV
Local Variable
• Local variables are declared inside the methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered
• Local variable will be destroyed once it exits the method, constructor, or block.
• Local variables are visible only within the declared method, constructor, or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be declared and
an initial value should be assigned before the first use.
• Access specifiers cannot be used for local variables.
Instance Variable
• A variable declared inside the class but outside the method, is called instance variable.
Instance variables are declared in a class, but outside a method, constructor or any
block.
• A slot for each instance variable value is created when a space is allocated for an
object in the heap.
• Instance variables are created when an object is created with the use of the keyword
‘new’ and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object’s state that must be present
throughout the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
ET
• The instance variables are visible for all methods, constructors and block in the
class. It is recommended to make these variables as private. However, visibility for
subclasses can be given for these variables with the use of access modifiers.
• Instance variables have default values.
C
○○ numbers, the default value is 0,
○○ Booleans it is false,
SV
• Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program
stops.
• Visibility is same as instance variables. However, most static variables are declared
public since they must be available for users of the class.
• Default values are same as instance variables.
○○ numbers, the default value is 0;
○○ Booleans, it is false;
○○ Object references, it is null.
• Values can be assigned during the declaration or within the constructor. Additionally,
values can be assigned in special static initializer blocks.
• Static variables cannot be local.
ET
• Static variables can be accessed by calling with the class name ClassName.
VariableName.
• When declaring class variables as public static final, then variable names (constants)
are all in upper case. If the static variables are not public and final, the naming syntax
C
is the same as instance and local variables.
1.13 Operators
SV
Operator in java is a symbol that is used to perform operations. Java provides a rich set
of operators to manipulate variables.For example: +, -, *, / etc.
All the Java operators can be divided into the following groups −
• Arithmetic Operators :
Multiplicative : * / %
Additive : + -
• Relational Operators
Comparison : < > <= >= instanceof
Equality : == !=
• Bitwise Operators
bitwise AND : &
bitwise exclusive OR : ^
bitwise inclusive OR : |
Shift operator: << >> >>>
• Logical Operators
logical AND : &&
logical OR : ||
logical NOT : ~ !
• Assignment Operators: =
• Ternary operator: ? :
• Unary operator
Postfix : expr++ expr—
Prefix : ++expr --expr +expr -expr
The Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations in the same way as they
are used in algebra. The following table lists the arithmetic operators −
Example:
ET
int A=10,B=20;
> (greater than) greater than the value of right operand, (A > B) true
if yes then condition becomes true.
Checks if the value of left operand is
< (less than) less than the value of right operand, if (A < B) true
yes then condition becomes true.
Checks if the value of left operand is
>= (greater than or greater than or equal to the value of
(A >= B) true
equal to) right operand, if yes then condition be-
comes true.
Checks if the value of left operand is
<= (less than or less than or equal to the value of right
(A <= B) true
equal to) operand, if yes then condition becomes
true.
checks whether the object is of a partic- boolean re-
ular type (class type or interface type) sult = name
instance of Operator True
(Object reference variable ) instanceof instanceof
(class/interface type) String;
Bitwise Operators
Java supports several bitwise operators, that can be applied to the integer types, long, int,
short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation.
Example:
int a = 60,b = 13;
binary format of a & b will be as follows −
a = 0011 1100
b = 0000 1101
Bitwise operators follow the truth table:
0011 1101)
^ (bitwise Binary XOR Operator copies the (A ^ B) will give 49 49
XOR) bit if it is set in one operand but which is 0011 0001 (in binary form:
not both. 0011 0001)
~ (bitwise Binary Ones Complement Opera- (~A) will give -61 -61
compli- tor is unary and has the effect of which is 1100 0011 (in binary form:
ment) ‘flipping’ bits. in 2’s complement 1100 0011)
form due to a signed
binary number.
<< (left The left operands value is moved A << 2 will give 240 240
shift) left by the number of bits speci- which is 1111 0000 (in binary form:
fied by the right operand. 1111 0000)
>> (right The left operands value is moved A >> 2 will give 15 15
shift) right by the number of bits speci- which is 1111 (in binary form:
fied by the right operand. 1111)
>>> (zero The left operands value is moved A >>>2 will give 15 15
fill right right by the number of bits speci- which is 0000 1111 (in binary form:
shift) fied by the right operand and 0000 1111)
shifted values are filled up with
zeros.
// Java program to illustrate bitwise operators
public class operators
{
public static void main(String[] args)
{
int a = 10;
ET
int b = 20;
System.out.println(“a&b = “ + (a & b));
System.out.println(“a|b = “ + (a | b));
C
System.out.println(“a^b = “ + (a ^ b));
SV
System.out.println(“~a = “ + ~a);
}
}
Logical Operators
The following are the logical operators supported by java.
Example:
A=true;
B=false;
/=
(Divide It divides left operand with the right
C /= A is equiva-
AND operand and assigns the result to left
lent to C = C / A
assignment operand.
operator)
%=
(Modulus It takes modulus using two operands C %= A is equiva-
AND assign- and assigns the result to left operand. lent to C = C % A
ment opera-
tor)
C <<= 2 is same as
<<= Left shift AND assignment operator.
C = C << 2
C >>= 2 is same as
>>= Right shift AND assignment operator.
C = C >> 2
ET
C &= 2 is same as
&= Bitwise AND assignment operator.
C=C&2
C
b -= 1;
e *= 2;
f /= 2;
System.out.println(“a, b, e, f = “ +
a + “,” + b + “,” + e + “,” + f);
}
}
Ternary Operator
Conditional Operator ( ? : )
Since the conditional operator has three operands, it is referred as the ternary operator.
This operator consists of three operands and is used to evaluate Boolean expressions. The
goal of the operator is to decide, which value should be assigned to the variable. The operator
is written as –
ET
variable x = (expression) ? value if true : value if false
Following is an example −
Example:
C
public class example
{
SV
Operator Description
- Unary minus negating the values
+ Unary plus converting a negative value to positive
++ :Increment operator incrementing the value by 1
— : Decrement operator decrementing the value by 1
! : Logical not operator inverting a boolean value
// Java program to illustrate unary operators
public class operators
{
public static void main(String[] args)
{
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
ET
boolean condition = true;
c = ++a;
System.out.println(“Value of c (++a) = “ + c);
C
c = b++;
System.out.println(“Value of c (b++) = “ + c);
SV
c = --d;
System.out.println(“Value of c (--d) = “ + c);
c = --e;
System.out.println(“Value of c (--e) = “ + c);
System.out.println(“Value of !condition =” + !condition);
}
}
Precedence of Java Operators
Operator precedence determines the grouping of operands in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator −
If Statement:
The if statement executes a block of code only if the specified expression is true. If the
value is false, then the if block is skipped and execution continues with the rest of the pro-
gram.
The simple if statement has the following syntax:
if (<conditional expression>)
<statement action>
The following program explains the if statement.
public class programIF{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
ET
System.out.println(“a > b”);
if (a < b)
System.out.println(“b < a”);
C
}
}
SV
status = 1;
}
else if (b > c)
{
status = 2;
}
else
{
status = 3;
}
switch (status)
{
case 1:System.out.println(“a is the greatest”);
break;
case 2:System.out.println(“b is the greatest”);
break;
case 3:System.out.println(“c is the greatest”);
break;
default:System.out.println(“Cannot be determined”);
}
}
}
Iteration statements
Iteration statements execute a block of code for several numbers of times until the condi-
tion is true.
While Statement
ET
The while statement is one of the looping constructs control statement that executes a
block of code while a condition is true. The loop will stop the execution if the testing expres-
sion evaluates to false. The loop condition must be a boolean expression. The syntax of the
while loop is
C
do {
System.out.println(count++);
SV
execution to resume at the top of the nearest enclosing loop. The continue statement can be
used when you do not want to execute the remaining statements in the loop, but you do not
want to exit the loop itself.
The syntax of the continue statement is
continue; // the unlabeled form
continue <label>; // the labeled form
It is possible to use a loop with a label and then use the label in the continue statement.
The label name is optional, and is usually only used when you wish to return to the outermost
loop in a series of nested loops.
The following program explains the continue statement.
public class ProgramContinue
{
public static void main(String[] args) {
System.out.println(“Odd Numbers”);
Example
public class myclass {
public myclass() { // Constructor
}
public myclass(String name) {
// This constructor has one parameter, name.
}
}
Types of Constructors
There are two type of constructor in Java:
1. No-argument constructor:
A constructor that has no parameter is known as default constructor.
If the constructor is not defined in a class, then compiler creates default con-
structor (with no arguments) for the class. If we write a constructor with ar-
guments or no-argument then compiler does not create default constructor.
Default constructor provides the default values to the object like 0, null etc. depending on the
type.
// Java Program to illustrate calling a no-argument constructor
import java.io.*;
class myclass
{
int num;
String name;
// this would be invoked while object of that class created.
myclass()
{
ET
System.out.println(“Constructor called”);
}
C
}
class myclassmain
SV
{
public static void main (String[] args)
{
// this would invoke default constructor.
myclass m1 = new myclass();
// Default constructor provides the default values to the object like 0, null
System.out.println(m1.num);
System.out.println(m1.name);
}
}
2. Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with your own values, then use parameterized constructor.
{
System.out.println(“Constructor with one argument : “ +”Long : “ + num);
}
}
class myclassmain
{
public static void main(String[] args)
{
myclass m1 = new myclass (“JAVA”);
myclass m2 = new myclass (“Python”, 2017);
myclass m3 = new myclass(3261567);
}
}
Creating an Object
The class provides the blueprints for objects. The objects are the instances of the class. In
Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The ‘new’ keyword is used to create the object.
ET
• Initialization − The ‘new’ keyword is followed by a call to a constructor. This call
initializes the new object.
1.18 Methods in Java
A method is a collection of statement that performs specific task. In Java, each method is
C
a part of a class and they define the behavior of that class. In Java, method is a jargon used
for method.
SV
Advantages of methods
• Program development and debugging are easier
• Increases code sharing and code reusability
• Increases program readability
• It makes program modular and easy to understanding
• It shortens the program length by reducing code redundancy
Types of methods
There are two types of methods in Java programming:
• Standard library methods (built-in methods or predefined methods)
• User defined methods
Standard library methods
The standard library methods are built-in methods in Java programming to handle tasks
such as mathematical computations, I/O processing, graphics, string handling etc. These
methods are already defined and come along with Java class libraries, organized in packages.
In order to use built-in methods, we must import the corresponding packages. Some of library
methods are listed below.
Packages Library Methods Descriptions
java.lang.Math acos() Computes arc cosine of the argument
All maths related methods exp() Computes the e raised to given power
are defined in this class
abs() Computes absolute value of argument
log() Computes natural logarithm
sqrt() Computes square root of the argument
pow() Computes the number raised to given
power
java.lang.String charAt() Returns the char value at the specified
index.
All string related methods concat()
are defined in this class
ET Concatenates two string
compareTo()
Compares two string
indexOf()
Returns the index of the first occurrence
of the given character
C
toUpperCase()
converts all of the characters in the String
to upper case
SV
Example:
Program to compute square root of a given number using built-in method.
public class MathEx {
public static void main(String[] args) {
System.out.print(“Square root of 14 is: “ + Math.sqrt(14));
}
}
Sample Output:
Square root of 14 is: 3.7416573867739413
User-defined methods
The methods created by user are called user defined methods.
Every method has the following.
• Method declaration (also called as method signature or method prototype)
• Method definition (body of the method)
• Method call (invoke/activate the method)
Method Declaration
The syntax of method declaration is:
Syntax:
return_type method_name(parameter_list);
Here, the return_type specifies the data type of the value returned by method. It will be
void if the method returns nothing. method_name indicates the unique name assigned to the
method. parameter_list specifies the list of values accepted by the method.
ET
Method Definition
Method definition provides the actual body of the method. The instructions to complete a
specific task are written in method definition. The syntax of method is as follows:
C
Syntax:
modifier return_type method_name(parameter_list){
SV
The first line of the method definition must match exactly with the method prototype. A
method cannot be defined inside another method.
Method Call
A method gets executed only when it is called. The syntax for method call is.
Syntax:
method_name(parameters);
When a method is called, the program control transfers to the method definition where
the actual code gets executed and returns back to the calling point. The number and type of
parameters passed in method call should match exactly with the parameter list mentioned in
method prototype.
Example:
method name
class Addition{
modifier
public int add(int a,int b){
ET body of the method
return type return(a+b);
}
Parameter list
}
class Main{
C
method call
method return
public static void main(String args[]){
int sum=0,a=1,b=12;
SV
Example:
Program to compute addition of two numbers (with argument and without return value)
public class Main {
public void add(int x,int y){ // method definition with arguments and no return value
System.out.println(“Sum:”+(x+y));
}
public static void main(String[] args) {
int a=10,b=20;
Main obj=new Main();
obj.add(a,b); // method call with arguments
}
}
Sample Output:
Sum:30
Sum:30
1.19 Parameter passing in Java
The commonly available parameter passing methods are:
• Pass by value
• Pass by reference
Pass by Value
In pass by value, the value passed to the method is copied into the local parameter
and any change made inside the method only affects the local copy has no effect on the
original copy. In Java, parameters are always passed by value. All the scalar variables (of
type int, long, short, float, double, byte, char, Boolean) are always passed to the methods by
value. Only the non-scalar variables like Object, Array, String are passed by reference.
Note:
Scalar variables are singular data with one value; Non scalar variables are data with mul-
tiple values.
Example:
Pass by value
class Swapper{
int a;
int b;
Swapper(int x, int y) // constructor to initialize variables
{
a = x;
b = y;
}
void swap(int x, int y) // method to interchange values
{
ET
int temp;
/* only the local copy x, y gets swapped. The original object
temp = x; value a, b remains unchanged*/
x=y;
C
y=temp;
}
SV
}
class Main{
public static void main(String[] args){
Swapper obj = new Swapper(10, 20); // create object
System.out.println(“Before swapping: a=”+obj.a+” b=”+obj.b);
obj.swap(obj.a,obj.b); // call the method by passing class object as parameter
System.out.println(“Before swapping: a=”+obj.a+” b=”+obj.b);
}
}
Sample Output:
Before swapping: a=10 b=20
After swapping: a=10 b=20
Here, to call method swap() first create an object for class Swapper. Then the method is
called by passing object values a and b as input parameters. As these values are scalar, the
parameters are passed using pass by value technique. So the changes carried out inside the
method are not reflected in original value of a and b.
Pass by Reference
In pass-by-reference, reference (address) of the actual parameters is passed to the local
parameters in the method definition. So, the changes performed on local parameters are re-
flected on the actual parameters.
Example:
class Swapper{
int a;
int b;
Swapper(int x, int y) // constructor to initialize variables
{
ET
a = x;
b = y;
}
C
ref.a = ref.b;
ref.b = temp;
}
}
class PassByRef{
public static void main(String[] args){
Swapper obj = new Swapper(10, 20); // create object
System.out.println(“Before swapping: a=”+obj.a+” b=”+obj.b);
}
public Addition display(Addition oa){
Addition tmp=new Addition();
/*method with same class object as input parameter &
tmp.no=no+oa.no; return value*/
return(tmp);
}
}
class Main{
public static void main(String args[]){
Addition a1=new Addition(10);
Addition a2=new Addition(10);
Addition a3;
a3=a1.display(a2); // method is invoked using the object a1 with input parameter a2
void add(){
System.out.println(“No parameters”);
}
void add(int a,int b){ // overloaded add() for two integer parameter
System.out.println(“Sum:”+(a+b));
}
void add(int a,int b,int c){ // overloaded add() for three integer parameter
System.out.println(“Sum:”+(a+b+c));
}
void add(double a,double b){ // overloaded add() for two double parameter
System.out.println(“Sum:”+(a+b));
}
}
public class Main {
public static void main(String[] args) {
MethodOverload obj=new MethodOverload();
obj.add(); // call all versions of add()
obj.add(1,2);
obj.add(1,2,3);
obj.add(12.3,23.4);
}
}
Sample Output:
ET
No parameters
Sum:3
Sum:6
C
Sum:35.7
Here, add() is overloaded four times. The first version takes no parameters, second takes
SV
two integers, third takes three integers and fourth accepts two double parameter.
1.21 Access Specifiers
Access specifiers or access modifiers in java specifies accessibility (scope) of a data mem-
ber, method, constructor or class. It determines whether a data or method in a class can be
used or invoked by other class or subclass.
Types of Access Specifiers
There are 4 types of java access specifiers:
1. Private
2. Default (no speciifer)
3. Protected
4. Public
The details about accessibility level for access specifiers are shown in following table.
Access Modifiers Default Private Protected Public
Accessible inside the class Yes Yes Yes Yes
Accessible within the subclass
Yes No Yes Yes
inside the same package
Accessible outside the package No No No Yes
Accessible within the subclass
No No Yes Yes
outside the package
Private access modifier
Private data fields and methods are accessible only inside the class where it is declared i.e
accessible only by same class members. It provides low level of accessibility. Encapsulation
and data hiding can be achieved using private specifier.
Example:
Role of private specifier
ET
class PrivateEx{
private int x; // private data
public int y; // public data
C
private PrivateEx(){} // private constructor
public PrivateEx(int a,int b){ // public constructor
SV
x=a;
y=b;
}
}
public class Main {
public static void main(String[] args) {
PrivateEx obj1=new PrivateEx(); // Error: private constructor cannot be applied
PrivateEx obj2=new PrivateEx(10,20); // public constructor can be applied to obj2
System.out.println(obj2.y); // public data y is accessible by a non-member
System.out.println(obj2.x); //Error: x has private access in PrivateEx
}
}
In this example, we have created two classes PrivateEx and Main. A class contains private
data member, private constructor and public method. We are accessing these private members
from outside the class, so there is compile time error.
Example:
class DefaultEx{
Sample Output:
10
In the above example, the scope of class DefaultEx and its data y is default. So it can be
accessible within the same package and cannot be accessed from outside the package.
Example:
Role of protected specifier
class Base{
protected void show(){
System.out.println(“In Base”);
}
}
public class Main extends Base{
public static void main(String[] args) {
Main obj=new Main();
obj.show();
ET
}
}
Sample Output:
C
In Base
SV
In this example, show() of class Base is declared as protected, so it can be accessed from
outside the class only through inheritance. Chapter 2 explains the concept of inheritance in
detail.
Public access modifier
The public access specifier has highest level of accessibility. Methods, class, and fields
declared as public are accessible by any class in the same package or in other package.
Example:
Role of public specifier
class PublicEx{
public int no=10;
}
Example :
StaticEx(){ StaticEx(){
System.out.println(no); System.out.println(no);
no++; no++;
} }
} }
{ {
} }
} }
10 10
10 11
10 12
Static Method
ET
The method declared with static keyword is known as static method. main() is most com-
mon static method.
• It belongs to the class and not to object of a class.
• A static method can directly access only static variables of class and directly invoke
C
}
}
public class Main
{
public static void main(String[] args) {
StaticEx obj=new StaticEx();
StaticEx.display(); // static method invoked without using object
obj.show();
}
}
Sample Output:
Static Method 0
ET
Non static method 10
Non static method 0
In this example, class StaticEx consists of a static variable x and static method display().
The static method cannot access a non-static variable. If you try to access y inside static
C
method display(), it will result in compilation error.
/*non-static variable y cannot be referred from a
SV
…………….
}
Example:
class StaticBlockEx{
StaticBlockEx (){
System.out.println(“Constructor”);
}
static {
System.out.println(“First static block”);
}
static void show(){
System.out.println(“Inside method”);
}
ET
static{
System.out.println(“Second static block”);
show();
C
}
SV
Static in main
Constructor
Nested class (static class)
Nested class is a class declared inside another class. The inner class must be a static class
declared using keyword static. The static nested class can refer directly to static members of
the enclosing classes, even if those members are private.
Syntax:
class OuterClass{
……..
static class InnerClass{
……….
}
}
ET
We can create object for static nested class directly without creating object for outer class.
For example:
OuterClassName.InnerClassName=new OuterClassName.InnerClassName();
C
Example:
class Outer{
SV
Sample Output:
30
Static Import
The static import allows the programmer to access any static members of imported class
directly. There is no need to qualify it by its name.
Syntax:
Import static package_name;
Advantage:
• Less coding is required if you have access any static member of a class oftenly.
Disadvantage:
• Overuse of static import makes program unreadable and unmaintable.
Example:
import static java.lang.System.*;
ET
class StaticImportEx{
public static void main(String args[]){
out.println(“Static Import Example”); //Now no need of System.out
C
}
}
SV
Sample Output:
Static Import Example
1.23 Arrays
Array is a collection of elements of similar data type stored in contiguous memory loca-
tion. The array size is fixed i.e we can’t increase/decrease its size at runtime. It is index based
and the first element is stored at 0th index.
Advantages of Array
• Code Optimization: Multiple values can be stored under common name. Date retrieval
or sorting is an easy process.
• Random access: Data at any location can be retrieved randomly using the index.
Disadvantages of Array
• Inefficient memory usage: Array is static. It is not resizable at runtime based on number
of user’s input. To overcome this limitation, Java introduce collection concept.
Types of Array
There are two types of array.
• One Dimensional Array
• Multidimensional Array
One Dimensional Array
Declaring Array Variables
ET
The syntax for declaring an array variable is
Syntax:
dataType[] arrayName; //preferred way
C
Or
dataType arrayName [];
SV
Here datatype can be a primitive data type like: int, char, Double, byte etc. arrayName is
an identifier.
Example:
int[] a;
Instantiation of an Array
Array can be created using the new keyword. To allocate memory for array elements
we must mention the array size. The size of an array must be specified by an int value and
not long or short. The default initial value of elements of an array is 0 for numeric types
and false for boolean.
Syntax:
arrayName=new datatype[size];
Or
dataType[] arrayName=new datatype[size]; //declaration and instantiation
Example:
int[] a=new int[5]; //defining an integer array for 5 elements
Alternatively, we can create and initialize array using following syntax.
Syntax:
dataType[] arrayName=new datatype[]{list of values separated by comma};
Or
}
Sample Output:
Sum:100
Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array. These are also known as Jagged Arrays.
Syntax:
dataType[][] arrayName=new datatype[rowsize][columnnsize]; // 2 dimensional array
dataType[][][] arrayName=new datatype[][][]; // 3 dimensional array
Example:
int[][] a=new int[3][4];
Example:
Program to access 2D array elements
class TwoDimEx
ET
{
public static void main(String args[])
{
C
// declaring and initializing 2D array
int arr[][] = { {1,1,12},{2,16,1},{12,42,2} };
SV
// printing 2D array
for (int i=0; i< arr.length; i++)
{
for (int j=0; j < arr[i].length ; j++)
System.out.print(arr[i][j] + “ “);
System.out.println();
}
}
}
Sample Output:
1 1 12
2 16 1
12 42 2
Jagged Array
Jagged array is an array of arrays with different row size i.e. with different dimensions.
Example:
class Main {
public static void main(String[] args) {
int[][] a = {
{11, 3, 43},
{3, 5, 8, 1},
{9},
};
}
Sample Output:
SV
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
Passing an array to a method
An array can be passed as parameter to method.
Example:
Program to find minimum element in an array
class Main{
static void min(int a[]){
int min=a[0];
for(int i=1;i<a.length;i++)
if(min>a[i])
min=a[i];
System.out.println(“Minimum:”+min);
}
public static void main(String args[]){
int a[]={12,13,14,5};
min(a);//passing array to method
}
}
Sample Output:
Minimum:5
Returning an array from a method
A method may also return an array.
Example:
ET
Program to sort array elements in ascending order.
class Main{
static int[] sortArray(int a[]){
C
int tmp;
for(int i=0;i<a.length-1;i++) { //code for sorting
SV
for(int j=i+1;j<=a.length-1;j++) {
if(a[i]>a[j]){
tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
}
}
return(a); // returning array
}
public static void main(String args[]){
int a[]={33,43,24,5};
a=sortArray(a);//passing array to method