0% found this document useful (0 votes)
7 views109 pages

Unit 2 PPT

The document provides an overview of classes and objects in Java, emphasizing their roles in object-oriented programming. It explains the concepts of class declaration, object creation, and the distinction between classes and objects, highlighting attributes, methods, and the importance of encapsulation. Additionally, it details the process of creating and initializing objects, along with the types of variables used in classes.

Uploaded by

mohitsatav7387
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views109 pages

Unit 2 PPT

The document provides an overview of classes and objects in Java, emphasizing their roles in object-oriented programming. It explains the concepts of class declaration, object creation, and the distinction between classes and objects, highlighting attributes, methods, and the importance of encapsulation. Additionally, it details the process of creating and initializing objects, along with the types of variables used in classes.

Uploaded by

mohitsatav7387
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 109

Unit 02

Classes and Objects

1
Contents
 Classes and Objects:
 Classes, Objects,
 Creating Objects,
 Methods, Constructors,
 Cleaning up Unused Objects,
 Class Variable and Methods,
 this keyword,
 Arrays,
 Command Line Arguments.

2
Classes
 Java is an object-oriented programming language.
 Everything in Java is associated with classes and objects,
along with its attributes and methods.
 For example: in real life, a car is an object.
 The car has attributes, such as weight and color, and methods, such
as drive and brake.
 A class can be defined as a template/blueprint that describes
the behavior/state that the object of its type support.
 In the object-oriented software, there are many objects of the
same kind, i.e., belonging to the same classes that share
certain characteristics.
 Like the bike manufacturer, we can take advantage of the fact that
objects of the same kind are similar and a blueprint for those objects
can be created.
 Software ‘blueprints’ for objects are called classes.
3
Example
In the real physical world, everyday we come across
various objects of the same kind.
Such as motorbikes.
In terms of object-oriented language, we can say that the
bike object is one instance of a class known as
‘motorbikes.’
 Attributes like- Bikes have gears, brakes, wheels, etc.
 They also follow certain behaviors,
behaviors when functions are
applied on them, e.g., bikes slow down when brakes are
applied, they accelerate when geared up and
acceleration is applied, and so on.

4
 Figure. 2.1 shows the bike class.
 which would also declare and provide implementations for
the instance methods or functions that allow the provision
to change gears, apply brakes, and accelerate.

Fig. 2.1 Bike Class


5
Object
 An object is an instance of a class.
 Objects have different states and behaviors.
 The state of an object is defined by the values of the
attributes at any instant.
 We see many objects around us such as table, chair, dog,
fan, computer, pen, and car.
 These objects need not be touchable ones only, but can be
intangible/untouchable also, e.g., bank accounts, marks, fees, etc.
Example
 Bikes have attributes (speed, engine capacity, number of wheels,
number of gears, brakes), behaviors (braking, accelerating,
slowing down, and changing gears) and on application of this
behavior on attributes, the state of the object will change.
 Bike object can be in various states, it can be stationary, moving
etc.
 For example, when we apply brakes, the speed will reduce and
when we accelerate speed increases. 6
 We can conceptualize these real-time objects as software
objects.
 They too have states and behaviors.
 The state in software objects is maintained in variables and
 The behavior can be implemented using methods.
 Eg-The object bike would also have methods to brake, accelerate,
and change gears.
 These are known as instance methods.
 Only relevant fields and behaviors are added into a class.
 In addition to instance variables and methods, classes can
define their own class variables and methods.
 Every object will have its own instance variables but class
variables will be shared by all the objects of the class.

7
Fig. 2.2 Bike Object

8
 You can access class variables and methods using an instance
of the class or using the class name.
 Class methods can only access the class variables directly.
 They don’t have direct access to instance variables or methods.
 A single copy of all class variables is created and all instances of
that class share it.
 For example, suppose all cars had the same number of gears.
 In such a situation, a class variable can be created that defines the
number of gears.
 All instances of the class will share this variable.
 If any object manipulates the class variable, then it changes for
all objects of that class.

9
1. Difference Between Objects and Classes
 Both objects and classes look the same.
 In the real world, it is obvious that classes are not
themselves the objects that they describe—a blueprint
of a bike is not a bike.
 However, it is difficult to differentiate between classes
and objects in programming.
 This is partially because objects in programming are
merely the electronic models of real-world objects or
abstract concepts.
 Classes have logical existence, whereas objects have
physical existence,
 e.g., furniture itself does not have any physical existence, but
chairs, tables, etc. do have.

10
2. Why Should we Use Objects and Classes?
 Modularity, information hiding, i.e., data encapsulation,
