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.

Thursday, December 27, 2018

Java Tutorial: Setting up workspace, Fundamental Concept, Letter Cases, Java Naming Convention

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

Chapters

Setting up our workspace

Hello everybody and welcome to my tutorial! In this tutorial we will discuss the OOP fundamental concept, naming convention, some basic java syntax and the definition of java package. We will also create some folders and a source file 

First, create a folder to store our codes I'll name it "java codes" you can name your folder anything you want then inside that folder create another folder and I'll name it "basic" this folder will be the package for our codes. You can decide  what your folder name would be but remember this, when naming a java package it should be in lowercase according to java naming convention rules. You might ask, what is lowercase? lowercase is a letter case where all letters in a word are written without any capitalization.

Next, create a text file in the package/folder that we created earlier. I'll name my text file to "Basic_codes" then change the file extension to "java". If you can't change the file extension of your file just go to "Control Panel" if you're using windows then go to "Folder Options" then select the "View" tab and uncheck "Hide extensions for known file types", click ok and close the "Control Panel". Also remember, our source file name should be in camelcase according to java naming convention rules because most of the time, our source file name represents a public class in it. We will declare a public class in our source file when we start coding.

Brief Introduction to Java Package

java package group classes, interfaces, enumerations and annotation types which are somewhat related to each other. You will learn more about classes, interfaces, enumerations and annotation as you progressed don't bother understanding them for now.

Java packages can be categorized in two forms, the built-in package and user-defined package, java built-in package are like Math,swing,io,javax,awt,etc. user-defined package is a package that has been created by us or other individuals that is not part of java built-in packages, we will learn more about packages as we progress further.

Java Application Fundamental Elements

Java is case-sensitive means that the identifier Hello in uppercase is different from hello in lowercase. Identifier are the names of variables, methods, classes, packages and interfaces. You will learn how to use identifier soon once we start coding. The main() method is a mandatory part of most java applications.

The main() is a method where the java application process starts. That's why we need the main() method because our program can't process input and output without main(). You will learn more about methods,main method and java syntax as you progress further, just absorb all the information I discusssed for now.

The name of the source file should exactly match the main class name, main class is a class with the main method.That's why the name of our source file must follow the java naming convention for classes because the class name that we will write in our source file and the source file name must be the same. Whitespace can't be part or used to name packages, classes, variables, interface, etc. use underscore instead.

Java Fundamental Concept

Now let's tackle the OOP fundamental concept, As you can see there are many fundamental concept to be discussed but for now we will focus on the class, objects and instance. Class can be defined as template/blueprint that tells the behavior/state of the object.

Objects have states,fields and behavior, An object is an instance of class. Instance is a definite realization of an object. The making of a realized instance is called instantiation example: objects, instance variables, instance methods.

It's alright if those definitions make you more confuse or they don't make sense, all things that we discussed here will be more clearer and start having sense as you progress further in learning java.

Letter Cases

Now that we know the concept of naming convention let's view the java naming convention rules but before that let's study the letter cases first to make naming convention much easier to understand. We will study four letter cases.

Lowercase is where all letters in a word are written without capitalization(e.g. bundle,stringpackage)

Uppercase is where all the letters in a word are capitalized(e.g.MAX_RPM,MAX_SPEED).

Mixed Case a combination of lowercase and uppercase(e.g. DoberMan,maxVelocity).

Now that we're done on letter cases we can continue to java naming convention rules.

Java Naming Convention Rules

Next is the naming convention rules for java, naming convention is a set of rules for choosing sequence to be used for identifiers which denotes variable, method/function, and other entities in source code and documentation. Naming convention helps our code to be more readable to ourselves and to other programmers.

You won't feel the impact of naming convention when you are just writing a small simple program but when you're writing a big and complex programs then that's a different story, learning to use java naming convention will be a great help in your java programming career. Here are the rules for java naming convention.

1.) When you name a variable, package, class, etc it must be meaningful, somewhat related to its value or somewhat related to the project you're working on.

2.) Package name should be in lowercase I already mentioned this earlier(e.g. package textpackage, package mypackage). 

