You are on page 1of 146

Section I: General

1) What is Java?

Java is a Programming Language and a Platform

Java is used as a programming to develop


Software Applications
Java is used as Software Platform to run Java
Applications

2) What are important Java Editions or Parts of


Java?

Java has Three Important Editions

i) Java Standard Edition / Core Java (* Old name


J2SE)
ii) Java Enterprise Edition / Advanced Java (*Old
name J2EE)
iii) Java Micro Edition (* Old name J2ME)

3) Where Java is used?

Java is used to create,


Desktop Applications
Web Applications
Enterprise Applications
Mobile Applications
Smart Cards
Embedded Systems
Scientific Applications
Computer Games Etc...

4) How Java is Used?

Java is an Open Source Software and Platform


independent,

For Software Development download and install


JDK (includes JRE and JVM) Software,
For Run-time (to run Software Applications that
developed in Java) download and install JRE
(includes JVM)

We can run Java byte code on any supported


platform.

5) What are important features of Java?

Important Features of Java are,

Simple
Object Oriented
Platform independent
Secured
Robust,
Architecture neutral
Portable
Interpreted
Multithreaded

Distributed

6) What is JVM?

Java Virtual machine (JVM) is the virtual machine


that run the Java bytecodes.
The JVM doesn't understand Java source code,
that's why you compile your *.java files to obtain
*.class files that contain the bytecodes
understandable by the JVM.

7) What is JRE?

The Java Runtime Environment (JRE) provides the


libraries, the Java Virtual Machine, and other
components to run applets and applications written
in the Java programming language.

8) What is JDK?

Java Development Kit (JDK) is a superset of the


JRE, and contains everything that is in the JRE,
plus tools such as the compilers and debuggers
necessary for developing applets and applications.
9) What are important Java Language Elements?

Important Language Elements of Java are,

i) Data Types
ii) Modifiers
iii) Variables
iv) Operators
v) Control Flow Statements
vi) Methods Etc...

10) What are the Fundamentals of OOPS?

Four fundamentals of Object Oriented


Programming are,

i) Inheritance
ii) Polymorphism
iii) Abstraction
iv) Encapsulation

11) What are Java Syntax Rules?

Java Syntax Rules:

Java is a case sensitive language.

First letter of Class name should be in Upper


case.
Method names should start with lower case
letter.

Java program file name should exactly match


with class name.

Java program execution starts from main


method, which is mandatory in every Java
program.

Every statement/step should end with semi colon


symbol.

Code blocks enclosed with {}.

12) How to setup Java Environment on Windows


Operating System?

Download Java Software (JDK) and Install.


(Download Java (JDK) Software from either
java.com or oracle.com, and Install)

Set Environment Variable path (Path variable)

Download Eclipse IDE and extract

Launch Eclipse IDE, Write Java Program and


execute.
13) How to set Environment Variable path in
Windows Operating environment?

After Java Installation then you can get Java folder


in C:\Program Files.

Set Environment Variable path (Path variable)

Navigation

First take jdk bin directory path

Select MyComputer and right click


> Properties
> Advanced System Settings
> Environment Variables
> Select Path variable from system variables
> Edit
> Paste java bin directory path in variable value
field
> OK
> Ok
>OK
> Close

14) How to write and execute Java Programs using


Windows Command Prompt (Without Eclipse IDE)?
In Computer Programming we have three steps.

Step 1: Write a Sample Program in Notepad and


save with .java extension

public class Sample {


public static void main (String [] args) {
System.out.println ("Hello Java World");
}
}

Step 2: Compile the Program

> Launch Command prompt


> Chang to Java program file directory.
> Type javac Sample.java

* It creates Java class file

Step 3: Run / Execute the program.

Type java Sample

Then it displays the Output on the Console.

15) What is Eclipse IDE?

Eclipse IDE (Integrated Development Environment)


Eclipse IDE is a platform to write and execute
computer programs like Java, Perl, Python, Ruby,
PHP etc...

Eclipse IDE is open source.

It provides Editor for writing programs, Syntax


guidance, Context help, auto compilation etc...

Note: Using Eclipse IDE we can write and execute


Java Programs.

16) How to write and execute Java programs using


Eclipse IDE?

Steps to Write and Execute a Java Program using


Eclipse IDE :

> Launch Eclipse IDE


> Create Java Project
> Create Java Package
> Create Java Class
Write Java Program and Run.

Note: Eclipse IDE provides auto compilation


facility.

17) Explain about Java Program Structure?


Sections of Java Program,

i) Documentation Section
ii) Package declaration statement
iii) Import Statement/s
iv) Class declaration
v) main Method (Java Program execution starts
from main method)
vi) Declarations (We declare Variables and
Constants.)
vii) General Statements (Ex: d = a + b + c;)
viii) Code blocks (Condition blocks, Loop Blocks
etc...)

Note: Every Normal Statement should end with


Semi colon and Every code block enclosed with {}
------------------------------------------------
Section II: Comments in Java

1) What are Comments in Computer Program?

Comments are English words used for Code


documentation

Purpose of Comments
i) To make the code Readable
ii) To make the code disable from Execution

2) How to write comments in Java?


Comments Syntax in Java

Java supports Single line comment and multiple


line comment.

a) Use // for Single line comment

b) Use /*..........
------------
----------
----------
-------------*/ for multiple line comment

Or
In Eclipse IDE,

Select Statements/Steps
Source menu -> Add Block Comment

Uncomment
Select Comment block
Source menu -> Remove Block Comment
------------------------------------------------
Section III: Java Modifiers

1) What are Modifiers?

Modifiers are keywords that we add to those


definitions to change their meaning.

2) What are the types of Modifiers in Java?

Two types of Modifiers in Java

i) Access Modifiers
ii) Non Access Modifiers

3) What are Access Modifiers?

We use access modifiers to define access control


for classes, methods and variables.

Access Modifiers in Java are,

i) public
public access modifiers is accessible everywhere.

Ex:
public class Sample{
}

ii) private
The private access modifier is accessible only
within class.

Ex:
private int a=100;
iii) default

If we don't specify any modifier then it is treated


as default, this can be accessible only within
package.

Ex:
class Sample {
}

iv) protected
The protected modifier is accessible within
package, outside of the package but through
Inheritance.

Ex:
protected class Sample {
}

4) What are the important Non Access Modifiers in


Java?

i) static
static modifier is used to create classes, methods
and variables.

ii) final
final modifier for finalizing classes, methods and
variables.

iii) abstract
abstract modifier is used to create abstract classes
and abstract methods.
Etc...
------------------------------------------------
Section IV: Java Data Types

1) What is Data type?

Data Type is a classification of the type of data


that a variable or Constant or Method can hold in
Computer program.

Ex: character, integer, float, boolean etc...

Java Supports Explicit declaration of data types.

2) What is Explicit declaration of data types?

We need to specify the data type before declaring


variables or Constants.

Examples in Java:

int a;
int b=100;
int c, d, e;
int f=10, g=20, h=30;

3) What are the categories of Data Types in Java?

Two categories of Data Types in Java

i) Primitive Data Types


ii) Non Primitive Data Types

4) What are Primitive Data Types in Java?

Primitive Data Types (8 Data types) in Java are,

i) Integer Data Types

a) byte (8 bits), Ex: byte a = 10;


b) short (16 bits), Ex: short b =10000;
c) int (32 bits), Ex: int c = 1000000;
d) long (64 bits), Ex: long d =
100000000000000000000;

ii) Relational data types (Numbers with decimal


places)

e) float (32 bits), Ex: float x = 10.23;


f) double (64 bits), Ex: double y =
1245.34567897345;

iii) Characters
g) Character, Ex: char z = "A";

iv) Conditional

h) Boolean, Ex: boolean x = true/false;

5) What are Non Primitive Data Types?

Non Primitive Data Types Or Reference data Types


in Java are Objects and Arrays.

Example:

Sample obj = new Sample();


------------------------------------------------
Section V: Java Variables

1) What is Variable?

A named memory location to store the temporary


data within a program.

Two types of memory in Computer environment.

i) Primary memory (RAM)


ii) Secondary memory (ROM - HDD, DVD, USB
drive etc...)
Note: Variables store in Primary memory (RAM).

2) How to Declare Variables in Java?

Java supports Explicit declaration of variables.

Syntax:

dataType variableName;

Example:
int a;
char x;

3) How to assign values to Variables in Java?

Two types of Assign values to variables,

i) Initialization

int a =100; //Initialization

ii) Reading (Reading using Input devices, from


files)

int a =100;
int b;
b=a;//Reading
4) What are Variable Naming restrictions in Java?

i) Java Variables are case sensitive.


ii) Java variable names should start with a letter or
$ or _
iii) Variable names should not match with Java
Keywords/Reserved words
iv) Must be unique in the scope of declaration.
v) Must not exceed 255 characters.
Etc...

5) What are the types of Variables in Java?

i) Local Variables
Local variables are declared in methods or blocks.

ii) Instance Variables


Instance Variables are declared in a class but
outside of a method or any block.

iii) Class / Static Variables


Static Variables are declared as static, these can't
be local.
------------------------------------------------
Section VI: Operators in Java

1) What are Operators?

Operators are used to perform mathematical,


comparison and logical operations.

2) What are the categories of Operators in Java?

i) Arithmetic Operators
ii) Relational Operators
iii) Assignment Operators
iv) Logical Operators
Etc...

3) What are Arithmetic Operators in Java?

Arithmetic Operators in Java are,

i) Addition + (Addition, String concatenation)


ii) Subtraction - (Subtraction, Negation)
iii) Multiplication *
iv) Division /
v) Modules %
vi) Increment ++
vii) Decrement --