can be incorporated using objects.
 Classes, being blueprints, also provide the benefit of
reusability along with the ease of changing and
debugging code.
 For example, bike manufacturers reuse the same blueprint over
and over again to build lots of bikes.
 Programmers use the same class repeatedly to create
many objects.

11
Class Declaration In Java
 Declaring a class is simple.
 A class can be declared using the keyword class
followed by the name of the class that you want to
define.
 Giving a name to a class is something which is totally in
the hands of the programmer.
 But while doing so, he must take care of the relevance
of the class name, the legality of Java identifiers used as
the class name, and the naming convention used in
Java.
 Thus, the simplest class declaration looks as follows:

12
 All the action in a Java program takes place inside the
class.
 Methods and variables are defined inside the classes.
 The class is the fundamental unit of programming in
Java.
 The class declaration can specify more about the class,
like you can:
 declare the superclass of a class
 list the interfaces implemented by the class
 declare whether the class is public, abstract, or final
 For each of the cases above, the class declaration will
differ accordingly.
 We can summarize the class declaration syntax as

13
 The items enclosed inside [ ] are optional.
 A class declaration defines the following aspects of the
class:
 modifiers declare whether the class is public, protected, default,
abstract or final
 ClassName sets the name of the class you are declaring
 SuperClassName is the name of the ClassName's superclass
 InterfaceNames is a comma-delimited list of the interfaces
implemented by ClassName
 Only the class keyword and the class name are
mandatory.
 Other parameters are optional.
 It is important to remember that a class declaration only
creates a template; it does not create an actual object. 14
Example
 Here is a class called Box that defines three instance
variables: width, height, and depth.

15
Class Body
 The class contains two different sections:
 Variable declarations and
 Method declarations.
 The variables of a class describe its state, and methods
describe its behavior.
 All the member variables and methods are declared within the
class.
 There are three types of variables in Java:
1. Local variables,
2. Class/static variables.
3. Instance variables,

16
1) Local Variable
 A variable declared inside the body of the method is called local
variable.
 You can use this variable only within that method and the other
methods in the class aren't even aware that the variable exists.
2) Static/class variable
 Class variables also known as static variables are declared with
the static keyword in a class, but outside a method, constructor
or a block.
 It is a variable that defines a specific attribute or property for a
class.
 You can create a single copy of the static variable and share it
among all the instances of the class.
 Memory allocation for static variables happens only once when
the class is loaded in the memory

17
Local Variable Example Static Variable Example

18
3) Instance Variable
 Instance variables are created when an object is
created and destroyed when the object is destroyed.
 A variable declared inside the class but outside the
body of the method, is called an instance variable.
 It is called an instance variable because its value is
instance-specific and is not shared among instances.

19
 It is important to understand that a class can have many
instances (i.e., objects) and each instance will have its
own set of instance variables.
 Any change made in a variable of one particular instance
will not have any effect on the variables of another
instance.
 Normally, you declare the member variables first followed
by the method declarations and implementations

20
Instance variable declaration in a class.

Example 2.2 Class Declaration


 Example 2.2 shows a sample class declaration with two
instance variables.
 Instance variables are part of the instance of the class
(object).
 These instance variables will be created when the
instance is created.
 In order to be able to access/manipulate these instance
variables, we need to create objects of this class.
21
Creating Objects
 In Java, you create an object by creating an instance of a class or
instantiating a class.
 A Java object is defined as an instance of a class.
 The type of the object is the class itself.
 Java object created with a statement like

 There are three steps when creating an object from a class −


1. Declaration − A variable declaration with a variable name with
an object type.
2. Instantiation − The 'new' keyword is used to create the object.
3. Initialization − The 'new' keyword is followed by a call to a
constructor. This call initializes the new object.

22
Creating Objects
 To create an object of class- specify the class name, followed by
the object name, and new keyword (Instantiate the class) is
followed by a constructor (constructor-initializes the object).
 Java object created with a statement like
ClassName objectName = new ClassName();
 Eg:
 This single statement declares, instantiates, and initializes the object.
 This statement creates a new SalesTaxCalculator object.
 SalesTaxCalculator obj1 is a reference variable declaration which simply
declares to the compiler that the variable obj1 will be used to refer to an
object whose type is SalesTaxCalculator.
 The new operator instantiates the SalesTaxCalculator class (thereby
allocating memory and creating a new SalesTaxCalculator object), and
constructor-SalesTaxCalculator() initializes the object.

23
 Example- Create an object called "myObj" of class Main and
print the value of x:

 Multiple Objects
 You can create multiple objects of one class:
 Example- Create two objects of Main