3.) Class name should be in mixed case with the first letter of each internal word capitalized. Use nouns because class is a representation of something in the real world(e.g. class DoberMan, class SaveFile).

4.) Interface name should be in mixed case same as class names. (e.g. interface Storable, interface Movable), some programmers like to differentiate interfaces by adding "I" at the beginning of  the name of the interface (e.g. interface IStrorable, interface IMovable). 

5.) Method name should be in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. Use verbs to describe what the method does(e.g. void calculateValue(), char[] sortCharacters()).

6.) Variable name should be in mixed case same as method names.  (e.g. int initialSpeed, int firstName).

7.) Constants should be in uppercase(e.g. MAX_VALUE, MAX_RPM).

java compiler doesn't enforce naming convention mistakes, it means that the compiler doesn't care if you follow the naming convention rule or not but that doesn't mean that you won't follow the naming convention rule, you may not follow the rules or not but I recommend you to follow the rules because first you and the potential readers of your code will benefit from it, second it will make you look more professional!

Java Tutorial: Installation

References/Links:  http://pasted.co/1667778f

Chapters

Java Packages and Editions

Hello Everybody and welcome to my tutorial in this tutorial I'll show on how to install java on your computer. Java has different platform editions
:
 Java SE(Standard Edition) which provides the core functionality of java programming language. We will be using Java SE to create projects throughout my java tutorial(Due to Oracle license changes in Java SE 11, I decided to use OpenJDK11 instead of Java SE 11 in my newly created tutorial, I'll provide an instruction on how to install OpenJDK11 on Windows 7 later). 

Java EE(Entreprise Edition) which is built on top of the Java SE platform and it provides an API(Application Programming Interface) and runtime environment for developing
and running large-scale, multi-tiered network applications. 

Java ME(Micro Edition) which provides an API for running java applications on small devices. 

JavaFX is a platform for creating rich internet applcations using a lightweight user-interface API, JavaFX in now part of JRE/JDK(In OpenJDK11 you need to install IcedTea-Web to add JavaFX/OpenJFX support, I provided a link in the description).

Java has a Java Runtime Environment(JRE) and Java Development Kit(JDK), if you just want to run a java application on your computer then you only need to install JRE, if you want to develop a java application you need to install JDK and JRE. We're developing a java application so we need the JDK, Note we only need to install JDK because JRE is part of JDK so we don't need to download separate installer. Note that the installation procedure in this tutorial is for windows Operating System, The procedure that will be showed in this tutorial might not work on other OS, If your Operating System is MAC or linux check the MAC and linux installation procedure link in the description.

How to Install Oracle Java JDK 8

Let's Download JDK in the oracle website, link in the description, after that you will see two downloads the java Platform(JDK) and Netbeans with JDK 8, Netbeans is an Integrated Development Environment(IDE) which will be explained later so for now click the java platform(JDK) download button, go to java SE Development Kit 8u131, Accept license agreement and download the appropriate JDK package for your PC, mine is Windows 7 Ultimate 64 bit system so I'll choose Windows x64; I don't need to download JDK because I downloaded it already.

Once you downloaded JDK, Open it and when the installer pops up click next, on the next part there is an option where you can change the JDK install location, if you want to change the installation location click the change button, then click the drop-down arrow and just click on the location that you want, I don't want to change my installation location so i'll use the default installation folder, click OK if you're done, then click next and wait for the part to pop up, on the next part we will be installing the Java Runtime Environment(JRE) if you want to change the location where the JRE will be installed click the change button, if not click next, I'm ok with the default installation folder so I'll click next and wait for the installation to complete, When the installation is complete you can click the close button or click the next step button to redirect you to Java SE8 documentation and see the java conceptual diagram. 

One more thing, we need to register the JDK path to our system variables so that the cmd can recognize the javac and java commands, to do it go to my computer, then right click, select properties, click the environment variables button, look at the System variables list and select the path variable, click edit then type semicolon first if there is no semicolon at the end of the variable value then type the path or the location of your JDK in your system.After that open cmd and type "java -version" if the java version is shown on the cmd then Congratulations! You now have JDK and JRE installed on your PC! If not please retrack your steps.

How to install OpenJDK11 with OpenJ9 virtual machine on Windows 7

To install OpenJDK11 and OpenJ9 virtual machine, head over to this AdoptOpenJDK link, then choose a JVM version and a virtual machine, for JDK choose OpenJDK11(LTS), for virtual machine choose OpenJ9. After that, click the big blue button on the bottom and wait for it to finish downloading. After you have the files, extract it and you will receive this file: "jdk-11.0.1+13" . Once you successfully extracted the files, go to My Computer, right click it and then click "properties". After that, go to "Advanced System Settings" on the top-left corner  and go to "Environment Variables". Once you're in the "Environment Variables" go to the "System Variables" and select the "Path" and click "Edit..." on the bottom. After that, put the path where your files are located in the "Variable Value", I put mine in "C: Program Files/" and created a folder named "OpenJDK" there. Here is the example of my JDK and JRE path in my "Variable Value": C:\Program Files\OpenJDK\jdk-11.0.1+13\bin;

After that, open command prompt and type this command "java -version" and you will see this information. If you encountered a problem or error, try to redo the steps.

How to install OpenJDK17 on Windows x64

Go to https://adoptium.net/, choose OpenJDK17(LTS) and click the blue button below to download the Eclipse Temurin installer. For beginners, use the default settings in the installer. In other words, just follow the installer and don't change anything except for the installation folder. You may change the installation folder if you want.

Take note that some IDEs such as NetBeans 13, require a JAVA_HOME variable in our system. if you want to use Eclipse Temurin in NetBeans 13, go to the setup section, click on the left icon besides "Set JAVA_HOME variable" label and choose "Will be installed on local hard drive" option.

Brief Introduction to IDE(Integrated Development Environment)

let's talk about IDE's. IDE provides comprehensive facilities to computer programmers for the ease of software development, IDE makes the programmers work much easier because of the tools that they provide.If you're interested on IDE's I provided a list of java IDE that you can use to create java application. In this tutorial we will use the cmd(command line or windows terminal), Mac Terminal if you're using mac and linux terminal if you're using linux to compile our code.

So why we will not use IDE's even it has numerous advantage? Remember, this is a beginner tutorial so learning the basics is crucial, when we use an IDE like netbeans; it will do the compiling and execution for us and as we progressed on learning java using an IDE, we have no idea on how IDE compiles our project which is bad in some cases like if your professor or colleagues asked you to compile a java code without using an IDE you will be stumped and can't do anything. So don't always rely on the IDE. If you're doing some tedious projects like business related projects then IDE's are necessary in order to complete your project fast. Since we're in the learning process it is not necessary to use an IDE.

Thursday, April 26, 2018

Introduction to java: Brief History, characteristics, compilation and execution process

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

Chapters

Java Brief History

Java was created by James Gosling and its team also known as green team in 1991 at Sun Microsystems."Java" was initially called "Oak" but was renamed in 1995 to "Java" which is now a part of Oracle Corporation. Java was designed to be platform-independent language that could be used to create software to be embedded in various electronic devices like remote controls and some appliances like a microwave oven.

In 1993 java design team used java on the internet that caused the focus of Java to switch from electronic devices to Internet programming which led to Java's success. Java was influenced by C++, If you're a C++ programmer you will be comfortable with java.

Java Characteristics as Programming Language

Java has its own structure, syntax, and paradigm. Java is a multi-paradigm programming language, Programming paradigm are a way to classify programming languages based on their features, Languages can be classified into multiple paradigms. Java's paradigm are: process-oriented, structured, imperative, generic, reflective, concurrent and object oriented programming(OOP) which is the core paradigm of java and it makes java coding much simplier.

Object Oriented Programming or OOP for short is a programming paradigm based on the concept of "objects" which may contain data in the form of fields, often known as attributes; and code, in the form of procedures often known as methods. You will learn more about OOP as you progress further. OOP has four principles: Abstraction, Encapsulation, Inheritance and Polymorphism; you will learn those principles as you progress further in learning java. I won't explain other paradigms because the focus of this tutorial is to give you some general knowledge about java and not to explain every paradigm here.

Java Features

 Here are some characteristics of java

Simple: java is easy to learn and the syntax is quite straightforward and java is easy to use.

Portable: java can run on browsers using applets, extends the capabilities of a server using java servlets, have a GUI for creating application like java Swing and can create an application on computers and mobile devices. Java is commonly used to create android app. Java is also a platform-independent, you can write a program once and run it anywhere.

Secured: here are some security features of java:

  • Java programs runs on virtual machine
  • Classloader adds security by separating the package for the classes locally and those that are imported from network.
  • Bytecode Verifier checks the bytecode fragments if there is an illegal code.
  • Security manager determines what resources a class can access.

Object-oriented: Java used object-oriented model paradigm.

Robust: Java has a strong memory management, garbage collection, exception handling and type checking that makes java robust.

Multithreaded: java supports multithreading - multithreading is a pretty advance topic in java

High performance: java bytecode makes java much faster than traditional interpretation but still a little bit slower than compiled language like C and C++.

Archtecture-Neutral: java can run on x86 and x64 architecture without worrying about implementation dependent features like fixed primitive types.

Statically Typed: Java variables has a specific type that is known at compile time unlike in dynamic typing where variables doesn't have a specific type, it means that every variables can be any type.

High-level language: Java syntax is closer to human readable language and easier to read and write than low-level languages.

Distributed: Remote Method Invocation(RMI) and Enterprise Java Bean(EJB) are used to create a distributed applications that is used to access files from any machine on the web.

Garbage Collection: garbage collection you can call it garbage collector,collector or GC for short is aform of automatic memory management that attempts to reclaim garbage, or memory that occupied by objects that are no longer in use by the program.

Java will handle the memory management for you so you can work on your project faster unlike some languages that has a manual memory management like c and c++.

Automatic and manual memory management have its advantages and disadvantages though.

How java converts codes to machine codes

Let's move on to the process of converting java codes to machine code, When we write a code in java, we can understand the code but our computer isn't, that's because computers can only understand binary numbers the "1" and "0" or "on" and "off" also called the machine code.

Programming language can implement a compiler or an interpreter or both when converting the language code to a machine code that computer understands. Compilers compile the whole code and convert it directly to a machine code while interpreters is a program that translate high level language code to a low level one line by line and executes code one at a time.

In depth explanation of compilers and interpreters are beyond to be covered in this tutorial, i only explained the general definition of those two. C and C++ implements a compiler while python,ruby and java implements an interpreter.

Java Compilation & Execution Process

java uses two compilation processes, Java compilation process starts at the compile-time environment, the source code that you wrote in the text editor with a file extension of .java will go through the java compiler or the javac.exe, we will see the javac and java.exe in action in future tutorials try to understand the process for now.

Java compiler will compile the source code into a bytecode, the bytecode also termed portable code or p-code is a highly optimized set of instructions designed for efficient execution by a software interpreter. Bytecodes can run on any platform as long as there is a Java Virtual Machine on that platform proving the java "Write once, run anywhere" principle is true.

When compiling is complete the bytecode will be contained in a file with a .class file extension which is called java class file. Now, we're done at the first compilation process of java the next compilation and execution process will be in the Java Virtual Machine.

Now that we have the bytecode of our source code we will now go to the run-time environment by executing java.exe, the next process is through the java classloader and to the bytecode verifier java classloader is a part of Java Runtime Environment the dynamically loads Java class files into the Java Virtual Machine.

Bytecode verifier will verify the bytecode first before loading it to the JVM. After passing through the java classloader and bytecode verifier, the bytecode will go through Java Virtual Machine, The Java Virtual Machine will execute the java bytecode, When the bytecode is loaded into the Java Virtual Machine some bytecode fragments will be interpreted and some will be compiled by Just-in-time compiler.

Just-in-time compiler or JIT continously analyses the code being executed and identifies parts of the code where the speedup gained from compilation would exceed the overhead of compiling that code. After that, the bytecode is now a machine code and will go to the machine's CPU to process and execute the code instructions.