Note: Arithmetic Operators return value based


result.

4) Give an Example for Arithmetic Operators?

public static void main(String[] args) {


int a =10, b =5;
String c = "Selenium", d ="Testing";

System.out.println("Addition of a, b is: "


+(a+b));//Addition of a, b is: 15
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a % b);//0
b=10;
a = ++b;
System.out.println(a);//11
b=10;
a = --b;
System.out.println(a);//9
}
}

5) What are Relational Operators in Java?

Relational Operators in Java are,

i) ==
ii) !=
iii) >
iv) >=
v) <
vi) <=
Note: Relational Operators return Boolean/logical
result (true/false)

6) Give an Example for Relational Operators?

public static void main(String[] args) {


int a =10, b =20;

System.out.println(a>b);//false
System.out.println(a>=b);//false
System.out.println(a<b);//true
System.out.println(a<=b);//true
System.out.println(a==b);//false
System.out.println(a!=b);//true
}
}

7) What are Logical Operators in Java?

Important Logical Operators in Java are,

i) Logical Not operator !


ii) Logical And Operator &&
iii) Logical Or operator ||

8) Give an Example for Logical Operators?

Example for Logical Operators,


public static void main(String[] args) {
boolean a =true, b =false;

System.out.println(!(a && b));//true


System.out.println(a && b);//false
System.out.println(a || b);//true
}

9) What are the important Assignment Operators


in Java?

Important Assignment Operators are,

i) Assignment =
ii) Add and Assign +=
iii) Subtract and Assign -=
iv) Multiply and Assign *=

10) Give an Example for Assignment Operators?

public static void main(String[] args) {

int a = 10;
System.out.println(a);//10

a += 10;
System.out.println(a);//20
a -= 10;
System.out.println(a);//10

a *= 10;
System.out.println(a);//100
}
}

11) What is Operator Precedence?

Java Modifiers
Modifiers are keywords that we add to those
definitions to change their meanings.
There are Two types of modifiers in Java.
a) Access Modifiers

b) Non-access Modifiers
---------------------
a) Access Modifiers
There are 4 types of modifiers in Java.
we use access modifiers to define access control
for classes, methods and variables etc...

1) private
2) default

3) protected

4) public
---------------------
1) private:
The private access modifier is accessible only
within class.

Ex:

class A {

private int a = 40;


.
.
---------------------
2) default
If we don't use any modifier, it is treated as default
by default. this can be accessible only within
package.

Ex:

package abc;

class Sample {
int a;
.
.
---------------------
3) protected
The protected access modifier is accessible within
package, and out side of the package but through
Inheritance only.

Ex:
---------------------
4) public
public access modifier is accessible everywhere. It
has widest scope among all other modifiers.

Ex:

public Class A{

public static void main (String [] args) {


.
.

Modifier Within Within Outside of Outside of


class Package the the
Package Package
(by sub
classes)
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

b) Non-access Modifiers
Java provides no of non access modifiers to
achieve many other functionality.

Static modifier to create class, methods and


variables.

Ex:

class Abc {

static String name ="Selenium"


.
.
--------------------------------
final modifier for finalizing the implementation of
classes, methods and variables.
Ex:
class Sample {

final int a =100;


-------------------------
abstract modifier is to create abstract classes and
methods.

public abstract Sample {


.
.

etc...

Java Data Types

What is Data Type?

Data type is a classification of the type of data that


a variable or object can hold in computer
programming.

Ex: character, integer, float etc....

> Java supports explicit declaration of Data types.


(we need to specify the data type before declaring
the Variable)

Syntax:data_type variable_name;

data_type variable_name = value;


Example:
int a;

int a = 100;
----------------------
Two types of Data types in java:

a) Primitive Data types

b) Non-primitive Data types / Reference Data


types
-----------------------------------
a) Primitive Data types (8 primitive data types)

Integer types1) byte (8 bits)

Ex:

byte a =100;

2) short (16 bits)

short a = 10000;

3) int (32 bits)

int a = 100000;

4) long (64 bits)


long a = 100000L
------------------
Rational types (Numbers with decimal
places)5) float (32 bits)

float a = 1.2;

6) double (64 bits)


ex:
double a = 19.3456;
---------------------
Characters7) char (16 bits)

Ex:

char a ='Z'
------------------------
Conditional8) boolean (undefined, depends on
JVM)

Ex:
boolean a = true
---------------------------------
b) Non-primitive / Reference data types

Non-primitive data types in Java are Objects and


Arrays.
Note:

Reference types are not passed value, passed by


reference

Ex:

Button a = new Button("OK")


-----------------------------------------------
Java String:

> Java String provides a lot of concepts that can


be performed on Strings.

> Java String is not a data type in Java, It is a


Class.

Declaring String variables and Arrays:

String myTool = "Selenium"; // String Variable

String [] myTools = {"Selenium", "UFT", "RFT",


"SilkTest", LoadRunner"}; Array of Strings

Java Variables

1) What is Variable?
A named memory location to store or hold the
data.

There are two types of memory in Computer


environment:

i) Primary memory -RAM

ii) Secondary memory -ROM


Ex: CD, DVD, HDD etc...

Note: Variables store in primary memory.


-------------------------
2) Declaration of Variables in Java.
Java Supports explicit declaration of variables

Syntax:

dataType VariableName;

Ex:

int a;
---------------
dataType variable1, variable2, variable3;

Ex:

int a, b, c;
------------------------
dataType VariableName = value;

Ex:

int a =100;
--------------------------
3) Assigning values to variables
a) Initialization

int a;
a=10; // Initialization
--------------
int a=10; // Initialization
----------------
b) Reading
using Input devices
from files(text/excel)
from databases
from Application objects
-------------------------
4) Types of Variables
a) Instance Variable
A variable that is declared inside the class but
outside the method

b) Local variable

A variable that is declared inside the method


c) Static variables
A Variable that is declared as static, It cannot be
local.
----------------------
5) Naming Conventions
> Java Variables are case sensitive, monkey is not
the as Monkey or MONKEY.

char monkey, Monkey, MONKEY

> Java variable name must start with a letter or $


or _

Ex:
myvar
MYVAR
$myvar
_myvar
myvar1
myvar_1
----------
1myvar - invalid
----------------------
> Variable names cannot be equal to java reserved
words

Ex:

int
for
import

> Must be unique in the scope of declaration.


----------------------------------------
6) Java Variables Declaration Example:

package JavaExamples;

public class VariablesExamples {

public static void main (String [] args){


// dataType variableName;
int a;
a = 10;
// dataType VariableName = Value;
int b = 20;
// Declaration of multiple variables in a
statement
int c, d, e;
c =30;
d =40;
e = 50;
// Declaration of multiple variables and
assigning values
int f=60, g=70, h=90;
int j;
j = a; // Reading
char x ='A';
double y = 2.3456;
String z = "Selenium";

System.out.println (a);
System.out.println (b);
System.out.println (c);
System.out.println (d);
System.out.println (e);
System.out.println (f);
System.out.println (g);
System.out.println (h);
System.out.println (x);
System.out.println (y);
System.out.println (z);
System.out.println (j);
}
}

Operators in Java

Operators are used to perform mathematical,


Comparison and Logical operations.

Important categories of Operators

a) Assignment Operators

b) Arithmetic operators
c) Relational Operators

d) Logical operators
etc...
-----------------------
a) Assignment Operators

1) Assignment operator =

a = 10;

2) Add and +=

a = 10;

a += 20;

3) Subtract and Assign -=

a = 10;

a -= 5;

4) Multiply and Assign *=

a = 10;

a *= 5;
------------------------
Example:
public static void main (String [] args){
int a = 10;
System.out.println (a); // 10
a += 10;
System.out.println (a); // 20
a -= 10;
System.out.println (a); // 10
a *= 5;
System.out.println (a); //50
}
--------------------------------------
b) Arithmetic operators

1) Addition + (for addition and string


concatenation)

2) Subtraction - (fro subtraction and negation)

3) Multiplication *

4) Division /

5) Modules %

6) Increment ++

7) Decrement --
-----------------------------
Example:
public static void main (String [] args){
int a= 10, b = 5;
String c ="Selenium", d = "Testing";

System.out.println ("Addition of a, b is: " +


(a+b)); // 15
System.out.println ("Concatenation of c, d is: "
+ (c+d)); // SeleniumTesting

System.out.println ("Subtraction of a, b is: "+


(a-b)); //5
System.out.println ("Multiplication of a, b is:
"+(a * b)); //50
System.out.println ("Division of a, b is: "+
(a/b)); //2
System.out.println ("Modulus of a, b is: "+
(a%b)); //0
b = 5;
a = ++b;
System.out.println (a); // 5
b = 5;
a = --b;
System.out.println (a); //4
b = 5;
a = b+4;
System.out.println (a); // 9

}
--------------------------------------
c) Relational operators
Types of Result in Computer Programming

i) Value based Result

3+5=8

2 * 7 = 14

ii) Boolean / Logical Result

True or false

iii) Constant based Result


-------------------------------------
Relational operators return Boolean / Logical
result

1) ==

2) !=

3) >

4) >=

5) <
6) <=
----------------------
Example:

public static void main (String [] args){


int a=10, b=20;
System.out.println ("a > b is "+ (a > b));
//False
System.out.println ("a >= b is "+ (a >= b));
//False
System.out.println ("a == b is "+ (a == b));
//False

System.out.println ("a < b is "+ (a < b));


//True
System.out.println ("a <= b is "+ (a <= b));
//True
System.out.println ("a != b is "+ (a != b));
//True
}
----------------------------
d) Logical Operators

