Thread Rating:
  • 4 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Introduction to Java
#1
Tutorial Color Legend
Yellow........Question
Aqua...........Examples
Green..........A term, see bottom of post for definition
Orange.........A literal




Primitive Data Types
We have byte, short, int, long, float, double, boolean and char.
For the sake of simplicity, I'll stick with: int, float, boolean and char.




int: We use int if we're storing normal whole integers between -2,147,483,648 and 2,147,483,647.* If a decimal number is stored in an int, the decimal part of the number will be truncated.
*: Integer ranges from here

NOTE: A common misunderstanding is that the decimal number will be rounded. This is not the case! The decimal part will simply cut right off.
Example:
15.5 becomes 15, 9.9 becomes 9. and so on.


float: A float can store decimal numbers. And for the sake of simplicity, nothing more will be said. Smile

boolean: A boolean is either true or false.

char: A char is a single character.

Where's String?
String is not a primitive data type; String is actually a class.




Variables
I really do hope you know what a variable is. ;(
I'll offer a brief explanation of variables.

A variable consists of a data type, an identifier, and a value.
Example:
Code:
int number = 1;
int being the data type, number being the identifier, and 1 being the value.




Operators
I'll be sticking with the simple operators.
+, -, *, /, %, +=, -=, *=, ++, --

Mathematical Operators
+: The addition operator. variable = variable + 1;
-: The subtraction operator. variable = variable - 1;
*: The multiplication operator. variable = variable * 2;
/: The division operator. variable = variable / 2;
%: The modulus operator. (Explained below) evenNumber = number % 2
+=: This operator adds specified value to variable given. variable += 2
-=: This operator subtracts specified value to varaible given. [i[variable -= 2[/i]
*=: This operator multiplies variable by specified value. variable *= 2
++: This operator increments variable by one. variable++
--: This operator decrements variable by one. [/i]variable--[/i]

The modulus operator (%):
People tend to get confused with this one. The modulus operator returns the remainder of division.
5 % 2 returns the remainder of 5 / 2... which is 1.

Logical Operators
!: This is the not logical operator. It returns true if a value does not equal another and false if it does.
==: This the the equal to operator. It returns true if a value equals another and false if it does not.
<: This is the less than operator. It returns true if the right operand is greater than the left, and left less than the right.
>: The greater than operator. Opposite of less than.
<=: The less than or equal to operator. Returns true if the right hand operand is less than OR equal to the left.
>=: The greater than or equal to operator. Opposite of less than or equal to operator.
!=: The not equal to operator. Returns true if the left operand is not equal to the right, and false otherwise.
&&: The && operator tests two expressions. If both are true, true is returned. If one is false, one true, false is returned.
||: The || operator tests two expressions. If one is true, true is returned.




Comments
Comments are used to describe your code. Let me emphasize on the word describe.
When we use a comment, we are trying to describe what the statement does, without simply repeating it in a comment.
Comments are completely ignored by the compiler, and are not compiled with it; therefore, more comments will not make the compiled result larger.

How do I use comments? When?
You use either // or /* */. // will comment out everything on the same line, after //.

First, the single line comment.
Code:
int a = 0; // comment
This will comment out everything after // only on the that line. It will not affect the variable declaration.

Code:
// int a = 0; comment
This will comment out the whole line.

And now the multi-line comment.
Multi-line comments start at /* and end at */
Code:
/* comment */
int a; /* hi
hi
hi hi hih hih ihi hhislkdjfsldfj */
The second and third lines are also commented here.

As for when you comment, that is completely up to you.




Structure of Your Program
The basic structure you will use most of the time is:
Code:
public class MyJavaApplication
{
    public static void main(String [] args)
    {
        // stuff stuff
    }
}

You start by naming your class. In this example its name is MyJavaApplication.
Within your class, you will have a main method. This is required for the program to run.
The main method is where most of your code will be (unless you're doing OOP, of course).




Basic Output
We use the System.out.print and System.out.println methods to display text in the console.
Example:
Code:
public class MyJavaApplication
{
    public static void main(String [] args)
    {
        // output "Hello World\n"
        System.out.println("Hello World");
    }
}

This is the classic Hello World application. I do not think you should comment things like that, as anyone reading your source should have the ability to comprehend
System.out.println, but for this tutorial, I'll be commenting often. :3

Difference between System.out.print and System.out.println?
System.out.println adds a line break to the end of the line, System.out.print does not.

System.out.print("Hello World\n");
is equivalent to
System.out.println("Hello World");




Basic Input/Output From User

We now know how to output to the console; however, we know nothing of inputting from the user yet.
We will be using the Scanner class to input from the user.
This will be the first object you'll use, too! ^_^

First, Scanner comes from the java.util package. Because of this, we'll need to include the Scanner class to use it.

How?
Code:
import java.util.Scanner;
public class MyJavaApplication
{
    public static void main(String [] args)
    {
        // stuff stuff
    }
}
You will use import to import the package and do this above your class. Simple, right? Smile

Now, to create an instance of Scanner
Code:
import java.util.Scanner;
public class MyJavaApplication
{
    public static void main(String [] args)
    {
        Scanner keyboard = new Scanner(System.in);
    }
}

We use Scanner as the data type and new to create an object of Scanner. keyboard is our identifier here.

Why 'keyboard'?
When we input an integer, it will make more sense for beginners. Smile

Example of inputting a number:
Code:
import java.util.Scanner;
public class MyJavaApplication
{
    public static void main(String [] args)
    {
        // instantiate Scanner object
        Scanner keyboard = new Scanner(System.in);
        
        // our variable to store user input
        int userInput;
        
        // store the input into userInput
        userInput = keyboard.nextInt();
    }
}

The third line is where your focus should be. We invoke all public methods of an object with dot notation.
In this case, we have the non-static method nextInt().
nextInt() reads an integer from the user.

The only problem is, the user will be presented with just a black screen and expected to input something.
How about a prompt?

Code:
import java.util.Scanner;
public class MyJavaApplication
{
    public static void main(String [] args)
    {
        // instantiate Scanner object
        Scanner keyboard = new Scanner(System.in);
        
        // our variable to store user input
        int userInput;
        
        // display prompt
        System.out.print("Input an integer: ");        

        // store the input into userInput
        userInput = keyboard.nextInt();
    }
}

Notice the usage of System.out.print, rather than println.

Why?
Prompt with System.out.print
Quote:Input an integer: _

Prompt with System.out.println
Quote:Input an integer:
_

Using System.out.println would bring the input down a line, making the prompt look ugly.

We may want to manipulate the integer we input and output it back to the user.

Addition example
Code:
import java.util.Scanner;
public class MyJavaApplication
{
    public static void main(String [] args)
    {
        // instantiate Scanner object
        Scanner keyboard = new Scanner(System.in);
        
        // our variable to store user input
        int userInput;
        
        // display prompt
        System.out.print("Input an integer: ");        

        // store the input into userInput
        userInput = keyboard.nextInt();

        // add one to the integer, twice
        userInput += 1;
        userInput++;

        // output integer back to the user
        System.out.println("Your number: " + userInput);
    }
}

In the above example, we use two methods to add one to the number. They work the same.
We then output the integer back to the user.
"Your number: " + useriInput will add that integer to the end of the output string.

Practice this using all of the mathematical operators. When you feel you understand, continue reading. Smile





Control Structures
Now that you have a basic understanding of input/output, we will discuss control structures.

The If statement
The If statement is the most commonly used flow control statement, and is where logic comes in.
In short, an If statement tests an expression and returns a boolean value.

So,
if (expression)
...doThis
else
...doThat


If our expression is: 5 == 1, the if statement would obviously return false.
When our if statement returns false, if the else statement is present, that will be executed instead.
So, as you may have guessed, the else statement containing "doThat" was executed, because the expression was false.

Example
Code:
import java.util.Scanner;
public class MyJavaApplication
{
    public static void main(String [] args)
    {
        // instantiate Scanner object
        Scanner keyboard = new Scanner(System.in);
        
        // our variable to store user input
        int userInput;
        
        // display prompt
        System.out.print("Input an integer: ");        

        // store the input into userInput
        userInput = keyboard.nextInt();
        
        // check if user entered 50
        if (userInput == 50)
            System.out.println("You entered 50, yay.");
        else
            System.out.println("You did not enter 50. :(");
    }
}

In this example, we check if the user entered 50.
If the user entered 50, we will output "You entered 50, yay."
If not, we'll tell them they did not with a sad face to guilt trip them. ;)

You can have more complex If statements, where you test two expressions.
if (var1 == 2 && var2 == 2)
...doThis();
else
...doThat();


If both var1 and var2 are equal to 2, doThis() is executed. Otherwise, if one or both of the expressions are false, doThat() is executed.
You can test for either/or, too.
if (var1 == 2 || var2 == 2)
...doThis();
else
...doThat();


If var1 is equal to 2 OR var2 is equal to 2, we execute doThis(), otherwise, we execute doThat().


Braces
We add braces to our flow control statements when they contain more than one line of code.

Example
Code:
if (number == 1)
{
    number++;
    System.out.println(number);
}
else
    number--;

Our If has two lines of code, which is more than 1; thus, we add braces.
Our else has only one line of code, so we use no braces.
You can use braces on one line of code if you'd like, but I consider it an eyesore to see them around one line of code.


Switch Statement
Sometimes you may prefer using a Switch statement instead of an if statement.
A Switch statement is setup like so:

Code:
switch(variable)
{
    case value : doThis; break;
    case value2: doThis; break;
    case value3: doThis; break;
    case value4:
    case value5: doThis; break;
    default: doThat; break;
}

The first line in the body of the switch tests if variable is equal to value.
If so, it will execute doThis and break.
You need a break statement after every case to separate the different cases.
Notice the 4th line of the switch's body. This tests if the variable is equal to value4, and if it is, it falls through.
It then tests if variable is equal to value 5, too. Almost like "&&" in an if statement.
If Switch statements remain unclear to you, I will consider revising this portion of my tutorial. Smile

Loops
Loops are another large part of programming. You will find times where it would be useful to loop.

The While Loop
The while loop is used when you do not know how many times you are going to loop.
An example would be allowing a user to enter an arbitrary amount of numbers until that user decides they do not want to enter any more.
There will be a value they can enter to stop entering number and exit the program.

That would be implemented like so:
Code:
import java.util.Scanner;
public class MyJavaApplication
{
    public static void main(String [] args)
    {
        // instantiate Scanner object
        Scanner keyboard = new Scanner(System.in);
        
        // our variable to store user input
        int userInput;
        
        // display prompt
        System.out.print("Input an integer: ");        

        // store the input into userInput
        userInput = keyboard.nextInt();
        
        // while the user still wants to enter numbers...
        while (userInput != -1)
        {
            // display user's number
            System.out.println("You entered: " + userInput);
            
            // get another number
            System.out.print("Enter another number or -1 to quit: ");
            userInput = keyboard.nextInt();
        }

        System.out.println("Have a nice day.");
    }
}

We first input a number from the user to start the loop off.
The first line of the while loop tests whether or not the user wants to quit.
I use -1 as my sentinel value here, since it's hard to accidentally hit -1.
We input the next number from the user to continue the loop.
This will go on forever until the user finall enters "-1" to quit.
When the loop finally ends, we tell the user to have a nice day and the program then ends.



The For Loop
Unllike the While loop, the For loop is used when we know how many times we are going to loop.
The For loop is typically executed like so: for (set; condition; action)
for (int i = 0; i < 10; i++)
We set i (Index) to 0. Our condition for this loop to remain active is that i stays less than 10.
Our action is incrementing i by one each run through the loop.
The body of our for loop will be executed each time i is less than 10.
After the body is executd, we add 1 to i. So our For loop's body will be executed 10 times.

This would be implemented like so:
Code:
import java.util.Scanner;
public class MyJavaApplication
{
    public static void main(String [] args)
    {
        // instantiate Scanner object
        Scanner keyboard = new Scanner(System.in);
        
        // our variable to store user input
        int userInput;
        
        // display prompt
        System.out.print("Input an integer: ");        

        // store the input into userInput
        userInput = keyboard.nextInt();
        
        // start the for loop here
        for (int i = 0; i < 10; i++)
        {
            userInput += i;
            System.out.print(userInput + ", ");
        }

        System.out.println("Have a nice day.");
    }
}

Each pass through our For loop, we'll add i to the user's number, and then display the number.
We will do this exactly 10 times.

The Do..While Loop
I don't think this loop is useful, and I don't think anyone should use it, to be honest.
I don't believe in forcing the user into a loop; I'll be skipping this one.



Constants
I realize it may be a strange time to mention constants, and am sorry if it bothers you. Smile

A constant?
A constant is basically a read-only variable.
You initialize this constant and it cannot be changed afterwards.
It is intialized the same as a variable, but with final before the data type.

Example:
Code:
final int constant = 10;

Constants are good for:
  • Readability
  • Easier debugging
  • Easier code management

While it is a little extreme to replace every literal with a constant, you should use one if you're using the same value over and over again.
Take Rock, Paper, Scissors for example. Is it easier to read:
Code:
if (choice == 0)
   // action
else if (choice == 1)
   // action
else
   // action
or
Code:
if (choice == ROCK)
   // action
else if (choice == PAPER)
   // action
else
   // action

I'll let you decide on this one. ;)

Another example would be a keylogger. If you're designing a keylogger in C++, you would likely use GetAsyncKeyState().
We know it returns -32767 if the key passed to GetAsyncKeyState() is pressed.
So, which is easier on your eyes?
Code:
const int PRESSED = -32767;

if (GetAsyncKeyState(key) == PRESSED)
    saveKey(key);
or
Code:
if (GetAsyncKeyState(key) == -32767)
    saveKey(key);

I think you get my point. Smile



Terms
Literal: A hardcoded value.




[/TUTORIAL]


Please give me critical feedback. I have NOT proof read this, so please, please tell me if you spot any typos or mistakes.
I am very tired, so this tutorial may be full of them, and I do apologize for that. I will fix them when I notice them, though.
I hope this tutorial helps anyone in some way. Smile Took some time.
Reply
#2
Great tutorial. Text in code tags is EXTREMELY hard to read as of now, and I have to highlight it. I hope omni will fix it soon.
Reply
#3
(10-04-2009, 07:15 PM)D3N Wrote: Great tutorial. Text in code tags is EXTREMELY hard to read as of now, and I have to highlight it. I hope omni will fix it soon.

Yeah, it hurts my eyes, did you set that colour or did it do it automatically?

Awesome tutorial by the way!
Reply
#4
I've studied Java before and I think you've covered the basics nice and clean. You have some italic tags to fix up, though.
Reply
#5
Thanks for this lesson, checking it out.
Reply
#6
Sweet. Thank you.
Reply
#7
Wow nice and big tutorial Big Grin
Reply
#8
This tut is fantastic! Thanks alot!
Reply
#9
That was a good one..thanks
[Image: 2d75599e9a.png]:superman:
Reply
#10
one of the best TUTs thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  why java haphazard 8 1,748 12-12-2011, 03:23 AM
Last Post: RDCA
  Need Java help from java expert. Blazin 2 2,086 09-07-2011, 02:43 PM
Last Post: AceInfinity
  Introduction to Java 2 Psycho 13 3,771 06-09-2011, 06:12 AM
Last Post: Livewire
  Java help php 1 1,022 04-06-2010, 06:41 AM
Last Post: php
  Java Problem for real java programmer Testgamma1 10 5,135 03-14-2010, 09:08 AM
Last Post: uber1337

Forum Jump:


Users browsing this thread: 1 Guest(s)