Christmas Special : Upto 40% OFF! + 2 free courses  - SCHEDULE CALL

- Java Blogs -

How to Call a Method in Java?

Call a Method in Java

Java is considered as an object-oriented, class-based, general-purpose and concurrent programming language which was created in 1995 by the Green Team comprising James Gosling, Mike Sheridan and Patrick Naughton at Sun Microsystems for various devices with a digital interface like set-top boxes, televisions, etc. It is similar in features to C++ but comes endowed with some simple and some advanced features. It can be run on all the platforms and is free to access. Over the years, it has found use in the following peripherals, namely banking, IT, retail, Big Data, Stock Market, Scientific research, Android, web development, framework, etc.

Salient Features of Java

Java serves as an excellent computing platform which can be used to develop various applications. It follows the logic of “Write once, Run anywhere” kind of programming language, i.e., the code which is compiled with Java can be run on all the platforms which support it. Some of the notable features which make it highly useful are as follows:

  • Simplicity: Java has eased many aspects of our lives by ridding us of many unwanted complexities like pointers, operator overloading as can be seen in C++ or some other kind of programming language.
  • Portability: Java is an independent platform, and thus, any application written on one platform can be easily ported to another.
  • Object-orientation: All operations of Java are performed, making use of the objects. Anything which has some kind of state and exhibits some behavior is considered as an object.
  • Security: Java enables its users to give shape to virus-free and even tamper-free applications to prevent any malicious activity from untrusted sources. The code is converted into bytecode after it is compiled and cannot be read by humans. There are no explicit pointers used by Java. Moreover, it usually runs the programs inside a sandbox.
  • Robust: It is endowed with a strong memory management system which helps in the elimination of error. The code is also checked during the compile and runtime.
  • Distributed: Java has a feature which helps in the creation of distributed applications. By making use of Remote Method Invocation (RMI), one program can invoke the method of another over a network to get the desired output. One can access the files by calling methods from any kind of machine on the internet.
  • Dynamic: Java can easily adapt to any kind of environment which has dynamic memory allocation. This significantly reduces the wastage of memory, thereby enhancing the performance of the application.
  • High Performance: High performance can be achieved in Java by making use of bytecode, which can be easily translated into the native machine code. Java can achieve high performance by making use of JIT or Just-in-time compilers.
  • Multithread Support: Multiple threads of execution are supported by Java, which also includes a set of synchronization primitives. This helps in making the programming easier by threads.

Parts of a Method

  • Modifiers: modifiers usually change the behavior of the class. E.g., private, public, etc. A method can have more than one modifier attached to it. g., you may want to use the private and static together but calling a non-static method from a static method is not possible as the former is linked with the object while the static method is linked with the class.
  • Return Type: The return type actually stands for the information which is returned to the caller after its work has been completed. In case nothing has to be returned, it can be set to Void, but every method has to have a return type.
  • Method Name: This is a must as in the absence of a name, the method cannot be called. It should begin with an alphabet and not a special character or a numeral. Latter can appear at some other place in the name but not in the beginning. Also, the only special character which is allowed is an underscore.
  • Argument List: You can state one or even more arguments or parameters if the method calls for any information from the caller for the task to be performed. These can be provided in a list which is contained in the parenthesis. The argument comprises the argument type followed by an argument name. Multiple arguments have to be separated by commas.
  • Exception List: This list shows the exceptions which will be encountered by the method.
  • Method Body: This is the code which defines the tasks a method is supposed to perform, and it always appears within the curly brackets.

Calling a Method in Java

There are many concepts which you will have to master as you start programming in Java-like classes, methods, exceptions, variables, constants, etc. Learning all of these in one-go may lead to information overload, so it is better to approach each one of these separately. Here are the steps which you will have to follow to call a method in Java.

1). The method is basically equal to a function in C, which is used for reusing code. It is comprised of a set of statements, and the method itself can be invoked through another statement. When it is called or invoked, all the statements which form a part of the method are executed. E.g. as the below figure shows “public static void methodExample ( ) { }”. Although there is no code in it, it does carry some keywords before the name like public, static, and void.

Read: Difference between ArrayList & LinkedList

package com.test.testing;

public class Test {

public static void methodexample (){

}

}

2). The meaning of the word “public” before the method is that the method can be called from anywhere like classes, even different packages as long the class can be imported. The public can thus be replaced by either private or even protected.

  • Protected: In this case, only this class and the subclasses will be able to call the method.
  • Private: In this case, the method can be called only inside the class.

If nothing is mentioned or specified in place of public, protected or private, then the scenario is called as the package-private or default. This will mean that only the classes under the same package will be able to call the method.


package con.test.testing;