1) Logical Not operator !

2) Logical And operator &&

3) Logical Or Operator ||
------------
Result Criteria

1) Not operator
----------------------------
Operand 1 Operand 2 Result
-------------------------------------
true true false
true false true
false true true
false false true
-----------------------------------
2) And operator
----------------------------
Operand 1 Operand 2 Result
-------------------------------------
true true true
true false false
false true false
false false false
---------------------------------------
3) Or operator
----------------------------
Operand 1 Operand 2 Result
-------------------------------------
true true true
true false true
false true true
false false false
------------------------------------
Example:

public static void main (String [] args){


boolean a= true, b=false;
System.out.println("! (a && b) is: " + ! (a &&
b )); //True
System.out.println("(a && b) is: " + (a && b
)); //False
System.out.println("(a || b) is: " + (a || b ));
//True
}
--------------------------------------------
Example 2:
public static void main (String [] args){
int a = 100, b = 500, c = 70;

if ((a > b) && (a > c)) {


System.out.println ("A is a Big Number");
}
else
{
System.out.println ("A is Not a Big
Number");
}

Java Conditional Statements


Conditional statements are used to insert
verification points and for Error handling.
Two types of Conditional statements in Java
1) if statement

2) switch statement
------------------------------
Types of Conditions
1) Single condition
Ex:

if (a > b) {
----
----

2) Compound condition
Ex:

if ((a > b) && or || (a > c)) {


--------
----------

3) Nested Condition
if (a > b){}
if (a < c) {}
if (a < d) {
----
----
}
------------------------------
Usage of Conditional Statements
1) Executing a block of statements when condition
is true.
Syntax:
if (Condition) {
Statements
---------
---------
}

Example:public static void main (String [] args){


int a, b;
a =10;
b =5;

if (a > b) {
System.out.println("A is a Big Nuber");
}
------------------------------------
2) Executing a block of statements when
compound condition is true
Syntax:
if ((condition) && (condition2)) {
Statements
----------
-----------
}

Example:int a, b, c = 2;
a =10;
b =5;

if ((a > b) && (a > c)) {


System.out.println("A is a Big Nuber");
}
-------------------------------------------
3) Executing a block of statements when condition
is true. otherwise executing another block of
statements.
Syntax:
if (Condition) {
Statements
----------
--------
}
else {
statements
---------
--------
}

Example:
public static void main (String [] args){
int a, b;
a =10;
b =50;

if (a > b) {
System.out.println("A is a Big Number");
}
else {
System.out.println("B is a Big Number");
}
-----------------------------------------
4) Decide among several Alternates (else if
structure)
Syntax:
if (condition) {
Statements
------
---------
}
else if (condition) {
Statements
------
---------
}
else if (condition) {
Statements
------
---------
}
else
{
statements
----------
--------
}

Example:
public static void main (String [] args){
int a = -100;

if ((a >= 1) && (a < 100)) {


System.out.println("A is a Small
Number");
}
else if ((a > 100) && (a <= 1000)) {
System.out.println("A is a Medium
Number");
}
else if (a > 1000) {
System.out.println("A is a Big Number");
}
else
{
System.out.println("A is either Zero or
negative value");
}
--------------------------------------------
5) Executing a block of statements when more
than one condition is true (Nested if).
Syntax:
if (condition) {}
if (condition) {}
if (condition) {
Statements
--------
---------
}
else
{
Statements
---------
---------
}

Example:
public static void main (String [] args){
int a =10, b =7, c = 5, d = 13;

if (a > b){}
if (a > c) {}
if (a > d){
System.out.println("A is a Big Number");
}
else {
System.out.println("A is Not a Big
Number");
}
---------------------------------------
6) Decide among several alternates (using Switch
case structure).
Syntax:
switch (expression) {
case value:
Statements
-------
break;
case value:
Statements
-------
break;
case value:
Statements
-------
break;
default
Statements
-------
------
}

Example:char grade = 'X';

switch (grade){

case 'A':
System.out.println ("Excellent");
break;
case 'B':
System.out.println ("Well Done");
break;
case 'C':
System.out.println ("Better");
break;
default:
System.out.println("Invalid Grade");
}
---------------------------------------------------------
Java Loop statements
Whenever we want to execute a block of
statements several times then we use Loop
structures.

There are four types of loop structure in Java.


1) for Loop

2) while Loop

3) do...while Loop

4) Enhanced for Loop


-------------------------
1) for Loop
It repeats a block of statements for a specified
number of times.

Syntax:
for(stratvalue; endValue; increment/decrement) {
Statements
---------
--------
}

Example:
for (int i=1; i<=10; i++)
{
System.out.println(i);
}
Example 2:
// print 10 to 1 Numbers using For Loop.

for (int i=10; i>=1; i--)


{
System.out.println(i);
}
Example 3:// print every 10th Number up to 100.

for (int i=10; i<=100; i=i+10)


{
System.out.println(i);
}
--------------------------------------
2) while Loop
It repeats a block of statements while condition is
true.

Syntax:
Initialization
while (condition) {
statements
------
-------
increment/decrement
}

Example:// print 1 to 10 Numbers using While


Loop.

int i = 1;
while (i <=10){
System.out.println(i);
i++;
}
Example 2:// print 10 to 1 Numbers using While
Loop.

int i = 10;
while (i >= 1){
System.out.println(i);
i--;
}
Example 3:// print every 10th number up to 100
using While Loop.

int i = 10;
while (i <= 100){
System.out.println(i);
i= i+10;
}
--------------------------------------
3) do ...while Loop----------------------------------
-----
it repeats a block of statements while condition is
true and Irrespective of the condition, it executes a
block of statements at least once.

Syntax:
do
{
Statements
----------
----------
Increment/Decrement
} while(Condition);
------------
Example:int i = 20;
do {
System.out.println("i value is : " + i);
i++;
} while(i <= 10);
---------------------------------------
4) Enhanced for Loop------------------------------
---------
It executes all elements in an Array

Syntax:
for (declaration: expression) {
statements
----------
-----------
}

Example:String languages [] = {"C", "C++",


"Java", "COBOL"};
for (String lang: languages)
{
System.out.println(lang);
}

String Handling in Java

String is sequence of characters written in double


quotes.

I) Java String Example:


package javaExamples;

class StringExample {
public ststic void main (String [] args) {

System.out.println ("Hello Selenium"); // Hello


Selenium is a String
System.out.println ("123 Hello Selenium");
System.out.println ("Hello Selenium 123");
System.out.println ("123*456 Hello Selenium");
}
}
Note: String may contain Alfa bytes, numbers and
special characters.
Creating Strings

> String is considered as object in java.

II) Example for Creating Strings:


package javaExamples;

public class StringExample {

public static void main (String []args){


String myTool = "Selenium"; // String Variable

String [] myTools = {"UFT", "Selenium",


"LoadRunner", "Quality Center"}; // Array of
Strings.

System.out.println(myTool);// Selenium

for (int i=0; i < myTools.length; i++) {


System.out.println(myTools[i]); // Print Array
of strings
}
}
}
--------------------------------------
III) Concatenating Strings
package javaExamples;

public class StringExample {

public static void main (String []args){


String str1 = "Selenium"; // String Variable
String str2 = "Testing";

System.out.println(str1 + str2);// Selenium


Testing
System.out.println("Test Automation " + "Using
Selenium" + " and Java"); // Test Automation
using Selenium and java
System.out.println(1 + 1 + " Selenium");
System.out.println("Selenium" +1 + 1);
}
}
-------------------------------
IV) String Comparison in Java:
a) String comparison using equals() method

b) String comparison using == (Relational


Operator)

c) String comparison using compareTo() method

Example:
package javaExamples;

public class StringExample {

public static void main (String []args){


String str1 = "SELENIUM";
String str2 = "selenium";
String str3 = "SELENIUM";
String str4 = "selenium testing";

System.out.println(str1.equals(str2));// false
System.out.println(str1.equals(str3));// true

System.out.println(str1 == str2); // false


System.out.println(str1 == str3); // true
}
}
--------------------------
V) Important operations on Strings:

package javaExamples;

public class StringExample {

public static void main (String []args){


String str1 = "Selenium";
String str2 ="gcreddy@gmail.com";
System.out.println(str1.length());//
8 (finding length of the String)

System.out.println(str1.contains("len"));//
true (finding sub string)
System.out.println(str1.contains("lem"));//
false (finding sub string)

// Returning Sub Strings


System.out.println(str2.substring(0)); //
gcreddy@gmail.com
System.out.println(str2.substring(9)); //
gmail.com
System.out.println(str2.substring(14)); //
com
System.out.println(str2.substring(9, 13)); //
gmail
}
}

Arrays in Java

1) Introduction:
> Java Array is an object that holds a fixed
number of values of a single data type.

> The length of an Array is established when the


Array is created.

> Array length is fixed, Java Array has Zero based


index.

2) Declaration of Arrays in Java:


int abc []; // Array of Integers

abc = new int[10]; //creating Array and defning


size.

System.out.println(abc.length); //Finding length of


the Array.

abc[0] =10;
abc[1] = 20;
.
.
--------------
int [] abc = new int[5];

abc[0] =2;
abc[1] =3;
System.out.println(abc[0]+abc[1]);
------------------------------
int [] abc = {10, 20, 30, 40, 50} //Creating Array
and Initializing

System.out.println(abc.length);
System.out.println(xyz[1]+xyz[2]);
//Priting Array
for (int i=0; i < xyz.length; i++) {
System.out.println(xyz[i]);
}
-------------------
Creating Arrays (Different data types)
int [] array1 ={1, 2, 3, 4, 5}; // Array of Integers
char [] array2 ={'A', 'B', 'C'}; // Array of
Characters
boolean [] array3 = {true, false, false, true,false};
// Array of Boolean values
String [] array4 = {"Selenium", "UFT", "Java",
"LoadRunner"}; // Array of Strings