24
1. Declaring an Object
 Object declarations are same as variable declarations.
 Generally, the declaration is as follows:
type name
 where type is the type of the object (i.e., class name) and name is the name of the reference
variable used to refer the object.
 Classes are like new data types.
 For example,

 So type can be any class such as the SalesTaxCalculator class or the name of an interface.
 The above declaration won’t create an object.
 It will create a variable with a name and specify its type.
 For example, SalesTaxCalculator is the type and obj1 is the reference variable.

25
2. Instantiating an Object
 After declaring a variable to refer to an object, an actual, physical
copy of the object must be acquired and assigned to that variable.
 This can be achieved by the new operator.
ClassName object = new ClassName();

 The new operator instantiates a class by dynamically allocating (i.e.,


at runtime) memory for an object of the class type and returns a
reference to it.
 This reference is nothing but the address in the memory of the object
allocated by new.
 This reference or memory address is then stored in the variable
declared.
 The new operator requires a single argument, i.e., a constructor call.
 The new operator creates the object or instantiates an object and the
constructor initializes it.
26
 Example

 The above statement just creates an instance of a class,


SalesTaxCalculator.
 In other words, the new operator creates an object obj1
by allocating memory for its member variables, i.e.,
amount and taxRate (Example 2.2) and few other items.

Example 2.2 Class Declaration


27
3. Initializing an Object
 By initializing an object, we mean the instance variables are
assigned initial values.
 The instance variables of a particular object will have
different values during the lifetime of an object.
 But to start with, initial values are required.
 If no value is specified for the instance variables, then the default
values will be assigned to those variables based on their respective
types.
 Initial values can be provided by instance variable initializers
and constructors.
 Three ways to initialize an object in Java
A. Using new keyword (Constuctor).

B. Using Class.forName() method

C. Using clone method.


28
3a. Using new keyword
The best and convenient approach is to create your own constructor.
A constructor is a special method provided within class that is used to
initialize objects.
The constructor is called when an object of a class is created.
Constructors have the same name as that of the class.
If you do not create a constructor for your class, Java compiler provides a
default constructor for your class automatically.
 The default constructor is a zero argument constructor with an empty
body.
 The default constructor is invoked as soon as the object is instantiated
with new keyword as shown below.

29
Fig. 2.3 Steps in Object Creation

30
 The final object creation can be said as complete, when the objects are
initialized, either with an implicit constructor or an explicit constructor.
 This object creation can be used in a programming code in two ways:

 Here all the three operations, object declaration, object instantiation,


and object initialization are done by a single statement.
 Example 2.2 shows how to create a class and objects for that class,
where we can do these things in one program only.
 The following program displays a class SalesTaxCalculator, with two instance
variable (initialized to some values) and two objects of the class
SalesTaxCalculator, obj1 and obj2 (created inside the main method).
 Instance variable initializers are used in this example to initialize objects: obj1 and
obj2 (Fig. 2.3).

31
Example 2.2 (a) Object and Classes

Output

32
Methods(Functions)
 A method is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a method.
 Methods are used to perform certain actions, and they are
also known as functions.
 It is similar to a function in any other programming language.
 None of the methods can be declared outside the class.
 All methods have a name that starts with a lowercase
character.

33
1. Why Use Methods?
 To Make the Code Reusable
 If you need to do the same thing or almost the same thing, many times,
write a method to do it and then call the method each time you have to do
that task.
 To Parameterize the Code
 You will often use parameters to change the way the method behaves.
 For Top-down Programming
 You can easily solve a bigger problem or a complex one(the ‘top’) by
breaking it into smaller parts.
 The entire complex problem (functionality) can be broken down into
methods.
 To Simplify the Code
 Because the complex code inside a method is hidden from other parts of
the program, it prevents accidental errors or confusion.

34
2. Method Type
 There are two types of methods in Java:
 Instance methods and
 Class methods.

 Instance methods
 Instance methods are used to access/manipulate the instance
variables but can also access class variables.
 Class methods.
 Class methods can access/manipulate class variables but
cannot access the instance variables unless and until they use
an object for that purpose.

35
3. Method Declaration
 The general syntax of a method declaration:

 The parameters enclosed within square brackets [ ] are optional.


 The square brackets are not a part of the code; they are included
here to indicate optional items.
 The method declaration includes
 Modifiers
 If you see the syntax of the method declaration carefully, there is an
optional part  of it, modifiers.
 There are a number of modifiers (optional) that can be used with a method
declaration.
 They are listed in Table 1.

36
Table 1- Optional Modifiers used While Declaring Methods

37
 Return Type
 It can be either void (if no value is returned) or if a value is returned, it
