All About Methods in Java

0
276
Spread the love
  • 24
  • 34
  • 16
  • 12
  •  
  •  
  •  
  • 12
  •  
  •  
    98
    Shares

Mutator methods allow us to change the data in a class object. Mutator methods often start with a word ‘set’ like setValue(),setData() etc. The Mutator method can return a boolean value to assure the user that the operation (set value) is successful.

A class generally provides public accessors and mutators methods.

General Subroutine/method contract

    • The precondition of a subroutine is something that must be true when the subroutine is called to work it correctly. This is the primary part of the contract. If we do not meet the contract correctly, there is no point in executing the subroutine as the result may be wrong or the program may crash.
    • The postcondition of a subroutine is another side of the contract. It is something that will be true after the subroutine has run(if the precondition is met). Subroutines are often described by comments that explicitly specify their precondition and postcondition. So a subroutine comes with a set of precondition and postconditions.
    • They can be part of a Javadoc command as well as @precondition or @postcondition tags.
    • methods set up a contract with the specified details like -modifier, return type, method name, parameter list etc.but if the caller of the method violets the contact the method can intercept that and can throw a statement. To throw a statement of the appropriate type we must create an object and have a throw statement.like -IllealArgumentException(“error message”)

public class MyTest{
static void myNumberTest(int value)
{
if (value<=0)
    throw new IllegalArgumentException("value must be greater than zero");
    //......
}
public static void main(String args[])
{
    myNumberTest(-1);
}
}
 

the output of the code:

$javac MyTest.java

$java -Xmx128M -Xms16M MyTest Exception in thread “main” java.lang.IllegalArgumentException: The value must be greater than zero at MyTest.myNumberTest(MyTest.java:5) at MyTest.main(MyTest.java:10) so if this method gets a negative or zero value, it will immediately terminate the execution by throwing an exception.

Read Method overloading here for more about this technique.

What Is Public Static Void Main Method in Java?

The main method in Java

For a standalone java program, the class name should be the same as the file name. we will get a compilation error if otherwise. The class should contain a main() method with the given signature:


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

Conceptually every java program must include a main() method to run independently.main() is the starting point or triggering point for the interpreter to begin execution. A java program can have n-numbers of classes but only one of them includes a main() method to initiate the execution.

public-> is available for the world to use.
String[] args->It declares a parameter named args of the type String array. The argument to the main is an array of String objects. In the IDE model of development, they will never be used in general, but they hold the arguments invoked on the command line.
Static: The static keyword declares this method /variable as one that belongs to the entire class and not part of any object of the class. The main() method must always be declared as static since the interpreter uses this method before any objects are created. Non-static things belong to the object. If the main is non-static, we can not have the main method until we create an object. But when we start java code, no objects have been created yet. The statements that are executed in the main method start creating objects.
void–>this modifier declares that the main() method does not return any value.

Methods with Varargs in Java

All About Methods with Varargs in Java:

Varargs represent variable-length arguments in the method. This makes java simple yet very powerful.

The general syntax is given as:


<access specifier><return type>methodName(<argument type>... arguments)
 

This method contains an argument referred to as varargs in which we are going to pass the specific type of arguments.
An ellipsis(…) is the key to varargs and argument is the name of the variable.


public void registration(String userName,String password,String emailId);
//can be written as:
public void registration(String... registrationDetails)
 

String… registrationDetails specifies that we can pass any number of String arguments to the registration() method.
How to retrieve the values:


class Registration{
testVarargs(String... registrationDetails)
{
for(String details:registrationDetails)
{
System.out.println(details);
}
} 
public static void main(String args[])
{
testVarargs("MydigitalVoice","abc123","[email protected]");
}
}
 

At compile time the String… registrationDetails are converted to String[] varargs. we can pass an array of Strings to the methods. Varargs does not generate any compile-time errors even if an empty argument is passed as a parameter to the method.

What is the Finalize method in Java?

Finalizer Method:

when a constructor initializes an object, the mechanism is called initialization. Similarly, java supports one more method just opposite to this, called finalization. Java garbage collector frees up memory used by the objects. But objects may hold other nonobjects (not created by Java new operator) resources(like file descriptor, window system fonts, etc). The garbage collector can not free up these items as they as not created by the new operator. To reclaim such memories, the finalize() method is used. The Finalize () method needs to define explicitly.

Cleanup:

Many times programmers forget to clean up memory. Nobody wants to clean up the small chunk of memory for int or character like this approach. To free up the memory java came up with a concept called Garbage collector to reclaim the memory of objects those which are no longer in use. But garbage collector can only reclaim memory for objects which are created by ‘new’ operator. If some program is occupying memory using some other way,Garbage collector won’t be able to reclaim those memories. To handle such conditions, Java has provided a method called finalize(). This method can be defined for any class.

How does it work?

When the Garbage collector is ready to release the storage of the object, it calls the finalize() method first. And only the next Garbage collection pass will reclaim the memory for the object. We can override the finalize() method by redefining the method.

We have to understand the below points while working with Garbage Collector:

  1. Garbage collection does not object to destruction. As java has no concept for destructor for clean up memory. It just ensures if there is some activity that must be performed before it reclaims the memory. We must perform that activity by ourselves. We can create our own methods to clean up the memory.
  2. All objects may not get garbage collected. It may so happen that our program never faces the memory shortage issue(maybe the code is too small and the available memory is too high).In that case, garbage collectors may reclaim the memory. So after the termination of the program, the memory is returned to the Operating system. The garbage collection process has some overhead, in the above way we never have to incur the expense.
  3. Garbage collection is not only about memory reclaim. If we use as a synonym of memory release the finalize has to be the same.

The role of Finalize():

Now if we create some other objects in our code and call finalize() method, will they be released? No, it won’t. The garbage collector will take care of the release of other objects in the memory, irrespective of how the objects are created. Since everything in java objects,in that case where we will define the finalize() method?

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 24
  • 34
  • 16
  • 12
  •  
  •  
  •  
  • 12
  •  
  •  
    98
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here