DEVTOME.COM HOSTING COSTS HAVE BEGUN TO EXCEED 115$ MONTHLY. THE ADMINISTRATION IS NO LONGER ABLE TO HANDLE THE COST WITHOUT ASSISTANCE DUE TO THE RISING COST. THIS HAS BEEN OCCURRING FOR ALMOST A YEAR, BUT WE HAVE BEEN HANDLING IT FROM OUR OWN POCKETS. HOWEVER, WITH LITERALLY NO DONATIONS FOR THE PAST 2+ YEARS IT HAS DEPLETED THE BUDGET IN SHORT ORDER WITH THE INCREASE IN ACTIVITY ON THE SITE IN THE PAST 6 MONTHS. OUR CPU USAGE HAS BECOME TOO HIGH TO REMAIN ON A REASONABLE COSTING PLAN THAT WE COULD MAINTAIN. IF YOU WOULD LIKE TO SUPPORT THE DEVTOME PROJECT AND KEEP THE SITE UP/ALIVE PLEASE DONATE (EVEN IF ITS A SATOSHI) TO OUR DEVCOIN 1M4PCuMXvpWX6LHPkBEf3LJ2z1boZv4EQa OR OUR BTC WALLET 16eqEcqfw4zHUh2znvMcmRzGVwCn7CJLxR TO ALLOW US TO AFFORD THE HOSTING.

THE DEVCOIN AND DEVTOME PROJECTS ARE BOTH VERY IMPORTANT TO THE COMMUNITY. PLEASE CONTRIBUTE TO ITS FURTHER SUCCESS FOR ANOTHER 5 OR MORE YEARS!

Java Programming Tutorials

Introduction

Hello, my name is TheDischarger, yes an alias, but we’ll use that anyway. Now, i’m going to assume that you are new to this whole programming and coding biz (which are both the same) so don’t expect anything very useful if you have previous experience with coding beforehand. So with that introduction, lets get started.

Installing your software

You want to start coding in Java? Not so fast, like any other popular programming language, you’ll need to install the compiler. What is a compiler? A compiler is a program designed to read source code that a user types in, and translate into code that the computer can read and do. It’s important to know vocabulary in programming, as you’ll be using it alot (Crying yet? Don’t worry, it’ll get better). In Java, you’ll want to grab the compiler from the website at http://www.java.com/en/download/index.jsp and download the installer by clicking that big red button in the middle of your screen (assuming you’re reading this before they change their site). Ok, so we downloaded a compiler, now what? We’re not done quite yet, we need an environment to work on now. An environment is a place where you do all of your typing, compiling and essentially it’s a place to do all of your dirty work. There are multiple environments out there like netbeans, and eclipse, but we’ll use eclipse for now since it’s the most popular http://www.eclipse.org/downloads/ (The Eclipse standard download is fine). Ok, now you’ve got the compiler, the environment, what do I do now? Well, you’re pretty much done here. Now, it’s not the time to throw on some party hats and have a celebration, cause you practically haven't done anything yet! So with that said, time for another chapter, shall we?

Setting up our workspace

Ok, we got our compiler, our environment, what magic can we do now?! I’m going to assume you have already installed the compiler, extracted the environment from his ZIP file and started up eclipse. In this case, we can get to coding! Now, i’m going to explain a little about what you see in this interface. You should have already set a destination to where your project files are going to be (I suggest you have your own folder for this). You’ll see this screen. you’ll want to click the ‘X’ on the right side of the ‘Welcome’ tab on the top left of the screen. This’ll remove that pesky welcome screen and give you the full workspace .Ok, now you’re on the workspace that you should have! There’s a few more steps you’re going to have to do in order to start coding in this environment, so we’ll go over it real quick.

  1. Right click the empty space in ‘Project Explorer’ and click on ‘Project’.
  2. A window should pop up, open up the ‘Java’ folder and click on ‘Java Project’, then press next.
  3. Give your project a name, and press ‘Finish’ (If it asks for a Java perspective, you might want to press yes, you’ll get used to the new layout in no time!).
  4. A folder with your project name should’ve been created, open it up and right click the ‘src’ folder, then click on New > Package.
  5. Type in a package name then press finish (TIP: Java recommends you should always start off the first letter in a package with a lowercase, you are free to use uppercase for the rest though).
  6. Your package with the name you typed in should’ve showed under the ‘src’ folder, you want to right click on your newly created package and press New > Class.
  7. Type in a name for your class file (This time uppercase first, lowercase second!) and press finish.

