In the previous lesson, you created a Java class called 'Tutorial' and created a method with the name 'main'. In this lesson you will understand these terms in detail.

What is a class in Java?

image alt text

In Java, a class is a template or a blueprint from which objects are created. You can compare a class to a chocolate mould in a chocolate factory. While the mould (class) is used to create chocolates (objects), it is the chocolate that we are more interested in than the mould. In a similar way in Object Oriented Programming (OOP), we heavily use objects that are created out of the class than the class itself. Although you will learn on objects a little later, for now it is important to understand that a class is the fundamental construct for writing a program and to create objects. You will first learn the basics of creating a class. Later you will learn how to create objects using the class.

A simple valid class with the name Tutorial would be:

class Tutorial{

}

A class, in its simplest form is defined with class keyword and the name of the class. In this case, we called our class ‘Tutorial’ but you can call whatever you want as long as you follow identifier rules. Every class starts with a left curly brace {, and ends with a right curly brace }.

Even though Tutorial class is empty, it is still a valid class as you can compile this class without errors. You can create this class using any text editor. When you save the file on the filesystem, the name of the file should exactly match the name of the class. This is especially true for classes with public modifier. So you have to save the file as Tutorial.java. In an IDE like AndroidStudio, these things are automatically taken care off for us. You will learn more about modifiers later. In the previous example, you did see public modifier before class. Modifiers are optional.

The class name is called identifier literal in Java. Identifier literals are also used to name methods, variables etc. All identifier literals are constructed with the same set of rules as follows:

Rules for Identifiers

Cannot start with a number

Can have a mix of letters and numbers and special characters $ and _

Cannot use one of the reserved keywords

Cannot use spaces - E.g; 'my class' is illegal

Identifiers are case-sensitive. They must be written the same way every time. e.g. MyClass is not the same as myClass

Reserved keywords

abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while

Although it is hard to make a mistake of using the reserved keywords if you are using an IDE, as most of the IDE's, in our case Android Studio, warns us as soon as you try to use it. So it is actually trivial but it is still good to have a glance at the keywords. There are many other IDE’s available for pure Java applications for e.g., Eclipse, IntelliJ etc.. But since our ultimate aim is to write Android apps, you will use Android Studio. An IDE makes it easy, fast and less error prone to write Java programs when compared to using simple text editors.

Recommendation for class names

As far as the computer is concerned, any class name as long as it meets the rules of the Identifier is fine. However you write programs to not only the computer to execute the program but also for other human being to read and understand your programs. So it is recommended to give meaningful names for a class. A class name should start with an uppercase and should be of a noun form.

If you decide to give two words for your class name then use camel casing. E.g., MyTutorial. The first letter of every word starts with an uppercase letter.

Even though you can use $ and _ for constructing a class name, it is better to avoid using them. Some programs which generates java classes do use $ symbol in the automatically generated class names but human programmers tend to avoid them.

If you remember from the last lesson, you also constructed a main method and added a System.out.println statement inside the main method. So...

What is a main method?

main method is coded as;

public static void main(String[] args) {
    // statements go in this area
}

In the Java programming language, every standalone application must contain a main method whose signature is:

public static void main(String[] args)

The modifiers public and static can be written in either order (public static or static public), but the general practice is to use public static as shown above. You can name the argument anything you want, but ‘args’ is again a general practice. The main method accepts a single argument of type String array. You will learn more about method signatures, modifiers, String and array in the following chapters.

The main method is the entry point for your application and all other methods are invoked later by your program. In our simple example, you only had a System.out.println statement and there were no other methods. So the program started the execution from the main method and executed System.out.println statement which printed out "hello" in the output.

When a program has a main method, you can also run that program from command line. Although in this course you will not run programs from command line. The single argument that the main method accepts is a way through which you can pass information to your application during runtime. These arguments are also called program arguments. If you had to run the Tutorial program from command line then you would open a terminal and invoke JRE's java executable by keying in:

java Tutorial arg1 arg2 arg3