can be either a primitive type or a class.
 If the method declares a return type, then before it exits, it must have
a return statement.
 Method Name
 The method name must be a valid Java identifier.
 Parameter List
 Zero or more type/identifier pairs make up a parameter list.
 Each parameter in the parameter list is separated by a comma.
 Curly Braces
 The method body is contained in a set of curly braces.
 Methods contain a sequence of statements that are executed
sequentially.
 The method body can also be empty.

38
 In Example 2.2(a), we have stored data: amount and
taxRate but we have not calculated the tax amount
based on the rate.
 These operations will be performed inside a method so
we need to add a method to that class and revise the
class.
 The method added is calculateTax()(L4) which
calculates the taxed amount.
 This method is invoked in L10 and 11 by the two objects
using the dot operator.

39
Example 2.2 (b) Added Instance Method

Output
40
 The following example 2.3 has a couple of instance methods,
setRadius() and calculateArea(), declared inside the class, Circle.
 The word instance has been particularly used to distinguish
between instance and class methods.
 The modifier static has not been used while declaring methods so
the methods become instance methods.

Example 2.3 Instance Method Declaration


(created a class (Circle) and two methods in that class) 41
4. Instance Method Invocation
 Methods (instance or class methods) cannot run on their own, they
need to be invoked.
 Instance method are methods which require an object of its class to
be created before it can be called.
 To invoke a instance method, we have to create an Object of the class
in which the method is defined.
 When an object calls a method, it can pass on certain values to the
methods (if methods accept them) and the methods can also return
values from themselves if they wish to.
 Data that are passed to a method are known as arguments or
parameters; the required arguments for a method are defined by a
method’s parameter list (method signature).
 Let us take an example and see how invoking is done.

42
Example 2.4 Instance Method Invocation
(shows how the methods of Circle class (Example 2.3)
are called from another class, i.e., CallMethod.)

Output

43
 The following definitions are useful in the above context.
 Formal Parameter
 The identifier used in a method to stand for the value that is passed into the method
by a caller.
 These formal parameters come in the category of local variables which can be used
in their respective methods only.
 For example, the parameter defined for setRadius(), i.e., rad in L5 of Example 2.3 is a
formal parameter, as it will be bound to the actual value sent by the caller method.
 Actual Parameter
 The actual value that is passed into the method by a caller.
 For example, in L7 of Example 2.4, 3.0f, passed to setRadius(), is the actual
parameter.
 The methods can also be called from within the class, as shown in
Example 2.5.

44
Example 2.5 Adding Instance Variable(s) and
Instance Method(s)
45
5. Method Overloading
 Method overloading is one way of achieving
polymorphism in Java.
 Each method in a class is uniquely identified by its name
and parameter list.
 What it means is that you can have two or more
methods with the same name, but each with a different
parameter list.
 This is a powerful feature of the Java language called
method overloading.
 Overloading allows you to perform the same action on
different types of inputs.

46
 In Java whenever a method is being called, first the name of the
method is matched and then, the number and type of arguments
passed to that method are matched.
 In method overloading, two methods can have the same name but
different signatures, i.e., different number or type of parameters.
 The concept is advantageous where similar activities are to be
performed but with different input parameters.
 Method overloading is achieved by either:
 Changing the number of arguments or
 Changing the data type of arguments.
 It is not method overloading if we only change the return type of
methods. There must be differences in the number of parameters.

47
Example 2.6 Method Overloading 48
Output

49
Constructors
 In Java, a constructor is a block of codes similar to the method.
 It is called when an instance of the class is created.
 At the time of calling constructor, memory for the object is
allocated in the memory.
 It is a special type of method which is used to initialize the
object.
 Every time an object is created using the new() keyword, at
least one constructor is called.
 It calls a default constructor if there is no constructor available in the
class.
 In such case, Java compiler provides a default constructor by default.
 Table 2 provides a summary on constructors versus methods.

50
Table 2 Constructors vs Methods

Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any. 51
Rules for creating Java constructor
Rules defined for the constructor are
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and
synchronized
An example 2.7 to illustrate the usage of constructor.
L3 of Example 2.7 defines an explicit default constructor
that does not accept any argument but initializes the
instance variables to the specified values.

52
Example 2.7 Constructor

Output
53
Types of Java constructors

 There are two types of constructors in Java:


 Default constructor (no-arg constructor)
 Parameterized constructor

 Default constructor (no-arg constructor)


 A constructor is called "Default Constructor" when it doesn't
have any parameter.
 Syntax of default constructor:
<class_name>(){}
 The default constructor is used to provide the default values
