The Basics of Java Code - JAVA: Easy Java Programming for Beginners, Your Step-By-Step Guide to Learning Java Programming (2015)

JAVA: Easy Java Programming for Beginners, Your Step-By-Step Guide to Learning Java Programming (2015)

Chapter 3. The Basics of Java Code

Before you start writing lines of Java code, this chapter will describe first what object-oriented programming is all about (which is one of the primary characteristics of Java programming). You will also encode your first simple Java program and understand the importance of every part. Also, you will be introduced to classes, objects and instances.

One must understand that the heart of Java language methodology is object-oriented programming (OOP). Over the years, software developers are progressively trying to find ways on how decrease the complexity of encoding programs. The first generation of programming languages involved toggling of binary machine codes, which are only a few hundred instructions long, into the computer’s front panel. When programs evolved that required IT experts to handle more complex instructions through symbolic representations, then the assembly language was developed. As programming methodologies were enhanced, more high-level languages were introduced. One example is FORTRAN, however, codes were not easy-to-understand yet.

Structured programming emerged during the 1960s that was used in C and Pascal languages. These programs were characterized by local variables, rich control constructs and stand-alone subroutines, among others. Even if they were considered as power tools, they are still limited when handling very large projects.

The demand for breaking through the barriers of encoding extremely large projects paved way to the advent of object-oriented programming. It is a combination of the best methodologies of structured programming plus new organizing concepts. This programming style is characterized by the following:

· Encapsulation

By the name itself, encapsulation is a strategy that binds the programming code and the data it manipulates and keeps them safe from outside interference. When code and data are linked together, an object is created. This object contains code and data that are either private or public. A private code or data cannot be accessed by any program that exists outside the said object. When it is public, then the other parts of the program are able to access even if they are not within the object.

· Polymorphism

This concept is often described as creating a single interface for multiple methods. It means you design a generic interface to a group of related activities. It further reduces the complexity of the program by letting the same interface to be used to specify a general class of action. A clear analogy is the steering wheel. No matter what type of steering wheel, whether a manual steering or a power steering, as long as you know how it works then you can drive any type of car.

· Inheritance

This process involves one object acquiring the properties of another object, which supports the concept of hierarchical classification. To better explain this, imagine a red delicious watermelon which belongs to the classification watermelon. The watermelon is further part of the fruit class, which belongs to a larger class called food. The food class has certain qualities such as edible and nutritious, that is further applied to its subclass fruit. The fruit has certain qualities as well, such as juicy and sweet. Now for the watermelon, it also has attributes specific to it, such as a tropical vine-like plant. Now combining all these qualities makes a unique red delicious watermelon.

Object-oriented programming is characterized by the application and organization of classes, objects and instances. These are actually the components that make up a Java program and are interconnected with one another.

· Class - Considered as the highest group, class encompasses everything in object-oriented programming.

· Object - Specifications set by the classes are being applied to the objects that are not loaded into the computer’s memory. They are also instances of a class that act as blueprints ready to be used when needed. Thus, one class can have any number of objects associated with it (can even have zero objects).

· Instance - Can be the same as objects since they describe an individual instantiation.

To understand their relationship with one another, imagine that you are developing a computer program that will keep track of the students enrolling in a school. Each student has a distinctive feature – hair style, eye color, skin complexion, height, weight and many more. In your OOP program, each student is an object. Now, even if the students differ from one another, they share the same list of physical features. These attributes or characteristics need to be compiled into a master list, which we call a class.

First Simple Java Program

Let us try again to encode a short sample program by following these instructions:

1. Launch Eclipse. Click FILE > NEW > JAVA PROJECT. Name your new project as EXAMPLE.

2. Create a new EXAMPLE class. Click FILE > NEW > CLASS > Type EXAMPLE for the class name.

3. Enter, compile and run the following program:

Encoding the Java program

In Java, a source file is called a compilation unit and the name that you give a source file is very important. By convention, the name of the main class should match the name of the file that holds the program. Take note that Java programming is case sensitive, which means the compiler distinguishes between lowercase and uppercase letters. Also, the filename extension required by the compiler is .java. Following this programming convention makes it easier to organize and keep track of your lines of code. Also, if you change the capitalization or the naming convention, then the whole program becomes meaningless and will stop working. So for this activity, we named it Example.java (since the public class defined by the program is also Example).

Compiling the Java Program

In this stage, the compiler javac is being executed and creates a file called Example.class that contains the bytecode version of the program. In the previous discussion, the bytecode is executed by the Java Virtual Machine. To actually run the program, use the Java interpreter called javaby passing the class name Example as a command-line argument as shown below:

java Example

The following output is displayed when the program is run:

Java is essential to the Web

During compilation, each individual class is placed into its own output file named after the class with .class extension. It has been a convention to name your Java source file the same name as the class file so that when you execute the Java interpreter, you are actually specifying the name of the class that you want to be executed.

Parts of the Java Program

· Comments

