Jump to content

[Tutorial]Java #1


Coolis®

Recommended Posts

Tutorial Color

Yellow........Question

Lime Green...........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,648* If a decimal number is

stored in an int, the decimal part of the number will be cut off.

*: 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. :)

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:

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.

int a = 0; // comment

This will comment out everything after // only on the that line. It will not affect the variable declaration.

 

// 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 */

/* comment */
int a; /* Hi!!!
Coolis
Coolis bla bla bla */

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:

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.print ln methods to display text in the console.

Example:

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. :)

 

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! :D

 

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

 

How?

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? :)

 

Now, to create an instance of Scanner

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. :)

 

Example of inputting a number:

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?

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

Input an integer: _

Prompt with System.out.println

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

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. :)

 

 

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.

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.

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:

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. :)

[move]______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________[/move]

 

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:

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:

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,(Loop Useless) 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. :)

 

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:

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:

if (choice == 0)
  // action
else if (choice == 1)
  // action
else 
  // action

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?

 

const int PRESSED = -32767;

if (GetAsyncKeyState(key) == PRESSED)
   saveKey(key);

or

if (GetAsyncKeyState(key) == -32767)
   saveKey(key);

 

I think you get my point. :)

 

 

Terms

Literal: A hardcoded value.

 

[move]________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________[/move]

 

*Please give me critical feedback. I have NOT proof read this, so please, please tell me if you spot any typos or mistakes

*Tutorial was writed about 3-4 hours by me and my friend programer(hackforum)

*I hope this tutorial helps anyone in some way. :) Took some time.

*[Tutorial]Java #2

Link to comment
Share on other sites

Really really nice. I didn't think that someone would ever have the patience to write such a text. Good job! You deserve +1 that's for sure.

Link to comment
Share on other sites

  • 1 month later...

1) where are the bitwise operators =) ?

 

2) Whats this effor of building a tutorial alredy existent? (and more complete)

http://java.sun.com/docs/books/tutorial/

I mean, your work is nice, but theres alredy a official tutorial

Link to comment
Share on other sites

  • 1 month later...

Now you edit the post and you give credits.

 

btw it isn't yours.

i ask my friend Psycho

 

Who want the link of real Topic PM Me ;)

 

someone remove the karma .

 

Edit : the same Here

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...