mazeingmazerules
Member
+8|6740|Canada
Basics of Java: by Rog3r (Mazeingmazerules)

Java is quite a rather interesting language.  It's not extremly diffucult to understand from the writing standpoint; however, it becomes more advanced when actually writing in OOP or in otherwords object orientented programming, which Java Sun highly reccommends.  But to begin doing that, you'd need some basic to advanced knowledge in Java programming.  Myself being young, can almost garuntee that you'll understand everything I write - besides, I'm not any professinal programmer but I do have the talent of writing easy to read tutorials which you are reading today.  You'll see new technical terms that you've probably never heard of before, but I'll explain them all.  Once I'm doing explaining them, you'll see them being used without explantation in the hope's of you remembering.  Don't worry, all of my stuff will be explained in ways that novice programmers or beginners will understand.  We aint' dealing with rocket engineering, just a forteen year old kid teaching about Java.  Ironic huh?

Before I begin, let's talk about creating our first class.  But what is a class?

Basically, every functional Java program has one super class and usually mulitple child classes.  Think of the super class as the parent.  Without the parent, you wouldn't be here today would you?  The super class in my defination holds the main method and the class that you extend too when you have child classes.  Relating to a parent in real life, the child class must extend some features from the parent class in order for it to work.  Anyhow, basically this main method is called upon automatically upon initialization of the class file.  In otherwords, when you click the run and you've set it's paths right, it'd say to the super class to execute what ever is in the main method.  Anyways, from there we can create new objects or do things - depending on what you like.  We talk about new objects in the sense of new child classes being called upon to work in that sense and other things as such.  Although, you don't have to have a child class for the program we're about to create to initially work.  We usually create files for purposes; however, if all we're doing is just making a simple 100 line program, we wouldn't need mulitple class files. 

What does the main method look of course?

Code:

public static void main(String args[]) {

}
This is just a code snippet, so it won't exactly work however this is basically what the main method looks like.  Although, inside the body of the main method, would be things but in this case, it's virtually useless. 

What's a method body?

Basically, { is an opening bracket and } is a closing bracket.  In between those brackets is called a body.  We have class bodies and method bodies; however, I'll explain about the class bodies later.  Anyhow, from the example above, you'll see one opening bracket and one closing bracket.  In between is that method's body and in there you can execute a set of things you want it to do.  For every opening bracket, we must have a closing bracket.  That's very important or chances are you'll get thrown errors when you compile.

You may ask yourself, what is compiling?

Compiling is essiental for programming.  We basically write in English; however, the computer doesn't read English.  When we compile, it turns the legiable into the nonlegiable for us.  It basically turns it into what the computer can read and that's what it's all about.  When we compile, it can show us any errors that we might have created in the Java classes.

Anyways, let's begin to write our first super class together.  Initially, we'll start of with a simple display of a message upon initialization of the class.  In other words, when you click the run prompt it'll display a simple message.

Code:

public class YoWorld {

}
We always begin with declaring the initial name of the class.  From this line, we already know what we must name the file as, YoWorld.java.  You must include all the capitalization as this is case sensitive.  Inside the class body, we can execute a set of things and that's what we are going to do.  But first, remember this is the super class and the only class we'll have in this simple program, so you won't need child classes; however, we'll need the main method.

Code:

public class YoWorld {
       public static void main(String args[]) {

       }
}
Right now, this class does nothing at the moment.  Doesn't print out a message, doesn't do anything really.  However, let's make it print out a line of text in the run prompt and see how things go from there.  However, we'll need to import a library.  What this means is that once we import a specific library, we can use what's in the library.  In one hand, it's giving us a library card and we can pick and choose what we want, when we want.  However, if we don't have that library card, we can't use anything in that library. 

To print out some line of text, we must import this library:

Code:

java.lang.System.out;
This allows us to use the println method which is useful for printing out a line of text.  So, let's import the library to our class file and make a simple display of text!

Code:

import static java.lang.System.out; // Imports the print line library