public class Test {

private string format = "";

public static void main(String[] args) {

system.out.println("Hellow Word!");

}

Protected String getformat(){

return this.format;

}

public void setformat(String format){

this.format = format;

}

}

3). The keyword, static typically means that the method belongs to the class and not just an instance of a class (object). All the static methods have to be called making use of the name of the class: “ExampleClass.methodExample ( ).“ If static as a keyword is not there, then the method can only be invoked through an object. E.g., if the class was called ExampleObject and is also had a constructor, then a new object could be made by typing ExampleObject obj =  new ExampleObject ( ); and method will be called with “obj.methodExample ( .”


package con.test.testing;

class ExampleClass {

static int j=0;

static void methodExample() {

j++;

system.out.println ("value of static variable J is" + j);

}

}

Class TestStatic {

public static void main (String[] args){

ExampleClass.methodExample();

}

}

4). Void is the last word mentioned before the method, and it basically means that the method does not return anything. If you want that the method should return something, then you have to replace the word void with some data type or some object which you want to be returned. Once replaced, you will have to add return plus an object of that type towards the end of the code of the method.

Read: What Is the Difference Between Java And JavaScript?

package con.test.testing;

class ExampleClass {

static int j=0;

static void methodExample() {

j++;

system.out.println ("value of static variable J is" + j);

}

}

Class TestStatic {

public static void main (String[] args){

ExampleClass.methodExample();

}

}

5). When you call a method which returns something, then you can make use of what has been returned. E.g., in case a someMethod ( ) returns an integer, the latter can be further be set to what it returns with “int a = some Method ( ).”


package con.test.testing;

public class testMax{

public static void main(String[] args) {

int i = 5;

int j = 2;

int k = max(i, j);

system.out.printIn("The Maximum Between" + i + "and" + j + "is" + k);

}

public static int max (int num1, int num2) {

int result;

inf (numb1 > num2)

result = num1;

else

result = num2;

return result;

}

}

6). There are some methods which need a parameter. E.g., if a method requires a parameter of an integer, it will be someMethod (int a). Thus, when you use the latter you will have to punch in the name of the method followed by the integer in the parentheses: someMethod (5) or even someMethod (n) if n is the designated integer.


package con.test.testing;

public class testInt{

public static void main(String[] args) {

int w = 5;

int s = computeSquare(a);

system.out.printIn("Square root is" + s);

}

public static int computeSquare (int x) {

int sq;

sq = (int) Math.sqrt(x);

returen sq;

}

}

7). Methods can also come with more than one parameter, which is simply separated by commas. E.g., if the method someMethod requires two parameters, int a and Object obj, it will seem like “someMethod (int a, Object obj).” For making use of this method, it will be called by the name of the method which is followed by an integer followed by an Object in parenthesis: someMethod (4, thing) where a thing is an object.


package con.test.testing;

public class testInt{

 public static void main(String[] args) {

    int w = 5;

    int h = 2;

    int a = computearea(w, h);

    system.out.printIn("area is" + a);

 }

public static int computeArea (int width, int height) {

 int area;

 area = width * height;

 returen area;

     }

}

Conclusion

Read: How to Start a Career as a Java Developer or Programmer

The methods are basically used to club the code together in a way that it can perform a particular task with ease and perfection. There are some components of the method which are needed to be used as per their rules. Java is a highly useful programming language with many features because of which it is used in multiple industries. There are many concepts of Java which you should possibly master one at a time for a thorough understanding of each as superfluous information will lead to patchy information and faulty programming.



fbicons FaceBook twitterTwitter lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    JanBask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

Cyber Security Course

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
Cyber Security Course

Upcoming Class

2 days 21 Dec 2024

QA Course

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing
QA Course

Upcoming Class

1 day 20 Dec 2024

Salesforce Course

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL
Salesforce Course

Upcoming Class

0 day 19 Dec 2024

Business Analyst Course

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum
Business Analyst Course

Upcoming Class

8 days 27 Dec 2024

MS SQL Server Course

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design
MS SQL Server Course

Upcoming Class

8 days 27 Dec 2024

Data Science Course

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning
Data Science Course

Upcoming Class

1 day 20 Dec 2024

DevOps Course

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing
DevOps Course

Upcoming Class

2 days 21 Dec 2024

Hadoop Course

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation
Hadoop Course

Upcoming Class

1 day 20 Dec 2024

Python Course

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
Python Course

Upcoming Class

2 days 21 Dec 2024

Artificial Intelligence Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence Course

Upcoming Class

1 day 20 Dec 2024

Machine Learning Course

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
Machine Learning Course

Upcoming Class

8 days 27 Dec 2024

 Tableau Course

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
 Tableau Course

Upcoming Class

1 day 20 Dec 2024

Search Posts

Reset

Receive Latest Materials and Offers on Java Course

Interviews