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..! 😀

Java Tutorials – An Introduction

Hello people…! This is the first post in Java Tutorials – An Introduction. This, is a whole new section of Theory of Programming, where we talk about one of the most widely used languages in industry, Java. I have quite a lot of experience programming in Java and developing small applications. So, I am combining my knowledge and experience to provide a series of posts which will be tutorials for various Java language topics.

Preface

As a prerequisite, I assume you already know at least one programming language such as C. Java cannot be explained in one post, it would be sheer madness..! So, there will be a several posts. There are a lot of sample programs which I have written to explain the topics. I have written my programs in NetBeans IDE, and I would suggest you the same. Believe me, writing Java in NetBeans is a luxury..!

For most of the posts there will be practise questions. I insist you to go through them carefully and try them for the best results. You can always comment if your have any doubts…! 🙂

What and Why ?

Java Logo

Java Logo

Java is a programming language developed by the Green Project Team of the Sun Microsystems, headed by James Gosling, in the late 1990’s. Perhaps the most prominent reason why Java became so successful is that it was the first programming language which was not chained to one operating system. Java is designed to be platform independent. Never before did any language posses such a remarkable feature. Other features of Java include –

  • Java Virtual Machine (JVM) – The JVM is what we need to run Java Programs, nothing else. So, if two systems have JVM installed, they both can run Java Programs and even share them irrespective of their native operating system. The JVM initially converts the programs to what is called the bytecode. This bytecode is then converted to the native machine code.
  • Object-Oriented – Java is an object-oriented language. The programs have data and code in the form of classes and objects. Java’s Object Oriented model is very easy to understand, that is why, many people prefer Java to be their starting step in Object Oriented Programming
  • Robust – Java was designed to be reliable, safe, small and simple, not exactly powerful. So, in comparison, Java will have lesser programming language features than the other object-oriented languages such as C++, or C#. But, the developers of Java didn’t want to design a language which would grant boons to programmers, but an error-free and reliable language so that the programmers need not pray every time they run code…! 😛

Java has always been one of the most-wanted languages by the industry. Tiobe measures the popularity of the programming languages. It is not at all surprising to see Java is always in the top 2..! So, let’s get started..! 😀

Hello Java…!

public class HelloJava {

    public static void main(String[] args) {
        System.out.println("Hello Java...!");
    }

}

This is the simplest Java program. It simply prints “Hello Java…!” on the terminal. Now, if you are a C programmer, almost every word must seem strange to you. That’s okay..! It should..! Everyone felt like that in the beginning. For now, digest whatever you don’t understand, and let’s look at the program from Line 1.

    public class HelloJava {

In this line, we are declaring what is called as a class. A class is a user defined data type, much like the structures in C. But unlike structures in C, we can write functions in class. The Java code, be it variables or functions, are always written inside a class. So, the class acts as a boundary for your program. But, the class is much more than it seems to be, we will get to it later. For now, remember that, whatever set of instructions we want to write to achieve an output, we do it inside a class.
This class is marked as public, which is an Access Modifier. Public means that it can be accessed from anywhere, you can think of it as marking the class global. And the name of the class is HelloJava. There are a couple of rules while writing a Java program –

  1. We can write multiple classes in one file. But, there can be at most one public class in a .java (Java programs are written in a file having .java extension) file. And if there is a public class, the name of the file must be exactly same as the name of the public class, otherwise, the file name can be arbitrary.
  2. We can have any number of non-public classes in one file.

These are some fundamentals. We won’t be writing more than one class in a .java file for quite a while, so you needn’t be too cautious about this. Now, let us look at the line where the main() was declared –

    public static void main(String[] args) {

This is the main() function. As we know, this is where the execution of a program starts. In C, the Operating System calls the main(), but here the Java Virtual Machine (JVM) calls the main(). Unlike in C, the main() function in Java cannot return anything, so its return type is void. It is marked public static for a reason, which we will discuss later. The main() function in Java must have an array of Strings as the parameter. Strings in Java, are not character arrays..! They are completely different..!  We will have a detailed discussion about them later. This is how an array of Strings are mentioned –

String[] args;

Note that the “[]” are given just after the data type. They can be given after the name also, but this is the right way to do it.
The name “args” might give you a hint as to what the array of Strings are meant for. They are meant to store the command line arguments, if any. The name “args” is just a tradition, it can be anything like, “JavaRocks”, or “Hacker”, or any name that is valid.
We can also write ellipses, “…”, instead of “[]”, but they must be just after the data type. It is the Java syntax for variable number of parameters. The last thing I want you to keep in the back of your mind is that the keywords static and public are interchangeable, but mandatory. So, putting all this together, we can say that, the following declarations of the main() function are perfectly valid –

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

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

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

public static void main(String... NewYork) {
    // code
}

Where as, the following are not –

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

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

public static int main(String... Java) {
    // return type not void

    return 0;
}

public void Main(String args[]) {
    // "main" not "Main"
}

public void main(string args[]) {
    // "String" not "string"
}

public void main(String.. SayHi) {
    // Ellipses is 3 dots !
}

The last line to discuss is –

System.out.println("Hello Java...!");

This, prints a line and takes the cursor to the next line. So, in C, it is equivalent to –

printf("Hello Java...!\n");

So, the println() method, implicitly brings the cursor to the next line. If you don’t want to come to the next line, you can use –

System.out.print("Hello Java...!");

So, these are the two variants of printing a line to the terminal. I know you still don’t understand what the “System.out.” thing is doing there. But trust me, we will de-mystify everything soon..! 😉 … So, you should be able to guess what Samy has to say without a sweat..!

public class FatherOfJava {

    public static void main(String... BeingHuman) {
        System.out.print("Samy : ");
        System.out.print("The Father of Java is ");
        System.out.println("James Gosling..!");
    }

}

Summary

  • This is how we write a “Hello World” program in Java –
    public class HelloWorld {
    
        public static void main(String[] args) {
            System.out.println("Hello World...!");
        }
    
    }
    
  • A class is a user-defined data type just like structures in C, but we can have functions too.
  • We can write any number of classes in a file, but there can be at most one public class.
  • If there is a public class, the .java file name should be exactly same as the name of the public class.
  • This is how we declare the main() function in Java –
    public static void main(String[] args) {
         // code
    }
    
  • The keywords static and public are mandatory but interchangeable.
  • The JVM calls the main() function.
  • The main() function in Java has a parameter which is an array of Strings, used for the command-line arguments.
  • This is how we print text on to the console –
    System.out.println("Printing with a new line.");
    System.out.print("Printing without a new line");
    

Practise

  1. I have given some examples regarding incorrect declarations of the main() function. Try running a sample Java program with those incorrect main() function declarations. Some give a compilation error, and some don’t..! Try to run those programs where it doesn’t give a compilation error. Try to guess why things ended up in the way they did..! 😉

This post was to introduce Java to you. I hope I did not scare you..! 😛 … Feel free to comment your doubts..! We will discuss more in the next post…! Keep practising…! Happy Coding..! 😀