to the object like 0, null, etc., depending on the type.

54
1. Parameterized Constructors
 A constructor which has a specific number of parameters is
called a parameterized constructor.
 The parameterized constructor is used to provide different
values to distinct objects.
 However, you can provide the same values also.
 Just like methods, arguments can be passed to the constructors,
in order to initialize the instance variables of an object.
 Example
 The example 2.7 had a limitation. Each Room has its own length, breadth,
and height and it is very unlikely that each room is of the same size.
 Also, all objects of Room class will have the same volume because the
values for length, breadth and height are fixed for all objects.

55
 You can explicitly change them using an object instance, e.g.,

 and then invoke the method volComp for calculating volume of the
Room.
 For example, if different dimensions can be specified for a
Room then each Room will have its own volume.
 For this, the instance variables should be assigned a
different set of values for different objects of the class.
 Hence we need to create a parameterized constructor
that accepts arguments to initialize the instance variables
with the arguments.
 Let us take an example 2.8 to see how parameterized
constructors can be used.

56
Example 2.8 Parameterized Constructor

Output

57
2. Constructor Overloading
 Just like methods, constructors can also be overloaded.
 Constructors are declared just as we declare methods, except
that the constructors don’t have any return type.
 Constructors for a class have the same name as that of the
class, but they can have different signatures, i.e., different types
of arguments or different number of arguments.
 Such constructors can be termed as overloaded constructors.
 Constructors are differentiated on the basis of arguments passed
to them.
 In the example below, we have used two overloaded
constructors, each having a different number of arguments, so
that the JVM can differentiate between the various constructors.

58
 The above example 2.9 shows a case of overloaded
constructors with differing number of arguments.
 Another 2.10 would be where different type of arguments
can also be passed into the overloaded constructors.

Example 2.9 Rectangle Class Depicting Constructor Overloading


59
Example 2.10 Testing the Overloaded Constructors

Output

60
Cleaning up unused Objects (Garbage Collection)
 Many other object-oriented languages require that you keep a track of all
the objects you create and that you destroy them when they are no longer
needed.
 Objects are allocated memory from the heap/stack memory and when they
are not needed their allocated memory should be reclaimed /brokened.
 The clean-up code is tedious and often error-prone.
 Java allows programmer to create as many objects as they want, but frees
them from worrying about destroying (deallocating memory) objects.
 The Java runtime environment deletes objects when it determines that
they are no longer required.
 It has its own set of algorithms for deciding when the memory allocated to
an object must be reclaimed.
 This automated process is known as garbage collection.

61
 An object is eligible for garbage collection when no references exist
on that object.
 References can be either implicitly dropped when it goes out of
scope or explicitly dropped by assigning null to an object reference.
 Garbage collection in Java is the process by which Java
programs perform automatic memory management.
 Java programs compile to bytecode that can be run on a Java
Virtual Machine, or JVM for short.
 When Java programs run on the JVM, objects are created on the
heap/stack, which is a portion of memory dedicated to the program.

62
1. Garbage Collector
 The Java runtime environment has a garbage collector that
periodically frees the memory used by objects that are no longer
needed.
 Two basic approaches used by garbage collectors are Reference
counting and tracing.
1a) Reference counting
 Reference counting maintains a reference count for every object.
 A newly created object will have count as 1.
 Throughout its lifetime, the object will be referred to by many other
object thus incrementing the reference count and as the referencing
object move to other objects, the reference count for that particular
object is decremented.
 When reference count for a particular object is 0, the object can be
garbage collected.

63
1b) Tracing
 Tracing technique traces the entire set of objects (starting from root) and
all objects having reference on them are marked in some way.
 Tracing garbage collector algorithm popularly known as is mark and
sweep garbage collector scans Java’s dynamic memory areas for objects,
marking those objects that are referenced.
 After all the objects are investigated, the objects that are not marked (not
referenced) are assumed to be garbage and their memory is reclaimed.
The garbage collector runs either synchronously or asynchronously in a low
priority daemon thread.
The garbage collector executes synchronously when the system runs out of
memory or asynchronously when the system is idle.
Garbage collector can be invoked to run at any time by calling System.gc() or
Runtime.gc(). But asking the garbage collector to run does not guarantee that
your objects will be garbage collected

64
2. Finalization

 Before an object gets garbage collected, the garbage


collector gives the object an opportunity to clean up itself
through a call to the object’s finalize() method. This
process is known as finalization.
 All occupied resources (sockets, files, etc.) can be freed
in this method.
 The finalize() method is a member function of the
predefined java.lang.Object class.
 A class must override the finalize()method to perform