Ok, so we done quite a few things here, what did we exactly do though? I’ll explain:

  • We gave our name a project to help us identify what we’re working on.
  • We created a Package in that ‘src’ folder so we can have our Class files in a organized place to store in.
  • We made Class files in Packages so that we can type in the actual coding in there.
  • We use lowercase, and uppercase for the first character in packages/classes simply because java is nit-picky.

I hope i’ve cleared enough in this topic, i’ll see you guys again in the next chapter!

Hello World!

Assuming you were paying attention to the last section, you should have something like this. Now, you’re probably wondering what's this random gibberish on this text editor. This is the source code, essentially this is everything what makes a program run. A source code is allowing your very web browser you’re using to run (Although, it’s most likely in a different code, I have yet to see browsers use Java). Now let’s get coding, shall we? We’ll start off by defining what’s already in here for us.

  • Notice how some words like ‘package’ and ‘public class’ are colored in purple, these indicate that they are ‘Keywords’ which essentially are words that are built in by default to run a certain line of code.
  • Also notice how after the Keyboard ‘package’ is the name of your Package you have choosen in your explorer. You always have to assign the package name for every class file they’re in, relative to what the class file’s package is.
  • There is a semicolon ; at the end of the word ‘tutorial’ which means the end of a line of code
  • ‘public class’ means that the code inside it is available for other class files to retrieve code from it (You’ll won’t need to know what this really means in depth until you start advancing on).
  • The word ‘Tutorial’ after ‘public class’ simply is the name of the Method. You can name this anything really.
  • The left bracket indicates the opening of a method, which is the code inside ‘public class Tutorial’ and the right bracket indicates the end of a method.

Whew! that was quite a lot, I certainly hope I won’t have to go that in depth again, but thanks for coping with me. But I’m proud to say we’ll start getting to type. Type in this line of code into the middle of the brackets.

 public static void main(String[] args) {  } 

Now, i’m not going to explain what this does, but essentially, every Java code requires this, so just bear with me. You will now want to type in the following into the brackets of your newly typed code, not in the brackets of your ‘public class’ method.

 System.out.println("Hello World"); 

Now, i’m going to lightly explain what this does. It simply means it’s going to print out the world ‘Hello World’ to the console (located bottom of your screen). Lets get a little more in depth, shall we?

  • System means we’re looking into the System files of java.
  • out meaning we’re going to give data to java’s console.
  • println meaning ‘Print a new line’, we can also say ‘System.out.print’ itself, but it’ll make everything jumbled up.
  • Notice how “Hello World” is in quotes because this lets java know we’re using a string to print out, What is a string? we’ll get to that later.
  • Also notice how “Hello World” is between parentheses, this means that it’s ‘System.out.println’ arguments, which are essentially parenthesis in most code.
  • As said before, a semicolon ; to end lines of code!

Ok, we typed in our first line of code! But what do we do now? You’ll have to compile it now, but how do we do such as thing in Eclipse? There should be a green circle with a white ‘Play’ logo in the center of it, click it and see what happens to the console (Bottom of the screen, it should open the tab every time you click the button). We have just created our first functioning code! Now as soon as you’re done partying, i’m going to take off for a bit, and surely to continue this later on. It was quite the adventure we go here, but all good things must end. See you on the next section!

But can you do math?

Ok, so we have just created out first functioning code (Yay!) but what else can we do now? Like the term ‘computer’ all programming languages have the ability to do some math (Boo). So how do we do this math? Lets’ type in something basic like this (Just delete the part where it says “Hello World” with the quotes)

int result = 2 + 2;
System.out.println(result);

Ok, so what does this do exactly? You can probably guess already from the few parts of this, but i’ll explain.

  • int is a variable type that tells Java to recognize ‘result’ as a integer (Exact Value)
  • ‘result’ in the same of the variable.
  • = tells Java that the variable is assigned to that number/string.
  • 2 + 2 is simply an addition operator, it says for itself. This is also what the value ‘result’ is.
  • We put the variable ‘result’ in the argument (Parenthesis after println, you’ll get used to these technical terms), note that there are no quotes since we are assigning an integer, not a string.

If we did it correctly, you should be able to get the number 4 in the console. But what if we don’t want to add? No problem, subtraction is here, as a matter in fact, you can do all sorts of operations:
Subtraction:

int result = 2 - 2;

Multiplication:

int result = 2 * 2;

Division:

int result = 2 / 2;

Modulo (Divides and gives you the remainder):

int result = 3 % 2;

Alright, so we now know the most basic math functions. With that said, i’ll see you in the next section! Good bye.

Variables

