0% found this document useful (0 votes)
41 views20 pages

Java 2

This document discusses Java escape sequences and provides examples of their usage. It also discusses static blocks in Java and how they are executed before the main method. Finally, it introduces some basic object-oriented programming concepts like abstraction, encapsulation, and polymorphism.

Uploaded by

naresh maddu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
41 views20 pages

Java 2

This document discusses Java escape sequences and provides examples of their usage. It also discusses static blocks in Java and how they are executed before the main method. Finally, it introduces some basic object-oriented programming concepts like abstraction, encapsulation, and polymorphism.

Uploaded by

naresh maddu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

Java Escape Sequences::

Escape sequence is a character which escapes normal sequence of output


(evaluation)". Escape sequences are very common in a language. Escape
sequence precedes with a \ (backslash). For example, \n stands for new
line; even though it looks two characters, Java treats them as one
character with ASCII code of 10. Escape sequence, being a single
character, should be put within single quotes. Observe the following
simple code.

public class Demo


{
public static void main(String args[])
{
int x = '\t'; // enclosed within single
quotes
System.out.println(x); // prints 9

int y = '\n';
System.out.println(y); // prints 10
}
}
You can try for other escape characters also what their ASCII codes.

Java also comes escape sequences and the list if given here under.

Escape Sequence Meaning


\n Gives a new line
\t Gives one tab space (Java gives 6 spaces)
\" Prints just double quotes, "
\' Prints just single qutotes, '
\r Carriage return; The second line comes to the beginning of the
line; that is, comes to extreme left where a new line begins.
\b Moves one space backwards. The character preceded to \b is deleted
\\ prints one slash (instead of two)
\f Form feed
Following code gives some escape sequences usage.

public class Demo


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

System.out.println("abc\ndef"); // abc and def are given in two


lines

System.out.println("ab\bcd"); // prints acd


System.out.println("ab \bcd"); // prints abcd, the space before
\b is gone
System.out.println("abcdefghij"); // prints ab cd, gives 3 spaces
between ab and cd
System.out.println("ab\tcd"); // prints ab cd, gives 3 spaces
between ab and cd

System.out.println("a\"bc\"d"); // prints a"bc"d

System.out.println("a\'bc\'d"); // prints a'bc'd


}
}
Static Blocks – Static Initialization:::
Generally, a Java programmer initializes variables in a constructor (or
init() method in case of applet). It is the best place chosen, as the
constructor is called implicitly when an object is created. Programmer
creates objects before anything is done in coding (as object is required
to call an instance variable or method).

In the place of a constructor, a static block can be chosen, if the


programmer does not like to have a constructor. One more advantage is
static block is executed even before main() method is executed. That is,
Java execution starts from static blocks and not from main() method.

Three programs are given on static blocks; each differ slightly.

In the following program, the instance variables are static. As they are
static, they called from main() without the help of an object.

public class Demo