System.out.println(array1[1]); // 2
System.out.println(array2[1]); // B
System.out.println(array3[1]); // false
System.out.println(array4[0]); // Selenium

--------------------------------
3) Copy of values an Array into another Array

Example 1:int [] array1 ={1, 2, 3, 4, 5};


int [] array2;
array2 = array1;

System.out.println(array2[2]);
Example 2:
int [] array1 ={1, 2, 3, 4, 5};
int [] array2 = new int [array1.length];

System.arraycopy(array1, 2, array2, 2, 3);


System.out.println(array2[2]);

4) Advantages of Arrays:

> Using Arrays we can optimize the code, data can


be retrieved or sorted easily.

> We can get required data using index position.

5) Disadvantages of Arrays

> We can store fixed number of elements only in


the Array, It doesn't change its size at Runtime.

> An Array holds only one type of data.

6) Types of Arrays

a) Single dimensional Array

b) Multidimensional Array

Creating multidimensional Array:


int [][] abc = new int [3][4];

abc [0][0] =1;


abc [0][0] =2;
.
.
-----------
int xyz [][] = {{1, 3, 5, 7, 9}, {2, 4, 6, 8, 10}};

Java Built in Methods

> Java has a library of classes and methods,


organized in packages.

> In order to use built in methods, we import pre-


defined packages/Classes.

> java.lang package is automatically imported in


any java program.

> Using import keyword we can import pre-defined


packages.

Categories of Built in methods:


I) Number methods
II) Character methods
III) String methods
IV) Array methods etc...
------------------------------
I) Number Methods

1) compareTo() Method
Example:
Integer a = 5;

System.out.println(a.compareTo(8)); //-1
System.out.println(a.compareTo(5));//0
System.out.println(a.compareTo(2));//1

Result Criteria:
if the integer is equal to the argument then 0
if the integer is less than the argument then -1
if the integer is greater than the argument then 1
-----------------------------------
2) equals() Method
Integer a = 5;

Integer b = 10;
Integer c = 5;
Short d = 5;
System.out.println(a.equals(b));//false
System.out.println(a.equals(c)); //true
System.out.println(a.equals(d)); //false
--------------------------------------
3) abs Method (Returns Absolute value)
Example:

Integer a = -5;
double b = -10.234;

System.out.println(Math.abs(a));// 5
System.out.println(Math.abs(b));// 10.234
----------------------------------------------
4) round Method (Rounds the value nearest
Integer)

Example:
double a = 10.575;
double b = 10.498;

System.out.println(Math.round(a));// 11
System.out.println(Math.round(b));// 10
-----------------------------------------
5) min Method (Returns minimum value between
two numbers)

Example:

int a =10, b =20;


double c = 1.234, d = 3.567;
System.out.println(Math.min(a, b)); // 10
System.out.println(Math.min(c, d)); // 1.234
System.out.println(Math.min(123, 124)); // 123
System.out.println(Math.min(10.345, 10.3451));
// 10.345
System.out.println(Math.min(1, 1)); // 1
-----------------------------------------
6) max Method (Returns maximum value
between two numbers)

Example:
int a =10, b =20;
double c = 1.234, d = 3.567;
System.out.println(Math.max(a, b)); // 20
System.out.println(Math.max(c, d)); // 3.567
System.out.println(Math.max(123, 124)); // 124
System.out.println(Math.max(10.345, 10.3451));
// 10.3451
System.out.println(Math.max(1, 1)); // 1
-------------------------------
7) random Method (Generates Random Number)

Example:
System.out.println(Math.random()); //
System.out.println(Math.random()); //
---------------------------------------------
II) Character Methods

1) isLetter Method (Checks weather the value is


Alfa byte or not?)

Example:
char a = '1';
System.out.println(Character.isLetter(a)); //false
System.out.println(Character.isLetter('A'));//true
System.out.println(Character.isLetter('a'));//true
System.out.println(Character.isLetter('*'));//false
--------------------------------
2) isDigit Method (It returns weather the value is
Number or not?)

char a = '1';
System.out.println(Character.isDigit(a)); //true
System.out.println(Character.isDigit('A'));//false
System.out.println(Character.isDigit('a'));//false
System.out.println(Character.isDigit('*'));//false
System.out.println(Character.isDigit('7')); //true
-----------------------------------------------
3) isUppercase Method (Checks weather the
value is Upper case or not?)

Example:
System.out.println(Character.isUpperCase('C'));//t
rue
System.out.println(Character.isDigit('z')); //false
-------------------------------------
4) isLowercase Method (Checks weather the
value is Lower case or not?)

Example:
System.out.println(Character.isLowerCase('C'));//f
alse
System.out.println(Character.isLowerCase('z'));
//true
------------------------------
5) toUppercase Method (Converts the value to
Upper case)

Example:
System.out.println(Character.toUpperCase('a'));//
A
System.out.println(Character.toUpperCase('A'));
//A
-----------------------------------
6) toLowercase Method (Converts the value to
Lower case)

Example:
System.out.println(Character.toLowerCase('a'));//a
System.out.println(Character.toLowerCase('A'));
//a
-------------------------------------------------------
III) String Methods

1) compareTo() Method (It compares two


strings)

Example:
String str1 ="SELENIUM";
String str2 ="selenium";
String str3 ="seleniuma";
String str4 ="selenium";
int result;
result = str1.compareTo(str2);
System.out.println(result); //

result = str3.compareTo(str2);
System.out.println(result); //

result = str2.compareTo(str4);
System.out.println(result); //
-------------------------------------
2) charAt Method (character by position)

String str1 ="SELENIUM";


char result = str1.charAt(0);
System.out.println(result); //S
-------------------------
3) concat Method (String concatenation)

String str1 ="Selenium";


String str2 = " Java";
str1 = str1.concat(str2);
System.out.println(str1);
-----------------------------
4) equals Method (String equals)

Example:
String str1 ="Selenium";
String str2 = "UFT";
String str3 ="Selenium";

System.out.println(str1.equals(str2)); //false
System.out.println(str1.equals(str3)); //true
-----------------------------
5) equalsIgnorecase Method

Examples:
String str1 ="selenium";
String str2 = "UFT";
String str3 ="SELENIUM";
String str4 ="SELENIUM";

System.out.println(str3.equalsIgnoreCase(str4));
//true
System.out.println(str1.equalsIgnoreCase(str3));
//true
System.out.println(str1.equalsIgnoreCase(str2));
//false
-----------------------------------------------
6) toUppercase Method (Converts values To
Upper case)

Example:
String str1 ="selenium";
String str2 ="SELEnium";
String str3 ="SELENIUM";

System.out.println(str1.toUpperCase());
System.out.println(str2.toUpperCase());
System.out.println(str3.toUpperCase());
-------------------------------------
7) toLowercase Method (Converts values To
Lower case)

String str1 ="selenium";


String str2 ="SELEnium";
String str3 ="SELENIUM";

System.out.println(str1.toLowerCase());
//selenium
System.out.println(str2.toLowerCase());
//selenium
System.out.println(str3.toLowerCase());
//selenium
---------------------------------------------
8) trim Method (removes spaces from both sides
of a String)

Example:

String str1 =" Selenium ";


String str2 =" SELEnium";
String str3 ="SELENIUM ";

System.out.println(str1);
System.out.println(str1.trim());
System.out.println(str2.trim());
System.out.println(str3.trim());
---------------------------------------------
9) substring Method (Returns sub string)

Example:
String str1 ="Welcome to Selenium Testing";

System.out.println(str1.substring(10)); //
Selenium Testing
System.out.println(str1.substring(19)); //Testing
System.out.println(str1.substring(10, 18));
//Selenium
------------------------------------------------
10) endsWith Method (ends with specified
suffix)

Example:
-----------
String str1 = "Selenium Testing";

System.out.println(str1.endsWith("Testing"));//tru
e
System.out.println(str1.endsWith("ing"));//true
System.out.println(str1.endsWith("Selenium"));//f
alse
--------------------------------------------------
11) length() Method (Returns length of a String)

String s = "Selenium";
System.out.println(s.length()); //8
--------------------------------------------------
IV) Array Methods

1) length() Method
int [] array1 = {10, 20, 30, 40, 50};
System.out.println(array1.length);//5
-------------------------------------
2) toString() Method (print Array)

String [] arr1 ={"UFT", "Selenium", "RFT",


"SilkTest"};
String str = Arrays.toString(arr1);
System.out.println(str);
--------------------------------------
3) contains() Method (Checks if the Array
contains certain value or not?)

String [] arr1 ={"UFT", "Selenium", "RFT",


"SilkTest"};
boolean a = Arrays.asList(arr1).contains("UFT");
boolean b = Arrays.asList(arr1).contains("uft");

System.out.println(a);// true
System.out.println(b);// false

Java Methods

I) What is Method?
Method is a set of statements to perform an
operation, methods are also known as procedures
or functions.

Generally, we use Functions (Built in and user


defined) in computer programming or scripting.

In Java we use methods for code reusability.

II) Use of Methods:

Whenever we want perform same operations


multiple times then we use methods, using
methods we can reduce the code size.

III) Types of Methods:

Basically we have two types of methods in java.

i) Built in methods

ii) User defined methods.

IV) Built in methods

> Java has a library of (pre-defined) classes and


methods, organized in packages.
> In order to use Built in methods, we import the
packages (or classes individually). (Group of
classes)

