Java – Keywords

Java – Keywords 2017-08-09T10:14:26+00:00

Java Keywords – New – This – Static with Syntax and Examples

We have already seen one keywords table in our first chapter.

But here we are going to learn few regularly used keywords.

1. new

2. this

3. static

4. super

5. final

The super and final keywords will demonstrate in further chapter.


The new keyword dynamically allocates memory for an object.
claas_name object _name  = new class_name();
Box b1 = new Box();
Box b2 = new Box();
We have already seen so many programs in which we used new keyword for creating objects.


This keyword is the name of a reference that refers to a calling object itself.

one common use of the this keyword is to reference a class hidden data fields.

You can have local variables, including formal parameters to methods which overlap with the names of the class instance variables.

The local variable hides the instance variable so we use this keyword.

Another common use of this keyword is to enable a constructor to invoke another constructor of the same class.

java requires that the this(arg-list) statement appear first in the constructor before any other statements.

EX :


Output :
local methods x = 10
local methods y = 20
x = 15
y = 25

static :

A class member must be accessed with the use of an object of its class but sometimes we want to define a class member that will be used independently without creating any object of that class.

It is possible in java to create a member that can be used by itself, without reference to a specific instance.

To create such a member, precede its declaration with the keyword static.

When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.

one can declare both methods and variables to be static.

The most common example of a static member is main().

main() is declared as static because it must be called  before any object exist.

Instance variables declared as static are actually, global variables.

When objects of its class are declared, no copy of a static variable is made.

Instead, all instances of the class share the same static variable.

Method declared as static have several restrictions:

1.    Can call only other static methods.

2.    Only access static data.

3.    Can not refer to this or super in any way.

One can also declare a static block which gets executed exactly once, when the class is first loaded.

EX : 


Output :
Static block initialized……….
a = 40
i = 5
j = 50

Prev Next