{
static double $rate;
static int numOfDollars;
static
{
$rate = 44.6;
numOfDollars = 12;
System.out.println("I am static block, I am called first.");
}
public static void main(String args[])
{
Demo d1 = new Demo();
System.out.println("I am main() method, executed after static
block.");
System.out.println("Dollar value in Rupees: " + $rate *
numOfDollars);
}
}
After executing static block, main() is executed. Observe the screenshot.

The previous program can be modified where instance variables are not
static. Then you require an object to call them from static main()
method.

public class Demo


{
double $rate;
int numOfDollars;
static Demo d1;
static
{
d1 = new Demo();
d1.$rate = 44.6;
d1.numOfDollars = 12;
System.out.println("I am static block, I am called first.");
}
public static void main(String args[])
{
System.out.println("I am main() method, executed after static
block.");
System.out.println("Dollar value in Rupees: " + d1.$rate *
d1.numOfDollars);
}
}

Multi Static Blocks

A program can have any number of static blocks.

public class MultiStaticBlocks


{
static
{
System.out.println();
System.out.println("From first static block.");
}
static
{
System.out.println("From second static block.");
}
static
{
System.out.println("From third static block.");
}
}

Observe, purposefully, the main() method is not included in the program.


Even then, the program compiles and runs as static blocks are called
before main(). Look at the screenshot, the main() is checked by the JVM
after calling all static blocks. As the main() is not available, an
exception is thrown.

JDK 1.7 Modifications

From JDK 1.7, main() method is required to execute static block. Anyhow,
static block is called before main() is executed.

OOPS concepts – introduction::


There are three basic concepts of OOPS

Abstraction
Encapsulation
Polymorphism

1. Abstraction

Abstraction means using the equipment (or code) without knowing the
details of working. For example, you are using your mobile phone without
knowing how a mobile operates internally. Just a click on a button
connects to your friend. This is abstraction. That is, the details of
mobile mechanism are abstracted. Similarly we use the code of somebody to
get the functionality without knowing how the code is written or working.
For example, you are using printf() function to write to the DOS prompt
without the awareness of what the code of printf(). One of the ways of
achieving abstraction is inheritance. Through inheritance a subclass can
use the super class methods as if they belong to it without caring their
implementation details.

2. Encapsulation
Object-oriented concepts borrowed many terms from other technologies like
encapsulation (from pharmaceuticals), inheritance (from biology), cloning
(from genetics) and polymorphism (from biology) etc. Placing a powdered
drug in a gelatin capsule and sealing it is known as encapsulation. With
encapsulation, a Pharmacist hides the properties of a drug like its taste
and color from the patient. Similar meaning is in OOPs also.
Encapsulation hides the implementation details of coding; other way it is
abstraction. With abstraction, implementation of information is hidden.

In a programming language, variables represent the properties and methods


are used to change the properties. For example, the speed variable
represent the property of a motor car and the method accelerator() is
used to change the speed. Objects are used to call the methods. There may
be multiple motor cars and every car has its own speed. Here, motor car
represents an object. Every object encapsulates its own data. This
encapsulation concept takes OOP languages a lead over traditional
procedure-oriented languages. Binding data with objects (generally
through method calls) is known as encapsulation.

In encapsulation, to have control over the manipulation of data (not to


feed wrong data, for example, the speed cannot be negative) by other
classes, a programmer declares variables as private and methods as
public. Other classes can access the private variables through public
methods. With encapsulation, every object maintains its own data and this
data is entirely private to that object. Other objects cannot access or
modify the data.

3. Polymorphism

Polymorphism is a Greek term and means many forms of the same ("poly"
means many and "morphism" means forms). It is an OOP paradigm where one
method can be made to give different outputs (functionalities) when
called at different times. Polymorphism is two ways – static polymorphism
where methods are binded at compile time and dynamic polymorphism where
methods are binded dynamically at runtime. The same person is called as
an officer (in office), husband (in house) and player (in cricket team).
The person can be treated as base class. Extra subclasses can be added by
hierarchical inheritance like son etc.

Java Naming Conventions – Readability::


After knowing the rules of identifiers, it is the time to know the
another grammar of Java known as "conventions". Conventions increase the
readability of the program. Conventions are applied to identifiers. An
identifier, in Java, may denote a class name, a variable name or a method
name. Java follows "Hungarian notation" in naming conventions.
Conventions are very simple to remember.

1. Convention for class Names

The starting letter of each word, in a class name, should be of


uppercase.

Identifier accepts Convention says


myfirsthouse MyFirstHouse
firsthouse FirstHouse
house House
wishes Wishes
numberformatexception NumberFormatException
2. Convention for Variable Names
The starting letter of the first word should be of lowercase and the
starting letter of all the remaining words should be of uppercase.

Identifier accepts Convention says


myfirsthouse myFirstHouse
firsthouse firstHouse
house house
wishes wishes
lightgray lightGray
price price
x x
3. Convention for Method Names

Convention for method is simply that of variable only but followed by


parenthesis.

Identifier accepts Convention says


myfirsthouse() myFirstHouse()
firsthouse() firstHouse()
house() house()
display() display()
indexof() indexOf()
lastindexof() lastIndexOf()

Basic Class Structure, Compilation and Execution::


What is a class in Java?

Two concepts existed in the minds of Java designers from the day one of
development – to make the language simple and easy to practice and
platform-independent. The basic entity of Java coding is a "class". A
class is delimited by a pair of braces, { and }. All the code resides
within a class. The name of the class is the name with which the whole
code is known. An object is a handle to manipulate the whole code of the
class. A class can comprise of constructors, variables, methods and some
blocks of code (like static blocks) etc.

First Java Program

Here, some procedure is to be followed. We know the basic construct of a


Java program is a "class".

Open a file with the same name of that of the class. Say, the name of the
class, you would like to write is "Wihses", then open the file as
"Wishes.java" as follows.

c:\basics> notepad Wishes.java


The above statement creates a file called Wishes.java in the current
directory c:\basics. In the notepad editor start typing the program.

import java.lang.*;
public class Wishes
{
public static void main(String args[])
{
System.out.println("Hello World");
System.out.println("Best wishes");
}
}
Just save the file after typing the code.
Compilation

Now it is the time for compilation. Compile as follows.

c:\snr> javac Wishes.java


"javac" is a Java command to compile the file, Wishes.java. If everything
goes smooth (no errors exist in the program), you obtain a file called
"Wishes.class". Wishes.class is the executable file (equivalent to .exe
of C/C++). Now you can open the Wishes.class and see. What you find is
the bytecode format. Bytecode makes Java platform-independent.

Execution

Type the following command at the DOS prompt to execute the code.

c:\snr> java Wishes

java" is a Java command of execution. That is, you are invoking the Java
interpreter to execute the bytecode. You get the output at the DOS
prompt.

Let us discuss some coding details of the above simple program.

import java.lang.*;

"import" is a keyword of Java equivalent to "include" of C/C++. Here, a


small difference exists. "java.lang" is known as package. A package is
equivalent to a header file of C-lang. A package contains classes and
methods exist in the classes. But, a header file contains directly
functions. Java classes (containing methods) are distributed through
packages and sub packages. "lang" is the sub package of package "java".
Distributing classes through packages has got an advantage over
traditional header files.

Note: "java.lang" package is implicitly imported if the programmer does


not import himself.

public class Wishes

In the above statement, "public" is a keyword and denotes an access


specifier. "public" means anybody can access the code without any
restrictions. Java includes other access specifiers also. The whole
program is known by the name "class Wishes". Again "class" is a keyword.
Observe, the class is delimited by two braces, { and }. Java demands that
all the code you write, may spread thousands of lines, should be within
the class declaration only.

public static void main(String args[])

The main() method comes with many decorative paraphernalia and each one
conveys some meaning to the compiler. The "static" means the main()
method can be called without the help of an object. "void" keyword means
the main() method does not return a value. The main() takes a String
array as parameter and is used later to access command-line arguments.

The System.out.println() prints the data at the DOS prompt (equivalent to


printf()). println() method gives an implicit "\n" character. "in" in
println() stands for new line. The output comes in two different lines.

Using Local and Instance Variables::


Variables – Properties

A program stores values in variables. As the name indicates, a variable


value can be varied by the programmer at any time. An object uses
variables to set its properties. For example, a motor car uses the
properties like speed and petrol etc. by storing them in variables. The
declaration of a variable requires a data type. A data type says what
type of value a programmer can store in the variable.

Using Local Variables

The variables declared within a method body are known as "local


variables". The method parameters are also treated as local variables
only. As their accessibility (or scope) is limited to the method only,
the local variables can be used within the method body only. That is,
other methods cannot use them.

public class MethodVariables


{
public static void main(String args[])
{
int mangoes = 10, bananas = 20;
System.out.println(mangoes);
System.out.println(bananas);
System.out.println(mangoes + bananas);

System.out.println("No of mangoes: " + mangoes);


System.out.println(mangoes + " and " + bananas + " sum is " +
(mangoes+bananas));
}
}
Observe, the variables mangoes and bananas are declared in the body of
the main() method. They can used within the main() only.

System.out.println(mangoes);

To print the values of variables, it is not required to use the place


holders like %d or %f etc. Just writing directly mangoes, prints the
value of the mangoes variable as in the above statement.

System.out.println("No of mangoes: " + mangoes);

In the above statement, + operator works for concatenation of a string


and a variable value.

System.out.println(mangoes + " and " + bananas + " sum is " +


(mangoes+bananas));

Java does not support operator overloading but designers overloaded the +
operator. In Java coding, + operator can be used both for addition and
concatenation. In the above statement, + is used for the concatenation of
" and " and also used for addition as in "mangoes+bananas". To get the
correct values, if there exists a string in println statement, the
variables that are to be added are to be placed in parenthesis. Observe,
mangoes+bananas are placed within parenthesis.

Basic Constructs – Objects


Java being an object-oriented language, objects play an important role.
Every real time entity can be treated as an object. For example, a motor
car can be treated as an object. Variables are used to set the properties
for an object. To manipulate the variables, methods are used. Methods are
called with objects. So variables, methods and objects constitute a
program. An object is a handle with which all the code of a class can be
accessed or manipulated.

A number of objects can be created for a single class. Each object can be
given properties through variables. OOP permits to have a separate set of
values for each object. Methods increase the reusability of code. Methods
of Java are called as procedures or functions in other languages.

Let us define what an object is. A C++ programmer says, an instance of a


class is known as object. Of course, he is right but the definition is
somewhat confusing. Let us put it more explanatory. Suppose, when we cut
the tree, we get the wood. Wood, as it is, is useless until and unless it
is converted into objects like door, table etc. Without the articles like
door or table, wood is waste. These articles are termed as objects in an
OOP language. A class comprises of methods, constructors and variables
etc. To use the class we require an object. So, the object represents the
whole class. We can treat object as a handle with which the whole class
can be handled. Without object, the class is useless as it cannot be
used. In our first simple program, the name of the class is “Wishes” and
includes only one method, main() method. We did not create any objects
and we do it in the next program.

Using Instance Variables from static main()

Java is a strongly-typed language where variables should be declared and


given values before they are used. Java coding uses both local variables
and global variables. The global variables are known as "instance
variables" in Java. Instance variables are to be called with instances
(objects) from static methods like main(). It is to be noted that local
variables do not require an object. The scope of instance variables is
for whole class and local variables are within the method in which they
are declared. In the following program local and instance variables are
used.
public class Employee { int salary; // instance variables String
department; public static void main(String args[]) { String company =
"Lorvent Solutions"; // local variable System.out.println(company); //
calling local variable without object Employee emp1 = new Employee();
emp1.salary = 8000; emp1.department = "Finance";
System.out.println(emp1.salary); // calling instance variables with
object System.out.println(emp1.department);
System.out.println(emp1.department + " section exists in " + company); //
System.out.println(salary); // compilation error } } -

In the above Employee class, one local variable "company" and two
instance variables "salary" and "department" are declared. They are used
from the static main() method. As you can observe from the above program,
to call the local variable "company", object "emp1" is not used; but to
call the instance variables emp1 is used. If not, the compiler raises
errors (as in the last statement).
Employee emp1 = new Employee();

First time we are creating an object of a class. Note the syntax. The
class name comes two times. Employee is the class and Employee() is known
as a constructor. “new” keyword is used to create an object.
emp1.salary = 8000;
emp1.department = “Finance”;

In the above two statements, to give values for the instance variables
salary and department, object emp1 is used.

System.out.println(company);
System.out.println(emp1.salary);
System.out.println(emp1.department);

To print the local variable company, object is not used. To print the
instance variables, object emp1 is used.

Using Methods and Method Overloading::

Using Methods

The procedures and functions are known as methods in Java. The methods
scope is for the whole class. Now here, you can make a small difference.
A function in C-lang can be called without object but a method is to be
called with an object. The first line of a method declaration is known as
"method signature". A Java method signature may comprises of an access
specifier, one or two optional access modifiers, return type, name,
optional parameter list and also optional exceptions the method can
throw. The parameter or a return type can be a variable, an object or an
array. Following program illustrates.

public class Employee


{
public void nature()
{
System.out.println("Hard working");
}
public int total(int basic, int da, int hra)
{
int sum = basic + da + hra;
return sum;
}
public static void main(String args[])
{
Employee emp1 = new Employee();
emp1.nature();
int salary = emp1.total(8000, 2000, 1000);
System.out.println("The total salary Rs." + salary);
}
}

The above code involves two methods – nature() and total(). The nature()
method just prints a message and does not have parameters and return
type. But total() method takes three parameters and a return type. The
return type must be only one value for a method. You will not see any new
information here, it is same as C/C++. Observe, the methods are called
with object emp1 (like instance variables). To make the program simple,
instance variables are not used. We will write another program later with
instance variables and methods. The global variables in Java are known as
"instance variables".

To talk technically, a method gives behavior to an object. For example,


an Employee object emp1 is given nature and total salary though methods
nature() and total(). Later even to change the nature of emp1, the same
methods are to be used. Methods are useful to write the logic and to give
actions to an object by manipulating the properties of an object.

Similar explanation is available at Three Great Principles – Data


Binding, Data Hiding, Encapsulation.
Method Overloading

Observe the following functions of C-lang.

void display() { }
void display(int x) { }

The above two functions of the same name display() raises compilation
error in C-lang as C cannot differentiate the same functions depending on
their parameters. But C++ and Java can differentiate the same named
functions depending on their parameters. The same method declared, in the
same class, a number of times, but with different parameters is known as
"method overloading". With method overloading, the same method called at
different times gives different outputs (functionalities).

public class Animal


{
public void eat() // I
{
System.out.println("All animals eat");
}
public void eat(int x) // II
{
System.out.println("Whale eats more than " + x + " tons of food
a day");
}
public void eat(String str) // III
{
System.out.println("Parrots eat " + str);
}
public static void main(String args[])
{
Animal a1 = new Animal();
a1.eat(); // calls I
a1.eat(5); // calls II
a1.eat("grains"); // calls III
}
}
In the above Animal class, the same eat() method is declared three times
and each time takes different parameters – no parameter, int parameter
and string parameter. Compiler can easily differentiate which method is
to be called depending upon the number of parameters and their sequence
of data types.

Return type in Overloading

See the following two method declarations.

public void eat()


public int eat()

The above two eat() methods differ in their return type but not in
parameters. Compiler cannot judge which is to be called depending on the
return types; judges only on the parameter list. The above statements
raise a compilation error. The return type may or may not be the same in
method overloading.

Static Binding

Compiler decides at compile time itself which overloaded method is to be


called. That is, method binding is done at compile time itself. This is
known as "static binding". At runtime, simply methods are called. Java
also supports dynamic binding which leads to dynamic polymorphism.

Static Polymorphism

In Greek, "poly" means "many" and "morphism" means "forms". Polymorphism


means many forms of the same method – the same method, called at
different times, gives different types of output. The three eat() methods
print different functionalities of the nature of animals like whale and
parrot. Because the polymorphism is achieved statically, at compile time,
it is known as "static polymorphism". Java achieves static polymorphism
with method overloading.

Three Great Principles – Data Binding, Data Hiding, Encapsulation:::

To go before into the subject, just read the program twice. You may guess
some values how they are printed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Officer
{
int salary;
public static void main(String args[])
{
Officer o1 = new Officer();
Officer o2 = new Officer();

o1.salary = 5000;
o2.salary = 6000;
System.out.println("Salary of o1 before initially Rs." +
o1.salary);// 5000
System.out.println("Salary of o2 before initially Rs." +
o2.salary);// 6000

o1.salary = 7000;
System.out.println("Salary of o1 after changing o1 Rs.:" +
o1.salary);// 7000
System.out.println("Salary of o2 after changing o1 Rs." +
o2.salary);// 6000

o2.salary = 8000;
System.out.println("Salary of o1 after changing o2 Rs.:" +
o1.salary);// 7000
System.out.println("Salary of o2 after changing o2 Rs." +
o2.salary);// 8000
}
}

salary is an instance variable and should be accessed with an object


only, through static main() method. Two objects o1 and o2 are created and
salary field is called. The object o1 gets a salary of 5000 and o2 gets
6000. If an instance variable is called with an object, a location is
created in the memory. Now two locations are created in the memory for
o1.salary and o2.salary. That is, one location of salary is binded with
o1 and another location of salary is binded with o2. This is is known as
data binding. Due to this binding habit, the salary location of o1 is
hidden from o2 and similarly the salary location of o2 is hidden from o1.
This is known as data hiding. Due to hiding, o1 cannot access o2 salary
and o2 cannot access o1 salary. That is, the variable salary is
encapsulated with object o1 and becomes one unit of data. Similarly
another unit o2 is made with its own salary, entirely separate from o1
unit. This is known as encapsulation. Encapsulation is a pharmaceutical
term where drug powder is placed in a capsule to hide its properties,
like taste and color etc., from the patients. Due to data hiding, the
properties (the value of fields(instance variables)) of an object are
hidden from other objects. This exactly resembles a capsule. The
advantage of encapsulation is one instance variable can be given multiple
values, of course, by calling with different objects. Encapsulation is an
object oriented concept or paradigam or design or principle; you may say
anything, all amounts the same.
In the later part of the program, salary of o1 is changed. Only the
salary of o1 is affected but not o2 and when o2 salary is changed, o1
salary is not affected. It is due the concept of encapsulation. This is
where object-oriented programming takes a lead over procedure-oriented
programming, like C. Finally, data binding leads to data hiding and data
hiding leads to encapsulation.

Encapsulation – Want or Don’t Want

Now let us see how to assign the properties of one object to another by
modifying the previous Officer program.

public class Officer1


{
int salary;
public static void main(String args[])
{
Officer1 o1 = new Officer1();
Officer1 o2 = new Officer1();
Officer1 o3 = new Officer1();
Officer1 o4 = new Officer1();
o1.salary = 5000;
o2.salary = o1.salary; // assigning variable to
variable
System.out.println("o1 initial salary Rs." + o1.salary); // 5000
System.out.println("o2 initial salary Rs." + o2.salary); // 5000

o1.salary = 6000;
System.out.println("o1 salary after changing o1 Rs." + o1.salary); //
6000
System.out.println("o2 salary after changing o1 Rs." + o2.salary); //
5000

o3.salary = 7000;
o4 = o3; // assigning object to
object
System.out.println("o3 initial salary Rs." + o3.salary); // 7000
System.out.println("o4 inital salary Rs." + o4.salary); // 7000

o3.salary = 8000;
System.out.println("o3 salary after changing o3 Rs." + o3.salary);
// 8000
System.out.println("o4 salary after changing o3 Rs." + o4.salary);
// 8000
}
}

The basic concept in the above code is to observe encapsulation by


assigning variable to variable and object to object. Four objects are
created. o1 salary is set to 5000 and later o1 salary is assigned to o2
salary. They maintain separate locations and advantage is if o1 salary is
changed to 6000, o2 salary is not affected. Observe the output. Later o3
salary is set to 8000. Object o4 is assigned with o3. In Java, when
object to object is assigned, they maintain or refer the same location.
That is, o3 and o4 refer or point to one salary only. The affect is if
one object o3 changes the salary, the other object o4 also changes.
Observe the output. Similarly, you can change o4 salary and notice o3
salary also changes; no encapsulation. Copying concepts are more
discussed in Copying an Object – Shallow Copying Vs. Deep Copying.

Final conclusion, we can make out is, if variable to variable is assigned


perfect encapsulation is maintained and object to object is assigned no
encapsulation is maintained. This must be kept in mind while assigning
properties of one object to another. Another style of copying is cloning
which we get later.

Using Thin main() Method

In the previous, Officer1 program, all the code is written in the main()
method only. You may get output but it is against coding principles.
Coding principles say, keep the main() method as thin as possible by
placing less code. Limit the main() method just to create objects and
calling the methods. Write any code in a method and call the method from
the main(). This increases the reusability, readability and debugging
becomes easier. Let us modify the previous program.

public class Officer2


{
int salary;
public void display(int sal)
{
salary = sal;
}
public static void main(String args[])
{
Officer2 o1 = new Officer2();
Officer2 o2 = new Officer2();

o1.display(5000);
o2.display(6000);

System.out.println(o1.salary); // 5000
System.out.println(o2.salary); // 6000
}
}

The difference between Officer1 and Officer2 programs is assigning the


values to objects o1 and o2. sal is a local variable to display() method
and salary is an instance variable (the other name of global variable).
Local variable sal is assigned to instance variable salary. When
o1.display(5000) is called, 5000 goes to sal and in turn sal gives to
salary. Because salary is an instance variable, one location on the name
o1.salary is created and is accessed though main(). But o1 is not linked
to sal because sal is a local variable and thereby no location is
created. Similar discussion is available in Using Variables from Methods.

Next program is a modification this program where "this" keyword is used.

Using Variables from Methods:::

We have seen earlier with, Using Methods program, how to use methods in
Java, but it was without using instance variables. Now let us use
instance variables through methods.

public class VariablesWithMethods


{
int a = 100;
public void show()
{
int b = 200; // calling instance
variable a
System.out.println("a value from show(): " + a);
// calling local
variable b
System.out.println("b value from show(): " + b);
a = 300;
}
public static void main(String args[])
{
VariablesWithMethods vwm = new VariablesWithMethods();
vwm.show();
System.out.println("a value from main(): " + vwm.a); // prints 300
}
}

Even though the code looks simple, there is a necessity to explain how
vwm.a called from main() method printed 300 and not 100. What are the
principles involved and what is going actually inside?
To make coding simple, designers share a lot of work which we are
supposed to do ourselves. Whenever a method is called with an object,
like vwm.show(), the instance variables inside the method are linked with
the object implicitly. For this reason, the a called from show() becomes
vwm.a. One more principle is, whenever an instance variable is called
with an object, a global location is created for vwm.a. This location
even though created through show() method, the location can be accessed
by any other method, but with vwm object only. The location a is private
to object vwm only. This is how encapsulation is maintained. If another
object is there like vwm1 and called the show() as vwm1.show(), then
there creates a location on the name of vwm1.a and this location is
private to vwm1.

Now a value in show() method is changed from 100 to 300. But a is nothing
but vwm.a. Earlier value in the location is 100 and now changed to 300.
By the time control comes to vwm.a in main() method, the value of vwm.a
is already changed. For this reason, vwm.a from main() method prints 300.

To get the concept more clearer, let us write one more program with an
additional explanation of data binding, data hiding and encapsulation.

Using this Keyword:::

"this" keyword refers an object, to say, the current object. Observe the
following program and pay attention to this.salary.

public class Officer3


{
int salary;
public void display(int salary)
{
this.salary = salary;
}
public static void main(String args[])
{
Officer3 o1 = new Officer3();
o1.display(5000);
System.out.println(o1.salary); // 5000
}
}
In the display() method, local variable and the instance variable are
same, salary. That is, local variable clashes with instance variable. If
"this" is removed in display() method, o1.salary in the main() method
prints 0. "this" refers the object o1 as with o1 the display() method is
called. Now we can make one rule, if a method is called with an object,
the instance variables inside the method are linked with the object
implicitly. Now, this.salary becomes o1.salary internally and one memory
location is created. If "this" is removed, both salaries are treated as
local variables and thereby the compiler does not create any memory
location. Use always "this" keyword to differentiate a local from
instance variable when they clash. C++ people, call "this keyword" as
"this pointer".

Unassigned Local and Instance Variables::

One of the features of Java is "Java does not support garbage values". If
a variable is used without a value assigned, it is either compilation
error or takes a default value. If a local variable is not given a value
and still used in the program it is a compilation error. But in case of
an instance variable, it takes a default value. For example, an integer
variable takes 0 by default. Following program illustrates.

public class Values


{
int price;
double rate;
boolean raining;

public static void main(String args[])


{
int marks;

// System.out.println(marks); // raises compilation error


Values v1 = new Values();
System.out.println(v1.price); // prints 0
System.out.println(v1.rate); // prints 0.0
System.out.println(v1.raining); // prints false
}
}

In the above code, price, rate and raining are instance variables and
printed default values. But local variable marks is placed in comments.
If comments are removed and compiled the program, it raises compilation
error. The following list gives the default values for instance
variables.

Date type Default value


byte 0
short 0
int 0
long 0
float 0.0
double 0.0
char \u0000 (does not print any value)
boolean false

static Keyword – Philosophy:::

After discussing the usage of "this" keyword, let us move to another


keyword "static". The "static" keyword is used as an access modifier.
Java has access specifiers and access modifiers and both are very
different. Access specifiers specify the access and access modifiers
modifies the access. It may be confusing right now and will be clear
soon.

Generally, you know earlier, to call a method and also a variable from
the static main(), you require an object. Of course it is right but not
with static methods and static variables. static modifier modifies the
access and allows to call without the help of an object. "static" keyword
can be applied to instance variables and methods and not with classes and
also not with local variables..

Static with Variables

Java permits to call a static variable or method in three ways.

Can be called without the help of an object


Can be called with the help of an object
Can be called with class name
The following program explains the static keyword with variables.

public class StaticDemo


{
static int price = 100;
public static void main(String args[])
{
System.out.println(price); // without object

StaticDemo sd1 = new StaticDemo();


System.out.println(sd1.price); // with object

System.out.println(StaticDemo.price); // with class name


}
}

The instance variable price is declared as static and is called in three


ways – without object, with object and with class name.

Static with Methods

The same style of static variables is followed with static methods also
and can be called in three ways. Following program explains.

public class StaticDemo2


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

StaticDemo2 sd1 = new StaticDemo2();


sd1.show(); // with object

StaticDemo2.show(); // with class


name
}
}
The show() method is declared as static and is called in three ways. It
is allowed with class name also to facilitate to call many methods of
Java API classes without the help of an object. Many methods are declared
static in Java classes like java.lang.Character and java.lang.Math etc.

Class Variable

A static variable is also known as "class variable" as all the objects of


the whole class refer (or share) the same variable (location); that is,
one variable is used by all the objects (in encapsulation, each object
will have separate location of a variable). As all the objects refer the
same location (variable), no encapsulation exist with static variable.

Can a local variable be declared static?

A local variable cannot be static. If static the meaning of static is


lost. A static variable scope is for the objects of whole class and if
declared local as static, the purpose of static is lost and compiler
raises error.

Why the main() is static?

main() method is declared as static to allow the JVM to call the main()
without the help of an object. JVM is a separate process and to call the
method of another process (your program), it requires an object. As the
execution starts from the main(), the JVM cannot create an object without
entering the main() method. If the main() method is allowed to call
without the need of an object, the JVM can create hundreds of objects
once enters the main(). For this reason, main() is declared as static.

Memory Allocation for static Variables

We know earlier every object will have its own copy of variables. But
with static variables, it is very different. A static variable location
is shared (or accessed or pointed) by all the objects of the class. The
result is, if one object changes the value, all the other objects also
get affected. With static variables, no encapsulation exists. Observe the
following program.

public class Demo


{
static int x = 10;
public static void main(String args[])
{
System.out.println(x); // 10

Demo d1 = new Demo();


Demo d2 = new Demo();

System.out.println(d1.x); // 10
System.out.println(d2.x); // 10

d1.x = 20;
System.out.println(d2.x); // 20

d2.x = 30;
System.out.println(d1.x); // 30

System.out.println(x); // 30
}
}

Variable x is declared as static. Objects d1 and d2 point to the same x


location. Observe, if d1 changes d2 and if d2 changes d1 are getting
affected. Because all the objects of the whole class share the same
location, the static variable is known as "class variable".

In and Outs on static keyword is available in the following topics.

Static Methods, Static Variables Java:::

In Java, static is keyword that can be applied to variables and methods


but not to classes. "static" is used as an access modifier.
In Java, to call an instance variable or method, an object is required.
But a static variable and method can be called without the help of an
object. This is the basic difference between static and non-static in
Java.

Observe the following code.

public class Demo


{
int marks = 50; // non-static
variable
static double average = 40.6; // static variable

public void display() // non-static


method
{
System.out.println("Hello 1");
}
public static void show() // static method
{
System.out.println("Hello 2");
}
public static void main(String args[])
{
// static members - no object is
required
System.out.println(average);
show();
// non-static members - object is
required
Demo d1 = new Demo(); // create the object
System.out.println(d1.marks);
d1.display();
}
}

Observe, average and show() are static members of the class Demo and are
called without the need of an object. marks and display() are non-static
members and are called with object d1.

Composition – "has-a" Relationship::::

One of the goals of OOP languages is reusability. Java gives good


importance for reusability. A method in Java can be called in two ways.

1. With the objects of the same class (through composition)


2. With the objects of other classes (through inheritance)
Here we discuss the composition.

class Bird
{
public void eat()
{
System.out.println("All birds eat for their metabolic
activities");
}
}
public class Parrot
{
public static void main(String args[])
{
Bird b1 = new Bird();
b1.eat();
}
}

Before going to composition, let us know how to write the above code and
on which name the Java file should be opened. The rule says, in a single
source code, if a number of classes exist, only one class can be public.
The file name must be of that class which is public. In the code, two
classes exist – Bird and Parrot. As Parrot is public, the file opened
must be on the name of "Parrot.java". So, open "Parrot.java" file and
write the source code and compile as usual as "javac Parrot.java" and
execute as "java Parrot".

The Parrot class, in its main() method, created an object of Bird and
called Bird's method eat(). Here, Bird and Parrot are no way connected or
related (I mean, no inheritance). Just they happened to be in the same
folder. This feature we call as "composition". Creating another class
object in our class and calling other class methods is known as
composition.

Composition uses the concept called "has-a" relationship. We say, our


class has a object of other class. Parrot "has a " object of Bird.
Composition is meant for reusability.

When compiled Parrot.java, we get two .class files – Bird.class and


Parrot.class. These classes work independently of each other even though
they are coming from a single source file. Any other third class can make
use of the methods of either both or any one these classes by
composition.

There is one more concept called aggregation which differs slightly from
composition. To know their narrow difference see Aggregation and
Composition.

You might also like