Friday, December 28, 2018

Java Tutorial: Coding, Reserved Keywords, Introducing main() and println() methods, Compiling Source File, Executing Program

References/Links: http://pasted.co/e2c5f8f3

Chapters

Introduction

Hello everybody and welcome to my tutorial. In this tutorial, we will study java reserved keywords, Source file declaration rules, basic program structure of a source file and compiling our source code. If you're ready then let's get started!

Java program can be written as a standalone application that can be run on any computer with JVM, an applet that run from a web browser and a servlet that run from a web server to generate dynamic web contents. java application is a popular program in java because most general tools/application that is needed in the computing world, can be done by creating a simple java application and java application is a good starting point for beginners.

Java Reserved Keywords

First of all let's discuss the java reserved keywords, reserved keywords have a predefined meaning in the language. Because of this, we programmers cannot use keywords as names for variables, methods, classes or as any other identifier. Most IDE and some text editor use syntax highlighting to display keywords in a different color. Here are some reserved keywords: for, while, case, switch, class, instanceof, implements, extends, etc.

Java Source File Declaration and Fundamental Code Structure

Now, let's study the source file declaration rules in java. Remember these rules because we're gonna follow some of it later.

1.) There can be only one public top-level class per source file.

2.) A source file can have multiple non-public classes.

3.) Top-level class name and source file name must be the same.

4.) package statement must be the first statement in the source file, If the class of the source file is defined in the package(comments are allowed above the package statement).

5.) There must be only one package statement in a source file, but multiple import statements are allowed as many as you desire.

6.) import statements must come after the package statement (or at the start of the source file is there is no package statement) and must come before the top-level class declaration.

7.) Package and import statements will be applied to all classes that is present in the source file, whether you want it or not.

You might ask yourself "what is statement, import and public? i have no idea what this guy is talking about." Don't worry if all of the things that we discussed don't make sense to you, it will all make sense to you as we progress further, so just be patient and accept how things are done for now.

Coding Our First Java Program

And now we can start coding, Remember the folder that we created? Well open that folder now and find the java source file there, then open it with your preferred text editor, mine is atom text editor. I hope you remember the java declaration rules that i discussed earlier because we're gonna apply those rules here. Remember I said that the folder where our source file reside will be the package for our source file? but how do we tell that to the java compiler? Well, the solution for that is to write a package statement.

Package Declaration

Since our source file is in the package then package statement will be the first code in our source file, to write a package statement, type the package keyword first then put a whitespace then type the packagename then put semicolon at the end of the statement.(package statement general form -> package packagename;)

Package Declaration


Before we proceed to the next line of code let's examine this code first. package is a reserved keyword of java, we can use the package keyword to assign a package to our source file, then you must put whitespace between the keyword and the actual package name so the compiler will know what is the keyword and what is the actual package name.

You might be wondering: "can we let the compiler distinguish what is the keyword and the actual package name without using whitespace?".Well, the compiler can't distinguish a keyword and the actual package name if we don't follow the java syntax, it means that to make this statement to work, we need to follow the proper syntax on writing package statement and this is the proper syntax on writing package statement.

Notice the semi-colon at the end of the statement, it is a part of java syntax that stated "statements must end with a semicolon." so to terminate the statement we will use semi-colon to tell the compiler that this is the end of the statement. We will learn more about statements as we progressed.

After the package statement the next line of code should be an import statement according to the java declaration rules, since we won't importing any packages we will skip the import statement for now, don't worry we will use the import statement in future tutorials. Use the return/enter key to go to the next line, you can leave a line empty or let's say skip the line, the skipped line is called a blank line and java ignores it.

Blank Line and Comment

Blank line can have whitespace or a comment, for example if I put a whitespace on this line, for us it's not empty because it has a whitespace character but for the compiler it is still consider as blank line because there is no code to execute on that line, same goes when you only write a comment on this line, the compiler will still consider that line is a blank line because java compiler doesn't execute comments.we will learn java comments in future tutorials.

Blank Line and Comment

Line Numbers

Also notice the number in the left corner, that's called a line number, line number indicate the the number of that line which can be helpful when we are debugging our codes. Some text editor like notepad doesn't have a line number on the left corner just like on this text editor, the only way to determine the line number on a text editor that doesn't have a line number display is to count the line from top to bottom, which is hard by the way.

Line Numbers
Next is we're gonna create a class. According to java declaration rules: "There can be only one public class per source file". Since this is a beginner's tutorial one class is enough and so I'll only create one class and if I follow the declaration rule this class should be public.

Class Definition