arg1, arg2, and arg3 are the program arguments (a.k.a command-line arguments). You can pass zero to many program arguments. arg1/2/3 are just placeholders for sending any values to your program.

bulb

A standalone application is made of one or more java files in which at least one file will have the main method. A user can start the application from the class which contains the main method using JRE's java executable program.

Our Tutorial program in the last lesson sent in zero program arguments. Now let us send a program argument and use that to display the message.

To send program arguments to the application being run from Android Studio, you invoke the Edit Configurations and add the program arguments as shown below:

image alt text

image alt text

Now change your System.out.println statement to use the program argument:

System.out.println("hello “+args[0] + “!");

Once added, run your program and see the output as shown in the figure below

image alt text

You can also run your application by selecting 'Tutorial' file on the left navigation and then right click to open the context menu - refer to the figure below; then select 'Run'.

image alt text

What is a statement?

Let us look at the line:

System.out.println("hello " + args[0] + "!");

This line is called a Statement and every statement ends with a semicolon. In this statement we use the System class from the core library to print the "hello world!" message to the standard output (a.k.a console).

"hello world!" is constructed from String value “hello” which is concatenated with program argument received through args[0] and an exclamation mark. Concatenation happens by using plus (+) operator.

Remember to add a space after hello to get the above output

bulb

A statement always ends with a ‘;’
Observe the indentation applied to the second line. It is a convention to apply indentation to statements within a block of code. A code block is anything within a set of two curly braces {}. The compiler does not care if you indent or not. You apply it so that humans can understand the code better. Some of the advanced IDE's like Android Studio, automatically indent for us for the most part.

What is a package?

You will notice that your Tutorial class is inside of com.javatutorial.mbcc.learnjava This dotted notation of a set of words is called a package. The package declaration is the first line in your program as well. Every class should have the package declaration unless it is in the default package. Default package is right underneath java folder. However it is not recommended to put any java files in the default package.

image alt text

Every word in the package belongs to a folder. If you now open your file explorer and move over to the AndroidStudioProjects folder, you will see the folder structure as shown below. If you read backwards from Tutorial.java class, you will see that the learnjava folder contains Tutorial.java and mbcc contains learnjava and javatutorial contains mbcc and finally com contains javatutorial. Every folder under java folder forms park of a package.

image alt text

The above screenshot is from a Mac computer, and based on the operating system of your computer, you would see similar folder structure.

Packages help us organize files into separate folders. When you start writing many java files, it could get unwieldy and difficult to understand the program structure if you keep all files in the one folder. In such cases, java files with similar features or functionalities are kept together in the same package to help us understand the code base quickly.

What happens when you run the program?

Android Studio compiles your Tutorial.java file using Java compiler (JDK) and converts that to Tutorial.class. After it is successfully compiled, Android Studio runs the Tutorial.class file using Java runtime (JRE). The Tutorial.class file is kept in a top level folder called build. This folder is automatically created by Android Studio. The below figure shows you the above two files in their respective folders.

image alt text

In Android Studio, java files are kept underneath src/main/java and class files are kept under build/classes/java/main. Notice that .class file is kept in the exact same package under build/classes/java/main folder as the src/main/java folder.

What is a method?

A method is a set of statements grouped together and given a name. Program of execution jumps to a method when that method's name is invoked (a.k.a called). You already learnt about the main method. main method is also a method. This method is invoked by the JRE when you execute run on the program containing the main method. However all others methods are invoked by main method or another method of the same or different class.

Along with the name, a method may contain optional modifiers like public, static etc., optional return type or void if it is not returning anything and optional comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.

Let us add another method called displayGreetings to our earlier program:

package com.javatutorial.mbcc.learnjava;

public class Tutorial{
   public static void main(String[] args){
       System.out.println("hello");
       displayGreetings();
       System.out.println("Good bye");
   }
   public static void displayGreetings(){
       System.out.println("Have a good day!");
   }
}