public class YoWorld { // Defines the name of the initial class
    public static void main(String args[]) { // The main method that's called automatically
        out.println("Yo wzup world."); // Prints out a single line saying 'Yo wzup world.'
    } // The end of this main method
} // The end of this class
When you import libraries to your class, you must put them on the very top of the file.  In the class body, you cannot put anything after the classes ending bracket or you'll get a parse error.  To quote out things or make comments within the class, without wanting them to do anything, you can either use these two symbols:

Code:

//
This symbol quotes out one whole line after it's called.  If you look at the example above, it shows a perfect example of that usage.  Please note once again, that it only quotes out one line and not multiple lines.  For multiple lines, use this:

Code:

/*

*/
In between these two, you'll get whatever you need quoted out.  You can use this for as many lines as you want that you wish to quote out making this useful for big comments or things you don't want to use yet.  You must keep these equal in the sense that once you add the /* you must close it with */ or it'd keep on quoting everything after it.

Before we move on, you may notice how everything is indented.  Apperantally, that's how the creators of Java wanted us to do it. 

Basically, Java conventions are the proper indenting of your statements, methods and other various things.  You can indent things by using the tab however explaining the conventions properly is a tough task.  It's easy to grasp however because you just look at an example and you get most of it.  You can learn properly about Java conventions by going to the official Java sun page which I'll provide to you here: http://java.sun.com/docs/codeconv/.  You'll have to download something but don't even bother to read it basically just look at the examples and you should immeditally know.  By the way, you don't HAVE to learn about conventions for your class file to work however it is helpful while rereading the initial file and other's will most likely understand it better.  Might as well get into the habit!

Now, if you run this program you'd see it print out a line of text saying, "Yo wzup world.".  Now you have to admit, this isn't very special at all but this is an example of a very simple program.  Let's say you wanted something like a mathematical problem being solved automatically without user input? 

Code:

import static java.lang.System.out; // Imports the print line library

public class Math {

    private int addThis = 0;
    
    public static void main(String args[]) {
    
        if (addThis == 0) {
            out.println("addThis is equal to 0");
        } else {
            out.println("addThis isn't equal to 0.");
        }
    }
}
This may be overwhelming to some people although literally it's very simple to understand.  We already know the name of the file, it's called Math so we save it as Math.java.  We know it imports the print line class, so this class will probably print out a line of text.  We already know that this is the super class since it contains the main method and it's capable of child classes extending the features of this class however if you look even further, you'll see we declared a variable.

When you declare a variable, you can put it inside the class body after it's declared or inside methods.  But for now, we'll focus on declaring it right after the class name is declared. 

When you set a variable of private, that means that this variable can only be used in the class it's declared in.  That means if your in another class and wanted to use this variable for what ever reason, you cannot because it's of private access.  However, if you change that private to a public, that means it can be used hence the word, public which we should all know what that means.  Next is the word, int.  It's basically short form for integer which is numbers.  When you make a variable of type int, that means that it's value can only hold numbers up to 2 to the power of 31 minus 1, which is somewhere around 2147B.  An int can also hold numbers as low as minus 2 to the power of 31 which is somewhere around -2147B.  That means if the variables value is let's say "HELLO" then you'd get an error because the variable holds of int not String.

However, that example shown above is wrong as we've made a simple error that pops up regularly.  When your using private access type declarations in static methods, you'll get an error.  Changing it to something like this, would work:

Code:

import static java.lang.System.out; // Imports the print line library

public class Math {

    public int addThis = 0;
    
    public static void main(String args[]) {
    
        if (addThis == 0) {
            out.println("addThis is equal to 0");
        } else {
            out.println("addThis isn't equal to 0.");
        }
    }
}
Private access declarations or methods must not be used in the static context (static methods/declarations).  It's like a private parking with public parking spaces, it just doesn't work.

Anyways, what does it mean to be of type String?  Basically, String is the mother where variables can hold numbers and characters.  An example of declaring a variable of type String:

Code:

