top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Java Modifiers

+2 votes
867 views

Java Modifiers

Java is a tightly encapsulated language. This means, that no code can be written outside the class. Not even the main() method. However, even within the class, code can become vulnerable to access from external environment. For this purpose, java provides a set of access specifiers such as public , private, protected, and default that help to restrict access to class and class members. However, at time, it is required to further restrict access to the members of a class to prevent modification by unauthorized code. Java provides additional field and method modifiers for this purpose.

Also, in some cases, it may be required to have a common data member that can be shared by all objects of a class as well as other classes. Java provides the concept of class variables and methods to solve this purpose. Classes sharing common attributes and behavior can also be grouped together for better understanding of the application. Java provides packages that can be used to group related classes. Also, the entire set of packages can be combined into a single file called the .jar file for deployment on the target system.

Field and Method Modifiers

 Field and method modifiers are keywords used to identify fields and methods that provide controlled access to users. Some of these can be used in conjunction with access specifiers such as public and protected. The different field modifiers that can be used are as follows:

  • Volatile
  • Native
  • Transient
  • Final

 

1. ‘volatile’ Modifier

The volatile modifier allows the content of a variable to be synchronized across all running threads. A thread is an independent path of execution of code within a program. Many threads can run concurrently within a program. The volatile modifier is applied only to fields. Constructors, methods, classes, and interfaces cannot use this modifier. The volatile modifiers is not frequently used.

While working with a multi threaded program, the volatile keyword is used. When multiple threads of a program are using the same variable, in general, each thread has its own copy of that variable in the local cache. In such a case, if the value of the variable is updated, it updates the copy in the local cache and not the man variable present in the memory. The other thread using the same variable does not get the updated value.

To avoid this problem, a variable is declared as volatile to indicate that it will not be stored in the local cache.

Also, whenever a thread updates the values of the variable, it is updates the variable present in the main memory. This helps other thread to access the updated value.

For example,

private volatile int testValue;  // volatile variable

2. ‘native’ Modifier

In some cases, it is required to use a method in java program that resides outside JVM. For this purpose, Java provide the native modifier. The native modifier is used only with methods. It indicates that the implementation of the method is in a language other than java such as C or C++. Constructors, fields, classes, and interfaces cannot use this modifier. The methods declared using the native modifier are called native methods.

The java source file typically contains only the declaration of the native method and not its implementation. In case of the native modifiers, the implementation of the method exists in a library outside the JVM. Before invoking a native method, the library that contains the method implementation must be loaded by making the following system call.

System.loadLibrary(“libraryName”);

To declare a native method, the method is preceded with the native modifier. Also, the implementation is not provided for the method. For example,

Public native void nativeMethod();

3. ‘transient’ Modifier

When a Java application is executed, the objects are loaded in the Random Access Memory (RAM). However, objects can also be stored in a persistent storage outside the JVM so that it can be used later. This determines the scope and life span of an object. The process of storing an object in a persistent storage is called serialization. For any object to be serialized, the class must implement the Serializable interface.

However, if transient modifier is used with a variable, it will not be stored and will not become part of the object’s persistent state. The transient modifier is useful to prevent security sensitive data from being copied to a source in which no security mechanism has been implemented. Also, transient modifier reduces the amount of data being serialized, improves performance, and reduces costs.

The transient modifier can only be used with instance variable. It informs the JVM not to store the variable when the object, in which it is declared, is serialized. Thus, when the object is stored in persistent storage, the instance variable declared as transient is not persisted.

4. ‘final’ Modifier

The final modifier is used when modification of a class or data members is to be restricted. The final modifier can be used with a variable, method, and class.

A variable declared as final is a constant whose value cannot be modified. A final variable is assigned a value at the time of declaration. A compile time error is raised if a final variable is reassigned a value in a program after its declaration.

final float PI =  3.14;

The variable PI is declared final so that its value cannot be changed later.

A method declared final cannot be overridden or hidden in a java subclass. The reason for using a final method is to prevent subclasses from changing the meaning of the method and increase the efficiency of code by allowing the compiler to turn method calls into inline java code. A final method is commonly used to generate a random constant in a mathematical application.

Code snippet

final float. getCommission (float sales)

{

System.out.println(“A final method…”);

}

The method getCommission() can be used to calculate commission based on monthly sales. The implementation of the method cannot be modified by other classes as it is declared as final. A final method cannot be declared abstract. As it cannot be overridden.

Rules and Best Practices for Using Field Modifiers

 Some of the rules for using field modifiers are as follows:

  • Final fields cannot be volatile.
  • Native methods in java cannot have a body.
  • Declaring a transient held as static or final should be avoided as far as possible.
  • Native methods violate Java’s platform independence characteristic. Therefore, they should not be used frequently.
  • A transient, variable may not be declared as final or static.
posted Aug 19, 2017 by Rameshwar Singh

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Working with StringBuilder Class

StringBuilder objects are similar to String objects, except that they are mutable. Internally, the system treats these objects as a variable-length array containing a sequence of characters. The length and content of the sequence of characters can be changed through methods available in the StringBuilder class. However, developers prefer to use String class unless StringBuilder offers an advantage of simpler code in some cases. For example, for concatenating a large number of strings, using a StringBuilder object is more efficient.

The StringBuilder class also provide a length() method that returns the length of the character sequence in the class.

However, unlike strings a StringBuilder object also has a property capacity that specifies the number of character spaces that have been allocated. The capacity to hold data in the instance of the StringBuilder class will automatically expand according to the user requirement to accommodate the new strings when added to the string builder.

Thus, the StringBuilder class is used for manipulating the String object. Objects of StringBuilder class are mutable and flexible. StringBuilder object allows insertion of characters and strings as well as appending characters and string at the end.

The constructors of the StringBuilder class are as follows:

  • StringBuilder(): Default constructor that provides space for 16 characters.
  • StringBuilder(int capacity): Constructs an object without any characters in it. However, it reserves space for the number of characters specified in the argument, capacity.
  • StringBuilder(String str): Constructs an object that is initialized with the contents of the specified string, str.

Methods of StringBuilder Class

The StringBuilder class provides several methods for appending, inserting, deleting, and reversing string as follows:

  • append() : The append() method is used to append values at the end of the StringBuilder object. This method accepts different types of argument, including char, int, float, double, boolean, and so on, but the most common argument is String.
  • insert(): The insert() method is used to insert one string into another. Similar to the append() method, it calls the String.valueOf() method to obtain the string representation of the value. The new string is inserted into the invoking StringBuildr object.
  • Delete(): The delete() method deletes the specified number of characters from the invoking StringBuilder object.
  • reverse(): The reverse() method used to reverse the characters within a StringBuilder object.
READ MORE
...