any clean up if required by the object.

65
3. Advantages and Disadvantages
Advantage
 Garbage collection is an important part of Java's security strategy.
 Java programmers are unable to accidentally (or purposely) crash
the Java virtual machine by incorrectly freeing memory.

Disadvantage
 The overhead to keep track of which objects are being referenced
by the executing program and which are not being referenced that
can affect program performance.
 The overhead is also incurred on finalization and freeing memory
of the unreferenced objects.
 These activities will incur more CPU time than would have been
incurred if the programmers would have explicitly deallocated
memory.

66
Class Variables and Methods - static Keyword
 When we create an object, a primitive type variable, or call a
method, some amount of memory is set aside for the said
object, variable, or method.
 Different objects, variables, and methods will occupy
different areas of memory when created/called.
 Sometimes we would like to have multiple objects, shared
variables, or methods. The static keyword effectively does
this for us.
 It is possible to have static methods and variables.
 The kind of variables Java supports include:
a. Local variables,
b. Instance variables, and
c. Class/static variables.
67
Kind of variables
a. Local Variables
 Local variables are declared inside a method, constructor,
or a block of code.
 When a method is entered, its contents (values of local
variables) are pushed onto the call stack. When the method
exits, its contents are popped off the stack and the memory
is freed up.
 Parameters passed to the method are also local variables
which are initialized from the actual parameters.
 The scope of local variables is limited to the method in
which they have been defined.
 A local variable must be initialized with some value.
 Access specifiers like private, public, and protected cannot
be used with local variables.
68
b. Instance Variables
 Instance variables are declared inside a class, but outside a method.
 They are also called data member, field, or attributes.
 An object is allotted memory for all its instance variables on the heap
memory.
 As objects instance variables remain live as long as the object is
active.
 They are accessible directly in all the instance methods and
constructors of the class in which they have been defined.
 By default, they are initialized to their default values according to
their respective types.

69
c. Class/static Variables
 Class variables are also known as static variables, and they are
declared outside a method, with the help of the keyword 'static'.
 Static variable is the one that is common to all the instances of the
class.
 A single copy of the variable is shared among all objects.
 Class/static variables declaration is preceded with the keyword static.
 They are also declared inside a class, but outside a method.
 The most important point about static variables is that there exists only
a single copy of static variables per class.
 All objects of the class share this variable.
 Static variables are normally used for constants.
 By default, static variables are initialized to their default values
according to their respective types.

70
1. Static Variables

 Java does not allow global variables.


 there is only one copy of the variable declared as static.
To make an instance variable static we simply precede the
declaration with the keyword static.

 It is worthwhile to note that people refer to static instance


variables as ‘class variables.’
 Example 2.11 shows how static variables are declared.

71
Example 2.11 Instance and Class Variables

72
Example 2.12 A Class Showing the Use of Class (Static) Variables
Output

73
2. Static Methods
 Like static variables, we do not need to create an object to call our
static method.
 Simply using the class name will suffice.
 Static methods however can only access static variables directly.
 Variables that have not been declared static cannot be accessed by
the static method directly, i.e., the reason why we create an object of
the class within the main (which is static) method to access instance
variables and call instance methods.
 To make a method static, we simply precede the method declaration
with the keyword static.

 An example 2.13 to show the use of static methods.

74
Example 2.13 A Class Having Static Members

Example 2.14 Calling Static Method from Another Class


Output
12 75
3. Static Initialization Block
 A block of statements can be enclosed in parenthesis with
static keyword applied to it.
 This block of statement is used for initializing static or class
variables.
 If the initialization logic is simple, the class variables can be
assigned values directly but in case some logic is used for
assigning values to the variables, static blocks can be used.
 The syntax for static block is as follows:

76
1. A Static Initialization Block in Java is a block that runs
before the main( ) method in Java.
2. Java does not care if this block is written after the main( )
method or before the main( ) method, it will be executed
before the main method( ) regardless.

77
this Keyword
 The keyword this is used in an instance method to refer to the
object that contains the method, i.e., it refers to the current object.
 Whenever and wherever a reference to an object of the current
class type is required, this can be used.
 It can also differentiate between instance variables and local
variables.
 There can be a lot of usage of Java this keyword.
 In Java, this is a reference variable that refers to the current
object.

78
Usage of Java this keyword
 Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method
(implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance
from the method.

79
Main Uses
1) this: to refer current class instance variable
 The this keyword can be used to refer current class instance variable.
 If there is ambiguity between the instance variables and parameters, this keyword
resolves the problem of ambiguity.
2) this: to invoke current class method
 You may invoke the method of the current class by using the this keyword.
 If you don't use the this keyword, compiler automatically adds this keyword while invoking
