Java Programming Basics

Updated on September 15, 2017
FluffyFlower profile image

Fluffy is currently studying towards a BSc in Computer Science. He wants to use his knowledge to help others.

Java
Java | Source

Java Background

Java is an easy to learn, but hard to master C-based language. Its heritage includes C, and C++. It was originally made around 1991 by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at what was Sun Microsystems.

One of Java's biggest selling points is that it is totally platform independent, meaning it could be (and nowadays probably is), used in any system. This could be from a PC to a toaster, so long as it had a circuit board Java could be programmed on.

Before You Code

Getting ready to code, especially with no prior experience, can be challenging. It seems like an impossibility at times. You may have looked at pieces of code and been completely lost.

Stop.

Breathe.

It's really not half as bad, or complex as many people make it out to be. Just imagine you want a task to be done. Let's say you want a program to display text on the screen.

Like many beginners, the 'Hello World' program is a great starting point. Let's examine how we get from nothing to our finished program.

First like we mentioned earlier, we need our program to display text on our screen. Let's break this down further, how can this be accomplished:

First we need the text to be displayed, in this case 'Hello World',

Then we want to display the text.

Right, so two steps, not too difficult, let's give it a go.

Creating Our First Program

Well, if you've made it this far, you probably really want to give Java programming a go. In which case you will need an Integrated Development Environment, IDE for short.

This is a piece of software used to write, and in some cases, compile, execute, and debug code.

I will say now, there is a great divide within the programming community as to what the best IDE really is, but for now I recommend using something light weight, and easy to use. I recommend in this case BlueJ. It is free, great for beginners, and gives you a lot of help.

Here is a link to the download:

BlueJ Official Download

Once downloaded, install and open up, and then we can begin.

Creating a New Project.

Once loaded your first task is to create a new project.

This is simple stuff, first click on Project in the top left corner of the screen, and then highlight new project, and click.

This will bring up a folder selection window, you need to create a folder. This is because BlueJ uses the project folder and codes them specifically for use with itself.

So navigate to My Documents, or somewhere similar, click on the folder name input and type; 'HelloWorld' (without quotes), and then click the Create button.

Once done you should be facing a screen similar to this:

Creating a Class

This is great, but it's a far cry from our program at the moment.

Now we need to create a file for our program, this file is a class file, this file will contain all of the instructions need for our program to work.

The class file upon execution, will be translated into machine code which the computer uses to make our program a reality.

Anyway, now you should have a dialog window called create a class on your screen. In this window there are two categories; Class Name, and Class Type.

For now we will leave Class Type as class, and we will focus on Class Name.

In Java there are certain unspoken rules, that for the most part are good practice, one of these rules is a naming convention. Our class will be called Hello World but you will see now there are a few ways to properly name our class.

Java Good Practice: Naming Convention

In Java, as well as many other languages, there are conventions, ways of doing things... Right.


The naming convention is pretty easy to remember, and in next to no time you will do it as habit.

First when naming a class its name should always begin with a capital letter.

So in our case 'H'. But one letter as a name is rubbish, it tells us nothing of the class's contents, or what it does, so we need the rest. Here we have a problem, we have two words Hello and World, and the name cannot use a space. Now we can move on to a few ways of getting around this problem.

First Camel Notation, camel notation is called such for reasons you will see now; ThisSentenceIsUsingCamelNotation.

As you can probably see, the sentence is rather legible, because a capital is used after every preceding word, but this is only one way let's look at another.

Underscoring is another great way to name things in Java, for example; This_sentence_is_using_underscores.

Extremely legible, but the trade off is flow, you have to break after every word to type an underscore. But it is very tidy. Now the opposite end of the spectrum.

And lastly we have just plain strung together text, it will work but it is extremely illegible; Thissentenceisextremelyillegible.

As we can see, very untidy, and best if never used at all.

Class Creation Cont.

Now we've looked at naming convention, let's either name our class HelloWorld, or Hello_world.

Once you have chosen just click Ok.

We've now finished creating our class, and should look similar to the image below:

The Program Code

Now we have our class, lets open it up and get coding.

To open our file, simply double click on it and a window should open.

You will notice your screen has lots of code already inside, not to worry, we dont need this code and will delete it later on.

Firstly at the top of the screen, there is a comment.

Java Feature: Comments

Comments are an important part of Java, they are used to describe not only the program as a whole, but to comment on specific methods, and variables, and to produce the program's documentation.

There are two types of Java comments, single line and multi-line.

Single Line:
Single line comments are used to help explain a line of code, or put before a code block for the same thing, for example;

Int x; //This is a comment explaing x.

Multi-Line: Multi-Line comments are used to describe the program as a whole, and are used to describe code blocks, when single line comments are not enough. They are also used with creating Java documentation for your program, for example:

/**
* This is a
* Multi-Line Comment
*/

The Program Code Cont.

In the comment we will need to delete all of the contents apart from the @author, and @version, and then we will give the program a description, it should go along the lines of; "This is a basic program used to display a set piece of text to the screen.".

Now add your name, and a version number to the @ tags.

It should look like this upon completion:

/**
 * This is a basic program used to display a set piece of text to the screen.
 * @author (FluffyFlower)
 * @version (1.00)
 */

Now lets delete everything inside the class until we just have this:

/**
 * This is a basic program used to display a set piece of text to the screen.
 * @author (FluffyFlower)
 * @version (1.00)
 */
public class Hello_world {

}

Now lets start coding for real;

First we have to declare somthing called a 'main method'. The main method is something that is used by the compiler to get our program to work.

To do this click on the line below to start, and then press the tab key to indent, then type:

public static void main() {

}

Java Good Practice: Indentation

Indentation is the act of putting a space before every line of code depending on where it is in the program. This make code easier to read, and can help you keep track of your program. For example:

a_code_block {
   avariable
   avariable
   anothercodeblock {
      somethinghappens
      avariable
   }
}

Is better than:

a_code_block {
avariable
avariable
anothercodeblock {
somethinghappens
avariable
}
}

The Program Code Cont.

Once done we need to declare a varible on the next line, our variable is of the String class:

String hw_text = "Hello World";

You will notice that I have ended this line with a semicolon. These denote the end of a line and the begining of another. So now we have our text safely stored in the String, the next line we need is to display that String:

System.out.println(hw_text);

Program Code Finished

The program's code is now finished, and should look like this:

/**
 * This program is used to display a set piece of text to the screen.
 * @author (FluffyFlower) 
 * @version (1.00)
 */
public class Hello_world {
    public static void main() {
        String hw_text = "Hello World";
        System.out.println(hw_text);
    }
}

If your code looks like the above, well done, you've created your first Java program, if not, have a look at the code and edit it to match.

Once matching, click on the compile button, and then close the window, you will be back at the start.

Now right click on your class file, highlight 'void main()', and click, a new window should open showing the text we entered:

And there it is, we've printed hello world to the console screen. pretty easy huh?

Well that is all there is for now, but you've taken the first steps into programming, have fun with it, explore and learn.

If this article helped, please leave a comment of support, and I will be back with some more.

© 2017 Martin C Wylde

Comments

    0 of 8192 characters used
    Post Comment

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://owlcation.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)