Comments are the descriptive parts of the program that explain what the codes are all about. They are special sections of text that improve the program’s readability - helping people understand the operation of the program. Basically, these are the words that we humans read but the compiler totally ignores. There are two types of comments, depending on how you write them:

1. One-Line or End-of-Line Comment

Starting with two slashes, this comment text is short enough to fit on one line. It is also written at the end of a line of code. In the previous simple Java program example, the one-line comment that we have is:

// A Java program begins with a call to main ().

Everything is ignored by the compiler starting from the first slash up to the end of the line.

2. Block or Multi-Line Comment

This type is characterized by multiple one-line comments (meaning, your comment text is too long to fit in one line). However, the two slashes are replaced with an opening “/*” at the start of the comment and ends with a closing “*/” (to save time in writing “//” for every line). Again, the compiler ignores everything between the two slashes. In the previous simple Java program example, we have:

/*

* This is a simple Java program

*

* Call this file Example.java

*/

Prologue is a version of a block comment that is placed at the top or very beginning of your programs. It contains important information about the code so that every programmer will be able to get an idea what the program is all about just by merely glancing at it. Usually, the prologue is enclosed in a box of asterisks and includes the following information: filename, programmer’s name and program description. If we are to modify the block comment above, it will look like this:

/*********************************************************************

* Example.java

* Felix & Khatz

*

* This is a simple program that displays “Java is essential to the Web” on your PC screen

************************************************************************/

· Class Heading

We now move to the next line in our first simple Java program:

public class Example {

This program line is called the class heading or class declaration, which is composed of 4 parts – the 3 words and the open curly brace (actually the entire program is considered as a class). Let’s discuss each one of them.

The first two words, public and class are what we call reserved words or keywords. Such words are used for a particular purpose as defined by the Java language. You cannot redefine or use them to mean something else, like making them as names for your program. Below is a list of the common keywords in Java language:

abstract

assert

boolean

break

Byte

case

catch

char

class

const

continue

default

do

double

else

enum

extends

final

finally

float

for

goto

if

implements

import

instanceof

int

interface

long

native

new

package

private

protected

public

return

short

static

strictfp

super

switch

synchronized

this

throw

throws

transient

try

void

volatile

while

Analyzing each word, class is a marker that signifies the start of the class or the beginning of the program. It also states that a new class is being defined. In our first simple program, Example is the name of the class. On the other hand, public is an access modifier that controls how the class is being accessed (in this case, the information can be accessed by all other classes). If it was set to private instead of public, then only the current class has the access to it. Finally, the open curly brace “{“ indicates the beginning of the class and has a corresponding closing brace “}” at the end of the entire program. Always coming in pairs, braces identify groupings of code for both the programmer and the computer.

· Main Method’s Heading

After the class heading, the main method heading comes next. Method is a subroutine in Java language that is the line of code at which the program will begin executing. It is simply a list of things to do. In our example, the main method has the following form:

public static void main(String args[]) {

Again, public is an access modifier keyword, which indicates that everyone can access the main method. This also means that this can be accessed by the code outside the class in which it was defined or declared. Static, also another reserved word, denotes that the method can be accessed immediately. The third reserved word is void that signifies the main method returns nothing (in some programs it could return a value).

Any information that is needed to pass to a method is received by variables specified within the set of parentheses that follow the name of the method. These variables are also called parameters and in our example it is only (String args[]). The declared parameter named args represents the arguments that the main method takes. String is the argument’s type that stores sequences of characters. The square brackets “[]” symbolizes that it is an array of objects of type strings. Even if there are no parameters required, you still need to indicate the empty parentheses.

· System.out.println

Based on our first simple Java program example, our main method contains the following line:

System.out.println(“Java is essential to the Web”);

System.out.println is a programming code that gives instructions to the computer to print something out. Let us discuss every part of it. System refers to the computer and when it becomes System.out it pertains to the monitor, which is the output device of the computer system. The next word, println (read as “print line”) is a built-in Java method that is in control of printing computer messages. Overall, the line of code is what it refers to as println method call. You simply call a method when you want to execute it. Please remember that the first letter of a method call is always in uppercase and the rest will be in lowercase.

The text enclosed in double quotation marks inside the parentheses is the message to be printed out to the screen. These double quotes are in charge of grouping the messages together. At the end of the line is a semi-colon that signifies the end of the method call or programming statement (it is like period in the normal English language). All programming statements to be executed in Java end with a semicolon.

This chapter gave you a guide on how to start encoding using the Java programming language. You also have a better picture of what are the different parts of a simple program. In the next chapter, you will take programming to a higher level by incorporating what you call a user input.

Before We Continue, Here Are Other Books Our Readers Loved!

http://amzn.to/1mBhUYM

http://amzn.to/1WOBiy2

http://amzn.to/1QzQPkY

http://amzn.to/21HWFWb

http://amzn.to/1VHtxZi

http://amzn.to/1R1vnCP

Thanks for checking out my other books, let’s now move on to Chapter 4 where we you learn about User Input!