the method.
3) this() : to invoke current class constructor
 The this() constructor call can be used to invoke the current class constructor.
 It is used to reuse the constructor. In other words, it is used for constructor chaining.

80
Arrays
 Normally, an array is a collection of similar type of elements which
has contiguous memory location.
Or
 It is a data structure where we store similar elements.
 Java array is an object which contains elements of a similar data
type.
 We can store only a fixed set of elements in a Java array.
 Array in Java is index-based, the first element of the array is stored
at the 0th index, 2nd element is stored on 1st index and so on.
 Unlike C/C++, we can get the length of the array using the length
member.
 In C/C++, we need to use the size of operator.

81
Arrays
 For example
 Marks[5] would store the marks of the fifth student. While the complete set of
values is called an array, the individual values are known as elements.

 Arrays can be two types:


1. One dimensional array
2. Multi-dimensional array

 Multi-dimensional array
 A multidimensional array is an array of arrays.
 In such case, data is stored in row and column based index (also known as
matrix form).

82
1. One-dimensional Arrays
 In a one-dimensional array, a single subscript or index is
used, where each index value refers to an individual array
element.
 The indexation will start from 0 and will go up to n –1, i.e.,
the first value of the array will have an index of 0 and the last
value will have an index of n –1, where n is the number of
elements in the array.
 So, if an array named marks has been declared to store the
marks of five students, the computer reserves five
contiguous locations in the memory, as shown in Fig. 2.4.

Fig. 2.4 Marks Array


83
 Suppose, the five marks to be assigned to each array element are 60,
58, 50, 78, and 89.
 It will be done as follows:

 Figure 2.5 shows the marks array with data elements.

 Creation of Array
Fig. 2.5 Marks Array Having Data Elements
 Creating an array, similar to an object creation, can inherently involve three
steps:
a. Declaring an array

b. Creating memory locations

c. Initializing/assigning values to an array

84
1a. Declaring an Array
 An array is same as declaring a normal variable except that you must use a set
of square brackets with the variable type.
 There can be two ways in which an array can be declared.
Or

 So the above marks array having elements of integer type can be declared
either as
int marks[ ]; or
int[ ] marks;
1b. Creating Memory Locations
 An array is more complex than a normal variable, so we have to assign memory
to the array when we declare it.
 You assign memory to an array by specifying its size. new operator helps in
doing the job, just as shown below:

85
 So, allocating space and size for the array named as marks
can be done as,

 Both (declaration of array and creation of memory location),


help in the creation of an array. These can be combined as
one statement, for example,
Or

 It is interesting to know what the JVM actually does while


executing the above syntax?
 During the declaration phase, int marks[];

 Figure 2.6 shows the marks array after memory is allocated


to the array on execution of the following statement:

86
 Here is an example to show how to create an array that
has 5 marks of integer type.

Fig. 2.6 Creation of Arrays 87


1c. Initializing/ assigning Values to an Array
 Assignment of values to an array, which can also be
termed as initialization of array, can be done as follows:

 We have just discussed how to create a list of


parameters to be assigned in an array. Example 2.16
shows how to set the values for an array of 5 marks (Fig.
2.6).

Example 2.16 Setting Values in an Array 88


 Arrays can alternately be assigned values or initialized in the
same way as the variables, i.e., at the time of declaration
itself. The syntax for the same can be,

 For example,
 int marks[] = {60, 58, 50, 78, 89} Here, the marks array is initialized at
the time of creation of array itself.
 The above statement does the same thing as the code between L3 to
8 of Example 2.16.
 An example of array creation and initialization is given below.

Example 2.17 Creation and Initialization of an Array 89


1d. How to Use for Loops with Arrays?
 The for loops can be used to assign as well as access values from an
array.
 To obtain the number of values in an array, i.e., the length of the
array, we use the name of the array followed by the dot operator and
the variable length.
 This length property is associated with all the arrays in Java.
 For example,

 will print the number of elements in the marks array, i.e., 5.


 Example 4.18 shows how to use a for loop to set all the values
of an array to 0 which, you will see, is much easier than setting
all the values to 0 separately.

90
Example 2.18 Setting Values in an Array Using for Loop

Example 2.19 Incrementing the Values of Data Elements in an Array

Example 2.20 Printing the Values of Data Elements of an Array 91


1e.Sorting an Array
 Let us take an example where we apply all the
concepts of array that we have learnt until now.
 If we have been given a set of marks and we have
to sort the marks in descending order.

92
Output

Example 2.21 Sorting an Array