> java.lang package is automatically imported, in


any Java program.

> Using import keyword we can import java pre-


defined libraries.(We can import entire packages or
particular class)

Categories of Built in methods:

a) String methods

b) Array methods

c) Character methods

d) Number methods

e) Date & Time methods

etc...

Example for Built in method:


System.out.println("Hello Selenium");
-------------------------------------
V) User defined methods
> Methods in Objects oriented Programming
equivalent of Functions in Non object oriented
programming.

Types of User defined methods


i) Method without return any value
ii) Method with return values.

Writing method:

Syntax:
modifier returnType methodName(Parameters) {
// Method body
}

modifier -It is optional, it defines access type of


the method

returnType - Method may retrun a value

methodName - Name of the method.

parameters - Parameters are optional, we can use


mutiple parameters by separating with ,

method body - set of statements define that what


the method does.
------------------------------------------------
Example 1: Method with returning a value.
public static int add(int a, int b){
Statements
----------
-----------
}

Method calling:

dataType variableName = methodName(Values)


--------------
int abc = add(5, 3);
System.out.println(abc);
}
public static int add(int a, int b){
int result;
result = a + b;
return result;
}
}
----------------------------------
Example 2: Method without returning any
value

modifier methodName(Parameters) {
//Method body
}

public static void add(int a, int b) {


Statements
-----------
--------
}

Examples:

Internal method:
----------------
public static void main(String [] args){
studentRank(499);
}
public static void studentRank(int marks) {
if (marks >= 600) {
System.out.println("Rank:A1");
}
else if (marks >= 500) {
System.out.println("Rank:A2");
}
else {
System.out.println("Rank:A3");
}
}
------------------------------------
Example 3: External Method (Calling from
external or another class).

import xyza.CopyArray;
public class Apple extends CopyArray {
public static void main (String [] args){
studentRank(678);
}
}
------------------------------------------
VI) Method Overloading in Java
If a class have multiple methods with same name,
but different parameters, It is known as Method
overloading.

There are two ways to overlad the Method in java

i) By changing number of Arguments.


Example: we have Two methods in our class with
the name of add.

a) int add (int a, int b)

b) int add (int a, int b, int c)

ii) By changing data types.


a) int add (int a, int b)

b) double add(double a, double b)


----------------------------
Example Java Program for Method
Overloading:
package javaExamples;
public class MethodOverLoading {

public static void main (String []args){


int x = add(5, 7);
int y = add(5, 7, 9);
double z = add(5.234, 7.23);
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
public static int add(int a, int b){
int result;
result = a + b;
return result;
}
public static int add(int a, int b, int c){
int result;
result = a + b + c;
return result;
}
public static double add(double a, double b){
double result;
result = a + b;
return result;
}
}
Advantages of Method Overloading:
> It increases the readability of the Program.

Exception Handling in Java


> An Exception is an event, it occurs during
execution of a program,
when normal execution of the program is
interrupted.

> Exception handling is mechanism to handle


exceptions
--------------------------
Common Scenarios where exceptions may occur:
1) Scenario where ArithmeticException
occurs
If we divide any number by Zero there
ArithmeticException occurs

Ex:

int a = 10/0;
----------------------------------------------
2) Scenario where NullPointerException
occurs
if we have null value in any variable, performing
any operation by the variable,

ex:
String s = null;
System.out.println(s.length());//NullPointerExcepti
on
---------------------------------------------------
3) Scenario where NumberFormatException
occurs
The wrong formatting of any value, may
occur NumberFormatException

Ex:
String s = "abc";
int y = Integer.parseInt(s);
System.out.println(y);//NumberFormatExcept
ion
--------------------------------------
4) Scenario where ArrayIndexOutOfBounds
exception occurs
If we are inserting any value in the wrong index.

Ex:
int [] a = new int [5];
a[10] = 100;
System.out.println(a[10]);//ArrayIndexOutOf
Bounds
---------------------------------------------------------
-----
Java Program Example:------------
int a =10;
int b = 0;
int result;
result = a/b;
System.out.println(result);
System.out.println("Hello Java");
System.out.println("Hello Selenium");
----------------------------------
Use try block for Exception Handling
Syntax:
--------
try {
Statements
------
-------
------
}
catch (exception e) {
Exception handling code
}
-----------------------------------
Java Program With Exception handling
int a =10;
int b = 0;
int result;

try{
result = a/b;
System.out.println(result);
}
catch (ArithmeticException e){
System.out.println("Divided by Zero Error");
}
System.out.println("Hello Java");
System.out.println("Hello Selenium");
}
--------------------------------------
Multiple try blocks for handling multiple exceptions
Example:
int a =10;
int b = 0;
int result;
int [] array1 = new int [4];

try{
result = a/b;
System.out.println(result);
}
catch (ArithmeticException e){
System.out.println("Divided by Zero Error");
}

try{
array1[10]= 100;
System.out.println(array1[10]);
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("Array Out of Bound Error");
}
System.out.println("Hello Java");
System.out.println("Hello Selenium");
}

I/O and File Handling in Java.

There are three ways available for reading


input:
i) Scanner

ii) DataInputStream

iii) BufferedReader
---------------
Using java.util.Scanner is the easier and includes
many methods to check input data is valid to read.

Example:---------------
package javaiooperations;
import java.util.Scanner;
public class ReadInput {
public static void main(String [] args){
Scanner scan = new Scanner(System.in);

System.out.println("Enter Your Name");


String s1 = scan.nextLine();
System.out.println("Your Name is: " + s1);
System.out.println("Enter Your City Name");
String s2 = scan.next();
System.out.println("Your City Name is: " + s2);

System.out.println("Enter Your Number");


int a = scan.nextInt();
System.out.println("Your Number is: " + a);

System.out.println("Enter Your City Name");


double b = scan.nextDouble();
System.out.println("Value is: " + b);
scan.close();
}
}
-------------------------------------------

File handling in Java

Two categories of File System Operations

i) High level operations / External operations

Create a folder

delete a folder

create a text file


delete a text file etc...

ii) Low level operations / Internal operations

Read data

Write data etc...


------------------------
Using File Class we can perform High level
operations
Examples:
1) Create a Folder
package javaiooperations;

import java.io.File;

public class CreateFolder {

public static void main(String [] args){


File fileObject = new File("C:/Users/G C
Reddy/Desktop/Selenium");
fileObject.mkdir();
}
}
---------------------------------
2) Check the existence of Selenium
Folderpublic static void main(String [] args){
File fileObject = new File("C:/Users/G C
Reddy/Desktop/UFT");
boolean a = fileObject.exists();
System.out.println(a);
}
-------------------------------------
3) Delete a Folder
public static void main(String [] args){
File abc = new File ("C:/Users/G C
Reddy/Desktop/Selenium");
abc.delete();
boolean a = abc.exists();
//System.out.println(a);
if (a == true) {
System.out.println("Folder exists");
}
else{
System.out.println("Folder doesn't
exist");
}
}
-----------------------------------
4) Create a Text file
public class CreateFolder {

public static void main(String [] args){


File abc = new File ("C:/Users/G C
Reddy/Desktop/Selenium.txt");
try {
abc.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
-------------------------------------------
5) Delete a text file public static void
main(String [] args){
File abc = new File ("C:/Users/G C
Reddy/Desktop/Selenium.txt");
abc.delete();

Java OOPS Concepts for Selenium


OOPS - Object Oriented Programming System

Four Fundamentals of OOPS:


i) Inheritance

ii) Polymorphism

iii) Abstraction

iv) Encapsulation
------------------------
i) Inheritance:
> It is a process of inheriting (reusing) the class
members 9variables and methods) from one class
to another class is called Inheritance.
> Non static (object level) class members only can
be inherited.

> The class from where the class members are


getting inherited is called as Super class/ Parent
class/base class

> The class to which the class members are


getting inherited is called
Sub class/ Child class / Derived class.

> The Inheritance between Super class and Sub


class is achieved using "extends" keyword.

Syntax:

Class SubClass extends SuperClass {


//body
}
They are three types of Inheritance:

i) Single Inheritance

Ex:

Class B extends Class A


---------------------------
ii) Multi level inheritance:
Ex:

Class B extends Class A

Class C extends Class B

iii) Multiple Inheritance (*Java doesn't support)

Ex:

Class B extends Class A

Class C extends Class B

In Class C
add method
-----------------------------
Class C extends Class D
-------------------------------

Inheritance example:
----------------------
public class B {
int a = 10;
int b = 20;
public void addition(){
System.out.println("Addition of a, b is: " +
(a+b));
}
public static void main (String [] args){
B myObject = new B();
myObject.addition();
}
}
---------------------------------
package javaiooperations;

public class C extends B {


/*int a =100;
int b =200;
public void addition(){
System.out.println("Addition of a, b is: " +(a+
b));
}*/
public static void main (String [] args){
C abc = new C();
abc.addition(); //
}
}
-------------------------------
package javaiooperations;

public class D extends C{


/*int a=1;
int b=2;
public void addition(){
System.out.println("Addition of a, b is: "+(a
+ b));
}*/
public static void main (String [] args){
D obj = new D();
obj.addition();
}
}
--------------------------------------
ii) Polymorphism:
Polymorphism means, existence of Object behavior
in many forms.

They are two types of polymorphism:

i) Compile Time/ Static binding/ Method


overloading

ii) Run Time polymorphism / Dynamic binding /


Method overriding
-----------------------
i) Compile Time
-------------------
If two or more methods having same method
name in the same class but they differ in the
following ways:

i) No of Arguments

Ex:
add (int a, int b){
}

add (int a, int b, int c) {


}
--------------------------
ii) Order of Arguments

