Java Tutorials – Enum and Methods in Java

Hello people..! This is a new post in Java Tutorials – Enum and Methods in Java. In this post I will talk about enum and methods (that is, functions) in Java. The full potential and usage of these constructs will be seen when we start creating classes. But you’ve gotta start somewhere..! So this post is to get you started with these constructs.

enum in Java

“enum” is the short form for “enumeration”… Here, an enum will be an enumeration of constants. In enum, what we do is –

  • Declare an enum. Which involves declaring a set of constants.
  • We create a variable of the enum type, which can hold any one value among the declared constants for that enum… Nothing else…!

Why would anyone use an enum..? … Well, it can look insignificant at most times, but there is a wide scope where we can use them…!

Let’s take the men’s T-shirt sizes for example. We all know that the sizes have fixed letters associated with them. We don’t have to bother ourselves about all of them… Let’s just pick a few –

  • S – Small
  • M – Medium
  • L – Large
  • XL – Extra Large

Now, if you wanted to create a variable to store the T-shirt sizes… Which data types would you choose..? And moreover, how will you ensure that the variable will have exactly anyone of these predefined values..? That’s where an enum comes into the picture.

Let’s look at a simple code which uses an enum

class Enumerations
{
	// Declaring an enum
	// Give the set of constants
	enum TShirtSizes {S, M, L, XL};

	public static void main (String[] args)
	{
		// Creating a variable of the enum
		TShirtSizes myShirt;

		// Assigning a value to the variable
		// Must assign a value among the
		// declared value
		myShirt = TShirtSizes.L;
		// Access the declared value
		// using dot operator 

		System.out.println(myShirt);	// L
	}
}

This is how we use an enum. As you can see, there are 3 steps involved in using an enum in Java –

  1. Declaring – Declare an enumeration using the enum keyword. Provide the set of constants in curly braces. One important thing is that, enum must be declared outside a method. They can be declared even outside a class, but not locally (inside a method)..!
    enum TShirtSizes {S, M, L, XL};
    
  2. Creating a variable – We create the variable using the name of the enum declared. It acts like a data type, similar to a struct.
    TShirtSizes myShirt;
    
  3. Assigning – Assign a value to the variable created. We must always assign a value among the constants declared before. We access these values by using the dot operator on the enum name. Assignment of any other value gives a compilation error.
    myShirt = TShirtSizes.L;
    

Those were about the legal declarations. Let’s look at some illegal declarations. The whole class is given as you could make a mistake at anyone of the steps –

class EnumGoneWrong
{
	enum TShirtSizes = {S, M, L, XL};
	// No '='. This is not an array!

	public static void main (String[] args)
	{
		TShirtSizes myShirt;

		myShirt = TShirtSizes.L;

		System.out.println(myShirt);
	}
}

// Another
class EnumGoneWrong
{
	enum TShirtSizes {S, M, L, XL};

	public static void main (String[] args)
	{
		TShirtSizes myShirt;

		myShirt = TShirtSizes.XXL;
		// XXL wasn't declared..!

		System.out.println(myShirt);
	}
}

// Another
class EnumGoneWrong
{
	enum TShirtSizes {S, M, L, XL};

	public static void main (String[] args)
	{
		TShirtSizes myShirt;

		myShirt = M;
		// It is TShirtSizes.M !

		System.out.println(myShirt);
	}
}

// Another
class EnumGoneWrong
{
	enum TShirtSizes {S, M, L, XL};

	public static void main (String[] args)
	{
		TShirtSizes myShirt;

		myShirt = 'M';
		// It is TShirtSizes.M !

		System.out.println(myShirt);
	}
}

// Another
class EnumGoneWrong
{
	enum TShirtSizes {S, M, L, XL};

	public static void main (String[] args)
	{
		TShirtSizes myShirt;

		myShirt = 1;
		// Cannot take any value
		// other than those declared !

		System.out.println(myShirt);
	}
}

Methods in Java

Functions in Java are actually called “methods”. That’s the terminology we are supposed to use here. In my previous posts, I have used the word “functions” more than “methods” so that you don’t feel too alien. But from now on, we use the term “methods”.

Methods as you know it, are subroutines that can be called from a method, where the control passes to the called method, and comes back to the caller method after execution of the subroutine, with or without a return type.

We will use a lot of methods when we start creating our own classes…. And by “a lot”, I mean really A LOT..! But for now, Let’s just learn how to call a method from the main() method.

class Methods
{
	public static void main (String[] args)
	{
		printMessage("This was printed from a ");
	}

	static void printMessage(String msg)
	{
		System.out.println(msg + "method !");
	}
}

Now the VERY IMPORTANT thing here is that, if you want to call any method from the main() method, it must be marked static, otherwise it is a compilation error..! Not just main() method, any static method can only call another static method..! So the following code gives a compilation error –

class Methods
{
	public static void main (String[] args)
	{
		printMessage("This was printed from a ");
	}