93
Fig. 2.7 Execution of Loops in SortArray Example
94
2. Two-dimensional Arrays
 There can be enumerable such situations where we can use a two-
dimensional structure.
 Java provides a solution for the storage of such a structure in the form
of two-dimensional arrays.
 In this values can be conceptualized in the form of a table that is in the
form of rows and columns.
 Suppose we want to store the marks of different subjects.
 Now if we want to add a second dimension in the form of roll no of the
student.
 This is possible only if we follow a tabular approach of storing data, as
shown in Table 4.
 The following statements create a two-dimensional array, named as
marks, which would have 4 rows and 5 columns, as shown in Table 4.

95
Table 4 Two-dimensional Marks Array

96
 This is done in the same way as it has already been explained while
discussing one-dimensional arrays.
 The two statements, used for array creation, can be merged into one as,

 Another way of representing the above statement can be,

 Like a one-dimensional array, two-dimensional arrays may be


initialized with values at the time of their creation. For example,

 This declaration shows that the first two rows of a 2 × 4 matrix have
been initialized by the values shown in the list above. It can also be
written as,

97
 The shown declaration of 2 × 4 array will create three 1-D array.
 One for storing the number of row arrays (i.e. 2) and the other two
arrays will be used for storing the contents of the rows.
 The size of these two arrays will be 4.
 The size of row array is the number of rows and each field in the
row array points to a 1-D array that contains the column values for
the rows.
 So marks [0][0]will have the value 2, marks [0][1] will have 3,
marks[1] [0] with 9, and so on.
 Assigning and accessing the values in a two-dimensional array is
done in the same way, as was done in a one-dimensional array.
 The only difference is that, here you have to take care of the
positional values of the array using two subscripts (shown in
square brackets), while in a one dimensional array, only one
subscript was used for the purpose.

98
Fig. 2.8 2-D Array

99
Example 2.22 Setting Values in a Two-dimensional Array
Output

100
3. Using for-each with Arrays
 We can also print the Java array using for-each loop.
 The Java for-each loop prints the array elements one by one.
 It holds an array element in a variable, then executes the body of the loop.
 The syntax of the for-each loop is given below:

 For example, we can use for-each loop to calculate the sum of elements
of an array as follows:

 The disadvantage of for-each approach is that it is possible to iterate in


forward direction only by single steps.

101
4. Passing Arrays to Methods
 Arrays can be passed to methods as well.
 The following example shows a two-dimensional array being
passed to a method.
 The static method displays the contents of that array.
Output

Example 2.24 Arrays as Arguments to 102


Methods
5. Returning Arrays from Methods
 Arrays can not only be passed to methods but we can
use arrays as return value from methods.
 If you are faced with a situation where you want to
return multiple values from a method, all the values can
be encapsulated in an array and returned.
 The following example shows a two dimensional array
being returned from a method.
 The main method displays the contents of that array.

103
Example 2.25 Returning Multiple Values
Output

104
6. Variable Arguments

 Variable arguments can be used when the number of


arguments that you want to pass to a method are not
fixed.
 The method can accept different number of arguments of
same type whenever they are called.
 The generic syntax for this notation is:

105
Example 2.26 Variable Arguments
Output

106
Command Line Arguments
 You must be aware of the basic DOS commands.
 Have you ever used the command to move a file from one location to
another, say abc.txt from C:\ to D:\,
Move C:\abc.txt D:\
 Here, Move is the program or application responsible for moving the file,
while C:\abc.txt and D:\ can be termed as command-line arguments,
which are passed to the Move program at the time of invocation of the
program.
 As the application is invoked from the command line and the arguments
are also passed to the application at the command line itself, these are
called command-line arguments.
 Just like C++, programs can be written in Java to accept command line
arguments.

107
 In this case, each of the elements in the array named args (including
the elements at position zero) is a reference to one of the command-
line arguments, each of which is a string object.
 Suppose, you have a Java application, called sort, that sorts the lines in a file
named Sort.text
 You would invoke the Sort application as,
java Sort Example.txt.
 When the application is invoked, the runtime system passes the
command-line arguments to the application’s main() method via an
array of strings.
 In the statement above, the command-line argument passed to the Sort
application contains a single string, i.e., Example.txt.
 This String array is passed to the main() method and it is copied in args.

108
Example 2.27 Echo Application Output

 After compiling the program, when it is executed, you can pass the
command-line arguments as follows:

 Note that there is one space between each of the three arguments
passed to the Echo application through the command line.
 If you have to pass a string of characters as an argument, then you
must use quotes (" ") to mark that string.
 For example,

Output
109

You might also like