Class definition/declaration is the process of writing class content in a source file. To create a class, we need to define its access modifier, "public" is an access modifier so we will type the "public" first, we will learn more about access modifier in future tutorials, put whitespace, type the class keyword, put whitespace again, type the class name that you want and it may follow the java naming convention, since this class is public then the name of this class must match with the name of our source file so i'm gonna name my class like the name of my source file so they will be the same.

After naming the class put open and close curly  braces after the class name, note that the class is a block and not a statement so, semi-colon is not necessary.

Class Definition

A block is enclosed between open and close braces and executed as a single statement, we will learn more about blocks in future tutorials.

Introducing the main() method

Inside the class block; we will write the syntax for main() method, make sure that you are typing between the class open and close braces. main() method is a block, so, this method needs an open and close curly braces.
General Form: public static void main(String[] args){}

main() method declaration
You might wondering what the hell is static and void? and why the main syntax looks too complicated? Okay, to give you an idea why main method looks like that let's examine the main method syntax. 

public is an access modifier, in other words, when you make your variable, class or method public it will be available to every part of your project, note that main() method access modifier should be in public so the JVM can access the main() easily.

static: Static variables or methods belongs to the class itself, in other words, we don't need to instantiate a class to access a static variable or methods, that's why the main is static and it has to be static no matter what so JVM can access main() without having to instantiate the class object.

void: is used for methods so the method won't return anything from the caller. Basically, main() method is designed not to return anything from its caller therefore, main() method must be void.

method parameters: When executing the program we can put arguments, in simplified term, a set of values.
Put this code in a text file and rename it as SampleClass.java

public class SampleClass{
  
  public static void main(String[] args){
	  for(String s : args)
		  System.out.print(s + " ");
  }
}
Compile the code first and then execute the program like this:
java SampleClass I am a beginner in Java.
Result
I am a beginner in Java.

You might wonder: "What's the value of args if we don't put any value in it?", The answer is nothing. args is empty if we don't put any values.

We can change String[] args to String... args
[] stands for array
... stands for varargs
We can also change args to any valid name that we want e.g. public static void main(String[] arguments){}
Apart from the things above, we can't change any part of main() method.
main() is a method, go to this topic to learn about methods: Java Tutorial: Methods


Introducing println() method

Next, i'll introduce you to another method the println() method, println() method is a pre-defined method in System package of java. println() method outputs a message on the console.

General Form: System.out.println("message");

calling println() method

if you want to change the message just change the words in double quotes( " " ). You might notice the double quotes in println parentheses and the println syntax, First the text in double quotes is called String literal, String literal is a string value that we typed in our source file in double quotes. We will learn more about literals and string as we progress further. 

Second, that syntax is a method call syntax. Method call is a way to call a method. In our case, we are calling the println() method in the System package.


Now, all we need to do is to compile our source code, Remember the compilation process that we discussed in previous tutorial? We will use those information when we compile our code, I hope u remember it.


Compiling Our Code

Alright! let's compile our code, select the package folder, then open the command terminal on that folder in windows press "ctrl+shift" on the keyboard then right click on the folder then choose "Open command window here"(Note: open the command window on the folder that we created before the package folder. In my case the folder that I created to hold packages named "java codes")then type "javac", your source file name and the file extension which is .java and click enter. After that, you see a file with .class extension, and that's the java bytecode!
javac command

When invoking the javac command on cmd, we are asking the java compiler to compile our code, then the compiler will check our codes first and if the compiler sees an error in our source file the compiler will throw a compile-time error and our source file won't compile. If our source file doesn't have any errors then the compiler will generate a bytecode for us then we can proceed to the next step. 

Executing Our Program

Now that we have the bytecode, we can use the java command to run our program, don't open cmd in the package folder, open cmd in the parent folder of our package instead. Loot at the message that we put in println() method is displayed on the console.

java command

println() output

Let's examine this command, first the java command, this command will run the java runtime environment then notice how packagename and source file name are concatenated.

This command "basic.Basic_codes" means that in the package "basic" find a class file that has this name. If your source file is not defined in a package you can directly open cmd at the source file directory and run the program. For example, Remove the package statement so the compiler won't assign a package to our source file then recompile the source code.

Open cmd at the source file directory. compile our source code then type the command(java Basic_Codes), this time we will only write the class name because we compiled our source code without a package statement so our class file is not assigned to any package.

Remember, javac refers to directories and expected a .java file and we used the forward slash and the java command refers to packages and expected a .class file and we used the dot character.(Note: the forward slash can be used in java command but the dot character cannot be used in javac command)

Once we invoke the java command, the bytecode will be loaded to JVM and JVM converts the bytecode to a machine code then the CPU will process that machine code and our program will run.

No comments:

Post a Comment