Ok, so what if you want to add decimals into the equation? An integer is obviously not going to work for you, so what we need is a float or a double:

  • A floating point is a 32-bit single precision variable (In other words, it simply allows binaries or decimals to be stored)
  • A double is almost exactly the same, except it is a 64-bit double precision variable, allowing much more data to be stored, so for example: If I wanted to store 1.79769313486231571e+308 (Max that a double can store) numbers, I would use double, but if I wanted to store up to 3.40282347e+38F numbers (Max that a float can store) I would use float, as initializing variables that can store more numbers tend to slow down the system (Unless you’re using a ton of double variables, you’re not going to notice a significant change)

We don’t just have to talk about decimals of course, take a look at these:

  • A byte is a 8-bit integer capable of storing up to 128 numbers and low as -127 numbers. Definitely not usable in most programs unless you want to save some memory in arrays (we’ll explain arrays later)
  • A short is a 16-bit integer with a max value of 32,767 and low value of -32,768. This is much larger than the byte, but then again, this is used for storing low value numbers, so saving some memory with this is not a bad idea in large arrays.
  • A int is a 32-bit integer with a max value of 2,147,483,647 and can go low as -2,147,483,648. Now this can definitely work for most programs, but if you for some reason see to go even higher, you might want to pay attention to the next one.
  • A long is a 64-bit integer, this can reach as high as 9,223,372,036,854,775,807 numbers and low as -9,223,372,036,854,775,808 numbers. I don’t see why you need to use this instead of int, but if you do, pray to god that your program doesn’t take hours to load.
  • A boolean only has two possible values: true and false. Just like binary code (On and Off), booleans are used in a lot of decision making functions (Like if and else statements, in which I will go in depth later on).
  • A char is a single 16-bit unicode character (in other words, a letter). There are really no limits other than one letter (if you want to go technical, it can store a max of '\uffff' and low as '\u0000', but I wouldn’t bother at all).
  • A string is well… a bunch of letters, numbers and text you could say. There’s not exactly a small limit on strings, but you shouldn’t worry about it as long as you’re not putting an entire novel (I would love to be proved wrong though). All you need to know is that you have to capitalise the first letter when assigning this value type like so:
 String HelloWorld = “Hello World”;

And you’re set. Whew, variables are quite a lot aren’t they? Just like they are, we use variables in everything. From written algebra to a mainframe computer. It’s quite important to know what every single variable is, so that the next time you want to type in a bajillion numbers at once, you know to use either a short, a int or a long. Until then, see me at the next chapter, and we’ll do some serious coding.

Our first program

With our newly gained knowledge of math operators, i’d say it’s finally time to get into some serious business. What I’m going to show you is a simple interest calculator that outputs the money after interest.

float principle, months, new_months, rate, simple_interest;
principle = 10000;
months = 6;
new_months = months/12;
rate = 8.5F;
simple_interest = principle * new_months * rate ;
simple_interest = simple_interest / 100 ;
simple_interest += principle;
System.out.println("\nMoney: " + principle + "\nMonths: " + months + "\nRate: " + rate + "%" + "\nFinal Amount: " + simple_interest);
     }
}

ok, now we’re represented some new things here, so let me explain:

  • You’ll notice that we use float variables, this is completely useless for the principle (unless you’re dealing with pennies) but I also have the variables months, new_months, rate and simple_interest all grouped up. This simply means that you can assign multiple variables using the same data type (As obvious enough, this is simply to save space in coding, you just only need to add commas between each variable name).
  • We have ‘rate = 8.5F;’ the F simply means that it is a floating point with a decimal. It’s also safe to say that it’s for the looks.
  • The line ‘simple_interest += principle;’ has a +=? This means that we are adding the variable simple_interest with principle, again, this is solely for shortening our code.
  • We have \n and + in and between each string? the \n inside quotes simply means that the string after it will code placed on a new line. Think of it as using println, but in the same line (Yes, for shortening the code). We use + in between each string and variable, this means that we are grouping up strings and variables to a single code (Should I say again?)

If you did this correctly, we should’ve gotten:

Money: 10000.0
Months: 6.0
Rate: 8.5%
Final Amount: 10425.0

Are you getting the hang of it? I hope so cause we’re about to do something even more advanced in the next section. Ciao!

If and else?

We talked about booleans before in the variables section, right? If you recall, a boolean has only two values: true and false. With these set in mind, an If and Else statement will run a line of code determining on the condition, if its true, the code in the brackets of ‘If’ will run, if it’s false, the code will run the ‘Else’ statement, or maybe not even run anything depending if the programmer adds it or not. Multiple if and else statements can be issued too, here’s an example of an If and Else statement:

    int decide = 1;
        if (decide==1){
            System.out.println("Yes");
        }
    else{
            System.out.println("No");
        }
     }