In this method, we used public and static modifiers, void return type and empty list of parameters. You invoke the method by keying in the name and parameters in between parentheses. Since this method does not take any parameters, you see nothing between left and right parentheses.

image alt text

The program of execution starts from the main method and executes the statement at line number 7 the when it hits the displayGreetings() statement at line number 8, the program of execution jumps inside of the displayGreetings method and executes the System.out.println statement which prints out "Have a good day" and then comes back to where it left off in main method and proceeds to execute the next statement which is System.out.println(“Good bye”)

In the above diagram, the program of execution jumps from line number 8 to line number 12 to execute the method and after the method statements are executed, the program of execution jumps back to line number 9 and then finishes the program.

Output of this program would be

image alt text

Now let us see another example where you can send a value to a method and also get another value as a return type from the method:

package com.javatutorial.mbcc.learnjava;

public class NumberDoubler{
   public static void main(String[] args){
       int doubledNumber = doubleTheNumber(10);
       System.out.println("doubled number is " + doubledNumber);
   }
   public static int doubleTheNumber(int a){
       System.out.println("received number:" + a + ". doubling it now..");
       return 2 * a;
   }
}

Note that 'int a' is being added as a parameter for doubleTheNumber method and void is replaced by int as the return type for the method. The method doubleTheNumber is called from the main method with an argument value of 10 for parameter 'a' declared in the method. The doubleTheNumber method is returning the doubled value using the return keyword used in the second statement of the method. The returned value from the doubleTheNumber method is saved in a variable named doubledNumber in the main method.

Method Names

The rules for creating variable names are similar to rules for creating identifiers. However from the naming conventions perspective method names always starts with a small case.

Methods denote an action being performed and hence the name should be of a verb form. This again is from the naming conventions perspective.

bulb Points to remember!

A class, a method and a statement. Let us summarize these three elements:

A Class: Class declaration in our example has three components:

  1. Modifiers such as public, static, etc., you will learn more later.

  2. Give any name of the noun form with first letter capitalized and follow java literal naming conventions.

  3. The class body is surrounded by braces, {}.

At the minimum a class must have a name and a set of curly braces for the JRE to compile. However to run it from the command line it has to have a main method.

A Method: method declaration should have five components, in order:

  1. Modifiers—such as public, static, and others you will learn about later.

  2. The return type—the data type of the value returned by the method, or void if the method does not return a value. You will learn more about return types going forward.

  3. The method name— give any name of the verb form and follow java literal naming conventions.

  4. The parameter list in parenthesis; a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.

  5. The method body, containing statements enclosed between left and right curly braces which forms the method code.

The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and statements if any between braces, {}.

A Statement: A Statement is a single line of executable. They end with a semicolon ‘;’ System.out.println statement will enable us to write something to the console. That is why we see ‘Hello World’ printed on the console.

Glossary

Java Program (a.k.a application)

A typical Desktop Java program is a collection of one or more classes with one of them containing the main method which is the program execution starting point. Java source file can contain more than one class definition however the file name should match the public class name. Each class definition is compiled into separate .class file containing the Java byte code. The name of the .class file matches the class name defined in the .java file. All .java files must be first compiled to .class files and then you run the .class file.

Java Runtime Environment (JRE)

The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applications written in the Java programming language. The JRE does not contain tools and utilities such as compilers for creating a .class file. But if a .class file is given to a JRE it will run it. JRE is already bundled with Android Studio so you did not have to download that separately.

Java Development Kit (JDK)

The JDK is a superset of the JRE, and contains everything that is in the JRE, plus more - tools such as compilers and debuggers necessary for developing applications. Using JDK you can convert a .java file into a .class file. Since JDK is also bundled with Android Studio you did not have to download that separately.

image alt text

Points to note

  • Every operating system has its own version of JDK and JRE. Popular operating systems (OS) on which you can install JDK and JRE are Windows, Linux, MacOS
  • Once a Java program is compiled on one OS, it can run on any other OS which has JRE installed. This is why Java had a debut with the slogan "Write once run anywhere!"

results matching ""

    No results matching ""