	static void printMessage(String msg)
	{
		printMessageToBob(msg + "method ");
	}

	void printMessageToBob(String msg)
	{
		System.out.println(msg + "Bob !");
	}
}

It is because we are calling a non-static method from a static method. This code gives compilation error which is pretty famous among the beginners –

Main.java:17: error: non-static method printMessageToBob(String) cannot be referenced from a static context
printMessageToBob(msg + "method ");
^
1 error

It is famous among the beginners because they don’t know what static really means. In Java, static means a lot. We will have a detailed discussion later. But you must remember this one rule.

Components in a Method’s Declaration

Methods in Java have six components. They are –

  1. Access Modifier – The access modifier define the scope of the method, that is, from where this method can/cannot be accessed. Access modifiers is a separate topic that we will see later.
  2. Return Type – This is the data type of the return value. It is void if the method does not return anything.
  3. Name – The name of the method.
  4. List of Parameters – Then comes the list of parameters enclosed in parenthesis. The data type of the parameter should be mentioned first.
  5. List of Exceptions – The method must declare unhandled exceptions using throws keyword. We will discuss this later.
  6. Body of the Method – The actual code of the method. Must be enclosed in curly braces.

I would like to introduce another important term –

Method Signature – It is the name of  the method + the list of parameters. It does not include the return type.

Method Signature will be a very frequent term in the upcoming discussions. So, do remember this term well..! As I said before, we will confine ourselves only on calling methods from the main() method. So, you needn’t be bothered about Access Modifiers or List of Exceptions for now.
Some examples of methods, their signatures, and whether they can be called from the main() method or not –

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

// Signature -
// main(String[] args)

// Method
void print() {
    // Can't be called from main()
}

// Signature -
// Print()

// Method
static String getMessage() {
    // Can be called from main()
    return "Hello";
}

// Signature -
// getMessage()

// Method
static void sort(int[] arr) {
    // Can be called from main()
}

// Signature -
// sort(int[] arr)

// Method
int distance(int x1, int y1, int x2, int y2) {
    // can't be called from main()
    return 0;
}

// Signature -
// distance(int x1, int y1, int x2, int y2)

// Method
public static void main(String args) {
    // Can be called from main()
    // But this is not "the" main()..!
}

// Signature -
// main(String args)

The examples are self-explanatory. But do feel free to comment if you have any doubts..! 🙂

Passing Variables of Primitive Data Types

The primitive data types are always passed by value in Java. There are no pointers in Java. So… You cannot exactly create a swap function in Java..! I know you are a genius, but still, I want to remind you that this function does not swap the elements –

public class SwapSwapSwap {

    public static void main(String[] args) {
        int x = 10;
        int y = 20;
        
        swap(x, y);
        
        System.out.println("x = " + x);     // 10
        System.out.println("y = " + y);     // 20
    }
    
    static void swap(int x, int y) {
        int temp = x;
        x = y;
        y = temp;
    }
    
}

Passing Objects

The objects are passed by their object references, so “in-effect”, they are passed by reference. But passing an object doesn’t exactly mean that we can change them in the method called. That depends on whether the object passed is mutable or not. For example, we know that String objects are immutable, whereas objects of StringBuilder are mutable. So look at the following example –

public class PassingAnObject {

    public static void main(String[] args) {
        String str = "String Object";
        StringBuilder strb 
            = new StringBuilder("String Builder Object");
        
        changeString(str);
        changeStringBuilder(strb);
        
        System.out.println(str);
        // Gives - String Object
        System.out.println(strb);
        // Gives - String Builder Object Changed..!
    }
    
    static void changeString(String str) {
        str = str.concat(" Changed..!");
    }
    
    static void changeStringBuilder(StringBuilder strb) {
        strb.append(" Changed..!");
    }
    
}

Strings are real tricky in this aspect. When we pass a String Object, initially, it does point to the object of the main() method, but once, we change it, we get a whole new object. This is not the case with objects of StringBuilder…! Objects of StringBuilder are mutable, so when we pass the object reference, the actual object can be modified by the called method, because inside the method, it’s just another reference pointing to the same StringBuilder object created in the main() method.
You may not understand this… That’s ok..! 🙂 … But remember this that whether the object can me modified depends on whether the object is immutable or not.

Naming Conventions

  • enums – As discussed, enum is a set of constants. According to the Oracle Code Convention, constants must be named in all caps. Such as –
    enum TShirtSizes {SMALL, MEDIUM, LARGE, EXTRALARGE};
    
  • Methods – Methods in Java follow the Camel Case Convention. Here, the first word is written in small letters and the rest of the words following are capitalized. Such as –
    int binarySearch(int[] arr, int key) {
        // code
    }
    
    String toString(int[] arr) {
        // code
    }
    
    char charAt(int index) {
        // code
    }
    
    int lastIndexOf(String str) {
        // code
    }
    

    I don’t know each and every method in the Java Library, but all the methods I have seen so far strictly follow the naming convention. I think Java library is the best example for everything we study in Java.