Now, if you did this properly, you’ll most likely get “Yes”, I’ll explain the code to you in our good ole bullet list:

  • ‘int decide = 1’ We made a integer with the variable ‘decide’ and gave it a value of 1.
  • We created a if or else statement, with a condition (The parenthesis) being ‘decide==1’ which means that, If the variable decide is equal to 1 (which it is), Java will say ‘true’. However, if it is false (the condition is incorrect), Java will say ‘false’. When Java detects a ‘true’ condition, any code under the ‘If’ block will run. When Java detects a ‘false’ condition, any code under the ‘Else’ block will run.
  • Note that ‘If’ and ‘Else’ blocks use brackets, which is required. You only need brackets though if you have multiple lines of code, so this would also work if you only needed to run one line of code, so something like this would work also:
    int decide = 1;
    if (decide==1)
                System.out.println("Yes");
    else
                System.out.println("No");

If and Else statements are used to decide on which code to run depending on the conditions. There are many comparing operators that can be used, here’s a list of them:

  • == equal to
  • != not equal to
  • > greater than
  • >= greater than or equal to
  • < less than
  • ⇐ less than or equal to

Now let’s say that I want to compare ages, this simple if, else statement would work just fine:

    int age = 16;
    if (age>=18)
            System.out.println("You may Enter this site!");
    else
            System.out.println("You are too young. Access Denied!");

You would probably guessed, the output is “You are too young. Access Denied!”. We use a >= operator to say that if our age (16) greater than or equal to 18, we would output our ‘true’ statement (in the ‘if’ code block). However, our ‘false’ statement was returned (in the ‘Else’ code block) since our age does not meet the conditions. However, what if we want multiple else statements? For example, what if we were making a program to make multiple decisions instead of just 2 (Or one if you leave out the ‘else’ statement, so you can run a code in the ‘if’ statement code block if it matches the condition, or continue running the rest of the code and skip the ‘if’ code if it’s false). This is exactly how e would have do it:

    int age = 17;
    if (age>=18)
                System.out.println("You may Enter this site!");
    else if (age>=16)
                System.out.println("You're almost there...");
    else
                System.out.println("You are too young. Access Denied!");

You should get a output of “You’re almost there…”. What we did we placed in a ‘else if’ statement along with a condition right in the middle of the function. Now, you can place these as much as you want (Hopefully with non-colliding conditions), so you can have a ton of decisions (Although, before you do anything crazy, you might want to wait up a bit on another function that handles this specific task). If and Else statements are one of the most useful functions in programming, and they’re practically used in almost every single application you can think of. With that said, we’ll go into more functions. See you in the next section!

The Switch Statement

I mentioned in the previous section about the ‘else if’ code block in If and Else statements. If you recall, this allows you to create multiple decisions depending on the conditions and if the variable being compared meets them. Lets say that you want to have a program that based on a number of a given variable (Like a product number), it returns a output. In this program, i’ll pretend that a customer is buying some potatoes , I want to create a statement that will go through a list, and try equal a serial number on those potatoes, and match it up with one of our conditions, it will then return “Potato selected!”:

int serialnumber = 103;
        switch (serialnumber) {
            case 100:
                    System.out.println("Cucumbers selected!");
                break;
            case 101:
                    System.out.println("Avocado selected!");
            break;
            case 102:
                    System.out.println("Pineapple selected!");
            break;
            case 103:
                    System.out.println("Potato selected!");
            break;
            case 104:
                    System.out.println("Strawberries selected!");
            break;
            case 105:
                    System.out.println("Watermelon selected!");
            break;
            case 106:
                    System.out.println("Tomatoes selected!");
            break;
            default:
                    System.out.println("Invalid Serial!");
        }

Ok, by looking at the list, you’re probably guessing that I just made a list of standard grocery supplies. Like any other tutorial I did, I’ll start by explaining:

  • We assigned an integer variable ‘serialnumber’ the number 103.
  • We created a switch statement that’ll take the value of ‘serialnumber’ and try to find a match within one of the ‘case’. If a match is found, it’ll run that code in that case code block. If a case doesn’t match up, it’ll run the ‘default’ case, which will return “Invalid Serial!” in this case (No pun intended).

Programming


QR Code
QR Code java_programming_tutorials (generated for current page)
 

Advertise with Anonymous Ads