private String example = "Hello";
It's declared differentially then of variable type int as you can see.  The value is in between the quotations rather then, well, nothing.  Anyways, back on topic. 

After the type of the variable comes the identifier - also known as the name of the variable.  This reserves the variable name so it can be used in the future.  You obviously don't want to declare a new variable and not use it, that'd be extremely useless.  After that variable name, comes the value of that variable and depending on what type that variable is, it could range from numbers without decimals, numbers with decimals, single letter and multiple characters and numbers.  Here's a small quick list of some of the types you can use while declaring a variable.

Code:

boolean - Allows the variable to be of true or false statements only
char - Allows the value of the variable to hold one character only
double - Allows the variable to hold numbers with decimals
int - Allows the variable to hold numbers from -2147B up to 2147B
String - Allows the variable to hold characters and numbers
byte - 8-bit data-type which holds non-unicode characters
Let's move onto another simple example with decelerations- another word for multiple variables.  Remember, when programming you always want to make your class the most efficient as it can possibly be.  You want to take the path less taken and stray away from long, repetitive things.  In more complex classes, you'll declare a lot more variables and sometimes without cleaning them up, it could be a burden.

Alright.  As you can see here we have three variables that are all declared as an int (stands for integer).  There initializing value is all the same (other words starting value).  What can you do to make this more convenient?  I'll show you!

Code:

public int example1, hello, wut;
This is an example of declaring similar variables together.  Although; however, this won't increase performance it'll save some space and basically in my eyes make the script overall cleaner.  When doing this, make sure each variable's initializing value is the same and that they are of equal type.  That is one way to do it however there is another way that allows us to group similar variable types together even with different initialization values.  Take a look at this example and we'll see:

Code:

public int example1 = 2, hello = 1, wut;
Notice how they are all still grouped together however there initialization values aren't the same?  We just put the equals operator to define the value and we could still do it without getting thrown any errors (without the compiler giving us errors).  There is one rule written in stone while grouping together variables and that is they MUST have the same type and access type - private and public etc.

Now, let's say we wanted to execute something multiple times using something like a loop?  Java happily provided us with some different types of loops however for beginners, I recommend the easy to understand for loop.

Code:

for (int i = 0; i < 10; i++) {
        out.println("Cheese");
}
This simple for loop will print out the line of text, "Cheese" 10 times.  Basically, from the beginning, we declared a new variable i which value is of 0.  If the variable's value is less then 10, it'd count up.  Basically, you use the greater then and lesser than operators in Java.

> - Greater than operator
< - Lesser than operator
You can use these operators in if statements as well.  Although, take a look at this for a couple of seconds and I'll try and do my best and explain it perfectly.

Code:

i++
This technically is called a postincrement which basically means it'll add something then total itself.  There are other's such as preincrements which add then total, postdecrements which decrease then total and finally predecrements which total then decrease itself.  Makes sense?

Anyways, I'll show you an example of using the for loop in a class that'd work.

Code:

import static java.lang.System.out;

public class Example {

    public static void main(String args[]) {
    
        for (int i = 0; i < 5; i++) {
            out.println("I C U P");
        }
    }
}
From this class, you'll see the for loop inside the main method's body.  Inside the loop's body, will be what is looped around a given amount of times.  In this case, I've set this loop to count loop around 5 times thus causing to print out the line of text, I C U P five times as well.  Simple, useless program at the moment, but your learning about Java which is all that counts.

Now, we've learn't about the for loop and how to declare variables and such.  However, how exactly do you declare a new method, and what is a method?  Basically, the definition of a method is an orderly executed set of instructions.  When we declare new methods, we must make sure that we don't do something like this:

Code:

public void exampleMethod() {
       public void exampleWrong() {

       }
}
You can't declare a method inside a method, that just doesn't make sense.  You must declare a method in the class body, and not inside any other however to simulate a method inside a method, we'd call upon the method.  Basically, when you call upon a method, it tells that method to do what ever it's suppose to do.  Here's an example:

Code:

public void exampleMethod() {
       exampleRight();
}