iii) Type of Arguments

Ex:

add (int a, int b){


}

add (double a, double b){


}
------------------------------------
Example:
package javaiooperations;

public class MethodOverLoading {


public void add (int a, int b){
System.out.println(a+b);
}
public void add (int a, int b, int c){
System.out.println(a+b+c);
}
public void add (double a, double b){
System.out.println(a+b);
}
public static void main (String [] args){
MethodOverLoading obj = new
MethodOverLoading();
obj.add(2, 5);
obj.add(2, 5, 7);
obj.add(1.234, 4.567);
}
}
---------------------------------
ii) Run time/Method Overriding

If two methods are having same name and same


arguments available in the Super class and sub
class, then we call those two methods are
overridden.

Ex:

public class Y {
int a = 10, b=20;
public void add () {
System.out.println(a+b);
}
}
-----------------
public class Z extends Y{
int a = 1, b=2;
public void add () {
System.out.println(a+b);
}
public static void main (String [] args){
Z obj = new Z();
obj.add(); // 3

Y obj1 = new Y();


obj1.add(); //30

Y obj2 = new Z();


obj2.add();
}
}
--------------------------------
iii) Abstraction:
> It is a process of hiding implementation details
and showing only functionality to the user.

> In Java, we have two types of methods

i) Concrete Methods (The methods which are


having body)

Ex:

public void addition()


{
// Method body
}
--------------
ii) Abstract Methods (The methods which are not
having body)

Ex:

public void addition ();


--------------------------------
If we know the method name, but don't know what
the method performs, then we go for abstract
methods.

Inheritance:
-------------
A sub class extends Super class is known as
Inheritance.

Class members in java:

Variables and Methods.

Static Class Members (Class Level)

> using class name we can access Static class


members.

Non Static Class Members (Object Level)


> Using Object/Instance
-----------------------
Note 1: Static Class members are not inherited to
the Sub class.

Note 2: Non Static class members are inherited to


the Sub class.
--------------------------------------------
Example for Accessing Static and Non static class
members:
-----------
package JavaOOPS;
public class AbstractionExample {
static int a = 10, b = 20; //Static variables
int c = 30, d = 40; // Non static variables

public static void add1() { // Static method


System.out.println(a+b);
}
public void add2() // Non static method
{
System.out.println(c+d);
}
public static void main (String [] args) {
// Access Static Class Members using Class
Name
System.out.println(AbstractionExample.a); //
10
System.out.println(AbstractionExample.b); //
20
AbstractionExample.add1();// 30

System.out.println("");
// Access Non static class members using
Object /Instance
AbstractionExample obj = new
AbstractionExample();
System.out.println(obj.c); // 30
System.out.println(obj.d); // 40
obj.add2(); //70
}

}
---------------------------------------
Abstract Class
> java Class contains 100% concrete methods

> Abstract (incomplete) class contains one or more


abstract methods.

> Abstract class may have abstract and concrete


methods.

Ex:

Class1 (having 10 methods)


10 methods are concrete methods
----------
Class2 (having 10 methods)

5 methods concrete
5 methods Abstract

* Abstract class
----------------------
Class3 (having 10 methods)

10 methods Abstract
* Abstract class
------------------------------
Example for Abstract Class:
--------------------------
Syntax:

public abstract class ClassName{

public void methodName(){


//Body
}

public abstract void methodname();

}
-----------------------------
Super Class
package JavaOOPS;

public abstract class Bike {


public void engine(){
System.out.println("Bikes have Engine");
}
public abstract void handle();

public abstract void seat();


}
--------------------------------
Sub Class:
package JavaOOPS;

public class HeroHonda extends Bike{

@Override
public void handle() {
System.out.println("Bikes have Handle");
}

@Override
public void seat() {
System.out.println("Bikes have Seats");
}
public static void main (String [] args){
HeroHonda obj = new HeroHonda();
obj.engine();
obj.handle();
obj.seat();
}
}
------------------------------------------------
iv) Encapsulation:
It is a process of wrapping code and data together
into a single unit.

Encapsulation is the technique making the fields in


a class private and providing access via public
methods.

Advantages:

> It provides us the control over the Data.

> By providing only setter and getter methods, we


can make a class read only or write only.

If we don't define setter method then read only

If we don't define getter method then write only.


---------------------------------------------
Java Interfaces:
> Interface is a Java type definition block which is
100% abstract.
(Contains 100% abstract methods)

> All the Interface methods are by default public


and abstract.

> Static and final modifiers are not allowed for


Interface methods.

> In Interfaces, variables have to initialize at the


time of declaration.

ex:

int a = 10; // Correct


int a; // Incorrect

> In Interfaces variables are public static final by


default.

> Interface is going to be used using "implements"


keyword.
------------------------
Example:

package JavaOOPS;

public interface Example2 {


int a = 10, b =20;
public abstract void add();
void sub();
}
--------------------------
package JavaOOPS;