More about an enum

This is an advanced discussion… So beginners can feel free to skip this section… 🙂 … There’s a lot more to an enum in Java. enums are like really special (or strange 😛 ) classes. As I told before, enums can be declared outside a class –

enum TShirtSizes {
    S, M, L, XL;
}

public class Enumerations {

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

}

Being able to declare it outside a class doesn’t make it a special kind of class… Then what..? … We can have constructors, methods and variables inside an enum..!
Take our example of the enum TShirtSizes… Well, saying S, M, L, is good… But wouldn’t it be nice if we had data about their actual measurements too..? I mean… What if we could store that size L meant 40 – 42 inches..? Now that would be great, wouldn’t it..? So, now, we bring the variables and constructors of an enum into picture. Go through the following code closely –

enum TShirtSizes {

    // Constant(value associated)
    S(36, 38), M(38, 40), L(40, 42), XL(42, 44);

    // Values to be stored
    final int START, END;
    
    // Constructor
    private TShirtSizes(int START, int END) {
        this.START = START;
        this.END = END;
    }

}

public class Enumerations {

    public static void main(String[] args) {
        TShirtSizes shirt = TShirtSizes.L;
        System.out.println(shirt);  // L
        System.out.println(shirt.START + " - " 
                                       + shirt.END);
        // Prints -> 40 - 42
    }

}

This is an enum with variables and a constructor. We cannot directly invoke the constructor. It is automatically called with the values specified at the time of declaring the constants. It is called when we try to create a variable of the enum type. Have a look at the following program –

enum TShirtSizes {

    // Constant(value associated)
    S(36, 38), M(38, 40), L(40, 42), XL(42, 44);

    // Values to be stored
    final int START, END;
    
    // Constructor
    private TShirtSizes(int START, int END) {
        System.out.println("Enum's constructor");
        this.START = START;
        this.END = END;
    }

}

public class Enumerations {

    public static void main(String[] args) {
        System.out.println("main() begins...");
        TShirtSizes shirt = TShirtSizes.L;
        System.out.println(shirt);  // L
        System.out.println(shirt.START + " - " 
                                       + shirt.END);
        // Prints -> 40 - 42
        
        TShirtSizes shirt2 = TShirtSizes.M;
        System.out.println(shirt2);  // M
        System.out.println(shirt2.START + " - "
                                        + shirt2.END);
        // Prints -> 38 - 40
        System.out.println("End of main()");
    }

}

It gives the output –

main() begins...
Enum's constructor
Enum's constructor
Enum's constructor
Enum's constructor
L
40 - 42
M
38 - 40
End of main()

So the constructor is called as many times as the number of constants in the enum, when we use it for the first time. If we don’t use it at all, then the constructor is never called.
We can also have non-static methods in a enum, which can use this reference to refer to the calling object.
enum has a static method called values() which returns an array of the enum constants. This method can be called from the main method –

public static void print() {
    for (TShirtSizes shirt : TShirtSizes.values()) {
        System.out.print(shirt);
        System.out.print("(" + shirt.START);
        System.out.print(" - " + shirt.END);
        System.out.println(")");
    }
}

So, we looked at enum as a special class. Does this mean that we can extend an enum to other classes..? No..! We cannot extend enum to other classes..!

Summary

  • Syntax for declaring an enum in Java –
    enum TShirtSizes {S, M, L, XL};
    
  • We can’t declare an enum locally, we must declare it outside the method.
  • This is how we create a variable of enum and assign a value to it –
    TShirtSizes myShirt = TShirtSizes.L;
    
  • Functions are actually called “methods” in Java.
  • Only static methods can be called from another static method. The main() method being static, can only call other static methods.
  • Methods in Java have six components –
    1. Access Modifier
    2. Return Type
    3. Name
    4. List of Parameters
    5. List of Exceptions
    6. Body of the Method
  • Method signature is the name of the method + list of parameters. It does not include the return type.
  • Primitive Data Types are always passed by value.
  • Objects are passed through their object references, so, they produce a pass-by-reference effect.
  • What really decides if an object can be modified inside a method is whether the object is mutable or not.
  • enums are actually a special kind of classes in Java.
  • We can have constructors, non-static and static variables and methods in a enum.
  • enum has a static method which returns an array of enum type variables which have all the enum’s declared constants.
  • We cannot extend an enum.

This was what you needed to know about enums and methods in Java. I hope it helped you. If you have anything to ask about this topic, feel free to comment..! Keep practising..! Happy Coding..! 😀

5 thoughts on “Java Tutorials – Enum and Methods in Java

  1. Hi,

    // Method
    static void sort(int[] arr) {
    // can’t be called from main()
    }

    // Signature –
    // sort(int[] arr)

    Above method can be called from main right? As you mentioned it is a static method.

    Regards,
    Anil

Leave a Reply to Anilkumar Nagamani Cancel reply