public void exampleRight() {
       out.println("This method has been called!");
}
As you can see the method, exampleMethod calls upon the exampleRight method and in turn, prints out a line of text.  You can of course change the access type of the methods, to something like a private access or static access however most of the time, we'll leave it as public.  This method is of type void and that basically means that it won't send back any value to it's caller (other wise known as the method that called upon this method).  However; please note void cannot be used in single lined statements or you'll get an error.  Example of single line statement that would cause an error:

Code:

public void hello;
However; there are other types of methods of course.  Instead of a method of type void which has no return value to it's caller, we could use primitive data types or just types.  We can make a method of type String, or of type int, boolean, double etc.  An example of a method that returns a String literal value is:

Code:

public String returnThis() {
       return "Hello Mate";
This method basically returns the literal value, "Hello Mate" to it's caller.   Don't know what a literal value is?  It's just a fancy term for distinguishing between a String's value from the rest.  Kind of think of it as a value but just with the literal part to it.  Anyhow, an example of a method that returns a numeric value (otherwise known as numbers):

Code:

public int returnThis() {
        return 1;
When you call upon this method, the caller will receive the number one.  You can set things to what ever this returns, by using something such as this.  By the way, this class will compile without any errors being thrown at you, so feel free to test this out if you wish:

Code:

public class Example {

    public static int variableLOL = 1; // Starts as 1
    
    public static void main(String args[]) {
        variableLOL = variableReturn(); // Sets variableLOL to what ever variableReturn is (and it's variableLOL + 2)
        System.out.print("WUT: "+variableLOL+""); // Sends a line of text saying "WUT" and then what ever variableLOL is (Now, 3)
    }
    
    public static int variableReturn() {
        return variableLOL + 2;
        System.out.print("Added the variable together with the number two.);    
    }
}
As you can see, we've declared the variable, variableLOL as it's initializing value 1.  However, the main method which is called upon automatically then calls upon the variableReturn method.  Since that method is not of type void, it'll return back the variable variableLOL's value plus two and of course will send a message notifying us of that change.

Code:

variableLOL = variableReturn();
That's the method call and it'll also set the variableLOL to of what ever variableReturn returns.  And finally, it'll send us a line of text in the run console saying "WUT" and what ever variableLOL's value is.

Code:

System.out.print("WUT: "+variableReturn+"");
We now know the extreme basics of Java; however, let's learn more.  When you want to create another class, you'll have to create basically what is a new object or a constructor - take a look at this example and find out more:

Code:

Example myExample = new Example();
When the computer executes new Example(); that basically tells the computer to create a new object by calling the Example class's constructor.  When you create a new object and execute it properly, it essentially tells the computer to do another set of tasks if the class has things to do.  You create constructors in the super class.  Basically, when you create a new object, there's new tasks and other various things and basically in the sense, the only difference is that the things are handled in that class rather then all in one class.  It's better in the sense of orginizing your classes to do certain things.  For instance, if you have a class that does everything such as calculating mathematical problems and creating the GUI (Graphical User Interface), then perhaps you can organize them into two separate classes.  One for calculating mathematical problems and creating the GUI.   By the way, I'll explain further in what a GUI is later in this tutorial because you aren't ready for that yet.

Last edited by mazeingmazerules (2009-07-09 07:17:27)

jsnipy
...
+3,277|6785|...

Again, i think we need a programming section

edit: just some advice if you want to capture people's attention build your examples so they lead up to something complete. Good to see jr programmers spreading the love.

Last edited by jsnipy (2009-07-08 14:54:59)

mazeingmazerules
Member
+8|6740|Canada
Updated some things about it such as the technical terms and fixed a compiling error from one of the examples.  And jsnipy, i'll take your idea into consideration when this tutorial is bigger.  At the moment, we are just covering the extreme basics with simple examples - nothing fancy.

EDIT: Updated the overall tutorial

Last edited by mazeingmazerules (2009-07-08 15:51:37)

Board footer

Privacy Policy - © 2025 Jeff Minard