public class Exa4 implements Example2{

@Override
public void add() {
System.out.println("Addition");
}

@Override
public void sub() {
System.out.println("Subtraction");
}
public static void main (String []args){
Exa4 obj= new Exa4();
obj.add();
obj.sub();
}

oops concept in Java

oops:

To develop an application we use a programming


language that follows one of the following
concepts.

1.procedure oriented concepts.


2.object oriented concepts

1.procedure oriented concepts:

The application that are developed using


procedure oriented concepts are based on
procedures or functions.

Drabacks of procedure oriented concepts:

i.The application that are developed using


procedure oriented concept or difficult to maintain
and difficult to debug.
ii.The data in the applications that are developed
using procedure oriented concepts is not secured.
iii.The data in the applications that are developed
using procedure oriented concepts is open and it
can be accessed by the entire applications,this
mechanism is not suitable for developing
distributed applications.
iv.In The procedured oriented languages lot of
importance is given to the operations that perform
on the data rather than to the data.

Note:The procedure oriented language are also


called as "Structured programming language".
Ex:C,PASCAL,COBOL,FORTRAN Etc...

2.object oriented concepts:

The application that are developed using object


oriented concepts give lot of importance to the
security ,they provide protection so that the data is
not accessed by the unauthorised access.

Ex:C++,JAVA,.NET ETC...

-->Even though c++ is called as object oriented


language,but according to the programming
language experts it is called as partially object
oriented language because of the following
reasons.
i.An application in c++ can be developed without
following the object oriented concepts.
ii.In c++ language Their is concept called friend
functions using which we can access any data even
though it is secured.

-->The object oriented concepts are derived from


the real world,from the lifes of a human being so
that the programming becomes simple.
-->The programmer can understand the concepts
easily and implement them without facing any
difficulty.
-->Using the object oriented concepts we can
develop real time applications which are complex
and large.Because the object oriented concepts are
very strong.
-->The object oriented concepts has very strong
fundamentalsentities called as 'class or 'object'.
-->A class is a specification of variables and
methods .Where variables are used for storing the
data and the methods are used for performing the
operations.
-->A class is a collection of common features of a
group of objects.
-->An object is any thing that exists physically in
the real world.
-->A class doesnot exist physically but it is
considered as a method or a blue print or a plan
for creating the objects.we can create any number
of objects for a class.with out a class we cannot
create any object.
-->An object is considered as an imnstance of a
class.

The various object oriented concepts are.

1.Encapsulations
2.Abstraction
3.Inheritance
4.polymorphism
1.Encapsulations:

Encapsulation is one of the four fundamental OOP


concepts. The other three are inheritance,
polymorphism, and abstraction.

Encapsulation is the technique of making the fields


in a class private and providing access to the fields
via public methods. If a field is declared private, it
cannot be accessed by anyone outside the class,
thereby hiding the fields within the class. For this
reason, encapsulation is also referred to as data
hiding.

Encapsulation can be described as a protective


barrier that prevents the code and data being
randomly accessed by other code defined outside
the class. Access to the data and code is tightly
controlled by an interface.

The main benefit of encapsulation is the ability to


modify our implemented code without breaking the
code of others who use our code. With this feature
Encapsulation gives maintainability, flexibility and
extensibility to our code.
Example:

Let us look at an example that depicts


encapsulation:

/* File name : EncapTest.java */


public class EncapTest{

private String name;


private String idNum;
private int age;

public int getAge(){


return age;
}

public String getName(){


return name;
}

public String getIdNum(){


return idNum;
}

public void setAge( int newAge){


age = newAge;
}

public void setName(String newName){


name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}

The public methods are the access points to this


class' fields from the outside java world. Normally,
these methods are referred as getters and setters.
Therefore any class that wants to access the
variables should access them through these
getters and setters.

The variables of the EncapTest class can be access


as below::

/* File name : RunEncap.java */


public class RunEncap{

public static void main(String args[]){


EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : " +
encap.getName()+
" Age : "+ encap.getAge());
}
}
This would produce the following result:

Name : James Age : 20

Benefits of Encapsulation:

i.The fields of a class can be made read-only or


write-only.
ii.A class can have total control over what is stored
in its fields.
iii.The users of a class do not know how the class
stores its data. A class can change the data type of
a field and users of the class do not need to
change any of their code.

2.Abstraction

It is aprocess of hiding the unnessecessary


information and presenting the required
information.We can achive abstraction by using
access specified using abstraction we can achive
security.

Abstraction refers to the ability to make a class


abstract in OOP. An abstract class is one that
cannot be instantiated. All other functionality of
the class still exists, and its fields, methods, and
constructors are all accessed in the same manner.
You just cannot create an instance of the abstract
class.

If a class is abstract and cannot be instantiated,


the class does not have much use unless it is
subclass. This is typically how abstract classes
come about during the design phase. A parent
class contains the common functionality of a
collection of child classes, but the parent class
itself is too abstract to be used on its own.
Abstract Class:

Use the abstract keyword to declare a class


abstract. The keyword appears in the class
declaration somewhere before the class keyword.

/* File name : Employee.java */


public abstract class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int
number)
{
System.out.println("Constructing an
Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println("Inside Employee
computePay");
return 0.0;
}
public void mailCheck()
{
System.out.println("Mailing a check to " +
this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}

Notice that nothing is different in this Employee


class. The class is now abstract, but it still has
three fields, seven methods, and one constructor.

Now if you would try as follows:

/* File name : AbstractDemo.java */


public class AbstractDemo
{
public static void main(String [] args)
{
/* Following is not allowed and would raise
error */
Employee e = new Employee("George W.",
"Houston, TX", 43);

System.out.println("\n Call mailCheck using


Employee reference--");
e.mailCheck();
}
}
When you would compile above class then you
would get the following error:

Employee.java:46: Employee is abstract; cannot


be instantiated
Employee e = new Employee("George W.",
"Houston, TX", 43);
^
1 error

Extending Abstract Class:

We can extend Employee class in normal way as


follows:

/* File name : Salary.java */


public class Salary extends Employee
{
private double salary; //Annual salary
public Salary(String name, String address, int
number, double
salary)
{
super(name, address, number);
setSalary(salary);
}
public void mailCheck()
{
System.out.println("Within mailCheck of
Salary class ");
System.out.println("Mailing check to " +
getName()
+ " with salary " + salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
public double computePay()
{
System.out.println("Computing salary pay for "
+ getName());
return salary/52;
}
}

Here, we cannot instantiate a new Employee, but if


we instantiate a new Salary object, the Salary
object will inherit the three fields and seven
methods from Employee.
/* File name : AbstractDemo.java */
public class AbstractDemo
{
public static void main(String [] args)
{
Salary s = new Salary("Mohd Mohtashim",
"Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams",
"Boston, MA", 2, 2400.00);

System.out.println("Call mailCheck using


Salary reference --");
s.mailCheck();

System.out.println("\n Call mailCheck using


Employee reference--");
e.mailCheck();
}
}

This would produce the following result:

Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary
3600.0
Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.

Abstract Methods:

If you want a class to contain a particular method


but you want the actual implementation of that
method to be determined by child classes, you can
declare the method in the parent class as abstract.

The abstract keyword is also used to declare a


method as abstract. An abstract method consists
of a method signature, but no method body.

Abstract method would have no definition, and its


signature is followed by a semicolon, not curly
braces as follows:

public abstract class Employee


{
private String name;
private String address;
private int number;

public abstract double computePay();

//Remainder of class definition


}
Declaring a method as abstract has two results:

The class must also be declared abstract. If a


class contains an abstract method, the class must
be abstract as well.

Any child class must either override the abstract


method or declare itself abstract.

A child class that inherits an abstract method must


override it. If they do not, they must be abstract
and any of their children must override it.

Eventually, a descendant class has to implement


the abstract method; otherwise, you would have a
hierarchy of abstract classes that cannot be
instantiated.

If Salary is extending Employee class, then it is


required to implement computePay() method as
follows:

/* File name : Salary.java */


public class Salary extends Employee
{
private double salary; // Annual salary

public double computePay()


{
System.out.println("Computing salary pay for "
+ getName());
return salary/52;
}

//Remainder of class definition


}

3.Inheritance:

Inheritance can be defined as the process where


one object acquires the properties of another. With
the use of inheritance the information is made
manageable in a hierarchical order.

When we talk about inheritance, the most


commonly used keyword would be extends and
implements. These words would determine
whether one object IS-A type of another. By using
these keywords we can make one object acquire
the properties of another object.
IS-A Relationship:

IS-A is a way of saying : This object is a type of


that object. Let us see how the extends keyword is
used to achieve inheritance.

public class Animal{


}

public class Mammal extends Animal{


}

public class Reptile extends Animal{


}

public class Dog extends Mammal{


}

Now, based on the above example, In Object


Oriented terms, the following are true:

Animal is the superclass of Mammal class.

Animal is the superclass of Reptile class.

Mammal and Reptile are subclasses of Animal


class.

Dog is the subclass of both Mammal and Animal


classes.

Now, if we consider the IS-A relationship, we can


say:

Mammal IS-A Animal


Reptile IS-A Animal

Dog IS-A Mammal

Hence : Dog IS-A Animal as well

With use of the extends keyword the subclasses


will be able to inherit all the properties of the
superclass except for the private properties of the
superclass.

We can assure that Mammal is actually an Animal


with the use of the instance operator.
Example:

public class Dog extends Mammal{

public static void main(String args[]){

Animal a = new Animal();


Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This would produce the following result:

true
true
true

Since we have a good understanding of the


extends keyword let us look into how the
implements keyword is used to get the IS-A
relationship.

The implements keyword is used by classes by


inherit from interfaces. Interfaces can never be
extended by the classes.
Example:

public interface Animal {}

public class Mammal implements Animal{


}

public class Dog extends Mammal{


}

The instanceof Keyword:

Let us use the instanceof operator to check


determine whether Mammal is actually an Animal,
and dog is actually an Animal
interface Animal{}

class Mammal implements Animal{}

public class Dog extends Mammal{


public static void main(String args[]){

Mammal m = new Mammal();


Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce the following result:

true
true
true

HAS-A relationship:

These relationships are mainly based on the usage.


This determines whether a certain class HAS-A
certain thing. This relationship helps to reduce
duplication of code as well as bugs.
Lets us look into an example:

public class Vehicle{}


public class Speed{}
public class Van extends Vehicle{
private Speed sp;
}

This shows that class Van HAS-A Speed. By having


a separate class for Speed, we do not have to put
the entire code that belongs to speed inside the
Van class., which makes it possible to reuse the
Speed class in multiple applications.

In Object-Oriented feature, the users do not need


to bother about which object is doing the real
work. To achieve this, the Van class hides the
implementation details from the users of the Van
class. So basically what happens is the users would
ask the Van class to do a certain action and the
Van class will either do the work by itself or ask
another class to perform the action.

A very important fact to remember is that Java


only supports only single inheritance. This means
that a class cannot extend more than one class.
Therefore following is illegal:
public class extends Animal, Mammal{}

However, a class can implement one or more


interfaces. This has made Java get rid of the
impossibility of multiple inheritance.

4.Polymorphism

Polymorphism is the ability of an object to take


on many forms. The most common use of
polymorphism in OOP occurs when a parent class
reference is used to refer to a child class object.

Any Java object that can pass more than one IS-A
test is considered to be polymorphic. In Java, all
Java objects are polymorphic since any object will
pass the IS-A test for their own type and for the
class Object.

It is important to know that the only possible way


to access an object is through a reference variable.
A reference variable can be of only one type. Once
declared, the type of a reference variable cannot
be changed.

The reference variable can be reassigned to other


objects provided that it is not declared final. The
type of the reference variable would determine the
methods that it can invoke on the object.
A reference variable can refer to any object of its
declared type or any subtype of its declared type.
A reference variable can be declared as a class or
interface type.
Example:

Let us look at an example.

public interface Vegetarian{}


public class Animal{}
public class Deer extends Animal implements
Vegetarian{}

Now, the Deer class is considered to be


polymorphic since this has multiple inheritance.
Following are true for the above example:

A Deer IS-A Animal

A Deer IS-A Vegetarian

A Deer IS-A Deer

A Deer IS-A Object

When we apply the reference variable facts to a


Deer object reference, the following declarations
are legal:
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

All the reference variables d,a,v,o refer to the


same Deer object in the heap.
Virtual Methods:

In this section, I will show you how the behavior of


overridden methods in Java allows you to take
advantage of polymorphism when designing your
classes.

We already have discussed method overriding,


where a child class can override a method in its
parent. An overridden method is essentially hidden
in the parent class, and is not invoked unless the
child class uses the super keyword within the
overriding method.

/* File name : Employee.java */


public class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int
number)
{
System.out.println("Constructing an
Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck()
{
System.out.println("Mailing a check to " +
this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}

Now suppose we extend Employee class as follows:

/* File name : Salary.java */


public class Salary extends Employee
{
private double salary; //Annual salary
public Salary(String name, String address, int
number, double
salary)
{
super(name, address, number);
setSalary(salary);
}
public void mailCheck()
{
System.out.println("Within mailCheck of
Salary class ");
System.out.println("Mailing check to " +
getName()
+ " with salary " + salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
public double computePay()
{
System.out.println("Computing salary pay for "
+ getName());
return salary/52;
}
}

Now, you study the following program carefully


and try to determine its output:

/* File name : VirtualDemo.java */


public class VirtualDemo
{
public static void main(String [] args)
{
Salary s = new Salary("Mohd Mohtashim",
"Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams",
"Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using
Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using
Employee reference--");
e.mailCheck();
}
}

This would produce the following result:

Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary
3600.0

Call mailCheck using Employee reference--


Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

Here, we instantiate two Salary objects . one using


a Salary reference s, and the other using an
Employee reference e.

While invoking s.mailCheck() the compiler sees


mailCheck() in the Salary class at compile time,
and the JVM invokes mailCheck() in the Salary
class at run time.

Invoking mailCheck() on e is quite different


because e is an Employee reference. When the
compiler sees e.mailCheck(), the compiler sees the
mailCheck() method in the Employee class.

Here, at compile time, the compiler used


mailCheck() in Employee to validate this
statement. At run time, however, the JVM invokes
mailCheck() in the Salary class.

This behavior is referred to as virtual method


invocation, and the methods are referred to as
virtual methods. All methods in Java behave in this
manner, whereby an overridden method is invoked
at run time, no matter what data type the
reference is that was used in the source code at
compile time.

Methods in Java

A Java method is a collection of statements that


are grouped together to perform an operation.
When you call the System.out.println method, for
example, the system actually executes several
statements in order to display a message on the
console.
Now you will learn how to create your own
methods with or without return values, invoke a
method with or without parameters, overload
methods using the same names, and apply method
abstraction in the program design.
Creating a Method:

Method:

The purpose of a method is to perform an


operation or a task
A method is devide into two parts:
Method declaration/Header/prototype:

The method declaration includes return


type.Method name and list of parameters.

Syntax: returnType methodname(list of


parameters)

In the method declaration specifying the return


type and the method name is mandatory and
specifying the list of parameters are optional.
The return type of the method must be
specified just before the method name.
To a method we can pass any number of
parameters any type of parameters.If we specify
multiple parameters separate them by a comma
symbol.
If a method doesnot want to return any value
then specify the return type has void.

2. Method definition/Body/Implementation:

The method definition includes the group of


statements enclosed with in the {}
Syntax: {
Statements
}
The method definition can contain any no.of
stmts.
If the return type of the method is void then
we need not specify the return .If the return stmt
of the method is any other type a part from void
then we must specify the return stmt in the
method definition.
Syntax: return value;
Ex: return 123;
Return 12.3;
Return a;
We specify the return statement generally as a
last statement in the method definition.
A method can return at most one value.

Types of Methods:
1.Method
without returntype and without parameters:
Eg: class Addition {
Void add(){
int a=11;
int b=22;
int c=a+b;
System.out.println(sum of
+a+and+a+is+c);
}
Public static void main(String[]ar){
Addition abc=new Addition();
Abc.add;
}
}

2. Method Without return Type and with


parameters:
Ex: class Addition{
Void add(int x,int y){
Int z=x+y
System.out.println(sum +z);

} Public static void main(String[]ar){


Addition ad=new Addition();
Int a =Integer.ParseInt(ar[0]);
Int b=Integer.ParseInt(ar[1]);
Ad.add(a,b);
}
}
The method declaration and method definition
invocation must be same no.of parameters and
same type of parameters.

3.Method With return type and without


parameters:
Ex:class Addition{
Void add(){
int a=10;
int b=20;
int c=a+b;
return c;
}
Public static void main(String[]ar){
Addition abc=new Addition();
Int z=abc.add()
System.out.println(sum:+z);
}
}

4.Method with return type and with parameters:


Ex:class Addition{
Double add(int x,doubley,doublez){
Double n=x+y+z;
Return n;
}
Public static void main(String[]ar){
Addition a=new Addition()
Double res=a.add(12,2.3,1.1);
System.out.println(sum:+res);
}
}
Calling a Method:
In creating a method, you give a definition of what
the method is to do. To use a method, you have to
call or invoke it. There are two ways to call a
method; the choice is based on whether the
method returns a value or not.
When a program calls a method, program control
is transferred to the called method. A called
method returns control to the caller when its
return statement is executed or when its method-
ending closing brace is reached.
If the method returns a value, a call to the method
is usually treated as a value. For example:
int larger = max(30, 40);
If the method returns void, a call to the method
must be a statement. For example, the method
println returns void. The following call is a
statement:
System.out.println("Welcome to Java!");
Example:
Following is the example to demonstrate how to
define a method and how to call it:
public class TestMax {
/** Main method */
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
System.out.println("The maximum between "
+i+
" and " + j + " is " + k);
}

/** Return the max between two numbers */


public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;

return result;
}
}
This would produce the following result:
The maximum between 5 and 2 is 5
This program contains the main method and the
max method. The main method is just like any
other method except that it is invoked by the JVM.
The main method's header is always the same, like
the one in this example, with the modifiers public
and static, return value type void, method name
main, and a parameter of the String[] type.
String[] indicates that the parameter is an array of
String.
The void Keyword:
This section shows how to declare and invoke a
void method. Following example gives a program
that declares a method named printGrade and
invokes it to print the grade for a given score.
Example:
public class TestVoidMethod {

public static void main(String[] args) {


printGrade(78.5);
}

public static void printGrade(double score) {


if (score >= 90.0) {
System.out.println('A');
}
else if (score >= 80.0) {
System.out.println('B');
}
else if (score >= 70.0) {
System.out.println('C');
}
else if (score >= 60.0) {
System.out.println('D');
}
else {
System.out.println('F');
}
}
}
This would produce the following result:
C
Here the printGrade method is a void method. It
does not return any value. A call to a void method
must be a statement. So, it is invoked as a
statement in line 3 in the main method. This
statement is like any Java statement terminated
with a semicolon.
Passing Parameters by Values:
When calling a method, you need to provide
arguments, which must be given in the same order
as their respective parameters in the method
specification. This is known as parameter order
association.
For example, the following method prints a
message n times:
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Here, you can use nPrintln("Hello", 3) to print
"Hello" three times. The nPrintln("Hello", 3)
statement passes the actual string parameter,
"Hello", to the parameter, message; passes 3 to n;
and prints "Hello" three times. However, the
statement nPrintln(3, "Hello") would be wrong.
When you invoke a method with a parameter, the
value of the argument is passed to the parameter.
This is referred to as pass-by-value. If the
argument is a variable rather than a literal value,
the value of the variable is passed to the
parameter. The variable is not affected, regardless
of the changes made to the parameter inside the
method.
For simplicity, Java programmers often say passing
an argument x to a parameter y, which actually
means passing the value of x to y.
Example:
Following is a program that demonstrates the
effect of passing by value. The program creates a
method for swapping two variables. The swap
method is invoked by passing two arguments.
Interestingly, the values of the arguments are not
changed after the method is invoked.
public class TestPassByValue {

public static void main(String[] args) {


int num1 = 1;
int num2 = 2;

System.out.println("Before swap method,


num1 is " +
num1 + " and num2 is " +
num2);

// Invoke the swap method


swap(num1, num2);
System.out.println("After swap method, num1
is " +
num1 + " and num2 is " +
num2);
}
/** Method to swap two variables */
public static void swap(int n1, int n2) {
System.out.println("\tInside the swap
method");
System.out.println("\t\tBefore swapping n1 is
" + n1
+ " n2 is " + n2);
// Swap n1 with n2
int temp = n1;
n1 = n2;
n2 = temp;

System.out.println("\t\tAfter swapping n1 is "


+ n1
+ " n2 is " + n2);
}
}
This would produce the following result:
Before swap method, num1 is 1 and num2 is 2
Inside the swap method
Before swapping n1 is 1 n2 is 2
After swapping n1 is 2 n2 is 1
After swap method, num1 is 1 and num2 is 2
Overloading Methods:
The max method that was used earlier works only
with the int data type. But what if you need to find
which of two floating-point numbers has the
maximum value? The solution is to create another
method with the same name but different
parameters, as shown in the following code:
public static double max(double num1, double
num2) {
if (num1 > num2)
return num1;
else
return num2;
}
If you call max with int parameters, the max
method that expects int parameters will be
invoked; if you call max with double parameters,
the max method that expects double parameters
will be invoked. This is referred to as method
overloading; that is, two methods have the same
name but different parameter lists within one
class.
The Java compiler determines which method is
used based on the method signature. Overloading
methods can make programs clearer and more
readable. Methods that perform closely related
tasks should be given the same name.
Overloaded methods must have different
parameter lists. You cannot overload methods
based on different modifiers or return types.
Sometimes there are two or more possible
matches for an invocation of a method due to
similar method signature, so the compiler cannot
determine the most specific match. This is referred
to as ambiguous invocation.
The Scope of Variables:
The scope of a variable is the part of the
program where the variable can be referenced. A
variable defined inside a method is referred to as a
local variable.
The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must be
declared before it can be used.
A parameter is actually a local variable. The scope
of a method parameter covers the entire method.
A variable declared in the initial action part of a for
loop header has its scope in the entire loop. But a
variable declared inside a for loop body has its
scope limited in the loop body from its declaration
to the end of the block that contains the variable
as shown below:

You can declare a local variable with the same


name multiple times in different non-nesting
blocks in a method, but you cannot declare a local
variable twice in nested blocks.
Using Command-Line Arguments:
Sometimes you will want to pass information into a
program when you run it. This is accomplished by
passing command-line arguments to main( ).
A command-line argument is the information that
directly follows the program's name on the
command line when it is executed. To access the
command-line arguments inside a Java program is
quite easy.they are stored as strings in the String
array passed to main( ).
Example:
The following program displays all of the
command-line arguments that it is called with:
public class CommandLine {

public static void main(String args[]){


for(int i=0; i<args.length; i++){
System.out.println("args[" + i + "]: " +
args[i]);
}
}
}
Try executing this program as shown here:
java CommandLine this is a command line 200 -
100
This would produce the following result:
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
The finalize( ) Method:
It is possible to define a method that will be called
just before an object's final destruction by the
garbage collector. This method is called finalize( ),
and it can be used to ensure that an object
terminates cleanly.
For example, you might use finalize( ) to make
sure that an open file owned by that object is
closed.
To add a finalizer to a class, you simply define the
finalize( ) method. The Java runtime calls that
method whenever it is about to recycle an object
of that class.
Inside the finalize( ) method, you will specify those
actions that must be performed before an object is
destroyed.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that
prevents access to finalize( ) by code defined
outside its class.
This means that you cannot know when or even if
finalize( ) will be executed. For example, if your
program ends before garbage collection occurs,
finalize( ) will not execute.

You might also like