Methods and variables in Java with example

In this article we will see what are Methods and variables (Instance and Local), how to create and call them in Java with example.

In Java Methods and Variables goes inside the body of the class, as shown in the example below:
public class ClassName {
	// variable
	String color;
	// Method
	public void bark(){

Methods in Java

Method describe behavior of an object. A method is declared to perform an operation and has statements (logic) to be performed on the instances of the class. A method can be declared as shown below:
// method return
public void bark(){
Where 'public' is access modifier, 'void' is return type and 'bark' in name of the method, by convention method names starts with a small lettter i.e. bark(), getName() etc. In jave a method can have no, one or multiple parameters, parameters goes inside '(' and ')' seperated by a comma(,).
public void bark(int type, String location){

A method can also return a value, as shown below:
public String getName(){
	return "BullDog";

Calling a method in Java

In Java methods can be called on any instance of its class as shown below:
// declaring an instance
Dog bullDog = new Dog();

// calling a method
Static methods can be called with class name, these methods are called class level methods(details later).

Variables in Java

In Java variables are of two types:
1) Instance Variables
2) Local Variables.

Instance variables are declared inside the body of a class but outside the body of methods, while local variables are defined inside the body of the method.

Instance variables can be accessed anywhere in the class, while local variables can be accessed only inside the body of the method it is declared.
public class Dog {
	// Instance variable
	String color;

	public String getName() {
		// Local variable
		String name = "BullDog";
		return name;
In this article we have seen what are Methods and variables (Instance and Local), how to create and call them in Java with example. In upcoming articles we will see more about Core Java.

About The Author

Nagesh Chauhan

Nagesh Chauhan has 8+ years of software design and development experience in variety of technologies like - Core Java, Java 8 (Streams, Lambda), J2EE (Servlet, JSP), Spring Framework (MVC, IOC, JDBC, SECURITY etc), Spring Boot and Microservices, Kafla, Redis, Cassandra and Spark.